# 九、附录

## 代码清单 1

```cs
  SET IDENTITY_INSERT [dbo].[Customers] ON;

  MERGE INTO [dbo].[Customers] AS Target
  USING (VALUES
    (1, 'Beth Massi', 'F', 'Burg 1', '8000', 'Brugge', 'Belgium', 1.00),
    (2, 'Chris Rummel', 'M', 'Burg 1', '8000', 'Brugge', 'Belgium', 0.90 ),
    (3, 'Matt Evans', 'M', 'Burg 1', '8000', 'Brugge', 'Belgium', 0.80 ),
    (4, 'Andy Kung', 'M', 'Burg 1', '8000', 'Brugge', 'Belgium', 0.70 ),
    (5, 'Brian Moore', 'M', 'Burg 1', '8000', 'Brugge', 'Belgium', 0.60 ),
    (6, 'Matt Sampson', 'F', 'Burg 1', '8000', 'Brugge', 'Belgium', 0.50 ),
    (7, 'Steve Lasker', 'M', 'Burg 1', '8000', 'Brugge', 'Belgium', 0.40 ),
    (8, 'Heinrich Wendel', 'M', 'Burg 1', '8000', 'Brugge', 'Belgium', 0.30 ),
    (9, 'General Awesome', 'F', 'Burg 1', '8000', 'Brugge', 'Belgium', 0.00)
  )
  AS Source(Id, Name, gender, Street,  ZipCode, City, Country, SatisfactionScore)
  ON Target.Id = Source.Id
  -- update matched rows
  WHEN MATCHED THEN
  UPDATE SET Name = Source.Name, gender = Source.gender, Street = Source.Street,
        ZipCode = Source.ZipCode,  City = Source.City, Country = Source.Country,
        SatisfactionScore = Source.SatisfactionScore, DateOfBirth = NULL,
        FullProfile = NULL, Email = NULL, Phone = NULL, AverageYearlySpending = NULL
  -- insert new rows
  WHEN NOT MATCHED BY TARGET THEN
  INSERT (Id, Name, gender, Street,  ZipCode, City, Country, SatisfactionScore)
  VALUES (Id, Name, gender, Street,  ZipCode, City, Country, SatisfactionScore)
  -- delete rows that are in the target but not the source
  WHEN NOT MATCHED BY SOURCE THEN
  DELETE;

  SET IDENTITY_INSERT [dbo].[Customers] OFF;

  GO

```

## 代码清单 2

```cs

 myapp.browseCustomers.created = function (screen) {
      // Write code here.
  };

```

## 代码清单 3

```cs
  myapp.browseCustomers.created = function (screen) {
      screen.HappinessLevel = 0;
      screen.addChangeListener(
          "HappinessLevel",
          function () {
              screen.HapinessFactor = screen.HappinessLevel / 100;
          }
     );
  }

```

## 代码清单 4

```cs

 myapp.browseCustomers.RowTemplate_postRender = function (element, contentItem) {
      // Write code here.
  };

```

## 代码清单 5

```cs

  myapp.browseCustomers.CustomersTemplate_postRender = function (element, contentItem) {   
      contentItem.dataBind("value.gender",
          function (gender) {
              // Code here gets executed when the Customer.gender changes...
      );   
  };

```

## 代码清单 6

```cs

 var customElement = $("<div />");

```

## 代码清单 7

```cs
  myapp.browseCustomers.CustomersTemplate_postRender = function (element, contentItem) {
      contentItem.dataBind("value.gender",
          function (gender) {
              $(element). // Wrapped a jQuery object around the element

      );   
  };

```

## 代码清单 8

```cs

 myapp.browseCustomers.CustomersTemplate_postRender = function (element, contentItem) {
      contentItem.dataBind("value.gender",
          function (gender) {
              $(element).css("color", "white");
      );   
  };

```

## 代码清单 9

```cs

 myapp.browseCustomers.CustomersTemplate_postRender = function (element, contentItem) {
      contentItem.dataBind("value.gender",
          function (gender) {
              $(element).CSS("color", "white");
              if (gender == "F")
                  $(element).parent('li').CSS("background", "#EE317C");
              else
                  $(element).parent('li').CSS("background", "#131083");
              }
      );   
  };

```

## 代码清单 10

```cs
  ReallyHappyCustomer, .HappyCustomer, .CouldBeHappierCustomer, .MadCustomer, .PureEvilCustomer {
      width: 48px;
      height: 48px;
  }

  .ReallyHappyCustomer {
      background-image: url(Images/ReallyHappy.png);
  }
  .HappyCustomer {
      background-image: url(Images/Happy.png);
  }
   .CouldBeHappierCustomer {
      background-image: url(Images/CouldBeHappier.png);
  }
   .MadCustomer {
      background-image: url(Images/Mad.png);
  }
   .PureEvilCustomer {
      background-image: url(Images/PureEvil.png);
  }.

```

## 代码清单 11

```cs
  myapp.browseCustomers.SatisfactionScore_render = function (element, contentItem) {
      // Write code here.
  };

```

## 代码清单 12

```cs
  myapp.browseCustomers.SatisfactionScore_render = function (element, contentItem) {
      var customElement = $("<div />");
      customElement.appendTo(element);
  };

```

## 代码清单 13

```cs
  myapp.browseCustomers.SatisfactionScore_render = function (element, contentItem) {
      var customElement = $("<div />");
      customElement.appendTo(element);

      contentItem.dataBind("value",
          function (satisfactionScore) {
             // You will add the appropriate CSS class here.
          }
       );
  };

```

## 代码清单 14

```cs
  myapp.browseCustomers.SatisfactionScore_render = function (element, contentItem) {

      var customElement = $("<div />");
      customElement.appendTo(element);

      contentItem.dataBind("value",
          function (satisfactionScore) {
              customElement.removeClass();
              if (satisfactionScore > 0.8)
                  customElement.addClass("ReallyHappyCustomer");
              else if (satisfactionScore > 0.6)
                  customElement.addClass("HappyCustomer");
              else if (satisfactionScore > 0.4)
                  customElement.addClass("CouldBeHappierCustomer");
              else if (satisfactionScore > 0.2)
                  customElement.addClass("MadCustomer");
              else
                  customElement.addClass("PureEvilCustomer");
          }
       );
  };

```

## 代码清单 15

```cs
  customElement.removeClass();

```

## 代码清单 16

```cs

     myapp.applyChanges();
      myapp.commitChanges();
      myapp.cancelChanges();

```

## 代码清单 17

```cs

 myapp.showAddEditCustomer(null);

```

## 代码清单 18

```cs

 myapp.showAddEditCustomer( new msls.application.Customer());

```

## 代码清单 19

```cs
  myapp.showAddEditCustomer(null,
      {
          beforeShown: function (detailScreen) {
              detailScreen.Customer = new msls.application.Customer();
          }
      });

```

## 代码清单 20

```cs

     myapp.showAddEditCustomer(null,
      {
          beforeShown: function (detailScreen) {
              detailScreen.Customer = new msls.application.Customer();
              detailScreen.Customer.SatisfactionScore = 0.85;
          },
          afterClosed: function (detailScreen, navigationResult) {
              if (navigationResult == msls.NavigateBackAction.cancel)
                  msls.showMessageBox("User cancelled out of changes.");
                                                         else
                                screen.showPopup("NewUserPopup");
                                                                 }
      });

```

## 代码清单 21

```cs
  myapp.Customer.created = function (entity) {
      entity.SatisfactionScore = 0.8;
  };

```

## 代码清单 22

```cs
  myapp.AddEditCustomer.created = function (screen) {
      if (screen.Customer.Id) {
          screen.details.displayName = screen.Customer.Name;
      }
      else {
          screen.details.displayName = "Add a new customer.";
      }
  };

```

## 代码清单 23

```cs
  myapp.AddEditCustomer.created = function (screen) {
      if (screen.Customer.Id) {
          screen.details.displayName = screen.Customer.Name;
      }
      else {
          screen.details.displayName = "Add a new customer.";
          screen.Customer.SatisfactionScore = 0.9;
      }
  };

```

## 代码清单 24

```cs
  SET IDENTITY_INSERT [dbo].[orders] ON;

  MERGE INTO [dbo].[orders] AS Target
  USING (VALUES
        (1, '20121103', 1, 238, 2),
  -- more random orders ...
        (298, '20120903', 1, 105, 2),
        (299, '20110220', 1, 1689, 3)
  )
  AS Source(Id, CreationDate, Completed, OrderTotal, Order_Customer)
  ON Target.Id = Source.Id
  -- update matched rows
  WHEN MATCHED THEN
  UPDATE SET CreationDate = Source.CreationDate, Completed = Source.Completed, OrderTotal = Source.OrderTotal,
        Order_Customer = Source.Order_Customer
  -- insert new rows
  WHEN NOT MATCHED BY TARGET THEN
  INSERT (Id, CreationDate, Completed, OrderTotal, Order_Customer)
  VALUES (Id, CreationDate, Completed, OrderTotal, Order_Customer)
  -- delete rows that are in the target but not the source
  WHEN NOT MATCHED BY SOURCE THEN
  DELETE;

  SET IDENTITY_INSERT [dbo].[orders] OFF;

  GO

```

## 代码清单 25

```cs
  myapp.AddEditCustomer.created = function (screen) {
      if (screen.Customer.Id) {
          screen.details.displayName = screen.Customer.Name;
      }
      else {
          screen.details.displayName = "Add a new customer.";
          screen.Customer.SatisfactionScore = 0.9;
      }
  };

```

## 代码清单 26

```cs
          screen.getOpenOrders().then(
                  function (orders) {  /* Callback code goes here */}          
   );

```

## 代码清单 27

```cs
  myapp.AddEditCustomer.created = function (screen) {
      if (screen.Customer.Id) {
          screen.details.displayName = screen.Customer.Name;
          screen.getOpenOrders().then(
                  function (orders) {
                      if (orders.count == 0)
                          screen.OpenOrderMessage = "No open orders";
                      else
                          screen.OpenOrderMessage = "orders pending";
                  }
              );
      }
      else {
          screen.details.displayName = "Add a new customer.";
          screen.Customer.SatisfactionScore = 0.9;
          screen.OpenOrderMessage = "";
      }
  };

```

## 代码清单 28

```cs
  Myapp.PromiseOrders.created = function (entity)
      // Set the default date for the Order
      entity.OrderDate = new Date();
      // Using a Promise object you can call the CallGetUserName function
      msls.promiseOperation(CallGetUserName).then(function (PromiseResult)
          // Set the result of the CallGetUserName function to the
          // UserName of the entity
          entity.UserName = PromiseResult;
      });
  };
  // This function will be wrapped in a Promise object
  function CallGetUserName(operation) {
      $.ajax({
          type: 'post',
          data: {},
          url: '../web/GetUserName.ashx',
          success: operation.code(function (AjaxResult)
              operation.complete(AjaxResult);
          })
      });
  }

```

## 代码清单 29

```cs
  using System.Linq;
  using System.Web.Http;

  namespace LightSwitchApplication.Controllers
  {
      public class CustomerOrderSummaryController : ApiController
      {
          // GET api/<controller>
          public IEnumerable<string> Get()
          {
              return new string[] { "value1", "value2" };
          }

          // GET api/<controller>/5
          public string Get(int id)
          {
              return "value";
          }

```

## 代码清单 30

```cs
  using System;
  using System.Web.Http;
  using System.Web.Routing;

  namespace LightSwitchApplication
  {
      public class Global : System.Web.HttpApplication
      {
          protected void Application_Start(object sender, EventArgs e)
          { 
              RouteTable.Routes.MapHttpRoute(
                 name: "ReportsApi",
                 routeTemplate: "reports/{controller}/{id}"
                 );
          }
      }
  }

```

## 代码清单 31

```cs
  http://{HostURL}/reports/{NameOfTheController}/{Id}

```

## 代码清单 32

```cs
  using System.Linq;
  using System.Web.Http;
  using Microsoft.LightSwitch;
  namespace LightSwitchApplication.Controllers
  {
      public class CustomerOrderSummaryController : ApiController
      {
          public object Get(int id)
          {
              using (ServerApplicationContext context = ServerApplicationContext.CreateContext()) {

              }
          }
      }
  }

```

## 代码清单 33

```cs
  using System.Linq;
  using System.Web.Http;
  using Microsoft.LightSwitch;

  namespace LightSwitchApplication.Controllers
  {
      public class CustomerOrderSummaryController : ApiController
      {
          public object Get(int id)
          {
              using (ServerApplicationContext context = ServerApplicationContext.CreateContext()) {
                  var query = context.DataWorkspace.ApplicationData.orders
                      .Where(o => o.Customer.Id == id)
                      .GroupBy(o => o.CreationDate.Year)
                      .Select(g => new
                      {
                          Label = g.Key,
                          Value = g.Sum(o => o.OrderTotal)
                      })
                      .OrderBy(g => g.Label);

                  return query.Execute().Select(
                      g => new {
                          Label = string.Format("'{0}" ,  (g.Label - 2000)),
                          Value = g.Value
                      }
                      ).ToArray();
              }
          }
      }
  }

```

## 代码清单 34

```cs
        <script type="text/javascript">
          $(document).ready(function () {
              msls._run()
              .then(null, function failure(error) {
                  alert(error);
              });
          });
      </script>

```

## 代码清单 35

```cs
      <!-- Syncfusion stylesheets-->
      <link href="Content/bootstrap.CSS" rel="stylesheet">
      <link href="Content/default.CSS" rel="stylesheet" />
      <link href="Content/default-responsive.CSS" rel="stylesheet" />

```

## 代码清单 36

```cs
      <!-- Syncfusion widgets-->
      <script src="Scripts/ej.widgets.all.min.js" type="text/javascript"></script>
      <script src="Scripts/properties.js" type="text/javascript"></script>

```

## 代码清单 37

```cs
      <script type="text/javascript" src="Scripts/Generated/generatedAssets.js"></script>

```

## 代码清单 38

```cs
  <!--<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>-->

```

## 代码清单 39

```cs
  myapp.AddEditCustomer.Customer_Id_render = function (element, contentItem) {
      $(element).append('<div id="container" style="width:700px" />');
      contentItem.dataBind(
                                                                                                                                                                  "value",
                                                                                                                                     function (customerId) { 

                                                                                                                                                                                    }
                                                                                                                                                                                   );
  };

```

## 代码清单 40

```cs
  $("#container")

```

## 代码清单 41

```cs
  $("#container").ejChart()

```

## 代码清单 42

```cs
  $("#container").ejChart(
                  { 
                      series: [{
                          dataSource: {
                              data: new ej.DataManager({
                                  url: "../reports/CustomerOrderSummary/" + customerId,

```

## 代码清单 43

```cs
  myapp.AddEditCustomer.Customer_Id_render = function (element, contentItem) {
      $(element).append('<div id="container" style="width:700px" />');
      contentItem.dataBind(
          "value",
          function (customerId) { 
              $("#container").ejChart(
                  {
                      chartAreaBorder: {
                          width: 1
                      },
                      primaryXAxis:
                      {
                          rangePadding: 'Additional',
                          title: {  },
                      },

                      primaryYAxis:
                      {
                          title: { text: "Total (in USD)" },
                      },

                      series: [{
                          name: ' ', type: 'column',
                          animation: true,
                          dataSource: {
                              data: new ej.DataManager({
                                  url: "../reports/CustomerOrderSummary/" + customerId,

                              }),
                              xName: "Label",
                              yNames: ["Value"],
                              query: ej.Query()
                          },

                          style: { interior: "#7ED600" }
                      }],
                      load: "loadTheme",
                      size: { height: 470 },
                      legend: { visible: false },
                  }
              );
          }
      );
  };

```

## 代码清单 44

```cs
  myapp.AddEditCustomer.HowDoIGetThere_execute = function (screen) {
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function (position) {
              msls.showMessageBox("Current location is " + position.coords.latitude + "," + position.coords.longitude);
          });
      }
      else { msls.showMessageBox("Geolocation is not supported by this browser."); } 
  };

```

## 代码清单 45

```cs
  myapp.AddEditCustomer.Customer_render = function (element, contentItem) {
      var mapDiv =  $("<div id='addressMap' class='msls-hauto msls-vauto' ></div>");
      $(mapDiv).appendTo($(element));
      var directionsDiv = $("<div id='directions' class='msls-hauto msls-vauto' ></div>");
      directionsDiv.appendTo($(element));

      mapDiv.lightswitchBingMapsControl({
          street: contentItem.value.Street,
          city: contentItem.value.City,
          zipcode: contentItem.value.ZipCode,
          state: contentItem.value.Country,
          mapTypeId: Microsoft.Maps.MapTypeId.road,
          height: "470"
      });
  };

```

## 代码清单 46

```cs
  myapp.AddEditCustomer.HowDoIGetThere_execute = function (screen) {
      $("#addressMap").lightswitchBingMapsControl("getLocationOfUser", $("#directions"));
  };

```

## 代码清单 47

```cs
      <!-- Change light-theme-2.0.0.CSS and msls-light-2.0.0.CSS to dark-theme-2.0.0.CSS and msls-dark-2.0.0.CSS respectively to use the
           dark theme.  Alternatively, you may replace light-theme-2.0.0.CSS with a custom jQuery Mobile theme. -->
      <link rel="stylesheet" type="text/CSS" href="Content/light-theme-2.0.0.CSS" />
      <link rel="stylesheet" type="text/CSS" href="Content/msls-light-2.0.0.CSS" />

```

## 代码清单 48

```cs
  Alternatively, you may replace light-theme-2.0.0.css with a custom jQuery Mobile theme.

```

## 代码清单 49

```cs
  <!--<link rel="stylesheet" type="text/css" href="Content/light-theme-2.0.0.css" />-->
      <link rel="stylesheet" type="text/css" href="Content/Syncfusion-blue.min.css" />

```

## 代码清单 50

```cs
  .msls-footer {
      background-image: url(http://www.syncfusion.com/Content/en-US/Hoimg/syncfusion-logo.png);
      background-repeat: no-repeat;
      background-size: contain;
  }

```