Complete Azure instance: online calendar

Source: Internet
Author: User

In this article, streamcompute Trojan demonstrates a complete Azure program development instance: online calendar. Compared to the previous Stick Love instance, which only supports adding and reading entities, the current data entity is slightly more complex. Data operations include complete addition, deletion, modification, and query (CRUD ), and added the function of integrating authentication with Windows Live Id.

The predecessor of this project is a small private calendar in my wife's office system. Now I extract it and use it with a set of liveids. The power of the old lady is indispensable.

(If you have never learned about Azure before, please refer to here .)

Online Demo: http://live.cloudapp.net/

Interface:

 

Key steps:

1. Integrate Live Services

As we mentioned in previous articles, Live Services is an integral part of Azure Services Platform. Live Services includes a lot of content. Today we want to use the integrated LiveId authentication feature in Windows Live Tools.

Before Azure was launched, Live opened its LiveId API. However, it was troublesome. Today's Windows Live Tools and Azure work seamlessly with each other, saving developers a lot of effort.

  1. First, open VS2008 and create a blank Cloud application.
  2. Right-click Roles, select "New Web Role Project", and select Windows Live Web Role, as shown in the following two figures.
  3. In this case, the control group of Windows Live appears in the Toolbar of the design view. Contains a variety of cool services. The most fun of course is MessagerChat, which is the control of MSN chat on the webpage! Of course, I will not introduce it today. Today, we use the IDLoginStatus control that can quickly integrate LiveId authentication. For example, drag the IDLoginStatus control to the right-side page.
  4. After dragging the control, you only need to perform simple configuration. Click the arrow on the right of the IDLoginStatus control and select "Configure Application ID" to bind the control to the Application ID on your Azure platform.
  5. Done! In subsequent development, you do not need to maintain the logon status. To enable livid for pages without the IDLoginStatus control, we need to write user information into the Session during user logon. My method is as follows:
    protected void IDLoginStatus1_ServerSignIn(object sender, Microsoft.Live.ServerControls.AuthEventArgs e)      {          Session["LiveId"] = IDLoginStatus1.ApplicationUserID;      }
    In this way, on the page where the IDLoginStatus control is not placed, we can obtain the user's identity information by judging the value of Session ["LiveId.

2. Create entity and data services

 Like Stick Love, we need to create entity and data services. (For detailed steps, see the basic chapter)

    1. Data entity Schedule. cs
      Public class Schedule: Microsoft. Samples. ServiceHosting. StorageClient. TableStorageEntity
      {
      PublicSchedule ()
      {
      Parttionkey = "000000 ";
      RowKey = (DateTime. MaxValue. Ticks-DateTime. Now. Ticks). ToString ();
      }

      Public stringId {get; set ;}
      Public stringTask {get; set ;}

      PublicDateTimeBuildDate {get; set ;}

      Public stringLiveId {get; set ;}
      }

    2. Create Data Service ScheduleDataServiceContext. cs (add, delete, modify, and query function)
      Public class metadata: TableStorageDataServiceContext {public ScheduleDataServiceContext (StorageAccountInfo accountInfo): base (accountInfo) {}// defines public attributes Schedules public IQueryable <Schedule> Schedules {get {return this. createQuery <Schedule> ("Schedules") ;}// Add a Schedule public void AddSchedule (Schedule c) {this. addObject ("Schedules", c); this. saveChanges ();} // delete a Schedule public void DelSchedule (Schedule c) {this. attachTo ("Schedules", c, "*"); this. deleteObject (c); this. saveChanges ();} // modify a Schedule public void UpdateSchedule (Schedule c) {this. attachTo ("Schedules", c, "*"); this. updateObject (c); this. saveChanges ();}}
      You have noticed that when deleting and modifying an object, you must first use this. AttachTo ("Schedules", c, "*") to specify the position of the object.

3. AJAX frontend call

The foreground uses jquery to implement simple AJAX, including foreground calls for "add, delete, modify, and query" data. The process of modifying, deleting, and adding data is similar. For example, to update data, the front-end js function is:

// Update task information function updateTask () {var taskId = $ ("# taskId "). val (); // task No. var taskInfo = $ ("# editTaskInfo "). val (); // task content // check whether the task information is empty if ($. trim (taskInfo) = "") {alert ("Please input task information. ");} else {$. post ("Calendar. aspx ", // server page address {action:" updateTask ", // action parameter taskId: taskId, // Date and month parameter taskInfo: taskInfo // task information parameter}, function () {// callback function $ ("# task" + taskId).html (taskInfo); // update the page task content closeEditBox (); // close edit box });}
The Calendar. aspx page is called by AJAX, that is, the main function page of the background.
In addition, the front-end also needs to read and fill in data in JSON format through AJAX.
/Obtain task information from the server. function getTasks () {$. getJSON ("Calendar. aspx ", // server page address {action:" getTasks ", // action parameter month: year +"-"+ (month + 1) // month parameter }, function (json) {// callback function // traverses the JSON array to create task information $ (json ). each (function (I) {buildTask (json [I]. builddate, json [I]. id, json [I]. task);} // create a function buildTask (buildDate, taskId, taskInfo) on the page Based on the date, task number, and task content) {$ ("#" + buildDate ). parent (). append ("<div id = 'Task" + taskId + "'class = 'task' onclick = 'edittask (this) '> "+ taskInfo +" </div> ");}

Iv. AJAX background processing

The left and right sides of the AJAX background processing page are processed based on the parameters of the frontend post function, and then the returned results are output. There are many ways to process pages in the AJAX background, such as using WebServices and ashx (HttpHandler). Here we use the most common aspx page.

  1. Create An aspx page Calendar. aspx. Delete all Page code. Retain only
    <% @ PageLanguage = "C #" AutoEventWireup = "true" CodeBehind = "Calendar. aspx. cs" Inherits = "AzureCalendar. Calendar" %>
  2. Process the post parameter in the Page_Load function in the background, and select the appropriate function to further process and output the data.
    Protected void Page_Load (objectsender, EventArgse)
    {
    If (Session ["LiveId"] = null)
    {
    Response. Redirect ("Default. aspx ");
    }
    // Set the page to no Cache Response. Cache. SetCacheability (HttpCacheability. NoCache );
    Request. contentEncoding = Encoding. UTF8; string action = Request. params ["action"]; // perform different operations if ("addTask ". equals (action) {// create a task String taskInfo = Request. params ["taskInfo"]; String buildDate = Request. params ["buildDate"]; Response. write (addTask (taskInfo, buildDate);} else if ("getTasks ". equals (action) {// obtain the task information of the entire month String month = Request. params ["month"]; String result = getTasks (month); Response. write (result);} else if ("delTask ". equals (action) {// Delete task String taskId = Request. params ["taskId"]; delTask (taskId);} else if ("updateTask ". equals (action) {// update task information String taskId = Request. params ["taskId"]; String taskInfo = Request. params ["taskInfo"]; updateTask (taskId, taskInfo );}}
  3. Write protected string getTasks (string month ).
    This step is critical. We use JSON to return data. The front-end uses AJAX to obtain the JSON object and fill in the front-end page appearance.
    Protected string getTasks (string month) {StorageAccountInfo accountInfo = StorageAccountInfo. getAccountInfoFromConfiguration ("TableStorageEndpoint"); TableStorage. createTablesFromModel (typeof (ScheduleDataServiceContext), accountInfo); ScheduleDataServiceContext context = new ScheduleDataServiceContext (accountInfo); List <Schedule> list = context. schedules. where (p => p. liveId = Session ["LiveId"]. toString ()). toList (); string json = "[\ n"; // start to encapsulate the JSON format foreach (Schedule s in list) {if (s. buildDate. toString ("yyyy-MM-dd "). replace ("-0 ","-"). contains (month) {string strSchedule = "{\" id \ ": \" "+ s. id + "\", \ "builddate \": \ "" + s. buildDate. toString ("yyyy-MM-dd") + "\", \ "task \": \ "" + s. task + "\"} "; json = json + strSchedule +", \ n ";}} json = json. substring (0, json. length-2); json + = "\ n]"; if (json. length <10) return "[\ n {\" id \ ": \" 0 \ ", \" builddate \ ": \" 0 \ ", \" task \": \ "0 \"} \ n] "; // if no data exists, a waste data is returned to ensure the format is correct. return json. replace ("-0 ","-");}
    To work with the front-end, we replace the string like "" with "2009-7-1 ". The implementation method is ugly. I believe you have more elegant methods.
  4. Other data additions, modifications, and deletions are similar. Take data deletion as an example:
    // Delete the task protected void delTask (string taskId) {StorageAccountInfo accountInfo = StorageAccountInfo. getAccountInfoFromConfiguration ("TableStorageEndpoint"); TableStorage. createTablesFromModel (typeof (ScheduleDataServiceContext), accountInfo); ScheduleDataServiceContext context = new ScheduleDataServiceContext (accountInfo); Schedule s = new Schedule (); s. rowKey = taskId; context. delSchedule (s );}
    There are two problems to NOTE: When modifying and deleting data, you must specify the primary key of the object.
    In Azure Storage, the primary keys of objects are RowKey and PatitionKey. Since the PatitionKey in this example is the same, we only need to specify the RowKey.


    Okay, you're done! Add more details!
    PS: all source code will be put on CodePlex later. Thank you for your support!
    More Azure technical articles are here.
    (Reprinted please keep author blog link, http://azure.cnblogs.com /)



     

     
     
     
     
     

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.