• 【Azure Services Platform Step by Step第4篇】SQL Data Services 编程基础


     

    在上一篇中,我们通过SSDS Explorer详细了解了SDS的工作和操作流程。
    这一篇,我们会详细讲解如何使用程序员的方法来操作SDS。

    SDS提供SOAP和REST两种接口,这里我们是用REST+C#的方法来讲解。SOAP与之殊途同归,请有兴趣的同学自己查阅MSDN。

    闲话少说,下面我们以创建Authority为例,给出REST操作SDS的“万能框架”:

    public   string  CreateAuthority()
           {
               //步骤一(蓝色部分):通过某种方式,构造要发送到服务的XML数据。显然,这一部分只有在POST方法和PUT方法时才会有,对于GET方法和DELETE方法则不需要。下面示例的是一个创建Authority的XML
           
       const string AuthorityTemplate =
                         @"<s:Authority xmlns:s='http://schemas.microsoft.com/sitka/2008/03/'>
                           <s:Id>{0}</s:Id>
                         </s:Authority>";

               if (String.IsNullOrEmpty(ServiceUri))
               {
                   throw new ArgumentOutOfRangeException("ServiceUri");
               }

               string authorityUri = null;
               try
               {

                   string requestPayload = string.Format(AuthorityTemplate, authorityId);
                  //步骤二:建立用以传送数据的HttpWebRequest对象
                  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServiceUri);
                  //步骤三:将用户名和密码放置在HttpWebRequest对象的Credentials中
                   request.Credentials = new NetworkCredential(userName, password);

                  //步骤四(:设置Http方法。HTTP方法与数据操作方法的对照: POST=create; PUT=update; DELETE=delete; GET=retrieve 。在这个例子中,我们需要create,所以选择POST方法。
                   request.Method = "POST";

                 //步骤五(蓝色部分):传送数据到服务器。显然,这一部分只有在POST方法和PUT方法时才会有,对于GET方法和DELETE方法则不需要。

                   UTF8Encoding encoding = new UTF8Encoding();
                   request.ContentLength = encoding.GetByteCount(requestPayload);
                   request.ContentType = XmlContentType;

                   // 传送数据
                   using (Stream reqStm = request.GetRequestStream())
                   {
                       reqStm.Write(encoding.GetBytes(requestPayload), 0, encoding.GetByteCount(requestPayload));
                   }
                
              //步骤六 :获取服务器响应,根据服务器的相应获取操作结果   
           HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                   if (response.StatusCode != HttpStatusCode.Created)
                   {
                       Console.WriteLine("Failed to create authority");
                   }
                   authorityUri = "
    https://" + authorityId + ".data.database.windows.net/v1/";
               }
               catch (WebException ex)
               {
                   Console.Error.WriteLine(ex);
                   HttpWebResponse response = ex.Response as HttpWebResponse;
                   if (response != null)
                   {
                       string errorMsg = ReadResponse(response);
                       Console.WriteLine(string.Format("Error: {0}", errorMsg));
                       Console.WriteLine("Unexpected status code returned: {0} ", response.StatusCode);
                   }
               }

               return authorityUri;
           }

    很简单吧? 所有的操作与这个“万能框架”相似。例如,我们稍微做一些改动,就可以得到下面这样一个删除Entity的函数:

    public   string  DeleteEntity(string entityId)
           {
    //由于删除是HTTP中的Delete操作,所以无步骤一和步骤五

    string EntityUri = string.Format("https://{0}.data.database.windows.net/v1/{1}/{2}",
                                                        authorityId, containerId, entityId);
             try
             {
    //步骤二: WebRequest request = HttpWebRequest.Create(EntityUri);
    //步骤三: request.Credentials = new NetworkCredential(userName, password);
    //步骤四: request.Method = "DELETE";            
    //步骤六:using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                 {
                     if (response.StatusCode != HttpStatusCode.OK)
                     {
                         Console.WriteLine("Failed to delete the entity resource.");
                     }
                 }
             }
             catch (WebException ex)
             {
                 string errorMsg = ex.Message;
                 Console.WriteLine("Deletion failed: {0}", errorMsg);

                 if (ex.Response != null)
                 {
                     using (HttpWebResponse response = ex.Response as HttpWebResponse)
                     {
                             Console.WriteLine("Unexpected status code returned: {0}", response.StatusCode);
                     }
                 }
             }
    }

    UPDATE的操作和"万能框架"中Create的方法基本雷同,唯一区别是在步骤4的地方,将"POST"改为"PUT"。比如以下这个函数:

    读取数据就不用说了吧?呵呵。。那太容易了,就连把URI直接输入浏览器都可以。不过作为编程来说,其实就是在上面给出的DeleteEntity()函数的代码中,步骤四的HTTP方法由DELETE改为GET,再大到HttpWebResponse 中去获取你想要获取的内容。

    至此,数据库的四种操作(CRUD,Create,Read,Update,Delete)我们都已经讲过了。对,就是这么容易。

    由于时间关系,我只在附件内写出了Authority,Container,Entity三种结构的Create操作。相信读者看完这篇文章后,自己改写成其他操作并非难事。下载地址:https://files.cnblogs.com/azure/BeginningAzureSDS.rar

    我正把SDS应用到我目前的项目之中。如果大家有兴趣的话,我争取过段时间提取一部分功能,做成Demo供大家参考。感谢大家的关注!by 流牛木马

  • 相关阅读:
    Linux下 高性能、易用、免费的ASP.NET服务器
    K-means算法
    K-means算法
    机器学习之深度学习
    机器学习之深度学习
    Tracking-Learning-Detection (TLD算法总结)
    Tracking-Learning-Detection (TLD算法总结)
    机器学习技法之Aggregation方法总结:Blending、Learning(Bagging、AdaBoost、Decision Tree)及其aggregation of aggregation
    机器学习技法之Aggregation方法总结:Blending、Learning(Bagging、AdaBoost、Decision Tree)及其aggregation of aggregation
    迭代是人,递归是神(迭代与递归的总结:比较)
  • 原文地址:https://www.cnblogs.com/azure/p/1359174.html
Copyright © 2020-2023  润新知