Lightswitch Desktopclinet 本质就是一个silverlight 桌面客户端程序,当然也有对应的asp.net后台服务,数据的真正处理都在后台端。那也可以尝试以WEB API 进行自定义的调用。(注:LS是很方便,但太不注意性能,获取的数据都是整个表及关联性数据)。

服务器端处理:

1 GLOBAL文件,添加WEBAPI路由注册信息

public class Global : System.Web.HttpApplication
    {

protected void Application_Start(object sender, EventArgs e)
        {
            // needs references: System.Web.Http, System.web.Http.WebHost en System.Net.Http
            RouteTable.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{action}/{id}",
               defaults: new { action = "get", id = RouteParameter.Optional }
           );
        }
    }

2. 添加 一个调用LS环境的基类(如果要使用现成的LS的数据访问功能,如自己用ADO.NET则无需)

或  PM> Install-package the lightswitchtoolbox.webapicommanding.server

手工代码:

LightSwitchApiControllerbase.cs

  public abstract class LightSwitchApiControllerbase : ApiController{private ServerApplicationContext _context;public ServerApplicationContext Context{get{return _context;}}public ServerApplicationContext GetContext(){return _context;}public LightSwitchApiControllerbase(){_context = ServerApplicationContext.Current;if (_context == null){_context = ServerApplicationContext.CreateContext();}}}

3.实现WEB API

    public class CommandController : LightSwitchApiControllerbase{[HttpGet]public IEnumerable<string> TestGetCommand(){List<string> list = new List<string>();try{using (var ctx = this.Context){if (ctx.Application.User.HasPermission(Permissions.CanSendCommand)){list.Add("can CanSendCommand ");}if (ctx.Application.User.HasPermission(Permissions.CanSendCommand)){list.Add("value 1");list.Add("value 2");string lastNameFirstCustomer = ctx.DataWorkspace.ApplicationData.Customers.First().LastName;list.Add(lastNameFirstCustomer);return list;}}}catch (Exception ex){list.Add(ex.Message);}return list;}[HttpPost]public HttpResponseMessage TestCommand(SimpleCommandRequestParameters parameters){Thread.Sleep(3000);string s="";try{using (var ctx = this.Context){if (ctx.Application.User.HasPermission(Permissions.CanSendCommand)){string lastNameFirstCustomer = ctx.DataWorkspace.ApplicationData.Customers.First().LastName;s = "ok for " + parameters.ReqParam + " for " + lastNameFirstCustomer;}else{s = "NOT OK for " + parameters.ReqParam;}}}catch(Exception ex){s = ex.Message;}return Request.CreateResponse<SimpleCommandResponseParameters>(HttpStatusCode.Accepted,new SimpleCommandResponseParameters{RespParam = s});}}

4. 添加请求响应参数帮助类,上面引用到的,注:同时在客户端也添加此文件连接以共享代码

  public class SimpleCommandResponseParameters{public string RespParam { get; set; }}
  public class SimpleCommandRequestParameters{public string ReqParam { get; set; }}

客户端处理:

1. 添加上述二个请求响应帮助类,以连接方式共享服务器代码

2.添加一个API代理调用类

using Microsoft.LightSwitch.Client;
using Microsoft.LightSwitch.Threading;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices.Automation;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;namespace LightSwitchApplication
{public static class LightSwitchCommandProxy{private static object GetPrivateProperty(Object obj, string name){BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;Type type = obj.GetType();PropertyInfo field = type.GetProperty(name, flags);return field.GetValue(obj, null);}private static object GetPrivateField(Object obj, string name){BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;Type type = obj.GetType();FieldInfo field = type.GetField(name, flags);return  field.GetValue(obj);}public static void StartWebApiCommand<T>(this IScreenObject screen, string commandrelativePath,object data, Action<Exception, T> callback){Uri baseAddress = null;baseAddress = GetBaseAddress();HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress, commandrelativePath));webRequest.Method = "POST";webRequest.ContentType = "application/json";if (System.Windows.Application.Current.IsRunningOutOfBrowser) //OOB模式,设置COOKIE{Object userState = null;var auths = Application.Current.AuthenticationService.LoadUser((loadOp) => { }, userState);var op = GetPrivateField(auths, "operation");var svc = GetPrivateProperty(op, "Service");System.Net.CookieContainer cc = (System.Net.CookieContainer)GetPrivateProperty(svc, "CookieContainer");webRequest.CookieContainer = cc;// CookieContainer的获取可以放在Application_LoggedIn 事件里获取,不用每次都取一下//public partial class Application//{//    partial void Application_LoggedIn()//    {//    }//}}webRequest.BeginGetRequestStream(iar =>{var requestStream = webRequest.EndGetRequestStream(iar);SerializeObject(data, requestStream);webRequest.BeginGetResponse(iar2 =>{WebResponse webResponse;try{webResponse = webRequest.EndGetResponse(iar2);}catch (Exception ex){screen.Details.Dispatcher.BeginInvoke(() =>{callback(ex, default(T));});return;}var result = Deserialize<T>(new StreamReader(webResponse.GetResponseStream()));screen.Details.Dispatcher.BeginInvoke(() =>{callback(null, result);});}, null);}, null);}//for a get,不带COOKIE,有可能会被拒绝public static void StartWebApiRequest<T>(this IScreenObject screen, string requestRelativePath,Action<Exception, T> callback){Uri serviceUri = new Uri(GetBaseAddress(), requestRelativePath);WebRequest.RegisterPrefix("http://",System.Net.Browser.WebRequestCreator.BrowserHttp);WebRequest.RegisterPrefix("https://",System.Net.Browser.WebRequestCreator.BrowserHttp);//out of browser does not work here !WebRequest webRequest = WebRequest.Create(serviceUri);webRequest.UseDefaultCredentials = true;webRequest.Method = "GET";webRequest.BeginGetResponse(iar2 =>{WebResponse webResponse;try{webResponse = webRequest.EndGetResponse(iar2);}catch (Exception ex){screen.Details.Dispatcher.BeginInvoke(() =>{callback(ex, default(T));});return;}var result = Deserialize<T>(new StreamReader(webResponse.GetResponseStream()));screen.Details.Dispatcher.BeginInvoke(() =>{callback(null, result);});}, null);}public static Uri GetBaseAddress(){Uri baseAddress = null;Dispatchers.Main.Invoke(() =>{baseAddress = new Uri(new Uri(System.Windows.Application.Current.Host.Source.AbsoluteUri), "../../");});return baseAddress;}private static void SerializeObject(object data, Stream stream){var serializer = new JsonSerializer();var sw = new StreamWriter(stream);serializer.Serialize(sw, data);sw.Flush();sw.Close();}private static T Deserialize<T>(TextReader reader){var serializer = new JsonSerializer();return serializer.Deserialize<T>(new JsonTextReader(reader));}}
}

注:添加一下Newtonsoft.Json引用

3.客户端调用,新增一个屏幕,加上按钮事件,如下:

partial void TestPostCommand_Execute()
        {
            string commandrelativePath = "api/Command/TestCommand";
            
            this.StartWebApiCommand<SimpleCommandResponseParameters>(commandrelativePath,
                new SimpleCommandRequestParameters { ReqParam = "hello" },
                (error, response) =>
                {
                    IsBusy = false;
                    if (error != null)
                    {
                        this.ShowMessageBox("error = " + error.ToString());
                    }
                    else
                    {
                        this.ShowMessageBox("result = " + response.RespParam);
                    }
                });
        }
        partial void TestGetCommand_Execute()
        {
            string commandrelativePath = "api/Command/TestGetCommand";

this.StartWebApiRequest<List<string>>(commandrelativePath,
                (error, response) =>
                {
                    if (error != null)
                    {
                        this.ShowMessageBox("error = " + error.ToString());
                    }
                    else
                    {
                        var result = string.Empty;
                        response.ForEach(s => result += (s + " "));

this.ShowMessageBox(result);
                    }
                });
        }



Lightswitch Desktopclinet 中如何调用WEB API相关推荐

  1. ASP.NET MVC4中调用WEB API的四个方法

    当今的软件开发中,设计软件的服务并将其通过网络对外发布,让各种客户端去使用服务已经是十分普遍的做法.就.NET而言,目前提供了Remoting,WebService和WCF服务,这都能开发出功能十分强 ...

  2. python 图表_Python入门学习系列——使用Python调用Web API实现图表统计

    使用Python调用Web API实现图表统计 Web API:Web应用编程接口,用于URL请求特定信息的程序交互,请求的数据大多以非常易于处理的格式返回,比如JSON或CSV等. 本文将使用Pyt ...

  3. 利用Fiddler模拟通过Dynamics 365的OAuth 2 Client Credentials认证后调用Web API

    微软动态CRM专家罗勇 ,回复337或者20190521可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me. 配置Dynamics 365 & PowerApps 支 ...

  4. 【ASP.NET Web API教程】3.3 通过WPF应用程序调用Web API(C#)

    注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容. 3.3 Calling a Web API From a WPF Application ...

  5. jQuery跨域调用Web API

    我曾经发表了一篇关于如何开发Web API的博客,链接地址:http://www.cnblogs.com/guwei4037/p/3603818.html.有朋友说开发是会开发了,但不知道怎么调用啊? ...

  6. android 调用 asp.net web api,从 .NET 客户端调用 Web API (C#)

    从 .NET 客户端调用 Web API (C#) 11/24/2017 本文内容 此内容适用于以前版本的 .NET. 新开发应该使用 ASP.NET Core. 有关使用 Core Web API ...

  7. WebApi系列~通过HttpClient来调用Web Api接口

    HttpClient是一个被封装好的类,主要用于Http的通讯,它在.net,java,oc中都有被实现,当然,我只会.net,所以,只讲.net中的HttpClient去调用Web Api的方法,基 ...

  8. 4gl调用WEB API,实现JSON传递(Demo)

    测试环境: GP5.25 , fjs版本2.32,解析json所需要的jar依赖包 (PS: 如果没有记错是fjs2.32版本及以上才支持java bridge,所以GP 5.25以下的同学就不要用这 ...

  9. java 调用webapi json_java通过url调用web api并接收其返回的json

    java通过url调用webapi并接收其返回的json数据,但现在结果总是:{"result":4,"data":{}}(未认证:),帮助文档如下:API使用 ...

最新文章

  1. 离开互联网大厂的年轻人都去了哪儿?
  2. 张高兴的 Windows 10 IoT 开发笔记:BH1750FVI 光照度传感器
  3. 手动部署 Ceph Mimic 三节点
  4. STM32命名,Flash分布,扇区
  5. 【机器学习】通俗的k-近邻算法算法解析和应用
  6. 爬虫综合大作业(震惊!爬取了590位微信好友后竟然发现了)
  7. char-embedding是如何输入到模型的
  8. html5 将资源存于客户端,HTML5离线应用与客户端存储的实现
  9. wxWidgets:wxMenuEvent类用法
  10. 深入浅出MFC:DDX_Control本质探究
  11. [转载]TopCoder兼职赚钱入门(Part. 1)
  12. Jax-RS自定义异常处理
  13. 字体缩放 SignedDistanceField
  14. 前端学习(2784):首页轮播图的渲染
  15. 暴露的全局方法_面试刷题36:线程池的原理和使用方法?
  16. js学习总结----字符串和Math综合应用-验证码(4位)
  17. 蓝桥杯 ALGO-158 算法训练 sign函数
  18. 三岁小孩开发搜索引擎,搜索引擎白热化[原创]
  19. js获取ie版本号与html设置ie文档模式的方法
  20. 语文学科html代码,语文教育专业介绍 [代码660201]

热门文章

  1. python基础第一课(小白piao分享)
  2. nc命令卡住不返回的分析
  3. 数据结构与算法篇-单链表
  4. AWD攻防技巧(水文)
  5. PPP协议讲解(PPP连接状态、PPP报文)
  6. django基于python的高校教室管理系统--python-计算机毕业设计
  7. vue的PC端和移动端分辨率适配
  8. wish - 简单的窗口式(windowing) shell
  9. oracle ORA-22992问题
  10. 进入BeOS的花花世界 系列四