Silverlight Study Notes (4): mvvm + wcf ria development architecture

Source: Internet
Author: User

In the first two days, I have learned a lot about the basic development ideas of Silverlight, but I still have some questions about the mvvm architecture. There are several mistakes that beginners often make.

1. Silverlight is a rich client application. The Silverlight application is loaded to the client as an xap package. As a client application, you cannot directly access the background database, this requires the use of WebService, WCF, wcf ria and other technologies to achieve data transmission between the client and the server. Therefore, let alone directly write SQL to call the background database when using Asp.net!

2. Silverlight does not support data transmission by means of datatable, dataset, and other datasets. We have to use the entity dataset for data transmission, however, a foreign cool man made a tool to convert datatable into XML and transmit it to the customer before further converting the string into an entity dataset for Silverlight. If you are interested, you can search for Silverlight. dataset. It is very convenient to use. It is very helpful for us to query objects in some situations where the entity class cannot be determined.

3. When mvvm is applied in Silverlight, model + viewmodel + view are all Silverlight client programs, which can be directly referenced by each other, but do not fantasizing about applying the web application library, because the web application library is used on the server

The following section focuses on the development architecture of using mvvm + wcf ria in Silverlight. Since I have only been studying for two days, I have not had much time to dive into it. I can only record what I have learned now.

1. mvvm is model (entity) + view (Interface) + viewmodel (logic). The model layer is responsible for establishing data entities to ensure data loading, is the basic element of data binding in the view (but not to say that the view is bound to a model instance ). Not to mention the view layer. We strongly recommend that you use Microsoft Expression blend for interface design. All data presentation and events are in the form of binding, so that the designer is completely separated from the developer, for specific implementation, see the previous section. The viewmodel layer is a bridge between the view layer and the model layer. All data bindings at the view layer direct to the viewmodel. Model, view, and viewmodel are client-side Silverlight applications. Multiple Silverlight application library projects can be created to split the system structure.

2. Silverlight data transmission: In most cases, I know that I use the WCF RIA method. For more information, see Google. The reason why I chose WCF RIA is that it is much easier to implement than WCF, and due to the existence of RIA link, the client uses the server-side application logic as the client, in this way, the Silverlight client and the server cannot share the business logic, and the RIA link will generate the "shadow code" on the client ", this frees developers from worrying about code synchronization between clients and servers.

3. Design of WCF Ria: currently, most of the materials found on the Internet are using the ado.net data entity + domain service method. What I know is that the ado.net data entity model only supports Ms sqlserver, oracle still needs to download an odac for 11 GB, which is painful! At the same time, if we want to provide data from the original system's WCF Service, it means to define our own curd in domain service. I simply use the custom object class + custom domain service method.

Next we will focus on the following steps:

1. In the solution, select create web application library (service ), note: If the web application is not in the same project as the Silverlight host, the host web project of Silverlight must reference the WEB Project (service) and modify the web. config, you can refer to the Web. config. Otherwise, an error occurs: the remote server returns the error notfound. Create an object class in the Web application library. Note that the object class must have a primary key.

 

 public class Items    {        [Key]        public string SItemCode { get; set; }        public string SItemName { get; set; }    }

2. Create a domain servcie class

[Enableclientaccess ()] public class domainservice1: domainservice {public list <items> getitems () {list <items> items = new list <items> (); for (INT I = 1; I <10; I ++) {items item = new items (); item. sitemcode = "A" + I. tostring (); item. sitemname = "this is" + I. tostring (); items. add (item) ;}return items;} [update] public void updatedata (items item) {// you can add SQL statements to perform database operations string S = item. sitemname;} [delete] public void deletedata (items item) {string S = item. sitemname;} [insert] public void insertdata (items item) {string S = item. sitemname ;}}

The [enableclientaccess ()] identifier indicates that the class will be reflected on the client in RIA link. In this example, four public methods are created, for ease, I did not add SQL to access the database. getitems () provides data for client queries, and updatedata () is used to update data, note that the [update] attribute is specified on this method, so that the client can apply this method to update database data after the object data changes, if no data update method is specified, an error occurs when the client data changes. Delete, the same as adding a method definition.

3. Create a Silverlight application and apply the RIA link to the Silverlight project by selecting the web application library project we created earlier on the WCF Ria service link in the Silverlight project properties, after the project is compiled, a hidden folder generated_code will be added to the Silverlight project. The content in this folder is generated by the system and is created based on the domain service class we defined earlier, it contains a domaincontext class and entity class. We can apply all classes in this folder.

4. Create a viewmodel. For simplicity, I do not create a model class. In viewmodel, you can use the domaincontext class generated by RIA link to include the object collection class.

 public EntitySet<Items> Items        {            get            {                return base.EntityContainer.GetEntitySet<Items>();            }        }

At the same time, the domaincontext will create a data query method based on the data created in the domainservice1 class.

 public EntityQuery<Items> GetItemsQuery()        {            this.ValidateMethod("GetItemsQuery", null);            return base.CreateQuery<Items>("GetItems", null, false, true);        }

Define attributes and events in viewmodel

Public class itemviewmodel: inotifypropertychanged {domainservice1 Server = new domainservice1 (); Private items _ seleteditem = new items (); Public items seleteditem {get {return _ seleteditem ;} set {If (value! = _ Seleteditem) {_ seleteditem = value; propertychanged (this, new propertychangedeventargs ("seleteditem "));}}} // Private entityquery <items> _ itemlist = new entityquery <items> (); Public entityset <items> itemlist {get {return server. items ;}} public icommand onload {get {return New delegatecommand (loaddata) ;}} private void loaddata (Object OBJ) {entityquery <items> List = server. getitemsquer Y (); loadoperation <items> loadop = server. load (list); // loadop. completed + = new eventhandler (loadop_completed);} void loadop_completed (Object sender, eventargs e) {foreach (items item in server. items) {items u = new items (); U. sitemcode = item. sitemcode; U. sitemname = item. sitemname; // itemlist. add (u) ;}} public icommand onupdate {get {return New delegatecommand (updatedata) ;}} private voi D updatedata (Object OBJ) {server. submitchanges ();} public icommand ondelete {get {return New delegatecommand (deletedata);} private void deletedata (Object OBJ) {server. items. remove (this. seleteditem); server. submitchanges ();} public icommand oninsert {get {return New delegatecommand (insertdata);} public void insertdata (Object OBJ) {items item = new items (); item. sitemcode = guid. newgu ID (). tostring (); item. sitemname = obj. tostring (); server. items. add (item); server. submitchanges ();} public icommand onselectchanged {get {return New delegatecommand (selectionchanged);} private void selectionchanged (Object OBJ) {If (OBJ! = NULL) {seleteditem = OBJ as items;} else {seleteditem = NULL ;}# region inotifypropertychanged member public event propertychangedeventhandler propertychanged; # endregion}

Through server. submitchanges (); the data changes can be fed back to the domainservice class on the server side. The domainservice class calls the corresponding Method for Data Processing Based on the Data status in the dataset, it should be noted that Silverlight adopts the asynchronous processing mode, so we should consider performing data synchronization verification and processing in the domainservice class on the server side, which will be explained in detail later.

5. Create a view and bind data

<Grid X: Name = "layoutroot" background = "white" datacontext = "{binding source = {staticresource itemviewmodeldatasource}"> <SDK: dataGrid autogeneratecolumns = "true" Height = "119" horizontalalignment = "Left" margin = "21,169," X: name = "maid" verticalalignment = "TOP" width = "320" itemssource = "{binding itemlist, source = {staticresource itemviewmodeldatasource} "datacontext =" {binding} "selecteditem =" {binding seleteditem, mode = twoway} "> <I: interaction. triggers> <I: eventtrigger eventname = "selectionchanged"> <I: invokecommandaction command = "{binding onselectchanged, mode = oneway} "commandparameter =" {binding seleteditem} "/> </I: eventtrigger> </I: interaction. triggers> </SDK: DataGrid> <button content = "query" Height = "23" horizontalalignment = "Left" margin = "35,55," X: name = "button1" verticalalignment = "TOP" width = "75" command = "{binding onload, mode = oneway} "/> <button content =" Update "Height =" 23 "horizontalalignment =" Left "margin =", "X: name = "button2" verticalalignment = "TOP" width = "75" command = "{binding onupdate, mode = oneway} "/> <button content =" delete "Height =" 23 "horizontalalignment =" Left "margin =" 197,55, "X: name = "button3" verticalalignment = "TOP" width = "75" command = "{binding ondelete, mode = oneway}" commandparameter = "{binding selecteditem, elementname = datagrid1} "/> <textbox Height =" 23 "horizontalalignment =" Left "margin =" 46,106, "X: name = "textbox1" verticalalignment = "TOP" width = "120"/> <button content = "add" Height = "23" horizontalalignment = "Left" margin = "172,106, 0, 0 "X: Name =" button4 "verticalignment =" TOP "width =" 75 "command =" {binding oninsert, mode = oneway} "commandparameter =" {binding text, elementname = textbox1} "/> </GRID>

The entire process demonstrates the implementation of the mvvm + WCF Ria architecture. There are still many internal details that are not yet in-depth, but the overall architecture has taken shape!

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.