<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-8395299768708339226</id><updated>2024-10-07T13:01:36.088+03:00</updated><category term="C#"/><category term="Design Patterns"/><category term="ASP.Net MVC"/><category term="Android"/><category term="MVC"/><category term="ASP.Net"/><category term="NoSQL"/><category term="android 4.x"/><category term="asp mvc"/><category term=".netcore"/><category term="AJAX"/><category term="Activity"/><category term="Android SDK"/><category term="Cloud Firestore"/><category term="Composite"/><category term="Composite Pattern"/><category term="Eclipse"/><category term="Factory Pattern"/><category term="Insertion Sort"/><category term="Iterator Pattern"/><category term="JQuery"/><category term="Linq"/><category term="Observer Pattern"/><category term="Razor"/><category term="Sorting"/><category term="VB.Net"/><category term="dotvvm"/><category term="firebase"/><category term="ASP.Net Cache"/><category term="ASP.Net Performance"/><category term="ASP.Net Pre-Compilation"/><category term="ASP.Net Tracing"/><category term="Abstract factory"/><category term="Action Attributes"/><category term="ActionLink"/><category term="ActionMethodSelectorAttribute"/><category term="Adapter Pattern"/><category term="Android AVD"/><category term="AndroidManifest.xml"/><category term="AntiForgeryToken"/><category term="Asynchronous Controllers"/><category term="Asynchronous Pages"/><category term="AutoComplete"/><category term="Bootstrap"/><category term="Bridge"/><category term="Bridge pattern"/><category term="Buffers"/><category term="Buffers Pattern"/><category term="Builder Pattern"/><category term="Cast"/><category term="Chain of Responsibility Pattern"/><category term="CheckBoxList"/><category term="Circular"/><category term="Circular Buffers"/><category term="Circular Buffers Pattern"/><category term="Circular Pattern"/><category term="Command"/><category term="Command Pattern"/><category term="Content Provider"/><category term="Cross Site"/><category term="Cross Site MVC Request Forgery cross site attacks ASP.Net Javascript injection ASP.Net MVC"/><category term="Decorator Pattern"/><category term="Facade Pattern"/><category term="Factory"/><category term="Flyweight Pattern"/><category term="Fragment"/><category term="Generic Sorter"/><category term="GridView"/><category term="GridView Events"/><category term="HtmlHelper"/><category term="HttpOnly"/><category term="IEnumerable"/><category term="Ice Cream Sandwich"/><category term="Intent"/><category term="Interpreter pattern"/><category term="IsAjaxRequest"/><category term="Iterator"/><category term="JQuery load()"/><category term="JQueury"/><category term="Java"/><category term="Javascript"/><category term="Javascript injection"/><category term="Lambda Expression"/><category term="MVC Pattern"/><category term="MarkDown"/><category term="Mediator"/><category term="Mediator Pattern"/><category term="Model view controller pattern"/><category term="Momento pattern"/><category term="Nested GridView"/><category term="NonAction"/><category term="OfType"/><category term="OnRowCommand"/><category term="OrderBy"/><category term="OrderByDesccending"/><category term="ProgressDrawable"/><category term="Prototype"/><category term="Prototype pattern"/><category term="Recycle bin pattern"/><category term="Request Forgery"/><category term="Required Attribute"/><category term="Ring Buffer"/><category term="Service"/><category term="Singleton Pattern"/><category term="State"/><category term="State Pattern"/><category term="Strategy Pattern"/><category term="TagBuilder"/><category term="Template Method Pattern"/><category term="TypeScript"/><category term="UIHint"/><category term="ValidationAttribute"/><category term="ViewState"/><category term="Visitor pattern"/><category term="android application"/><category term="azure"/><category term="conditional vaidation"/><category term="cosmosdb"/><category term="cross site attacks"/><category term="double buffer"/><category term="double buffer pattern"/><category term="entityframework"/><category term="firestore"/><category term="interpreter"/><category term="json"/><category term="mvvm"/><category term="partial page"/><category term="pattern catalog style"/><category term="progressbar"/><category term="progressbar bounds"/><category term="progressbar color"/><category term="progressbar progress"/><category term="recycle bin"/><category term="run configurations"/><category term="session Hijacking"/><category term="web application performance"/><category term="web development"/><title type='text'>ME.Dev</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>43</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-4844964311698898264</id><published>2020-01-02T13:48:00.001+02:00</published><updated>2020-01-02T14:12:38.882+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".netcore"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Cloud Firestore"/><category scheme="http://www.blogger.com/atom/ns#" term="dotvvm"/><category scheme="http://www.blogger.com/atom/ns#" term="firebase"/><category scheme="http://www.blogger.com/atom/ns#" term="firestore"/><category scheme="http://www.blogger.com/atom/ns#" term="mvvm"/><category scheme="http://www.blogger.com/atom/ns#" term="NoSQL"/><category scheme="http://www.blogger.com/atom/ns#" term="web development"/><title type='text'> DotVVM CRUD application with Cloud Firestore</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
&lt;div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
In &lt;a href=&quot;https://miroprocessordev.blogspot.com/2019/12/dotvvm-crud-application-with-entity.html&quot; target=&quot;_blank&quot;&gt;previous post&lt;/a&gt; we demonstrated how to use DotVVM to create CRUD application with Azure Cosmos DB as your data store.&lt;br /&gt;
&lt;br /&gt;
In this post we will demonstrate how to do the same with Cloud Firestore by Google.&lt;br /&gt;
To know more about DotVVM Framework you can check its &lt;a href=&quot;https://www.dotvvm.com/&quot; target=&quot;_blank&quot;&gt;official website&lt;/a&gt;&lt;br /&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;What is Cloud Firestore?&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: 12pt;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;font-size: 12pt;&quot;&gt;Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. It keeps your data in sync across client apps through realtime listener and offers offline support for mobile and web apps.&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: 12pt;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;font-size: 12pt;&quot;&gt;You can know more about Cloud Firebase &lt;a href=&quot;https://firebase.google.com/docs/firestore&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: 12pt;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;div style=&quot;font-size: 12pt;&quot;&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;Install DotVVM extension&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif;&quot;&gt;refer to&amp;nbsp;&lt;/span&gt;&lt;a href=&quot;https://miroprocessordev.blogspot.com/2019/12/dotvvm-crud-application-with-entity.html&quot; target=&quot;_blank&quot;&gt;previous post&lt;/a&gt;&amp;nbsp;and follow the steps.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;To know more about
the DotVVM extension visit its page on visual studio marketplace:&lt;/span&gt;&lt;a href=&quot;https://marketplace.visualstudio.com/items?itemName=TomasHerceg.DotVVM-VSExtension2019&quot; style=&quot;font-family: Calibri, sans-serif; font-size: 11pt;&quot;&gt;https://marketplace.visualstudio.com/items?itemName=TomasHerceg.DotVVM-VSExtension2019&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;Now you are ready to
start coding with DotVVM framework. DotVVM extension installs DotVVM sample
project which we will use to demonstrate how it is easy to connect to Cloud Firestore database from DotVVM application.&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;Create Cloud Firestore Project&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif;&quot;&gt;To use cloud Firestore as your database you need to create a project on Firestore.&lt;/span&gt;&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif;&quot;&gt;Go to&amp;nbsp;&lt;/span&gt;&lt;a href=&quot;https://console.firebase.google.com/&quot;&gt;https://console.firebase.google.com/&lt;/a&gt;&amp;nbsp;and login with your google account or create new one.&lt;/li&gt;
&lt;li&gt;Click on Add Project&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Enter &quot;&lt;span style=&quot;color: #3d85c6;&quot;&gt;&lt;b&gt;dotvvm&lt;/b&gt;&lt;/span&gt;&quot; as project name.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
In next step, Disable Google Analytics for this project. It is recommended to enable it for real project.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Click on Create Project. it will take one or two mins to create your project. When it is ready click on continue.&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPf0owsr2awl7Fz649FVUOpl0LhhkkeYnkN3xRpxBmCPlTAgeTX-zKAScgwrjiyM9OfJQCKwsBYNIlBGD_g7p03fjaROtiI0dPbIhW7BB2ELLmPksPP23uiPwLUYTUZcOxL8mZ6lxov5A2/s1600/project+created.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1282&quot; data-original-width=&quot;1415&quot; height=&quot;180&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPf0owsr2awl7Fz649FVUOpl0LhhkkeYnkN3xRpxBmCPlTAgeTX-zKAScgwrjiyM9OfJQCKwsBYNIlBGD_g7p03fjaROtiI0dPbIhW7BB2ELLmPksPP23uiPwLUYTUZcOxL8mZ6lxov5A2/s200/project+created.png&quot; width=&quot;200&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
From the left navigation pan, open database then click on Create database&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHKU7TvE38al1v1In2NNf2q2mRKvIeamVHu62EpQJ2VpVLEKos0X8todLCtV3asu4y5w1TrR8mQfKBTWe5xcZi48fls6L_vOanfvL6u0-Jf62HHiKrCUjY73ExXAgqaZKLOQwo5N6B3RKI/s1600/database.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;481&quot; data-original-width=&quot;1600&quot; height=&quot;96&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHKU7TvE38al1v1In2NNf2q2mRKvIeamVHu62EpQJ2VpVLEKos0X8todLCtV3asu4y5w1TrR8mQfKBTWe5xcZi48fls6L_vOanfvL6u0-Jf62HHiKrCUjY73ExXAgqaZKLOQwo5N6B3RKI/s320/database.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
In the popup window, select &lt;b&gt;&lt;i&gt;&lt;u&gt;Start in test mode&lt;/u&gt;&lt;/i&gt; &lt;/b&gt;then click next.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Select the location of your database(you can keep the default selection) then Click Done.&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
Congratulation, your Cloud Firestore database is created and ready.&lt;/div&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;br /&gt;
To be able to connect to your Firestore database from your application(server) you need to set the&amp;nbsp;&lt;span style=&quot;background-color: #f1f3f4; color: #37474f; font-family: &amp;quot;roboto mono&amp;quot; , monospace; font-size: 12.6px;&quot;&gt;GOOGLE_APPLICATION_CREDENTIALS&amp;nbsp;&lt;/span&gt;environment variable to point to JSON service account key file.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #cc0000;&quot;&gt;To setup your service account, go to&amp;nbsp;&lt;a href=&quot;https://cloud.google.com/docs/authentication/getting-started&quot;&gt;https://cloud.google.com/docs/authentication/getting-started&lt;/a&gt;&amp;nbsp;and follow the instructions.&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;DotVVM Web Application&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif;&quot;&gt;In&amp;nbsp;&lt;/span&gt;&lt;a href=&quot;https://miroprocessordev.blogspot.com/2019/12/dotvvm-crud-application-with-entity.html&quot; target=&quot;_blank&quot;&gt;previous post&lt;/a&gt;&amp;nbsp;you can find the complete steps for creating DotVVM web application. In this post we focus on code changes required to connect to Firestore database.&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Uninstall entity framework Sql Server related nuget package&lt;br /&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/span&gt; and &lt;span style=&quot;color: #3d85c6;&quot;&gt;Microsoft.EntityFrameworkCore&lt;/span&gt;&lt;br /&gt;As we will connect to Cloud Firestore database not Sql Server database&lt;/li&gt;
&lt;li&gt;Install &lt;span style=&quot;color: #3d85c6;&quot;&gt;Google.Cloud.Firestore&lt;/span&gt; nuget package. This package is required to run CRUD operations against your firestore database from your web application.&lt;/li&gt;
&lt;li&gt;Open &lt;i&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;appsettings.json&lt;/span&gt;&lt;/i&gt; file and remove the connection string. keeping it will not harm but we need our code to be clean.&lt;/li&gt;
&lt;li&gt;Delete &lt;i&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;DAL/StudentDbContext.cs&lt;/span&gt;&lt;/i&gt; file.&lt;/li&gt;
&lt;li&gt;Open &lt;i&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;Startup.cs&lt;/span&gt;&lt;/i&gt; file and delete the following lines
&lt;pre class=&quot;source-code&quot;&gt;services.AddEntityFrameworkSqlServer()
                .AddDbContext&amp;lt;Studentdbcontext&amp;gt;(options =&amp;gt;
                {
                    options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;));
                });
&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Open &lt;span style=&quot;color: #3d85c6;&quot;&gt;&lt;i&gt;DAL/Entities/Student.cs&lt;/i&gt;&lt;/span&gt; file and add the following using statement&lt;pre class=&quot;source-code&quot;&gt;using Google.Cloud.Firestore;&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Decorate the Student class with&amp;nbsp;&lt;span style=&quot;color: #3d85c6;&quot;&gt;[FirestoreData]&lt;/span&gt; attribute and each property with&amp;nbsp;&lt;span style=&quot;color: #3d85c6;&quot;&gt;[FirestoreProperty]&lt;/span&gt; attribute. Also change the type of&amp;nbsp;&lt;span style=&quot;color: #3d85c6;&quot;&gt;EnrollmentDate&lt;/span&gt; property to &lt;span style=&quot;color: #3d85c6;&quot;&gt;Timestamp&lt;/span&gt; instead of &lt;span style=&quot;color: #3d85c6;&quot;&gt;DateTime&lt;/span&gt;. The complete code of Student class will be&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;    [&lt;span style=&quot;color: #e69138;&quot;&gt;FirestoreData&lt;/span&gt;]
    public class Student
    {
        [&lt;span style=&quot;color: #e69138;&quot;&gt;FirestoreProperty&lt;/span&gt;]
        public int Id { get; set; }

        [&lt;span style=&quot;color: #e69138;&quot;&gt;FirestoreProperty&lt;/span&gt;]
        public string FirstName { get; set; }

        [&lt;span style=&quot;color: #e69138;&quot;&gt;FirestoreProperty&lt;/span&gt;]
        public string LastName { get; set; }

        [&lt;span style=&quot;color: #e69138;&quot;&gt;FirestoreProperty&lt;/span&gt;]
        public string About { get; set; }

        [&lt;span style=&quot;color: #e69138;&quot;&gt;FirestoreProperty&lt;/span&gt;]
        public &lt;span style=&quot;color: #cc0000;&quot;&gt;Timestamp&lt;/span&gt; EnrollmentDate { get; set; }
    }
&lt;/pre&gt;
Those attributes are required and used to serialize/deserialize your entities from and to json objects.&lt;span style=&quot;color: #3d85c6;&quot;&gt;
Timestamp&lt;/span&gt; is the Firestore datatype used to represent date/time values.
&lt;/li&gt;
&lt;li&gt;Open &lt;i&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;Services/StudentService.cs&lt;/span&gt;&lt;/i&gt; file and add the following private properties to &lt;span style=&quot;color: #3d85c6;&quot;&gt;StudentService&lt;/span&gt; class
&lt;pre class=&quot;source-code&quot;&gt;private const string project = &quot;dotvvm&quot;;
private const string collection = &quot;students&quot;;
&lt;/pre&gt;
where &lt;span style=&quot;color: #3d85c6;&quot;&gt;project&lt;/span&gt; is the name of your Firestore project and&amp;nbsp;&lt;span style=&quot;color: #3d85c6;&quot;&gt;collection&lt;/span&gt; is the name of your database collection where you will insert/retrieve records 
&lt;/li&gt;
&lt;li&gt;Replace the&amp;nbsp;&lt;span style=&quot;color: #3d85c6;&quot;&gt;GetAllStudentsAsync&lt;/span&gt; method with the following
&lt;pre class=&quot;source-code&quot;&gt;public async Task&amp;lt;List&amp;lt;StudentListModel&amp;gt;&amp;gt; GetAllStudentsAsync()
{
     var studentsList = new List&amp;lt;Student&amp;gt;();
     FirestoreDb db = FirestoreDb.Create(Project);
     Query allStudentsQuery = db.Collection(Collection);

     QuerySnapshot allStudentsQuerySnapshot = await allStudentsQuery.GetSnapshotAsync();
     foreach (DocumentSnapshot documentSnapshot in allStudentsQuerySnapshot.Documents)
     {
         studentsList.Add(documentSnapshot.ConvertTo&amp;lt;Student&amp;gt;());
     }

     return studentsList.Select(
            s =&amp;gt; new StudentListModel
                {
                    Id = s.Id,
                    FirstName = s.FirstName,
                    LastName = s.LastName
                }
            ).ToList();
}
&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Replace the&amp;nbsp;&lt;span style=&quot;color: #3d85c6;&quot;&gt;GetStudentByIdAsync&lt;/span&gt; method with the following
&lt;pre class=&quot;source-code&quot;&gt;public async Task&amp;lt;StudentListModel&amp;gt; GetStudentByIdAsync()
{
     FirestoreDb db = FirestoreDb.Create(Project);
     Query docRef = db.Collection(Collection).WhereEqualTo(&quot;Id&quot;, studentId).Limit(1);
     QuerySnapshot snapshot = await docRef.GetSnapshotAsync();
     if (snapshot.Count &amp;gt; 0)
     {
          Student student = snapshot.ElementAt(0).ConvertTo&amp;lt;Student&amp;gt;();
          return new StudentDetailModel()
          {
              About = student.About,
              EnrollmentDate = student.EnrollmentDate.ToDateTime(),
              FirstName = student.FirstName,
              Id = student.Id,
              LastName = student.LastName
          };
      }
      else
      {
           return null;
      }
}&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Replace the &lt;span style=&quot;color: #3d85c6;&quot;&gt;UpdateStudentAsync &lt;/span&gt;method with the following
&lt;pre class=&quot;source-code&quot;&gt;public async Task UpdateStudentAsync(StudentDetailModel student)
{
     FirestoreDb db = FirestoreDb.Create(Project);
     Query docRef = db.Collection(Collection).WhereEqualTo(&quot;Id&quot;, student.Id).Limit(1);
     QuerySnapshot snapshot = await docRef.GetSnapshotAsync();
     if (snapshot.Count &amp;gt; 0)
     {
           DocumentReference studentRef = db.Collection(Collection).Document(snapshot.ElementAt(0).Id);
           Dictionary&amp;lt;string, object&amp;gt; updates = new Dictionary&amp;lt;string, object&amp;gt;
           {
               { nameof(student.About), student.About},
               { nameof(student.EnrollmentDate), Timestamp.FromDateTime(student.EnrollmentDate.ToUniversalTime())},
               { nameof(student.FirstName), student.FirstName},
               { nameof(student.LastName), student.LastName}
           };
           await studentRef.UpdateAsync(updates);
     }
}&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Replace the &lt;span style=&quot;color: #3d85c6;&quot;&gt;InsertStudentAsync&lt;/span&gt; method with the following
&lt;pre class=&quot;source-code&quot;&gt;public async Task InsertStudentAsync(StudentDetailModel student)
{
     var entity = new Student()
     {
          Id = new Random().Next(1, int.MaxValue),
          FirstName = student.FirstName,
          LastName = student.LastName,
          About = student.About,
          &lt;span style=&quot;color: green;&quot;&gt;//create Timestamp from DateTime value&lt;/span&gt;
          EnrollmentDate = Timestamp.FromDateTime(student.EnrollmentDate.ToUniversalTime())
     };

     FirestoreDb db = FirestoreDb.Create(Project);
     var Id = Guid.NewGuid().ToString();
     DocumentReference docRef = db.Collection(Collection).Document(Id);
     await docRef.SetAsync(entity);
}&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Replace the &lt;span style=&quot;color: #3d85c6;&quot;&gt;DeleteStudentAsync&lt;/span&gt; method with the following
&lt;pre class=&quot;source-code&quot;&gt;public async Task DeleteStudentAsync(int studentId)
{
     FirestoreDb db = FirestoreDb.Create(Project);
     Query docRef = db.Collection(Collection).WhereEqualTo(&quot;Id&quot;, studentId).Limit(1);
     QuerySnapshot snapshot = await docRef.GetSnapshotAsync();
     if (snapshot.Count &amp;gt; 0)
     {
         DocumentReference studentRef = db.Collection(Collection).Document(snapshot.ElementAt(0).Id);
         await studentRef.DeleteAsync();
     }
}&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;Run your application and if there is no error you will see the following page in your browser&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhh42CSLAL_onk5j0qloAXag-kWR4qPQ8teJzsa6UfI-F2sDbUsvbSRb8dIlrIR7HPBbi2OxlMxUVhPnESv4XhEdU4DK-KMiup_gdmM8Z31MeusqEKYqaaYBfQhIRECBjN-ps0nZCuM3c89/s1600/home-page.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;569&quot; data-original-width=&quot;1600&quot; height=&quot;142&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhh42CSLAL_onk5j0qloAXag-kWR4qPQ8teJzsa6UfI-F2sDbUsvbSRb8dIlrIR7HPBbi2OxlMxUVhPnESv4XhEdU4DK-KMiup_gdmM8Z31MeusqEKYqaaYBfQhIRECBjN-ps0nZCuM3c89/s400/home-page.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Click on New Item and fill the form then click Add&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJTdG1j-jshTiPzL5ziD3mcb-hDZR-CNYc3yueuvXUZkl0d2-GqI_J2Y1xHnidXEZ81Is7QD4lAMH4zN-xfH8FvDpNXBPSqPNfp0mAUHDLYHgj0NpQbcRZcTrvhCXH5hCIuhTCQuZIREEY/s1600/Create.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1487&quot; data-original-width=&quot;1140&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJTdG1j-jshTiPzL5ziD3mcb-hDZR-CNYc3yueuvXUZkl0d2-GqI_J2Y1xHnidXEZ81Is7QD4lAMH4zN-xfH8FvDpNXBPSqPNfp0mAUHDLYHgj0NpQbcRZcTrvhCXH5hCIuhTCQuZIREEY/s320/Create.png&quot; width=&quot;245&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Congratulation, you added your student to students Firestore collection&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1KeDAatFQCTPjuhWLCY5_7cjihM9YrujgOtIYReWc4jywONRNzyO2sZKeqKoHBZ7rO2jCBgJTb7XyaVphGKD79kER2lvnTPdCSz2BDgV-A0zH59ePJ6GPHPY8YNBfAVdXxthyKIrungHc/s1600/List.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;637&quot; data-original-width=&quot;1495&quot; height=&quot;136&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh1KeDAatFQCTPjuhWLCY5_7cjihM9YrujgOtIYReWc4jywONRNzyO2sZKeqKoHBZ7rO2jCBgJTb7XyaVphGKD79kER2lvnTPdCSz2BDgV-A0zH59ePJ6GPHPY8YNBfAVdXxthyKIrungHc/s320/List.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Go to your Firestore database, it should look like &lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgG5eSp4MHzu5HfeLLNF_nfS3Q2nhgFYMK13qa3OxyYH_AVHW60mHkMgiDX8f3alqoFAthoCRy8PUFXyVvj98Xfk-AiabpGFlb0iXCe-WJ2aLA6aeWUtZ0iLZR-qeK0lLh5N3_x4Pu8BxLs/s1600/record.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;654&quot; data-original-width=&quot;1600&quot; height=&quot;130&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgG5eSp4MHzu5HfeLLNF_nfS3Q2nhgFYMK13qa3OxyYH_AVHW60mHkMgiDX8f3alqoFAthoCRy8PUFXyVvj98Xfk-AiabpGFlb0iXCe-WJ2aLA6aeWUtZ0iLZR-qeK0lLh5N3_x4Pu8BxLs/s320/record.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
notice that, Firestore is created a student collection and inserted your student entity as &lt;span style=&quot;color: #3d85c6;&quot;&gt;JSON&lt;/span&gt; document and also notice how it represents the &lt;span style=&quot;color: #3d85c6;&quot;&gt;EnrollmentDate &lt;/span&gt;value as timestamp.
&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;Summary&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
In this article we demonstrated how to create a sample DotVVM web application, Cloud Firestore database and perform CRUD operations as we used to do with SQL Server database or any other relational database.
We have done changes in the sample project code to twist it from using Entity Framework Code First approach (SQL Server) to use Google Cloud FireStore .Net SDK.
&lt;br /&gt;
&lt;br /&gt;
You can find the complete source code on &lt;a href=&quot;https://github.com/miroprocessor/dotvvm-firestore&quot; target=&quot;_blank&quot;&gt;github&lt;/a&gt;

&lt;/div&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/4844964311698898264/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2020/01/dotvvm-crud-application-with-cloud.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4844964311698898264'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4844964311698898264'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2020/01/dotvvm-crud-application-with-cloud.html' title=' DotVVM CRUD application with Cloud Firestore'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiPf0owsr2awl7Fz649FVUOpl0LhhkkeYnkN3xRpxBmCPlTAgeTX-zKAScgwrjiyM9OfJQCKwsBYNIlBGD_g7p03fjaROtiI0dPbIhW7BB2ELLmPksPP23uiPwLUYTUZcOxL8mZ6lxov5A2/s72-c/project+created.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-9085357333423066946</id><published>2019-12-19T15:49:00.000+02:00</published><updated>2019-12-21T16:48:02.998+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term=".netcore"/><category scheme="http://www.blogger.com/atom/ns#" term="azure"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="cosmosdb"/><category scheme="http://www.blogger.com/atom/ns#" term="dotvvm"/><category scheme="http://www.blogger.com/atom/ns#" term="entityframework"/><category scheme="http://www.blogger.com/atom/ns#" term="NoSQL"/><title type='text'> DotVVM CRUD application with  Entity Framework and Cosmos DB</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;

&lt;br /&gt;
&lt;h3&gt;
&lt;b&gt;&lt;span style=&quot;font-size: 14pt; line-height: 107%;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;What
is DotVVM?&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/h3&gt;
&lt;div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;DotVVM is
open source MVVM framework for ASP.Net Core and OWIN and it is member of &lt;a href=&quot;https://dotnetfoundation.org/&quot; target=&quot;_blank&quot;&gt;.NetFoundation&lt;/a&gt;. DotVVM is a free to use under &lt;/span&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;Apache License&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt; but also have commercial extensions.&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;span style=&quot;font-size: 12pt; line-height: 107%;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;DotVVM lets you build interactive web UIs with
just C# and HTML using MVVM pattern. DotVVM framework is shipped with many
build-in controls like &lt;i&gt;GridView&lt;/i&gt;, &lt;i&gt;FileUpload&lt;/i&gt;, &lt;i&gt;Validators&lt;/i&gt;, and more.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: 12pt; line-height: 107%;&quot;&gt;&lt;span style=&quot;font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;Why DotVVM?&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: 12pt;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;span style=&quot;font-size: 12pt;&quot;&gt;There are
many reason and business scenarios that DotVVM is suitable for and very helpful
like:&amp;nbsp;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&lt;div&gt;
&lt;ul&gt;&lt;span style=&quot;line-height: 107%;&quot;&gt;
&lt;li&gt;&lt;div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;font-size: 12pt; text-indent: -0.25in;&quot;&gt;Migrating legacy ASP.Net web forms application to .Net
Core.&lt;/span&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;font-size: 12pt; text-indent: -0.25in;&quot;&gt;New ASP.Net applications that contains many forms with
a lot of controls/components.&lt;/span&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/span&gt;&lt;/li&gt;
&lt;/span&gt;&lt;/ul&gt;
&lt;div style=&quot;font-size: 12pt;&quot;&gt;
&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;div style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;To learn
more about DotVVM framework visit &lt;/span&gt;&lt;a href=&quot;https://www.dotvvm.com/&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;DotVVM.com&lt;/span&gt;&lt;/a&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;.&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;What is Azure Cosmos DB?&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #0b5394; font-family: inherit;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;
&lt;/span&gt;
&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;Azure Cosmos
DB is a NoSQL distributed and fully managed database service. Azure Cosmos DB
provides different API for different NoSQL models like Document databases,
Column databases, Graph databases and Key-Value database.&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;You can
easily migrate your existing database on your prim to Azure Cosmos DB using
Cosmos migration tool.&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;In this
article we will go through a sample project to demonstrate how it is easy to use DotVVM framework in building your web application with Azure
Cosmos DB as your data store.&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;span style=&quot;font-size: 12.0pt; line-height: 107%;&quot;&gt;&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;Install DotVVM extension&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;/div&gt;
&lt;ol style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;line-height: 107%;&quot;&gt;
&lt;li&gt;&lt;span style=&quot;line-height: 107%;&quot;&gt;&lt;div class=&quot;MsoNormal&quot; style=&quot;font-size: 12pt;&quot;&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;Open Visual Studio 2019
(you can use Visual Studio 2017 as well)&lt;/span&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;&lt;span style=&quot;font-size: 12pt; line-height: 107%;&quot;&gt;Open Manage Extension
window&lt;/span&gt;&lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12pt;&quot;&gt;&amp;nbsp;&lt;/span&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12pt; line-height: 107%;&quot;&gt;Extensions &lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;wingdings&amp;quot;; font-size: 12pt; line-height: 107%;&quot;&gt;à&lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12pt; line-height: 107%;&quot;&gt; Manage Extensions &lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;wingdings&amp;quot;; font-size: 12pt; line-height: 107%;&quot;&gt;à&lt;/span&gt;&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12pt; line-height: 107%;&quot;&gt; Online menu&lt;/span&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12pt; line-height: 107%;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;In search box
type DotVVM and click Download&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtPsT-hpLuVf-GbtSpITiBYyfowWcjasXptw4k0dJwMt4tBO6KHCtKBKHTt-aNgaMWsziNuhtDcmPF6a0f2UitunfxLh37OE5QfXA-evMSApx3129s9I6FQ3B5jOwlPa8l4GJBcQ2dyAfd/s1600/0-+install+DotVVM+extension.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1098&quot; data-original-width=&quot;1600&quot; height=&quot;274&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtPsT-hpLuVf-GbtSpITiBYyfowWcjasXptw4k0dJwMt4tBO6KHCtKBKHTt-aNgaMWsziNuhtDcmPF6a0f2UitunfxLh37OE5QfXA-evMSApx3129s9I6FQ3B5jOwlPa8l4GJBcQ2dyAfd/s400/0-+install+DotVVM+extension.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/span&gt;&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;Restart Visual Studio
to complete DotVVM installation&lt;/span&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;You should find
DotVVM in Extension menu.&lt;/span&gt;&lt;/span&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;/span&gt;&lt;/ol&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;To know more about
the DotVVM extension visit its page on visual studio marketplace:&lt;/span&gt;&lt;a href=&quot;https://marketplace.visualstudio.com/items?itemName=TomasHerceg.DotVVM-VSExtension2019&quot; style=&quot;font-family: Calibri, sans-serif; font-size: 11pt;&quot;&gt;https://marketplace.visualstudio.com/items?itemName=TomasHerceg.DotVVM-VSExtension2019&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;Now you are ready to
start coding with DotVVM framework. DotVVM extension installs DotVVM sample
project which we will use to demonstrate how it is easy to connect to Azure
Cosmos DB from DotVVM application.&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;&lt;br /&gt;&lt;/span&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;DotVVM Web Application&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;Create new project&lt;/span&gt;&lt;br /&gt;In create new project window, filter project list by DotVVM and select DotVVM Web Application (.NET Core) and click next.&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRTnTdemVxHJnEEGn8pdjNMr9RKDFlSfZxLbqF3K8B9QfDHlaMhzHlDio9e4nBNqE9Qk4CcTQT6l_0pAE1YHM20bzBl7v6Uc2vqRsxB5UFLxEwGbBUQPdWzk5nTCbIjXIAVhRFZVumMgjE/s1600/1-+new+DotVVM+project.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1104&quot; data-original-width=&quot;1600&quot; height=&quot;275&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjRTnTdemVxHJnEEGn8pdjNMr9RKDFlSfZxLbqF3K8B9QfDHlaMhzHlDio9e4nBNqE9Qk4CcTQT6l_0pAE1YHM20bzBl7v6Uc2vqRsxB5UFLxEwGbBUQPdWzk5nTCbIjXIAVhRFZVumMgjE/s400/1-+new+DotVVM+project.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;font-family: &amp;quot;calibri&amp;quot; , sans-serif; font-size: 12.0pt; line-height: 107%;&quot;&gt;Enter “&lt;i&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;DotVVMCosmos&lt;/span&gt;&lt;/i&gt;”
as project name, project path, and “&lt;span style=&quot;color: #3d85c6;&quot;&gt;&lt;i&gt;DotVVMCosmos&lt;/i&gt;&lt;/span&gt;” as solution name then click
create&lt;/span&gt;&lt;br /&gt;&lt;i&gt;Project name and solution name can be any value you want.&lt;/i&gt;&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4KYRLHdFNt2fbUwjo15K0ldVhWx1dC0xVWd9xGICP9XCO0Pzbg1Too4ww9yMLV1iByAJ6PZkEtfIcMQbuxnp4nQMIboBaWUAr0AV4qogQlJOGWicEIYhp5N1vm9ytbby4xdOxJkn-_3hV/s1600/2-+project+name+and+path.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1127&quot; data-original-width=&quot;1600&quot; height=&quot;282&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4KYRLHdFNt2fbUwjo15K0ldVhWx1dC0xVWd9xGICP9XCO0Pzbg1Too4ww9yMLV1iByAJ6PZkEtfIcMQbuxnp4nQMIboBaWUAr0AV4qogQlJOGWicEIYhp5N1vm9ytbby4xdOxJkn-_3hV/s400/2-+project+name+and+path.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;In “Customize Your DotVVM Project” window select:
&lt;ul&gt;
&lt;li&gt;Select Bootstrap 3&lt;/li&gt;
&lt;li&gt;No Authentication&lt;/li&gt;
&lt;li&gt;Sample CRUD Page&lt;/li&gt;
&lt;li&gt;.NET Core 3.0 (you can target another .NET core version)&lt;/li&gt;
&lt;/ul&gt;
Then click Create Project.
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJOJ41HzbQMGL3CpNtV8YyLx2XI6EuMxEAyPejDYFXs6MtN_7wYSfytqKqxUr1-xTjnY6Tx2q8aURDx_qu6CUFktssU-QRCpaY3mCfgTHXQioSTPHPlPq0EPDJuIR9u8OItLTrVwz8hnD_/s1600/3-+customize+DotVVM+project.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1445&quot; data-original-width=&quot;1460&quot; height=&quot;396&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJOJ41HzbQMGL3CpNtV8YyLx2XI6EuMxEAyPejDYFXs6MtN_7wYSfytqKqxUr1-xTjnY6Tx2q8aURDx_qu6CUFktssU-QRCpaY3mCfgTHXQioSTPHPlPq0EPDJuIR9u8OItLTrVwz8hnD_/s400/3-+customize+DotVVM+project.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;br /&gt;
Your project structure will be as shown
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEw5INQdv_RjxCFAOaasvSmhMw17Y7H4qtD33w7nigP7Us3PpWkaEG771XuzkVUrLH6fGwjMtUvC7eWh3pFL7PAiz_gxTCUNRUrvSUKZwunFKYd-7Pnrc8jFu7Z4DucDWYjSJ1Pb75rO-c/s1600/solution.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1097&quot; data-original-width=&quot;1047&quot; height=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEw5INQdv_RjxCFAOaasvSmhMw17Y7H4qtD33w7nigP7Us3PpWkaEG771XuzkVUrLH6fGwjMtUvC7eWh3pFL7PAiz_gxTCUNRUrvSUKZwunFKYd-7Pnrc8jFu7Z4DucDWYjSJ1Pb75rO-c/s400/solution.png&quot; width=&quot;382&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;br /&gt;
DotVVM sample project uses Entity Framework Code First approach and provides:
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Sample entity (&lt;span style=&quot;color: #3d85c6;&quot;&gt;Student&lt;/span&gt;)&lt;/li&gt;
&lt;li&gt;DbContext class (&lt;span style=&quot;color: #3d85c6;&quot;&gt;StudentDbContext&lt;/span&gt;)&lt;/li&gt;
&lt;li&gt;Two model classes (&lt;span style=&quot;color: #3d85c6;&quot;&gt;StudentDetailModel&lt;/span&gt;, &lt;span style=&quot;color: #3d85c6;&quot;&gt;StudentListModel&lt;/span&gt;)&lt;/li&gt;
&lt;li&gt;CRUD Service class (&lt;span style=&quot;color: #3d85c6;&quot;&gt;StudentService&lt;/span&gt;) : contains all methods required to do your CRUD operations&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div&gt;&lt;br /&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;Create Azure Cosmos DB Account&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;
&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
You can use existing Azure subscription to create Azure Cosmos DB account. If you don’t have active azure subscription still you can try Azure Cosmos DB for free for 30 days.
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Go to &lt;a href=&quot;https://azure.microsoft.com/en-us/try/cosmosdb/&quot;&gt;https://azure.microsoft.com/en-us/try/cosmosdb/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Sign in with your Microsoft account or GitHub account&lt;/li&gt;
&lt;li&gt;Select SQL API&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj28khnvEsgP3ombtuwwjjuzWNP7_j6ad-hDQzWpyodZ8RrueBlhb-2P4PJJcotblzCmDeaiA4yKRitcKp3-XoXkwmsWGqefxOfjCCsCfc8WXNkn6m25-2J5bGkyuXUojEI7t-z5N0kiRz-/s1600/5-+select+SQL+API.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;626&quot; data-original-width=&quot;763&quot; height=&quot;262&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj28khnvEsgP3ombtuwwjjuzWNP7_j6ad-hDQzWpyodZ8RrueBlhb-2P4PJJcotblzCmDeaiA4yKRitcKp3-XoXkwmsWGqefxOfjCCsCfc8WXNkn6m25-2J5bGkyuXUojEI7t-z5N0kiRz-/s320/5-+select+SQL+API.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Microsoft will create Azure Cosmos DB Account for you and the overview page will look like&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyre870DGd4yhM1YRgz-P0qlI_cRlEnWe2Wpu5ffLBE2h_FS3XBAYZqzB2ZhpHcoxZBIKkfvviJT1tBwIffuqOluiF7eu6-_rwXD7MejyLfEZtdrDR0Gn4nFYG0KjrRxtH_KXMiZEto5CS/s1600/cosmos+account.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;499&quot; data-original-width=&quot;1600&quot; height=&quot;125&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiyre870DGd4yhM1YRgz-P0qlI_cRlEnWe2Wpu5ffLBE2h_FS3XBAYZqzB2ZhpHcoxZBIKkfvviJT1tBwIffuqOluiF7eu6-_rwXD7MejyLfEZtdrDR0Gn4nFYG0KjrRxtH_KXMiZEto5CS/s400/cosmos+account.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;In left side menu click on Keys. From read-write keys tab, copy URI and Primary Key values and keep it.&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJ8oiaZe3gKo-cg3A7PZEl11XMb1vH8ylOQdWp-4wdvXBQ4IF6ijrxIQNNvmc3CgTOr6S0FA6wY-6Ve2OtveTKzHZWwUFQHwN-hOQ1UwXaXUobuxDKUv5z_YkcADY-LTSc3o99DRhbRGr1/s1600/keys.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;498&quot; data-original-width=&quot;1428&quot; height=&quot;139&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJ8oiaZe3gKo-cg3A7PZEl11XMb1vH8ylOQdWp-4wdvXBQ4IF6ijrxIQNNvmc3CgTOr6S0FA6wY-6Ve2OtveTKzHZWwUFQHwN-hOQ1UwXaXUobuxDKUv5z_YkcADY-LTSc3o99DRhbRGr1/s400/keys.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
&lt;br /&gt;
Back to our DotVVM project to make the required modification to connect to Azure Cosmos DB.
&lt;/div&gt;
&lt;ul&gt;
&lt;li&gt;Uninstall entity framework Sql Server related nuget package&lt;br /&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;Microsoft.EntityFrameworkCore.SqlServer&lt;/span&gt; and &lt;span style=&quot;color: #3d85c6;&quot;&gt;Microsoft.EntityFrameworkCore&lt;/span&gt;&lt;br /&gt;As we will connect to Azure Cosmos DB not Sql Server database&lt;/li&gt;
&lt;li&gt;Install &lt;span style=&quot;color: #3d85c6;&quot;&gt;Microsoft.EntityFrameworkCore.Cosmos&lt;/span&gt; nuget package&lt;/li&gt;
&lt;li&gt;Open &lt;i&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;appsettings.json&lt;/span&gt;&lt;/i&gt; file and replace its content with the following&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;{
  &quot;AppSettings&quot;: {
    &quot;EndPoint&quot;: &quot;&amp;lt;your cosmos db uri&amp;gt;&quot;,
    &quot;Cosmoskey&quot;: &quot;&amp;lt;your cosmos db primary key&amp;gt;&quot;,
    &quot;DatabaseName&quot;: &quot;DotVVM-Cosmos&quot;
  }
}
&lt;/your&gt;&lt;/your&gt;&lt;/pre&gt;
Appsetting.json file contains the default connection string for Local DB but we will connect to Azure Cosmos DB so no need to keep default connection string in our code.
&lt;/li&gt;
&lt;li&gt;Open &lt;i&gt;&lt;span style=&quot;color: #3d85c6;&quot;&gt;Startup.cs&lt;/span&gt;&lt;/i&gt; file and replace&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;services.AddEntityFrameworkSqlServer()
                .AddDbContext&lt;studentdbcontext&gt;(options =&amp;gt;
                {
                    options.UseSqlServer(Configuration.GetConnectionString(&quot;DefaultConnection&quot;));
                });
&lt;/studentdbcontext&gt;&lt;/pre&gt;
with&lt;pre class=&quot;source-code&quot;&gt;services.AddEntityFrameworkCosmos()
                .AddDbContext&lt;studentdbcontext&gt;(options =&amp;gt;
                {
                    options.UseCosmos(Configuration.GetSection(&quot;AppSettings&quot;).GetValue&lt;string&gt;(&quot;EndPoint&quot;),
                        Configuration.GetSection(&quot;AppSettings&quot;).GetValue&lt;string&gt;(&quot;Cosmoskey&quot;),
                        databaseName: Configuration.GetSection(&quot;AppSettings&quot;).GetValue&lt;string&gt;(&quot;DatabaseName&quot;));
                });
&lt;/string&gt;&lt;/string&gt;&lt;/string&gt;&lt;/studentdbcontext&gt;&lt;/pre&gt;
Here we tell the .Net to use EntityFramework Cosmos Provider instead of EntityFramework Sql Server provider and adding our &lt;span style=&quot;color: #3d85c6;&quot;&gt;StudentDbContext&lt;/span&gt; and passing the required option to create a connection with our Cosmos DB instance.&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Open &lt;span style=&quot;color: #3d85c6;&quot;&gt;&lt;i&gt;DAL/StudentDbContext.cs&lt;/i&gt;&lt;/span&gt; file and add the following method to &lt;span style=&quot;color: #3d85c6;&quot;&gt;StudentDbContext&lt;/span&gt; class
&lt;pre class=&quot;source-code&quot;&gt;protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultContainer(&quot;Students&quot;);

            modelBuilder.Entity&lt;student&gt;().ToContainer(&quot;Students&quot;);
        }
&lt;/student&gt;&lt;/pre&gt;
In first line we set the default Cosmos DB Container to be “&lt;span style=&quot;color: #3d85c6;&quot;&gt;Students&lt;/span&gt;”. In the second line we map the Student entity to &lt;span style=&quot;color: #3d85c6;&quot;&gt;Students&lt;/span&gt; Container. If we have other entities we need to map ‘em to the corresponding container as well.&lt;br /&gt;&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Run your application and if there is no error you will see the following page in your browser&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhh42CSLAL_onk5j0qloAXag-kWR4qPQ8teJzsa6UfI-F2sDbUsvbSRb8dIlrIR7HPBbi2OxlMxUVhPnESv4XhEdU4DK-KMiup_gdmM8Z31MeusqEKYqaaYBfQhIRECBjN-ps0nZCuM3c89/s1600/home-page.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;569&quot; data-original-width=&quot;1600&quot; height=&quot;142&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhh42CSLAL_onk5j0qloAXag-kWR4qPQ8teJzsa6UfI-F2sDbUsvbSRb8dIlrIR7HPBbi2OxlMxUVhPnESv4XhEdU4DK-KMiup_gdmM8Z31MeusqEKYqaaYBfQhIRECBjN-ps0nZCuM3c89/s400/home-page.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Click on New Item and fill the form then click Add&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitwMLMopJaPvwLLkzqzYBnT-6-yP8oQVbSxA3mY-Bl-O3NT0DBkoHriZIiGvb5BWcQ70RijVo4MP0WmjnrHZWule10unc7xLMAhZGKTVJibr6x2gF0bmq37lQ4TrrHGZyEoTWhNNVuPFFh/s1600/add-page.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;1502&quot; data-original-width=&quot;1412&quot; height=&quot;400&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitwMLMopJaPvwLLkzqzYBnT-6-yP8oQVbSxA3mY-Bl-O3NT0DBkoHriZIiGvb5BWcQ70RijVo4MP0WmjnrHZWule10unc7xLMAhZGKTVJibr6x2gF0bmq37lQ4TrrHGZyEoTWhNNVuPFFh/s400/add-page.png&quot; width=&quot;376&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Congratulation, you added your student to Student Cosmos DB container&lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixA2NloNTEJTrVj5fIL3a5TnrjX7GAv26I45mifTk7d1j5hVMXJ01Z-QiKaGvhRhZnenIEwivHpBA1L8ypbJpN1zAF2sGABKyrCas-PREnJpmBpd4i1mXCmrlbA6a6Joy7KnvYS_vmKgm6/s1600/list-page.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;590&quot; data-original-width=&quot;1472&quot; height=&quot;160&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixA2NloNTEJTrVj5fIL3a5TnrjX7GAv26I45mifTk7d1j5hVMXJ01Z-QiKaGvhRhZnenIEwivHpBA1L8ypbJpN1zAF2sGABKyrCas-PREnJpmBpd4i1mXCmrlbA6a6Joy7KnvYS_vmKgm6/s400/list-page.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Go to your Cosmos DB web page and open Data Explorer, it should look like &lt;br /&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYrDy0Hsx2UaB6fTecVc9M367530Xu8aUyk3Eq1KOC48K6ezftSjx8EUbIC_fCvHp6rAkcvas9VBG28QM2Kx9528LqbwYRFVulSdq1onJztpN1CU3kq8hp7ycagVxtkksWcydPHL-i5qLq/s1600/json-item.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;507&quot; data-original-width=&quot;1428&quot; height=&quot;142&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYrDy0Hsx2UaB6fTecVc9M367530Xu8aUyk3Eq1KOC48K6ezftSjx8EUbIC_fCvHp6rAkcvas9VBG28QM2Kx9528LqbwYRFVulSdq1onJztpN1CU3kq8hp7ycagVxtkksWcydPHL-i5qLq/s400/json-item.png&quot; width=&quot;400&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;b style=&quot;font-size: 12pt;&quot;&gt;&lt;span style=&quot;font-size: 14pt; line-height: 19.9733px;&quot;&gt;&lt;span style=&quot;color: #6fa8dc; font-family: inherit;&quot;&gt;Summary&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;div class=&quot;MsoNormal&quot;&gt;
In this article we demonstrated how to create a sample DotVVM web application and connect to Azure Cosmos DB NoSQL database and perform CRUD operations as we used to do with SQL Server database or any other relational database.
We have done few changes in the sample project code to twist it from using Entity Framework Code First approach (SQL Server) to use Entity Framework Code First approach (Cosmos DB).
&lt;br /&gt;
You can find the complete source code on &lt;a href=&quot;https://github.com/miroprocessor/dotvvm-cosmosdb&quot; target=&quot;_blank&quot;&gt;github&lt;/a&gt;

&lt;/div&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/9085357333423066946/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2019/12/dotvvm-crud-application-with-entity.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/9085357333423066946'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/9085357333423066946'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2019/12/dotvvm-crud-application-with-entity.html' title=' DotVVM CRUD application with  Entity Framework and Cosmos DB'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtPsT-hpLuVf-GbtSpITiBYyfowWcjasXptw4k0dJwMt4tBO6KHCtKBKHTt-aNgaMWsziNuhtDcmPF6a0f2UitunfxLh37OE5QfXA-evMSApx3129s9I6FQ3B5jOwlPa8l4GJBcQ2dyAfd/s72-c/0-+install+DotVVM+extension.png" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-6365097605730295322</id><published>2019-02-02T19:08:00.000+02:00</published><updated>2019-02-02T19:17:02.792+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Cloud Firestore"/><category scheme="http://www.blogger.com/atom/ns#" term="firebase"/><category scheme="http://www.blogger.com/atom/ns#" term="json"/><category scheme="http://www.blogger.com/atom/ns#" term="NoSQL"/><category scheme="http://www.blogger.com/atom/ns#" term="TypeScript"/><title type='text'>Clean your JSON object before saving into Cloud Firestore database</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
span
{
   color:#6fa8dc;
}
span.comment
{
   color:green;
}
&lt;/style&gt;
If you have a registration form and you are collecting user&#39;s inputs to json object like&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;
user = {
&amp;nbsp;&amp;nbsp;&#39;first_name&#39; : &#39;Amir&#39;,
&amp;nbsp;&amp;nbsp;&#39;middle_name&#39;:&#39;&#39;,
&amp;nbsp;&amp;nbsp;&#39;last_name&#39;:&#39;Ismail&#39;
&amp;nbsp;&amp;nbsp;&#39;age&#39; : 25,
&amp;nbsp;&amp;nbsp;&#39;address&#39; : &#39;&#39;,
&amp;nbsp;&amp;nbsp;&#39;phone&#39;:null
};
&lt;/pre&gt;
&lt;div&gt;
notice &lt;span&gt;middle_name&lt;/span&gt;, &lt;span&gt;address&lt;/span&gt;, and &lt;span&gt;phone&lt;/span&gt; fields have no value (empty string and null). If you want to save this in &lt;a href=&#39;https://firebase.google.com/&#39; target=&#39;_blank&#39;&gt;Cloud Firestore &lt;/a&gt;database, these fields&amp;nbsp;will be saved which is not recommended because you are losing one of the advantages of&amp;nbsp; NoSQL document database which any document should contain only fields have value&lt;i&gt;(except your business case requires that field to be exist in all documents even has no value)&lt;/i&gt;.&lt;/div&gt;
&lt;div&gt;&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
To remove empty fields you have to check each input value and save only fields that have value. But if you have big form with many input fields or you have many forms checking each fields will be a nightmare and your code will be dirty.&lt;/div&gt;

&lt;div&gt;
So I tried to write a &lt;span&gt;TypeScript&lt;/span&gt; function that takes any json object and build new object contains only fields have values.&lt;/div&gt;

&lt;pre class=&quot;source-code&quot;&gt;
export class AppUtils {

&amp;nbsp; static cleanObject(input: any): any {
&amp;nbsp; &amp;nbsp; &amp;nbsp; let output: any = {};
&amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;span class=&#39;comment&#39;&gt;//loop over object fields&lt;/span&gt;&amp;nbsp;
&amp;nbsp; &amp;nbsp; &amp;nbsp; for (var key in input) {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;span class=&#39;comment&#39;&gt;//check if field have value or not&lt;/span&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; if (input.hasOwnProperty(key) &amp;amp;&amp;amp; input[key] != null &amp;amp;&amp;amp; input[key] !== &#39;&#39;) {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;span class=&#39;comment&#39;&gt;//check if primitive type or object&lt;/span&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; if (typeof (input[key]) === &#39;object&#39;) {&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; var subOutput = AppUtils.cleanObject(input[key]);
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; if (Object.keys(subOutput).length !== 0) {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; output[key] = subOutput;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; else {
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; output[key] = input[key];
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; &amp;nbsp; }
&amp;nbsp; &amp;nbsp; &amp;nbsp; return output;
&amp;nbsp; }
}
&lt;/pre&gt;

If we passed our user object to this function
&lt;pre class=&quot;source-code&quot;&gt;
let cleanObj = AppUtils.cleanObject(user);
&lt;/pre&gt;
the new object will be 
&lt;pre class=&quot;source-code&quot;&gt;
cleanObj = {
&amp;nbsp;&amp;nbsp;&#39;first_name&#39; : &#39;Amir&#39;,
&amp;nbsp;&amp;nbsp;&#39;last_name&#39;:&#39;Ismail&#39;
&amp;nbsp;&amp;nbsp;&#39;age&#39; : 25
};
&lt;/pre&gt;
</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/6365097605730295322/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2019/02/clean-your-json-object-before-saving.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/6365097605730295322'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/6365097605730295322'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2019/02/clean-your-json-object-before-saving.html' title='Clean your JSON object before saving into Cloud Firestore database'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-6087741407516837011</id><published>2018-10-22T22:28:00.001+02:00</published><updated>2018-10-23T17:24:11.178+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="ActionLink"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="Bootstrap"/><category scheme="http://www.blogger.com/atom/ns#" term="HtmlHelper"/><title type='text'>ASP.Net MVC : ActionLink with bootstrap icon</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;

How many times you wanted to add an icon to your action link?!. using Html.ActionLink method is not possible to add icon as it renders the link with just HtmlAttribute you provide.&lt;br /&gt;
&lt;div&gt;
ex :&lt;/div&gt;
&lt;div&gt;
&lt;pre class=&quot;source-code&quot;&gt;@Html.ActionLink(&quot;My Link&quot;,&quot;actionName&quot;,&quot;controllerName&quot;,new {id = Model.Id},
new {style=&quot;margin:10px&quot;, @class=&quot;btn btn-info&quot;});&lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
this will be rendered as shown in&amp;nbsp;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5E__tUkp2-zolbrEYQnIkL9QtQv4eZhQ4gxk_mBSj062bPJiEIct1HVcMCjdy9wmzsgixvKc78JcfXl_auDmCchikU2LFhdtHiSlte0F7dUyP_eOAdWzlGvN7h9UlhRfvIVtpRbZUPXnX/s1600/btn-info.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;55&quot; data-original-width=&quot;106&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5E__tUkp2-zolbrEYQnIkL9QtQv4eZhQ4gxk_mBSj062bPJiEIct1HVcMCjdy9wmzsgixvKc78JcfXl_auDmCchikU2LFhdtHiSlte0F7dUyP_eOAdWzlGvN7h9UlhRfvIVtpRbZUPXnX/s1600/btn-info.PNG&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
&amp;nbsp;if I want to add icon using bootstrap css classes, I can not use HtmlHelper methods and have to use plain html tags like this&lt;/div&gt;
&lt;div&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;div&gt;
&amp;lt;a href=&quot;url-here&quot; class=&quot;btn btn-info&quot; style=&quot;margin:10px;&quot;&amp;gt;&lt;/div&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;lt;i class=&quot;glyphicon glyphicon-pencil&quot;&amp;gt;&amp;lt;/i&amp;gt;&lt;/div&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;lt;span&amp;gt;My Link&amp;lt;/span&amp;gt;&lt;/div&gt;
&lt;div&gt;
&amp;nbsp; &amp;nbsp; &amp;lt;/a&amp;gt;&lt;/div&gt;
&lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
this will be rendered&amp;nbsp; as&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhdr6r9-p1B9XCeE3fVO2CPNZUmnCnb-s2ji3nrLuh9BEEvnLi6LLVljvmz4GXjJIu0o4GR5bVvQG6q1Hd2usnMBBRfc3PjA4DfT5nHkrWrLdZedA07kC-M8UbTDCCTk7g3202ndU_oZ7g/s1600/btn-info-icon.PNG&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; data-original-height=&quot;66&quot; data-original-width=&quot;132&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjhdr6r9-p1B9XCeE3fVO2CPNZUmnCnb-s2ji3nrLuh9BEEvnLi6LLVljvmz4GXjJIu0o4GR5bVvQG6q1Hd2usnMBBRfc3PjA4DfT5nHkrWrLdZedA07kC-M8UbTDCCTk7g3202ndU_oZ7g/s1600/btn-info-icon.PNG&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div&gt;
so to simplify my .cshtml file and make it easy for developers to add icon to their action links, I have created an extension method IconActionLink that will replace the previous html sinppet and give the same result.&lt;/div&gt;
&lt;div&gt;
&lt;pre class=&quot;source-code&quot;&gt;@Html.IconActionLink(&quot;My Link&quot;, &quot;actionName&quot;, &quot;controllerName&quot;, null, 
new { @class = &quot;btn btn-info&quot; }, &quot;glyphicon glyphicon-pencil&quot;)
&lt;/pre&gt;
&lt;/div&gt;
&lt;div&gt;
the big difference and most important is the icon css class parameter .&lt;br /&gt;
&lt;br /&gt;
Nuget Package :&amp;nbsp;&lt;a href=&quot;https://www.nuget.org/packages/Mirosoft.Utilities.Mvc&quot; target=&quot;_blank&quot;&gt;https://www.nuget.org/packages/Mirosoft.Utilities.Mvc&lt;/a&gt;&lt;br /&gt;
Source code :&amp;nbsp;&lt;a href=&quot;https://github.com/miroprocessor/Mirosoft.Utilities.Mvc&quot; target=&quot;_blank&quot;&gt;https://github.com/miroprocessor/Mirosoft.Utilities.Mvc&lt;/a&gt;&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/6087741407516837011/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2018/10/aspnet-mvc-actionlink-with-bootstrap.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/6087741407516837011'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/6087741407516837011'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2018/10/aspnet-mvc-actionlink-with-bootstrap.html' title='ASP.Net MVC : ActionLink with bootstrap icon'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5E__tUkp2-zolbrEYQnIkL9QtQv4eZhQ4gxk_mBSj062bPJiEIct1HVcMCjdy9wmzsgixvKc78JcfXl_auDmCchikU2LFhdtHiSlte0F7dUyP_eOAdWzlGvN7h9UlhRfvIVtpRbZUPXnX/s72-c/btn-info.PNG" height="72" width="72"/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-2639503932783448470</id><published>2016-08-13T11:59:00.000+02:00</published><updated>2017-05-05T17:01:36.653+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="asp mvc"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="AutoComplete"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="JQuery"/><category scheme="http://www.blogger.com/atom/ns#" term="UIHint"/><title type='text'>AutoComplete using customized UIHint attribute in ASP.Net MVC</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
span
{
   color:#6fa8dc;
}
span.comment
{
   color:green;
}
&lt;/style&gt;

In one project I worked on recently, I wanted to display list of suppliers which is very very long list, it was more than 6000 items. to display such number of items in dropdown list in a page of course will affect page load time.&lt;br /&gt;
&lt;br /&gt;
The best solution was using &lt;a href=&quot;https://jqueryui.com/autocomplete/&quot;&gt;Autocomplete jQuery plugin&lt;/a&gt;, it is light, powerful, and covers my needs but unfortunately I need to display that suppliers list in many pages for different view models.&lt;br /&gt;
&lt;br /&gt;
One of possible solutions copy/paste autocomplete code snippet in each view.This solution didn&#39;t make me satisfied and I thought of course there is better way and more elegant to do it.&lt;br /&gt;
&lt;br /&gt;
One possible alternative is Editor Template, in most cases we need the &lt;b&gt;Id&lt;/b&gt; value not the item full details. for simplicity I&#39;m using list of programming languages as a data source.&lt;br /&gt;
&lt;br /&gt;
I override UIHint attribute to pass the URL of our datasource, the URL will be used as source for autocomplete jQuery plugin.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;public class AutoCompleteUIHintAttribute : UIHintAttribute
{
   private readonly UrlHelper _urlHelper = new UrlHelper(Current.Request.RequestContext);
   public AutoCompleteUIHintAttribute(string url) :
        base(&quot;&lt;strong&gt;&lt;span style=&quot;color: #e91e63;&quot;&gt;AutoComplete&lt;/span&gt;&lt;/strong&gt;&quot;) &lt;span class=&quot;comment&quot;&gt;//Editor template name&lt;/span&gt;
   {        
       DataSourceUri = url;
   }   
   public AutoCompleteUIHintAttribute(string action, string controller) :
        base(&quot;AutoComplete&quot;)
   {
        DataSourceUri = _urlHelper.RouteUrl(new { action = action, controller = controller });
   }
   public AutoCompleteUIHintAttribute(string action, string controller, string area) :
        base(&quot;AutoComplete&quot;)
   {
        DataSourceUri = _urlHelper.RouteUrl(new { action = action, controller = controller, area = area });
   }
   public string DataSourceUri { get; set; }
}
&lt;/pre&gt;
In customized attribute we have three overloads of its constructor, first one accepts the full url as string. We can use it if our datasource is external or remote datasource. Second accepts action name and controller name and third accepts same values plus area name, these can be used if our datasource inside the current web application.&lt;br /&gt;
&lt;br /&gt;
In our view model what we need is just decorate the &lt;span&gt;LanguageId&lt;/span&gt; property with the &lt;span&gt;AutoCompleteUIHint&lt;/span&gt; attribute.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt; public class MyTestModel
 {
     [DisplayName(&quot;Language&quot;)]
     &lt;span class=&quot;comment&quot;&gt;//Here I used constructor that accepts action name and controller name&lt;/span&gt;
     &lt;strong&gt;&lt;span style=&quot;color: #e91e63;&quot;&gt;[AutoCompleteUIHint(&quot;datasource&quot;,&quot;home&quot;)]&lt;/span&gt;&lt;/strong&gt;
     public int LanguageId { get; set; }        
 }
&lt;/pre&gt;
in view, we just use &lt;span&gt;EditorFor&lt;/span&gt; helper method
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;@Html.EditorFor(m =&amp;gt; m.LanguageId)
&lt;/pre&gt;
in controller, we have action method return languages as &lt;span&gt;JsonResult&lt;/span&gt;
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;public JsonResult DataSource(string term)
{
     &lt;span class=&quot;comment&quot;&gt;//_datasource is a predefined list of programming languages&lt;/span&gt;
     var langauges = _dataSource.Where(x =&amp;gt; x.Name.ToLower().StartsWith(term.ToLower()));
     return Json(langauges.Select(i =&amp;gt; new
     {
         id = i.ID,
         value = i.Name
     }&lt;span class=&quot;comment&quot;&gt;// autocomplete jquery plugin accepts result in this format(id &amp;amp; value)&lt;/span&gt;
     ), JsonRequestBehavior.AllowGet);
}
&lt;/pre&gt;
Now we should write HTML version of our editor template. Add new file with name &lt;span&gt;&lt;strong&gt;AutoComplete.cshtml&lt;/strong&gt;&lt;/span&gt; to &lt;span&gt;&lt;strong&gt;Views/Shared/EditorTemplates&lt;/strong&gt;&lt;/span&gt; folder then copy following code into new file.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;@using AutoCompleteUIHint.Core;
@{
    &lt;span class=&quot;comment&quot;&gt;//get the full qualified name of property decorated with our attribute&lt;/span&gt;
    var propertyName = ViewData.TemplateInfo.GetFullHtmlFieldName(&quot;&quot;);
    &lt;span class=&quot;comment&quot;&gt;//javascript doesn&#39;t work properly with ids contain dot&lt;/span&gt;
    var propertyId = propertyName.Replace(&quot;.&quot;, &quot;_&quot;);
    &lt;span class=&quot;comment&quot;&gt;//generate random Id in case our view contains many instances&lt;/span&gt;
    var textBoxId = Guid.NewGuid().ToString();
}

@functions{
    &lt;span class=&quot;comment&quot;&gt;//generate text box for autocomplete feature&lt;/span&gt;
    private MvcHtmlString TextBox(string name)
    {
        var tagBuilder = new TagBuilder(&quot;input&quot;);
        tagBuilder.MergeAttribute(&quot;id&quot;, textBoxId);
        tagBuilder.MergeAttribute(&quot;type&quot;, &quot;text&quot;);

        return MvcHtmlString.Create(tagBuilder.ToString());
    }
    &lt;span class=&quot;comment&quot;&gt;//genarete hidden field to keep selected value(id) of selected language ID&lt;/span&gt;
    private MvcHtmlString Hidden(string name)
    {
        var tagBuilder = new TagBuilder(&quot;input&quot;);
        tagBuilder.MergeAttribute(&quot;type&quot;, &quot;hidden&quot;);
        tagBuilder.MergeAttribute(&quot;id&quot;, name.Replace(&quot;.&quot;, &quot;_&quot;));
        tagBuilder.MergeAttribute(&quot;name&quot;, name);

        return MvcHtmlString.Create(tagBuilder.ToString());
    }

    &lt;span class=&quot;comment&quot;&gt;//get url of datasource, that has been generated from Attribute constructor&lt;/span&gt;
    private string GetUrl()
    {
        var attribute = ViewData.ModelMetadata.ContainerType
                        &lt;span class=&quot;comment&quot;&gt;// Get the property we are displaying for (LanguageId)&lt;/span&gt;
                        .GetProperty(ViewData.ModelMetadata.PropertyName)
                        &lt;span class=&quot;comment&quot;&gt;// Get all attributes of type AutoCompleteUIHintAttribute&lt;/span&gt;
                        .GetCustomAttributes(typeof(AutoCompleteUIHintAttribute), false)
                        &lt;span class=&quot;comment&quot;&gt;// Cast the result as AutoCompleteUIHintAttribute&lt;/span&gt;
                        .Select(a =&amp;gt; a as AutoCompleteUIHintAttribute)
                        &lt;span class=&quot;comment&quot;&gt;// Get the first one or null&lt;/span&gt;
                        .FirstOrDefault(a =&amp;gt; a != null);

        return attribute?.DataSourceUri;
    }
}
&lt;span class=&quot;comment&quot;&gt;// render text box&lt;/span&gt;
@Html.Raw(TextBox(textBoxId))
&lt;span class=&quot;comment&quot;&gt;// render hidden field&lt;/span&gt;
@Html.Raw(Hidden(propertyName))

&amp;lt;script&amp;gt;
    $(function () {
        $(&quot;#@textBoxId&quot;).autocomplete({
            source: &#39;@Url.Content(GetUrl())&#39;,&lt;span class=&quot;comment&quot;&gt;// datasource url &lt;/span&gt;
            minLength: 1,&lt;span class=&quot;comment&quot;&gt;// type at least 1 character&lt;/span&gt;
            select: function (event, ui) {
                $(&#39;#@propertyId&#39;).val(ui.item.id);&lt;span class=&quot;comment&quot;&gt;// set hidden field value with the id of selected language.&lt;/span&gt;
            }
        });
    });
&amp;lt;/script&amp;gt;
&lt;/pre&gt;
when we run our application and start typing we get the following result
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEia8JAKYlQ-mvxI-iB-ijZlD4tAicfOUCNnDGZZYgJYnH3FefGS70ClHN27Y3Zkuy0MsayFZqdf_T8Td-0Z-Wk0DvFtfC6KHh0EUaaV5A6eR9_ztFRpCztNh4VZ4Efu4be_QiH7VV1ePAqW/s1600/auto1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEia8JAKYlQ-mvxI-iB-ijZlD4tAicfOUCNnDGZZYgJYnH3FefGS70ClHN27Y3Zkuy0MsayFZqdf_T8Td-0Z-Wk0DvFtfC6KHh0EUaaV5A6eR9_ztFRpCztNh4VZ4Efu4be_QiH7VV1ePAqW/s1600/auto1.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
when select a language and click submit button, you will get selected language ID and Name
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnIiYiFJ-y_RgEJwTT_BCnU6xolND516W2980-F7FYSpo-UCLX5t2wIxtD2w895kfeZ76gj8AD4IV3GD8KVS-t9hGHcwY2XxYEd8bs9x8S64mkx8LR5W28vYx41JovGibRVOFlIa5rFnzz/s1600/auto2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjnIiYiFJ-y_RgEJwTT_BCnU6xolND516W2980-F7FYSpo-UCLX5t2wIxtD2w895kfeZ76gj8AD4IV3GD8KVS-t9hGHcwY2XxYEd8bs9x8S64mkx8LR5W28vYx41JovGibRVOFlIa5rFnzz/s1600/auto2.png&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
Your feedback are very welcome and you can download full code &lt;b&gt;&lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzd185bEN0X18xZjA&quot;&gt;here&lt;/a&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;h4&gt;
References&lt;/h4&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;http://stackoverflow.com/questions/33157103/custom-dataannotations-attribute-like-uihint&quot;&gt;Custom DataAnnotations Attribute like UIHint&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;
</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/2639503932783448470/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2016/08/autocomplete-using-customized-uihint.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/2639503932783448470'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/2639503932783448470'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2016/08/autocomplete-using-customized-uihint.html' title='AutoComplete using customized UIHint attribute in ASP.Net MVC'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEia8JAKYlQ-mvxI-iB-ijZlD4tAicfOUCNnDGZZYgJYnH3FefGS70ClHN27Y3Zkuy0MsayFZqdf_T8Td-0Z-Wk0DvFtfC6KHh0EUaaV5A6eR9_ztFRpCztNh4VZ4Efu4be_QiH7VV1ePAqW/s72-c/auto1.png" height="72" width="72"/><thr:total>2</thr:total><georss:featurename>Egypt</georss:featurename><georss:point>30.0444196 31.235711600000059</georss:point><georss:box>29.9344751 31.074350100000057 30.154364100000002 31.39707310000006</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-7636250840279440773</id><published>2013-04-04T23:32:00.000+02:00</published><updated>2013-04-05T01:33:36.162+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net Cache"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net Performance"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net Pre-Compilation"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net Tracing"/><category scheme="http://www.blogger.com/atom/ns#" term="Asynchronous Controllers"/><category scheme="http://www.blogger.com/atom/ns#" term="Asynchronous Pages"/><category scheme="http://www.blogger.com/atom/ns#" term="ViewState"/><category scheme="http://www.blogger.com/atom/ns#" term="web application performance"/><title type='text'>5 Tips to Improve ASP.NET Application Performance</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
Web application is designed to handle hundreds and thousands of requests per seconds so to handle these requests effectively and successfully it is important to resolve any potential performance bottlenecks. Now we will state some tips that improve the performance of your web application.&lt;br /&gt;
&lt;b&gt;&lt;br /&gt;&lt;/b&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;1 -&amp;nbsp;Cache Commonly used objects&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;div&gt;
You can cache commonly used objects in ASP.Net using &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Cache &lt;/span&gt;class that provides an extensive caching mechanism that storing resources and allow you to:&lt;/div&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Define an expiration for a cached object either by specified a &lt;span style=&quot;color: #6fa8dc;&quot;&gt;TimeSpan&lt;/span&gt; or a fixed &lt;span style=&quot;color: #6fa8dc;&quot;&gt;DateTime&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;Define priority for cached objects. when there is a memory lack and objects need to be freed.&lt;/li&gt;
&lt;li&gt;Define validity for a cached object by adding dependacies&lt;/li&gt;
&lt;li&gt;Attach callbacks to cached objects,so when an objects is removed from cache the callback is invoked.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
you can add objects to cache by adding it to cache&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Dictionary&lt;/span&gt;&lt;/div&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Cache[&quot;Mykey&quot;] = myObject;
&lt;/code&gt;&lt;/pre&gt;
or using Insert method of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Cache&lt;/span&gt; class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Cache.Insert(&quot;MyKey&quot;,myObject, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(60), dependacies : null );
&lt;/code&gt;&lt;/pre&gt;
&lt;div&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;2 - Using&amp;nbsp;Asynchronous Pages,Modules and Controllers&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
When IIS passes a request to ASP.NET, the request is queued to the thread pool and a worker thread is assigned to handle this request. the worker thread is limited so any new request will be queued to be handle after the current requests handled. If a request need to do some I/O operation like retrieving data from &amp;nbsp;a database or calling web service that mean you need to reduce the request time.&lt;br /&gt;
&lt;br /&gt;
You can change I/O operation in your web page by making it as&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Asynchronous&amp;nbsp;Page&lt;/span&gt;. In ASP.NET you can do that by firstly marking the page as async&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&amp;lt;%@ Page Async=&quot;true&quot;....&lt;/code&gt;&lt;/pre&gt;
then create new &lt;span style=&quot;color: #6fa8dc;&quot;&gt;PageAsyncTask&lt;/span&gt; object and pass it the delegates for the begin, end, and timeout methods. After creating &lt;span style=&quot;color: #6fa8dc;&quot;&gt;PageAsyncTask&lt;/span&gt; object, call the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Page.RegisterAsuncTask&lt;/span&gt; method to start the asynchronous opertaion.&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public partial class MyAsyncPage : System.Web.UI.Page
{
   private SqlConnection _sqlConnection;
   private SqlCommand _sqlCommand;
   private SqlDataReader _sqlReader;

   IAsyncResult BeginAsyncOp(Object sender, EventArgs e, AsyncCallback cb, Object state)
   {
       // this method will be executed in the original worker thread, 
       //so don&#39;t do any lengthy operation here
       _sqlcommand = CreateSqlCommand(_sqlConnection);
       return _sqlCommand.BeginExecuteReader();
   }
   void EndAsyncOp(IAsyncResult asyncResult)
   {
       _sqlReader = _sqlCommand.EndExecuteReader(asyncResult);
       // read the data and build page contents
       .............
   }
   void TimeoutAsyncOp(IAsyncResult asyncResult)
   {
       _sqlReader = _sqlCommand.EndExecuteReader(asyncResult);
       // read the data and build page contents
       .............
   }
   public override void Dispose()
   {
       if(_sqlConnection != null)
       {
           _sqlConnection.Close();
       }
   }
   protected void btnClick_Click(Object sender, EventArgs e)
   {
       PageAsyncTask task = new PageAsyncTask( new BeginEventHandler(BeginAsyncOp),
                                               new EndEventHandler(EndAsyncOp),
                                               new TimeoutEventHandler(TimeoutAsyncOp),
                                               state : null);
       RegisterAsyncTask(task); 
   }
}
&lt;/code&gt;&lt;/pre&gt;
There is another way to create async pages is by using completion events.&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public partial class MyAsyncPage2 : System.Web.UI.Page
{
   protected void btnGetData_Click(Object sender , EventArgs e)
   {
       Services.MyService serviceProxy = new Services.MyService();
       serviceProxy.GetDataCompleted +=Services.GetDataCompletedEventHandler(GetData_Completed);
       serviceProxy.GetDataAsync();
   }
   void GetData_Completed(Object sender,Services.GetDataCompletedEventArgs e)
   {
       //Extract the result from the event args and build the page&#39;s content
   }
}&lt;/code&gt;&lt;/pre&gt;
In ASP.NET MVC you can create such mechanisme by creating &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Asynchronous Controller&lt;/span&gt;. To create such contoller you need to follow these four steps:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Create a &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Controller&lt;/span&gt; class that inherits from the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;AsyncController&lt;/span&gt; type.&lt;/li&gt;
&lt;li&gt;Implement &amp;nbsp;a set of action methods for each async operation according to the following convention, where &lt;span style=&quot;color: #6fa8dc;&quot;&gt;xx&lt;/span&gt; is the name of the action: &lt;span style=&quot;color: #6fa8dc;&quot;&gt;xxAsync&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;xxCompleted&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;In the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;xxAsync&lt;/span&gt; method, call the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;AsyncManager.OutstandingOperations.Increment&lt;/span&gt; method with the number of asynchronous operations you are about to perform.&lt;/li&gt;
&lt;li&gt;In the code which executes during the return of the async operation, call the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;AsyncManager.OutstandingOperations.Decrement&lt;/span&gt; method to notify the operation has completed.&lt;/li&gt;
&lt;/ol&gt;
The following code shows you how to implement these steps:&lt;/div&gt;
&lt;/div&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class MyController : AsyncController
{
   public void IndexAsync()
   {
       AsyncManager.OutStandingOperations.Increment();       
       MyService serviceProxy = new MyService();
       serviceProxy.GetDataCompleted&amp;nbsp;+= (sender , e) =&amp;gt; { 
                                        AsyncManager.Parameters[&quot;result&quot;] = e.Value;
                                        AsyncManager.OutStandingOperations.Decrement();
                                        };
       serviceProxy.GetHeadlinesAsync();
   }
   public ActionResult IndexCompleted(MyData result)
   { 
       return view(&quot;Index&quot;,new MyViewModel { TheData = result });
   }
}&lt;/code&gt;&lt;/pre&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;3 - Turn off ASP.NET Tracing and debugging&lt;/span&gt;&lt;/b&gt;
&lt;br /&gt;
&lt;div&gt;
before deploying your web application turn of tracing feature by setting it to false in &lt;span style=&quot;color: #6fa8dc;&quot;&gt;web.config&lt;/span&gt; file&lt;/div&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&amp;lt;configuration&amp;gt;
    &amp;lt;system.web&amp;gt;
        &amp;lt;trace enabled=&quot;&lt;b&gt;false&lt;/b&gt;&quot; /&amp;gt;
    &amp;lt;/system.web&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
While development phase you need to enable debugger to debug your code by setting it to true in &lt;span style=&quot;color: #6fa8dc;&quot;&gt;web.config&lt;/span&gt; file. Neglecting change it again to false before deploying will affect your web application performance by facing many problems:
&lt;br /&gt;
&lt;div&gt;
&lt;ul&gt;
&lt;li&gt;Scripts that are downloaded using the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;WebResources.axd&lt;/span&gt; handler, by setting debug to false responses from that handler will be returned with caching headers, allowing browsers to cache the responses for future use.&lt;/li&gt;
&lt;li&gt;Request will not timeout when debug is set to true. By setting it to false will enable ASP.NET to define timeouts for requests according to the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HttpRuntime.Execution&lt;/span&gt; Timeout configuration settings.&lt;/li&gt;
&lt;li&gt;JIT optimization will not be applied to the code when running with debug = true. JIT can efficiently improve the performance of your ASP.NET application without requiring you change your code.&lt;/li&gt;
&lt;li&gt;The compilation process does not use batch compilation when using debug = true. without batch compilation an assembly will be created for each page and control causing web application to load so many of assemblies during runtime. When debug set to false batch compilation is used, generating a single assembly for the user control and a several assemblies for pages.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
in case you fear to forget setting debug to false when deploying your application, you can force all ASP.NET applications in a server to ignore the debug setting by adding &amp;nbsp;the following configurations in the server&#39;s &lt;span style=&quot;color: #6fa8dc;&quot;&gt;machine.config&lt;/span&gt; file&lt;/div&gt;
&lt;/div&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&amp;lt;configuration&amp;gt;
    &amp;lt;system.web&amp;gt;
        &amp;lt;deployment retail=&quot;true&quot; /&amp;gt;
    &amp;lt;/system.web&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;4 - Disable View State&lt;/span&gt;&lt;/b&gt;
&lt;br /&gt;
View state is used to allow ASP.NET to keep the state of the page between postbacks performed by user. View state data is stored in HTML output inside hidden field. If your page displays many controls that contains a huge data, the view state field will be big enough to affect the response time of your page. if your page just display data without need any postback so it will be better to disable the view state of the whole page by set &lt;span style=&quot;color: #6fa8dc;&quot;&gt;EnableViewState&lt;/span&gt; to false&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&amp;lt;%@ Page EnableViewState=&quot;false&quot;.......%&amp;gt;&lt;/code&gt;&lt;/pre&gt;
or disable view state of some controls in your page&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&amp;lt;Asp:GridView ID=&quot;MyGrid&quot; runat=&quot;server&quot; DataSource=&quot;MyDataSource&quot; EnableViewState=&quot;false&quot; /&amp;gt;&lt;/code&gt;&lt;/pre&gt;
if you don&#39;t want to use view state in all pages of your web application it recommended to disable view state for whole web application by setting it to false in your &lt;span style=&quot;color: #6fa8dc;&quot;&gt;web.config&lt;/span&gt; file&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&amp;lt;system.web&amp;gt;
    &amp;lt;pages enableViewState=&quot;false&quot; ....../&amp;gt;
&amp;lt;/system.web&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;5 - Pre-Compiling ASP.NET Application&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
When compiling an ASP.NET application project, a single assembly is created to hold all application&#39;s code but web pages(.aspx) and user controls(.ascx) not compiled and be deployed as it is. In the first request ASP.NET dynamically compiles the web pages and user control and places the compiled files in the ASP.NET temporary files folder.&lt;br /&gt;
To reduce the time of first request the web application can be pre-compiled, including all code, pages, and user controls, by using the ASP.NET compilation tool (&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Aspnet_compiler.exe&lt;/span&gt;). Running this tool in production servers can reduce the delay users experience on first requests.&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Open a command prompt in your production server.&lt;/li&gt;
&lt;li&gt;Navigate to the &lt;i&gt;&lt;b&gt;%windir%\Microsoft.Net&lt;/b&gt;&lt;/i&gt; folder&lt;/li&gt;
&lt;li&gt;Navigate&amp;nbsp;to either the &lt;i&gt;&lt;b&gt;Framework &lt;/b&gt;&lt;/i&gt;or &lt;b&gt;&lt;i&gt;Framework64 &lt;/i&gt;&lt;/b&gt;according to the configuration of web application&#39;s application pool.&lt;/li&gt;
&lt;li&gt;Navigate to framework version&#39;s folder.&lt;/li&gt;
&lt;li&gt;Enter the following command to start the compilation&lt;/li&gt;
&lt;/ol&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Aspnet_compiler.exe  -v  /FullPathOfYourWebApplication&lt;/code&gt;&lt;/pre&gt;
</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/7636250840279440773/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2013/04/5-tips-to-improve-aspnet-application.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/7636250840279440773'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/7636250840279440773'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2013/04/5-tips-to-improve-aspnet-application.html' title='5 Tips to Improve ASP.NET Application Performance'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Cairo Governorate, Egypt</georss:featurename><georss:point>30.0444196 31.235711600000059</georss:point><georss:box>29.9344751 31.074350100000057 30.154364100000002 31.39707310000006</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-5394638084655602269</id><published>2012-09-06T15:49:00.000+02:00</published><updated>2017-05-05T16:57:49.512+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Android"/><category scheme="http://www.blogger.com/atom/ns#" term="android 4.x"/><category scheme="http://www.blogger.com/atom/ns#" term="progressbar"/><category scheme="http://www.blogger.com/atom/ns#" term="progressbar bounds"/><category scheme="http://www.blogger.com/atom/ns#" term="progressbar color"/><category scheme="http://www.blogger.com/atom/ns#" term="progressbar progress"/><category scheme="http://www.blogger.com/atom/ns#" term="ProgressDrawable"/><title type='text'>Android : How to change progress bar color at runtime programmatically?</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
I faced this problem while creating one of my android applications(in fact, it is my first application :) ). Lets consider we want to create an android application to calculate the&amp;nbsp;commitments&amp;nbsp;progress of a certain category for &lt;a href=&quot;http://area51.stackexchange.com/&quot;&gt;http://area51.stackexchange.com/&lt;/a&gt;&amp;nbsp;website (&lt;i&gt;note we will display a progress bar with one color red or green for simplicity&lt;/i&gt;).&lt;br /&gt;
&lt;br /&gt;
Each time we run this application it calculate the commitment percentage and display a red progress bar if it is less than 50% or green one if it equal or greater than 50%. For learning purpose we will insert the number of total required committed users and the number of committed users and calculate the progress of commitment process.
&lt;br /&gt;
&lt;br /&gt;
Now lets write our code. If it is your first android application you can refer to this &lt;a href=&quot;http://miroprocessordev.blogspot.com/2012/07/your-1st-android-application-hello.html&quot;&gt;post&lt;/a&gt; to know how to create an android application.
&lt;br /&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkQd1T7vsDY1ILGm8uYM8ykT-yXZCy5L8h9D_ssW0TREWsCvuPdBP2vjZjHpNihA1u5shbeq4y86YI-tAWwsUFmDQvaupny79MUUwKJs861RbC4vu1ni0kZ5aPk60ynFjn6x8Lg7eYasjQ/s1600/redprogressbar.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkQd1T7vsDY1ILGm8uYM8ykT-yXZCy5L8h9D_ssW0TREWsCvuPdBP2vjZjHpNihA1u5shbeq4y86YI-tAWwsUFmDQvaupny79MUUwKJs861RbC4vu1ni0kZ5aPk60ynFjn6x8Lg7eYasjQ/s320/redprogressbar.png&quot; width=&quot;214&quot; /&gt;&lt;/a&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidLisdtcFs3plnSqxYJ9F0DMZKRaipUtwvCISzuBYlsj3J6E6A12pz1pLko1tCakjg1LCMNBnQ2Jj0A6OWnle0Wrw6XvbvODLSHRBjpYfooTs1Y1VXf-GHRpe-TAa78sU3_X7R0wrdCFfw/s1600/greenprogressbar.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidLisdtcFs3plnSqxYJ9F0DMZKRaipUtwvCISzuBYlsj3J6E6A12pz1pLko1tCakjg1LCMNBnQ2Jj0A6OWnle0Wrw6XvbvODLSHRBjpYfooTs1Y1VXf-GHRpe-TAa78sU3_X7R0wrdCFfw/s320/greenprogressbar.png&quot; width=&quot;216&quot; /&gt;&lt;/a&gt;
&lt;br /&gt;
&lt;br /&gt;
How to create the full layout of this simple application is beyond this post, we will concentrate on the progress bar. The following code snippet is the definition of a progress bar and setting its properties in the layout xml file of the main activity&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&amp;lt;progressbar 
   android:id=&quot;@+id/myprogressbar&quot; 
   android:layout_alignparenttop=&quot;true&quot; 
   android:layout_centerhorizontal=&quot;true&quot; 
   android:layout_height=&quot;wrap_content&quot; 
   android:layout_margin=&quot;20dp&quot; 
   android:layout_width=&quot;fill_parent&quot; 
   &lt;span style=&quot;color: red;&quot;&gt;android:max=&quot;100&quot;&lt;/span&gt; 
   &lt;span style=&quot;color: red;&quot;&gt;style=&quot;android: attr/progressBarStyleHorizontal;&lt;/span&gt;
&quot;/&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;android:max&lt;/span&gt; is the max value of the progress bar and we set its &lt;span style=&quot;color: #6fa8dc;&quot;&gt;style&lt;/span&gt; with the built-in android style of horizontal progress bar.&lt;br /&gt;
&lt;br /&gt;
To change the progress bar with colors you want you need to create a&lt;span style=&quot;color: #6fa8dc;&quot;&gt; layer-list&lt;/span&gt; xml file and save it into &lt;span style=&quot;color: #6fa8dc;&quot;&gt;res/drawable&lt;/span&gt; folder of your project. This xml file will contains the new style of the progress bar that will be attached to it at run time.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&amp;lt;layer-list xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; &amp;gt;
    &amp;lt;item android:id=&quot;@android:id/background&quot;&amp;gt;
        &amp;lt;shape&amp;gt;
            &amp;lt;gradient
                    android:startColor=&quot;#000001&quot;
                    android:centerColor=&quot;#0b131e&quot;
                    android:centerY=&quot;0.75&quot;
                    android:endColor=&quot;#0d1522&quot;
                    android:angle=&quot;270&quot;
            /&amp;gt;
        &amp;lt;/shape&amp;gt;
    &amp;lt;/item&amp;gt;
    &amp;lt;item android:id=&quot;@android:id/progress&quot;&amp;gt;
        &amp;lt;clip&amp;gt;
            &amp;lt;shape&amp;gt;
                &amp;lt;gradient
                    android:startColor=&lt;span style=&quot;color: red;&quot;&gt;&quot;#00ff00&quot;&lt;/span&gt;
                    android:centerColor=&lt;span style=&quot;color: red;&quot;&gt;&quot;#00dd00&quot;&lt;/span&gt;
                    android:centerY=&quot;0.75&quot; 
                    android:endColor=&lt;span style=&quot;color: red;&quot;&gt;&quot;#00bb00&quot;&lt;/span&gt;
                    android:angle=&quot;270&quot;
                /&amp;gt;
            &amp;lt;/shape&amp;gt;
        &amp;lt;/clip&amp;gt;
    &amp;lt;/item&amp;gt;
&amp;lt;/layer-list&amp;gt;&lt;/code&gt;&lt;/pre&gt;
This is the new drawable of the red progress bar, you can replace values with red font with the color you want. In our example you need to create another one for green progress bar.(In the end of this post there is a link for downloading the full project of this example).
&lt;br /&gt;
&lt;br /&gt;
Now we prepared the required files that we need to change the progress bar color and it is time to apply this new style programmatically when the user click the calculate button.&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public void Calculate(View view)
{
  if(view.getId()==R.id.btncalc)
  {
     EditText etcomusers = (EditText)findViewById(R.id.comusersnumber);
     double commiteduser =Double.parseDouble(etcomusers.getText().toString());
      
     EditText ettotcomusers = (EditText)findViewById(R.id.totalcomusersnumber);
     double totalcommiteduser =Double.parseDouble(ettotcomusers.getText().toString());
      
    int percent = (int) ((commiteduser/totalcommiteduser)*100);
      
    ProgressBar myprogressbar = (ProgressBar)findViewById(R.id.myprogressbar);
      
    &lt;span style=&quot;color: darkblue;&quot;&gt;Resources res = getResources();
    Rect bounds = myprogressbar.getProgressDrawable().getBounds();&lt;/span&gt;
      
    if(percent &amp;gt;= 50)
    {
     &lt;span style=&quot;color: green;&quot;&gt;myprogressbar.setProgressDrawable(res.getDrawable(R.drawable.greenprogressbar));&lt;/span&gt;
    }
    else
    {
     &lt;span style=&quot;color: red;&quot;&gt;myprogressbar.setProgressDrawable(res.getDrawable(R.drawable.redprogressbar));&lt;/span&gt;
    }
    &lt;span style=&quot;color: darkblue;&quot;&gt;myprogressbar.getProgressDrawable().setBounds(bounds);
    myprogressbar.setProgress(percent);&lt;/span&gt;
  }
}&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
first section of code for getting the entered values and calculate the committed users percentage. Before changing the progress bar color we need to get the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Bounds&lt;/span&gt; of the current progress drawable to be applied after setting the new &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ProgressDrawable&lt;/span&gt; with new color. If comitted users percentage is greater than 50% we set the&lt;span style=&quot;color: #6fa8dc;&quot;&gt; ProgressDrawable&lt;/span&gt; with the green one else we set it with the red then we set the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Bounds&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Progress&lt;/span&gt; of the progress bar(the length of colored bar).&lt;br /&gt;
&lt;br /&gt;
You can download sample code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzeTQ5WENWTG5iTUU&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/5394638084655602269/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/09/android-how-to-change-progress-bar.html#comment-form' title='10 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5394638084655602269'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5394638084655602269'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/09/android-how-to-change-progress-bar.html' title='Android : How to change progress bar color at runtime programmatically?'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgkQd1T7vsDY1ILGm8uYM8ykT-yXZCy5L8h9D_ssW0TREWsCvuPdBP2vjZjHpNihA1u5shbeq4y86YI-tAWwsUFmDQvaupny79MUUwKJs861RbC4vu1ni0kZ5aPk60ynFjn6x8Lg7eYasjQ/s72-c/redprogressbar.png" height="72" width="72"/><thr:total>10</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.0444196 31.2357116</georss:point><georss:box>29.989439100000002 31.1567476 30.0994001 31.314675599999998</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-5242602282554039716</id><published>2012-08-05T17:21:00.001+02:00</published><updated>2017-05-05T17:03:53.042+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="asp mvc"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="conditional vaidation"/><category scheme="http://www.blogger.com/atom/ns#" term="Required Attribute"/><category scheme="http://www.blogger.com/atom/ns#" term="ValidationAttribute"/><title type='text'>ASP.Net MVC : Conditional Validation using ValidationAttribute</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;

In ASP.Net MVC we can validate each input field by decorating the corresponding property in the model class with some validation attributes like &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Required&lt;/span&gt;, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;MaxLength&lt;/span&gt;, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;MinLength&lt;/span&gt;,...etc. 
&lt;br /&gt;
&lt;br /&gt;
Sometime we need to validate a property according to another property value for example if we have a registration form and we need the user enter his age if he is a male and age not required if the user sex is female. So if we decorated the Age property with &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Required&lt;/span&gt; attribute it will show error message even if the user is female, so we need to bypass this check with females.
&lt;br /&gt;
&lt;br /&gt;
Assume our registration form will contains three fields, name, sex and age, and its model will be as follows
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class RegisterationModel
{
    [Required(ErrorMessage = &quot;*&quot;)]
    public String Name { get; set; }

    [Required(ErrorMessage = &quot;*&quot;)]
    [Display(Name = &quot;Gender&quot;)]
    public Sex Sex { get; set; }

    &lt;b style=&quot;color: #7f0000;&quot;&gt;[RequiredIf(&quot;Sex&quot;, Sex.Male, &quot;enter your age&quot;)]&lt;/b&gt;
    public Int32? Age { get; set; }
}
public enum Sex
{
    Female = 1,
    Male = 2
}
&lt;/code&gt;&lt;/pre&gt;
Note we decorated the Age property with &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RequiredIf&lt;/span&gt; attribute, that we will create and it inherits &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ValidationAttribute&lt;/span&gt; class and override &lt;span style=&quot;color: #6fa8dc;&quot;&gt;IsValid&lt;/span&gt; method.&lt;br /&gt;
&lt;br /&gt;
The&lt;span style=&quot;color: #6fa8dc;&quot;&gt; RequiredIf&lt;/span&gt; attribute accepts three pramaters in its constructor, first parameter is the name of the property will affect the validation (Sex property), second parameter is the value of that property that make the Age is required(Male), and third parameter is the error message that will be displayed if the validation failed.

&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class RequiredIfAttribute : ValidationAttribute
{
    private String PropertyName { get; set; }
    private String ErrorMessage { get; set; }
    private Object DesiredValue { get; set; }

    public RequiredIfAttribute(String propertyName, Object desiredvalue, String errormessage)
    {
        this.PropertyName = propertyName;
        this.DesiredValue = desiredvalue;
        this.ErrorMessage = errormessage;
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        Object instance = context.ObjectInstance;
        Type type = instance.GetType();
        Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
        if (proprtyvalue.ToString() == DesiredValue.ToString() &amp;&amp; value == null)
        {
            return new ValidationResult(ErrorMessage);
        }
        return ValidationResult.Success;
    }
}
&lt;/code&gt;&lt;/pre&gt;
In the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;IsValid&lt;/span&gt; method we get the current instance of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RegisterationModel&lt;/span&gt; class using &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ValidationContext&lt;/span&gt; object and get the value of the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Sex&lt;/span&gt; property then compare it with the desire value(Male) which make the Age is required. If the current value of Sex property equal the desired value then &lt;span style=&quot;color: #3d85c6;&quot;&gt;IsValid&lt;/span&gt; will return new &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ValidationResult&lt;/span&gt; object with the supplied error message.
&lt;br /&gt;
&lt;br /&gt;
Unfortunately this technique is working in server side only. You can download sample code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzVVdoRFdFWFZFOWs&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/5242602282554039716/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/08/aspnet-mvc-conditional-validation-using.html#comment-form' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5242602282554039716'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5242602282554039716'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/08/aspnet-mvc-conditional-validation-using.html' title='ASP.Net MVC : Conditional Validation using ValidationAttribute'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>9</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.0444196 31.2357116</georss:point><georss:box>29.989439100000002 31.1567476 30.0994001 31.314675599999998</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-5858058713877811829</id><published>2012-08-01T15:56:00.000+02:00</published><updated>2018-10-22T21:17:20.690+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Action Attributes"/><category scheme="http://www.blogger.com/atom/ns#" term="ActionMethodSelectorAttribute"/><category scheme="http://www.blogger.com/atom/ns#" term="AJAX"/><category scheme="http://www.blogger.com/atom/ns#" term="asp mvc"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="IsAjaxRequest"/><category scheme="http://www.blogger.com/atom/ns#" term="MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="VB.Net"/><title type='text'>Restrict non-ajax requests using ActionMethodSelectorAttribute</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
In ASP.Net MVC each coming request is routed to a certain action method inside some controller and with JQuery it became piece of cake to call this action method using ajax. In some scenarios we need to restrict the incoming requests to be ajax request only, fortunately ASP.Net MVC represent a new method to&lt;span style=&quot;color: #6fa8dc;&quot;&gt; Request&lt;/span&gt; object called &lt;span style=&quot;color: #6fa8dc;&quot;&gt;IsAjaxRequest()&lt;/span&gt; that return &lt;span style=&quot;color: #6fa8dc;&quot;&gt;true&lt;/span&gt; if the current request come from ajax call and return &lt;span style=&quot;color: #6fa8dc;&quot;&gt;false&lt;/span&gt; if current request is normal request(typing url in address bar of a browser, click a link to this page,..etc).
&lt;br /&gt;
&lt;br /&gt;
We can use that method to deny any request come from ajax call or vise versa.
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class HomeController
{
   public ActionResult Index()
   {
      if(Request.IsAjaxRequest())
      {
        //Do something
      }
      else
      {
        //Do something else
      }
   }
}&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
As we see if we need to make this check many times in our project, we will rewrite the same if statement for each action we need it be called via ajax only, but is there another way to do this check with elegant manner?. One of elegant ways that will save rewriting this if statement is creating a new attribute that will decorate actions to deny any request except ajax request. 
&lt;br /&gt;
&lt;br /&gt;
To create such attribute you must override &lt;span style=&quot;color: #6fa8dc;&quot;&gt;IsValidForRequest&lt;/span&gt; method of &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.web.mvc.actionmethodselectorattribute.aspx&quot;&gt;ActionMethodSelectorAttribute&lt;/a&gt; class. All what you have to do is create a new class, its name will be the name of the new attribute, and it will inherit&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;ActionMethodSelectorAttribute&lt;/span&gt; class, in the overriden &lt;span style=&quot;color: #6fa8dc;&quot;&gt;IsValidForRequest&lt;/span&gt; method you can put your logic, in our case denying non-ajax requests.
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class OnlyAjaxRequestAttribute : ActionMethodSelectorAttribute
    {
        public override Boolean IsValidForRequest(ControllerContext context, MethodInfo info)
        {
            return context.HttpContext.Request.IsAjaxRequest();
        }
    }&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
Now the attribute is ready for decorating the action method
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class HomeController
{
   [OnlyAjaxRequest]
   public ActionResult Index()
   {
      //Do something
   }
}&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
Now you can decorate any action with this attribute to deny normal request.
&lt;br /&gt;
You can find the full source code &lt;a href=&quot;https://github.com/miroprocessor/Mirosoft.Utilities.Mvc&quot;&gt;https://github.com/miroprocessor/Mirosoft.Utilities.Mvc&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/5858058713877811829/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/08/restrict-non-ajax-requests-using.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5858058713877811829'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5858058713877811829'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/08/restrict-non-ajax-requests-using.html' title='Restrict non-ajax requests using ActionMethodSelectorAttribute'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>1</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.0444196 31.2357116</georss:point><georss:box>29.989439100000002 31.1567476 30.0994001 31.314675599999998</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-4561046655303824528</id><published>2012-07-02T19:45:00.001+02:00</published><updated>2012-07-11T13:14:49.820+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Activity"/><category scheme="http://www.blogger.com/atom/ns#" term="Android"/><category scheme="http://www.blogger.com/atom/ns#" term="android 4.x"/><category scheme="http://www.blogger.com/atom/ns#" term="android application"/><category scheme="http://www.blogger.com/atom/ns#" term="Android AVD"/><category scheme="http://www.blogger.com/atom/ns#" term="Android SDK"/><category scheme="http://www.blogger.com/atom/ns#" term="Eclipse"/><category scheme="http://www.blogger.com/atom/ns#" term="run configurations"/><title type='text'>How to create android application?</title><content type='html'>We&amp;nbsp;have already showed &lt;a href=&quot;http://miroprocessordev.blogspot.com/2012/01/how-to-prepare-your-machine-for.html&quot;&gt;how to prepare your machine to develop your android application&lt;/a&gt;&amp;nbsp;now it is the time to check if we prepared our machine successfully and we can write our first android application or not.&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;&lt;br /&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
We will start learning developing android application by writing a simple application that will display &lt;i&gt;&quot;Hello World&quot;&lt;/i&gt; sentence (the most famous example to start learning new tech). Follow the next steps to create your first android application:&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Lunch Eclipse and select File &amp;gt; New &amp;gt; Project you will find a list of available projects templates select &amp;nbsp;android project template then click next, you will see window like this&lt;span style=&quot;background-color: white;&quot;&gt;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiP1YcH3FLiyms9VJ0G5nHbNPjfQ-8sveuPg9ySRUvxo8ZgntlfpvuKftwPjiFgE-n0eri-zoaajErDOSQ9fxbvoWiasEyfbMiaY70G52m1h8-Nfym9pocjkYmb0Fg26VEEngLXPO7hDb5D/s1600/newandroidapp.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;588&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiP1YcH3FLiyms9VJ0G5nHbNPjfQ-8sveuPg9ySRUvxo8ZgntlfpvuKftwPjiFgE-n0eri-zoaajErDOSQ9fxbvoWiasEyfbMiaY70G52m1h8-Nfym9pocjkYmb0Fg26VEEngLXPO7hDb5D/s640/newandroidapp.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;br /&gt;&lt;b&gt;
Application Name&lt;/b&gt; : the name of your applications that will be appear on application list of your device(mobile or tablet)&lt;br /&gt;&lt;b&gt;
Project Name&lt;/b&gt; : the name that will be appear in your eclipse work-space.&lt;br /&gt;&lt;b&gt;
Packaeg Name&lt;/b&gt; : it will be used as identifier for your application and must be unique across all applications.&lt;br /&gt;&lt;b&gt;
Build SDK&lt;/b&gt; : specify which sdk version you will target.&lt;br /&gt;&lt;b&gt;
Minimum required SDK&lt;/b&gt; : specify min sdk version required for running your application.&lt;/li&gt;
&lt;li&gt;In configure launcher icon window, configure the launcher icon of your application or use the default configuration then click next.&amp;nbsp;&lt;/li&gt;
&lt;li&gt;In Create Activity window check &lt;b&gt;Create Activity&lt;/b&gt; chekbox and select &lt;b&gt;BlankActivity&lt;/b&gt;&amp;nbsp;and click next.&lt;br /&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiI8iXsaZkRD0DioDKqauPe3kLG7Nje9CsyRnssFvssZYREa_9RkNO5q9OAuQ3ySEZehBSDKvMcpOyvCXZdju4WqW1wD-kZO-rbNjhRG-3vRcdQwfAeYGaG1tk8Zjdc2r27ISzhEDImRzN2/s1600/createactivity.png&quot; imageanchor=&quot;1&quot; style=&quot;font-weight: normal; margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;592&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiI8iXsaZkRD0DioDKqauPe3kLG7Nje9CsyRnssFvssZYREa_9RkNO5q9OAuQ3ySEZehBSDKvMcpOyvCXZdju4WqW1wD-kZO-rbNjhRG-3vRcdQwfAeYGaG1tk8Zjdc2r27ISzhEDImRzN2/s640/createactivity.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;
&lt;/li&gt;
&lt;li style=&quot;text-align: left;&quot;&gt;In New Blank Activity window, specify the activity name, layout name, and title. this window will appear with default values, for now we will use these default values. Click finish button to create your android project.&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgK1q8EnJ0wfm0vNOwu0lNEiHeGk95JfJVoll_q_BQKG3DDIO0Q5sektyC1eRkvD11mecixk-aFUcHBTVBYqrNI_DDCXztiigAXaPqui5O45Se7-omvNARu7pE6HEiUYh9Nu8B2MnsaX24w/s1600/newblankactivity.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;592&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgK1q8EnJ0wfm0vNOwu0lNEiHeGk95JfJVoll_q_BQKG3DDIO0Q5sektyC1eRkvD11mecixk-aFUcHBTVBYqrNI_DDCXztiigAXaPqui5O45Se7-omvNARu7pE6HEiUYh9Nu8B2MnsaX24w/s640/newblankactivity.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;In Package explorer you will find your &lt;b&gt;HelloAndroid&lt;/b&gt; project, expand &lt;b&gt;src&lt;/b&gt; folder and open &lt;b&gt;MainActivity.java&lt;/b&gt; file replace the code inside &lt;span style=&quot;color: #6fa8dc;&quot;&gt;MainActivity&lt;/span&gt; class with the following code&lt;br /&gt;&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;@Override
public void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  TextView tv = new TextView(this);
  tv.setText(&quot;Hello World!&quot;);
  setContentView(tv);
}&lt;/code&gt;&lt;/pre&gt;
if&lt;span style=&quot;color: #6fa8dc;&quot;&gt; import android.widget.TextView;&lt;/span&gt; statement doesn&#39;t exist, add it.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
Now we have finished creating our first android application that will display &quot;Hello, world&quot;. To run this application we need to create launch configuration and we need also a virtual device on which to run it instead of lunching it on real android device. Follow the following steps :&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;ol&gt;
&lt;li&gt;select Run &amp;gt; Run configuration, in run configuration window double click &lt;b&gt;Android Application&lt;/b&gt; in left pane and rename the configuration &lt;b&gt;HelloAndroidConfig&lt;/b&gt;, click browse and select &lt;b&gt;HelloAndroid &lt;/b&gt;project and leave &lt;b&gt;Launch Default Activity&lt;/b&gt; selected.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjImnZA0wQWRnSJLRxo3Nezlg4bdC1PtPiwiQ4ewXdA3zWcsHKASVzpEFk3cIEgwfUlQlPB4KgnLZYwt62hZ7oM3rIzpVi-LvVTKPvowS_nNZ1JJQckU-1LTpb9-xskyJ2URxvW1QoQvI5P/s1600/runconfiguration.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;484&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjImnZA0wQWRnSJLRxo3Nezlg4bdC1PtPiwiQ4ewXdA3zWcsHKASVzpEFk3cIEgwfUlQlPB4KgnLZYwt62hZ7oM3rIzpVi-LvVTKPvowS_nNZ1JJQckU-1LTpb9-xskyJ2URxvW1QoQvI5P/s640/runconfiguration.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;Click Apply and then Run. Now&amp;nbsp;Eclipse is ready for running your application but you did not create the virtual device yet so it will fire error message &lt;i&gt;&quot;No compatible targets were found. Do you wish to a add new Android Virtual Device?&quot;&lt;/i&gt; click yes.
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBs9NW68uVK0mCHbZMb39GmsagbJlu5S9AK-vD0Vtpl7tjOgq6SzSjuY2BT1Wam4Pd0brYXaYjS7UWG_buU-n_xhGSxNz3SGYK11EIYK1wgoKuMvT9s8sno0nKvYL4B87jbTTAW-RqwQoK/s1600/AVDError.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;184&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBs9NW68uVK0mCHbZMb39GmsagbJlu5S9AK-vD0Vtpl7tjOgq6SzSjuY2BT1Wam4Pd0brYXaYjS7UWG_buU-n_xhGSxNz3SGYK11EIYK1wgoKuMvT9s8sno0nKvYL4B87jbTTAW-RqwQoK/s640/AVDError.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li style=&quot;text-align: left;&quot;&gt;In Android Virtual Device Manager window click new to create one. In Create new Android virtual Device window, name it &lt;b&gt;HelloAndroid2.3.3 &lt;/b&gt;and in target field select &lt;b&gt;Android 2.3.3 - API Level 10&lt;/b&gt;, in SD Card select size and type &lt;b&gt;10&lt;/b&gt; (10 MB) and leave the remaining fields with its default values.
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgllDyEXpv9PnKl-9UPqF3ta_COIqtSyy3Oihz9vezjJpq8hluuPEHTWpQ_jK-9mORnPt8ytUeUxMP9HygWTonYAlohECsDCp-XSZveTToqma8pGBrOExqDzLGE3nziJHubtTnb55CwoMoH/s1600/newandroidVD.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;640&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgllDyEXpv9PnKl-9UPqF3ta_COIqtSyy3Oihz9vezjJpq8hluuPEHTWpQ_jK-9mORnPt8ytUeUxMP9HygWTonYAlohECsDCp-XSZveTToqma8pGBrOExqDzLGE3nziJHubtTnb55CwoMoH/s640/newandroidVD.png&quot; width=&quot;472&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Click Create AVD. it will be displayed &amp;nbsp;in Android Virtual device Manager window. close it by click X in the upper right corner.&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;background-color: white;&quot;&gt;Select Run &amp;gt; Run to run your application, eclipse will &amp;nbsp;start the virtual device (emulator) with your first android application. &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/span&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimfJ5P60ZPkA0z4pTy2ut54mUKixnGJfy-P8nRim1JsRruvjk_KiIeRzefNV_no3sibOFXN0WiLY1SqydzdnSVIAWPyXrYb3OrkBw01zE0ilIJPk14aqNsyQvYLsGU-eNW1L5DHJFhfOJ1/s1600/emulator.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em; text-align: center;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;454&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEimfJ5P60ZPkA0z4pTy2ut54mUKixnGJfy-P8nRim1JsRruvjk_KiIeRzefNV_no3sibOFXN0WiLY1SqydzdnSVIAWPyXrYb3OrkBw01zE0ilIJPk14aqNsyQvYLsGU-eNW1L5DHJFhfOJ1/s640/emulator.png&quot; width=&quot;640&quot; /&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
Previous steps are the main steps to create any android application, you can take this post as a reference for creating android application, configuring your launch configuration and to create android virtual device(emulator) in the future.&lt;/div&gt;
&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div style=&quot;text-align: left;&quot;&gt;
In the next posts we will explore in details what does code we added in this post mean and know more about android framework.&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/4561046655303824528/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/07/your-1st-android-application-hello.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4561046655303824528'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4561046655303824528'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/07/your-1st-android-application-hello.html' title='How to create android application?'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiP1YcH3FLiyms9VJ0G5nHbNPjfQ-8sveuPg9ySRUvxo8ZgntlfpvuKftwPjiFgE-n0eri-zoaajErDOSQ9fxbvoWiasEyfbMiaY70G52m1h8-Nfym9pocjkYmb0Fg26VEEngLXPO7hDb5D/s72-c/newandroidapp.png" height="72" width="72"/><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.0444196 31.2357116</georss:point><georss:box>29.989439100000002 31.1567476 30.0994001 31.314675599999998</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-4373230632989991142</id><published>2012-06-21T16:22:00.000+02:00</published><updated>2012-06-21T16:26:10.225+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Activity"/><category scheme="http://www.blogger.com/atom/ns#" term="Android"/><category scheme="http://www.blogger.com/atom/ns#" term="android 4.x"/><category scheme="http://www.blogger.com/atom/ns#" term="AndroidManifest.xml"/><category scheme="http://www.blogger.com/atom/ns#" term="Content Provider"/><category scheme="http://www.blogger.com/atom/ns#" term="Fragment"/><category scheme="http://www.blogger.com/atom/ns#" term="Ice Cream Sandwich"/><category scheme="http://www.blogger.com/atom/ns#" term="Intent"/><category scheme="http://www.blogger.com/atom/ns#" term="Service"/><title type='text'>Fundamental components of android application</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;

This post is a one of some posts about android platform I will write to explore this platform and learn you(and me) developing android applications for mobiles and tablets devices. You don&#39;t have to own android mobile to create android application, what is you really need is a tool (Emulator) to test and debug your application.&lt;br /&gt;
&lt;br /&gt;
You can refer to this &lt;a href=&quot;http://miroprocessordev.blogspot.com/2012/01/how-to-prepare-your-machine-for.html&quot;&gt;post &lt;/a&gt;&amp;nbsp;where&amp;nbsp;I showed how to prepare your machine to be able to create your android application. That post was written before releasing &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Ice Cream&amp;nbsp;Sandwich&lt;/span&gt;&amp;nbsp;version (android 4.x) but it does not matter, just you should download the latest version of all tools you have to install.&lt;br /&gt;
&lt;br /&gt;
My reference for writing these posts is &lt;a href=&quot;http://www.apress.com/9781430239307&quot;&gt;Pro Android 4&lt;/a&gt; book.&lt;br /&gt;
&lt;br /&gt;
In this post we will explore the key components of android framework which we must understand before delving into coding process.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;View:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
views are user interface(UI) elements such as buttons, labels, text fields, or any other UI element. Views also can contain other views. Anything you see is a view.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Activity:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
Any android application contains at least one activity, each activity represent one screen in you application. An activity is a thing that helps user to do one thing (view, create, or editing data). An activity contains one or more views and also sometimes does not contain any view.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Fragment:&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
Fragments are like sub-activity and an activity can display one or more fragments on the screen at the same time. We use fragments when there are many functionality in one activity.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Intent:&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&amp;nbsp;It defines an intention to do something like starting a service, lunching an activity, or dial a phone number..etc. Intents also used by the system to notify your application of specific events. It can be explicit or implicit and you can provide specific information about what should handle the intention. Intents loosely couple the action and action handler.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Content Provider:&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
It is a standard mechanism for sharing data among mobile application on a device without exposing the underlying storage, structure and implementation. By using &amp;nbsp;content providers you can make your application use data from other applications.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Service:&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
It is a background process that can run for long time. There are two types of &amp;nbsp;services in android&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Local service: that is only&amp;nbsp;accessible&amp;nbsp;by the application host it.&lt;/li&gt;
&lt;li&gt;Remote service: the service that is accessed remotely by other applications on the same device(mobile or tablet).&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;AndroidManifest.xml:&lt;/b&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
like web.xml in J2EE and like web.config in ASP.Net, it defines the contents and behavior of your application. It lists all activities, services, permission, features&amp;nbsp;of your application.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Android Virtual Device(ADV):&lt;/b&gt;&lt;/span&gt;&lt;/div&gt;
&lt;div&gt;
&amp;nbsp;it allows developers to test their application without need to android device. it can be created in various configuration to emulate different types of real devices.&lt;/div&gt;
&lt;div&gt;
&lt;br /&gt;&lt;/div&gt;
&lt;div&gt;
In the next posts we will cover these components in more details.&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/4373230632989991142/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/06/fundamental-components-of-android.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4373230632989991142'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4373230632989991142'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/06/fundamental-components-of-android.html' title='Fundamental components of android application'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.0444196 31.2357116</georss:point><georss:box>29.989439100000002 31.1567476 30.0994001 31.314675599999998</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-7515081123681562434</id><published>2012-05-24T16:30:00.000+02:00</published><updated>2017-05-05T17:10:18.502+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="AJAX"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="JQuery"/><category scheme="http://www.blogger.com/atom/ns#" term="JQuery load()"/><category scheme="http://www.blogger.com/atom/ns#" term="partial page"/><category scheme="http://www.blogger.com/atom/ns#" term="Razor"/><title type='text'>Load partial page in jquery and ASP.Net MVC</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
In this post I will show you how much &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net MVC&lt;/span&gt; and &lt;a href=&quot;http://www.jquery.com/&quot;&gt;JQuery&lt;/a&gt; are making up a dangerous duet and how you can do big tasks in simple way with little efforts. We can take a look at a live example of what we will do in this post. In &lt;a href=&quot;http://www.stackoverflow.com/&quot;&gt;stackoverflow&lt;/a&gt; website specially &lt;a href=&quot;http://www.stackoverflow.com/users&quot;&gt;users&lt;/a&gt; page and &lt;a href=&quot;http://www.stackoverflow.com/tags&quot;&gt;tags&lt;/a&gt; page you will find a text box to search users/tags. the page is loaded with some users info sorted with default setting. if you start to write something in that text box, the users collection will be filtered by the name you entered in ajax&amp;nbsp;manner&amp;nbsp;and ordered&amp;nbsp;alphabetically(ascending).&lt;br /&gt;
&lt;br /&gt;
The issue here is how using the same piece of code that produce the whole page when it be loaded in first time to filter the users when you type some letters in the text box and update just the part that display the users data. Here the magic of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net MVC&lt;/span&gt; and&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;JQuery&lt;/span&gt;&amp;nbsp;come to the scene.&lt;br /&gt;
&lt;br /&gt;
Lets start to build our page first then start to filter our users collection. I will not show you how to create new &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net MVC&lt;/span&gt; project this is beyond of scope of this post. I will concentrate on the pieces of code that serve the purpose of this post.&lt;br /&gt;
&lt;br /&gt;
In the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HomeController&lt;/span&gt; class we will add &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Index()&lt;/span&gt; method that will display all users into a view but we will add an optional string parameter called &lt;span style=&quot;color: #6fa8dc;&quot;&gt;name&lt;/span&gt; that I will use to filter users collection.&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class HomeController
{
   public ActionResult Index(String name = &quot;&quot;)
   {
      List&amp;lt;user&amp;gt; users = GetUsers()
                           .Where(u =&amp;gt; u.Name.ToLower().StartWith(name.ToLower()) 
                                    || String.IsNullOrEmpty(search)).ToList();
      return view(users);
   }
}&lt;/code&gt;&lt;/pre&gt;
Note, in &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Where&lt;/span&gt; method we select users who their name starts with the value of name variable or select all users if name variable is empty string and return the result into strongly typed view like this
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;@model List&amp;lt;user&amp;gt;
.
.
.
&amp;lt;body&amp;gt;
&amp;lt;center&amp;gt;
    &amp;lt;div&amp;gt;
        Find :
        &amp;lt;input type=&quot;text&quot; name=&quot;search&quot; id=&quot;search&quot; /&amp;gt;
    &amp;lt;/div&amp;gt;
    &amp;lt;/center&amp;gt;
    &amp;lt;br /&amp;gt;
    &amp;lt;div id=&quot;usersdiv&quot;&amp;gt;
        &amp;lt;table align=&quot;center&quot; width=&quot;30%&quot; cellspacing=&quot;0&quot;&amp;gt;
            &amp;lt;tr&amp;gt;
                &amp;lt;td style=&quot;border-bottom: 1px solid #000&quot;&amp;gt;
                    ID
                &amp;lt;/td&amp;gt;
                &amp;lt;td style=&quot;border-bottom: 1px solid #000&quot;&amp;gt;
                    Name
                &amp;lt;/td&amp;gt;
                &amp;lt;td style=&quot;border-bottom: 1px solid #000&quot;&amp;gt;
                    Age
                &amp;lt;/td&amp;gt;
            &amp;lt;/tr&amp;gt;
            @foreach (var user in Model)
            {
                &amp;lt;tr&amp;gt;
                    &amp;lt;td style=&quot;border-bottom: 1px solid #000&quot;&amp;gt;@user.ID
                    &amp;lt;/td&amp;gt;
                    &amp;lt;td style=&quot;border-bottom: 1px solid #000&quot;&amp;gt;@user.Name
                    &amp;lt;/td&amp;gt;
                    &amp;lt;td style=&quot;border-bottom: 1px solid #000&quot;&amp;gt;@user.Age
                    &amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
            }
        &amp;lt;/table&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/body&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;amp;format=728x90_as&amp;amp;output=html&amp;amp;h=90&amp;amp;w=728&amp;amp;lmt=1337862628&amp;amp;host=pub-1556223355139109&amp;amp;h_ch=L0202%2BS0013&amp;amp;alternate_ad_url=http%3A%2F%2Fimg2.blogblog.com%2Fimg%2Fblogger_ad.html&amp;amp;flash=11.2.202&amp;amp;url=http%3A%2F%2Fmiroprocessordev.blogspot.com%2F2012%2F05%2Fload-partial-page-in-jquery-and-aspnet.html&amp;amp;dt=1337869678526&amp;amp;shv=r20100101&amp;amp;jsv=r20100101&amp;amp;correlator=1337869678586&amp;amp;pv_h_ch=L0202&amp;amp;frm=4&amp;amp;adk=2737856453&amp;amp;ga_vid=1910128048.1330525087&amp;amp;ga_sid=1337864538&amp;amp;ga_hid=1916648062&amp;amp;ga_fc=1&amp;amp;u_tz=120&amp;amp;u_his=1&amp;amp;u_java=1&amp;amp;u_h=900&amp;amp;u_w=1440&amp;amp;u_ah=870&amp;amp;u_aw=1440&amp;amp;u_cd=32&amp;amp;u_nplug=16&amp;amp;u_nmime=98&amp;amp;biw=1440&amp;amp;bih=785&amp;amp;ref=http%3A%2F%2Fwww.blogger.com%2Fblogger.g%3FblogID%3D8395299768708339226&amp;amp;loc=http%3A%2F%2Fmiroprocessordev.blogspot.com%2F2012%2F05%2Fload-partial-page-in-jquery-and-aspnet.html&amp;amp;fu=0&amp;amp;js=uds&amp;amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;

Till now we just display all users into a view that contains an extra textbox for filtering users. Now we will start to add the required scripts that will actually do filter by an ajax call to the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Index&lt;/span&gt; method, the method that has been called when page loaded.
in the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;head&lt;/span&gt; tag of our view we will add the following scripts
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&amp;lt;script src=&quot;@Url.Content(&quot;https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js&quot;)&quot; type=&quot;text/javascript&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script type=&quot;text/javascript&quot;&amp;gt;
    $(document).ready(function () {
         $(&#39;#search&#39;).keyup(function () {
             $(&#39;#usersdiv&#39;).load(&#39;/home?name=&#39; + $(this).val());
         });
    });
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;
First we load jquery library itself then we declare the script that will run after loading all DOM objects of the page. We attach &lt;span style=&quot;color: #6fa8dc;&quot;&gt;keyup&lt;/span&gt; event to the textbox to filter the users list each time we type something into textbox. &lt;a href=&quot;http://api.jquery.com/load/&quot;&gt;load&lt;/a&gt; function is a jquery function that load data from the server and place the returned HTML into the matched element(using ajax call). Notice the argument that load function accept, it the url of the current page with query string(name). We set the query string paramter to the value of the textbox, that is the reason we attached &lt;span style=&quot;color: #6fa8dc;&quot;&gt;keyup&lt;/span&gt; event not another event, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;keypress&lt;/span&gt; event for example, to get the last value of the textbox.&lt;br /&gt;
&lt;br /&gt;
If we run this code as it is, that means we will load the whole html of our view into the div element with id &lt;span style=&quot;color: #6fa8dc;&quot;&gt;usersdiv&lt;/span&gt;. But what we need is to update just the part that displays the users list. Here the magic of jquery come, we can select certain part of returned html by appending a selector to the url parameter as follows
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;$(&#39;#usersdiv&#39;).load(&#39;/home?name=&#39; + $(this).val() + &#39; #usersdiv&#39;);
&lt;/code&gt;&lt;/pre&gt;
Of course you can use any valid jquery selector&lt;br /&gt;
Now we can filter the users list using jquery without writting any extra piece of code in server side and without reloading the whole page.&lt;br /&gt;
Thanks for the awesome duet, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net MVC&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;JQuery&lt;/span&gt;.
&lt;br /&gt;
&lt;br /&gt;
you can download the full source code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzNGN2SzhBejlhbjQ&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/7515081123681562434/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/05/load-partial-page-in-jquery-and-aspnet.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/7515081123681562434'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/7515081123681562434'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/05/load-partial-page-in-jquery-and-aspnet.html' title='Load partial page in jquery and ASP.Net MVC'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.0444196 31.2357116</georss:point><georss:box>29.989439100000002 31.1567476 30.0994001 31.314675599999998</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-5459209907411245911</id><published>2012-04-26T17:52:00.001+02:00</published><updated>2017-05-05T17:12:48.832+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="CheckBoxList"/><category scheme="http://www.blogger.com/atom/ns#" term="MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="Razor"/><category scheme="http://www.blogger.com/atom/ns#" term="TagBuilder"/><title type='text'>Generic CheckBoxList in ASP.Net MVC</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
&lt;link href=&quot;http://csharpindepth.com/codestyles.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;&lt;/link&gt;

In &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net&lt;/span&gt;&amp;nbsp;web forms you can easily create a list of check boxes and bind it into a data collection using &lt;span style=&quot;color: #6fa8dc;&quot;&gt;CheckBoxList&lt;/span&gt; control and specify which property will be the text of each check box and which one will be the value of the check box. You even don&#39;t need to write it, you can drag it from tools window, drop it into your page and set its properties and style with wizards that Visual studio provide.&lt;br /&gt;
&lt;br /&gt;
But in &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net MVC&lt;/span&gt; there is no any server controls like that exists in web forms, all what we have is a helper methods to create HTML tags. In&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net MVC&lt;/span&gt; we have two helpers methods for creating a check box, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Html.CheckBox&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Html.CheckBoxFor&lt;/span&gt; that will be rendered as just one check box. If we want to create many check boxes or check boxes list we can call it inside a loop as follows
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;@foreach (var item in MyCollection)
{
   @Html.CheckBox(&quot;checkBoxName&quot;, new {value=item.checkBoxValue })@item.CheckBoxText&amp;lt;br /&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;
Here is a generic extension method for create a check boxes list in an elegant manner.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public static MvcHtmlString CheckBoxList&amp;lt;T&amp;gt;(this HtmlHelper helper,
                                               String name,
                                               IEnumerable&amp;lt;T&amp;gt; items,
                                               String textField,
                                               String valueField,
                                               IEnumerable&amp;lt;T&amp;gt; selectedItems=null)
{
  Type itemstype = typeof(T);
  PropertyInfo textfieldInfo = itemstype.GetProperty(textField,typeof(String));
  PropertyInfo valuefieldInfo = itemstype.GetProperty(valueField);

  TagBuilder tag;
  StringBuilder checklist = new StringBuilder();
  foreach(var item in items)
  {
      tag = new TagBuilder(&quot;input&quot;);
      tag.Attributes[&quot;type&quot;] = &quot;checkbox&quot;;
      tag.Attributes[&quot;value&quot;] = valuefieldInfo.GetValue(item,null).ToString();
      tag.Attributes[&quot;name&quot;] = name;
      if (selectedItems != null &amp;amp;&amp;amp; selectedItems.Contains(item))
      {
          tag.Attributes[&quot;checked&quot;] = &quot;checked&quot;;
      }
      tag.InnerHtml = textfieldInfo.GetValue(item,null).ToString();
      checklist.Append(tag.ToString());
      checklist.Append(&quot;&amp;lt;br /&amp;gt;&quot;);
  }
  return MvcHtmlString.Create(checklist.ToString());
}
&lt;/code&gt;&lt;/pre&gt;
In the first three lines we get the type of the data collection then get the property info of text field and value field that will be used to create each check box. We&amp;nbsp;enumerate over the input data collection and use&amp;nbsp;&lt;a href=&quot;http://www.asp.net/mvc/tutorials/older-versions/views/using-the-tagbuilder-class-to-build-html-helpers-cs&quot;&gt;TagBuilder&lt;/a&gt; class to create input tag and set its attributes like type,name, and value. We check the selectedItems collection to set checked attribute of our check box.
&lt;br /&gt;
&lt;div class=&quot;adsense&quot; data-alternateurl=&quot;http://img2.blogblog.com/img/blogger_ad.html&quot; data-client=&quot;pub-5399953879255109&quot; data-format=&quot;leaderboard&quot; data-host=&quot;pub-1556223355139109&quot; data-maxheight=&quot;&quot; data-maxwidth=&quot;&quot; data-type=&quot;&quot; data-url=&quot;http://miroprocessordev.blogspot.com/2012/04/generic-checkboxlist-in-aspnet-mvc-3.html&quot;&gt;
&lt;iframe frameborder=&quot;0&quot; height=&quot;90&quot; marginheight=&quot;0&quot; marginwidth=&quot;0&quot; scrolling=&quot;no&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;amp;format=728x90_as&amp;amp;output=html&amp;amp;h=90&amp;amp;w=728&amp;amp;lmt=1335448485&amp;amp;host=pub-1556223355139109&amp;amp;h_ch=L0202%2BS0013&amp;amp;alternate_ad_url=http%3A%2F%2Fimg2.blogblog.com%2Fimg%2Fblogger_ad.html&amp;amp;flash=11.2.202&amp;amp;url=http%3A%2F%2Fmiroprocessordev.blogspot.com%2F2012%2F04%2Fgeneric-checkboxlist-in-aspnet-mvc-3.html&amp;amp;dt=1335455603789&amp;amp;shv=r20100101&amp;amp;jsv=r20100101&amp;amp;correlator=1335455603797&amp;amp;pv_h_ch=L0202&amp;amp;frm=4&amp;amp;adk=2737856453&amp;amp;ga_vid=1910128048.1330525087&amp;amp;ga_sid=1335454938&amp;amp;ga_hid=1066998485&amp;amp;ga_fc=1&amp;amp;u_tz=120&amp;amp;u_his=4&amp;amp;u_java=1&amp;amp;u_h=900&amp;amp;u_w=1440&amp;amp;u_ah=870&amp;amp;u_aw=1440&amp;amp;u_cd=32&amp;amp;u_nplug=15&amp;amp;u_nmime=97&amp;amp;biw=1440&amp;amp;bih=785&amp;amp;ref=http%3A%2F%2Fmiroprocessordev.blogspot.com%2F2012%2F04%2Fgeneric-checkboxlist-in-aspnet-mvc-3.html&amp;amp;loc=http%3A%2F%2Fmiroprocessordev.blogspot.com%2F2012%2F04%2Fgeneric-checkboxlist-in-aspnet-mvc-3.html&amp;amp;fu=0&amp;amp;js=uds&amp;amp;eid=37464000&quot; style=&quot;visibility: visible;&quot; width=&quot;728&quot;&gt;&lt;/iframe&gt;&lt;/div&gt;
Say we have a list of users that we display it as checkboxlist to select some users, we can use our helper method as follows
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;@Html.CheckBoxList(&quot;SelectedUsers&quot;, AllUsersList, &quot;Name&quot;, &quot;ID&quot;)&lt;/code&gt;&lt;/pre&gt;
To get the values of checked users we have two scenarios:
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Strongly typed model scenario:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
The model must have property with the same name that we provided to our helper method.
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;class MyModel
{
   //Note you can define it as array of strings, dates or any primitive data type 
   //according to the type of the property of value field.
   Public Int32[] SelectedUsers{get; set;}
}&lt;/code&gt;&lt;/pre&gt;
when we post the view, the model binder will bind the values of selected check boxes into the property with the same name.
&lt;/li&gt;
&lt;li&gt;&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Not Strongly typed model scenario:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
In this case, our action method that will handle our request(decorated by &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HttpPost&lt;/span&gt; attribute) should be defined to accept a &lt;span style=&quot;color: #6fa8dc;&quot;&gt;FormCollection&lt;/span&gt; parameter that will contain key with the same name we provided to our helper method
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;[HttpPost]
public ActionResult ActionMethodName(FormCollection myForm)
{
  String selectedusers = myForm[&quot;SelectedUsers&quot;];
  //Note this will return the selected users ids as comma separated string.
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
You can download sample code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzMmpLM2NqeXRFQWs&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/5459209907411245911/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/04/generic-checkboxlist-in-aspnet-mvc-3.html#comment-form' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5459209907411245911'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5459209907411245911'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/04/generic-checkboxlist-in-aspnet-mvc-3.html' title='Generic CheckBoxList in ASP.Net MVC'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>4</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-3900874668089526688</id><published>2012-04-18T14:47:00.001+02:00</published><updated>2017-05-05T17:14:32.624+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Generic Sorter"/><category scheme="http://www.blogger.com/atom/ns#" term="Lambda Expression"/><category scheme="http://www.blogger.com/atom/ns#" term="Linq"/><category scheme="http://www.blogger.com/atom/ns#" term="OrderBy"/><category scheme="http://www.blogger.com/atom/ns#" term="OrderByDesccending"/><title type='text'>Generic Lambda Expression to sort collections of different types</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
Suppose you have many collections with different types that you want to sort, of course you can do it by &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OrderBy&lt;/span&gt; or &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OrderByDescending&lt;/span&gt; extension methods but you have to specify the order criteria every time you call these methods. If the order criteria is determined in runtime, then you have to build a separate function to each order criteria of each type. To clear what I want to tell you suppose you have two classes,&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Employee&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Department&lt;/span&gt;.&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class Employee
{
    public String Name { get; set; }
    public Int32 Age { get; set; }
    public DateTime HiringDate { get; set; }
}

public class Department
{
    public String DepartmentName { get; set; }
    public String Code { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
And you want to order the employee collection by one of its properties (Name,Age,or HiringDate) and order department collection by one of its properties.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;OrderBy&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OrderByDescending&lt;/span&gt; methods need &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Func&amp;lt;TSource,TKey&amp;gt;&lt;/span&gt; as selector to compare the collection items and order them. So the issue here is, How do you create a generic&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Func&amp;lt;TSource,TKey&amp;gt;&lt;/span&gt; to be passed to &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OrderBy&lt;/span&gt; or&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;OrderByDescending&lt;/span&gt; methods? The answer is, by using &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.lambda.aspx&quot;&gt;Expression.Lambda&lt;/a&gt; method.
&lt;br /&gt;
&lt;br /&gt;
We will create a generic method with one string argument which will be the name of the property that we will order by and the return will be Lambda expression will be passed to &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OrderBy&lt;/span&gt; or &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OrderByDescending&lt;/span&gt;.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public Func&amp;lt;T, Object&amp;gt; GetExpression&amp;lt;T&amp;gt;(String sortby)
{
    var param = Expression.Parameter(typeof(T));
    var sortExpression = Expression.Lambda&amp;lt;Func&amp;lt;T, Object&amp;gt;&amp;gt;(Expression.Convert(Expression.Property(param, sortby), typeof(Object)), param);
    return sortExpression.Compile();
}
&lt;/code&gt;&lt;/pre&gt;
The &lt;span style=&quot;color: #6fa8dc;&quot;&gt;GetExpression&lt;/span&gt; method do the following:
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Create &lt;span style=&quot;color: #6fa8dc;&quot;&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/system.linq.expressions.parameterexpression.aspx&quot;&gt;ParameterExpression&lt;/a&gt;&lt;/span&gt; object by calling &lt;span style=&quot;color: #6fa8dc;&quot;&gt;&lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb355908.aspx&quot;&gt;Expression.Parameter&lt;/a&gt;&lt;/span&gt; method which accepts the type of the collection we want to sort.&lt;/li&gt;
&lt;li&gt;Create the Lambda expression tree.&lt;/li&gt;
&lt;li&gt;Compile the lambda expression by calling &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/bb345362.aspx&quot;&gt;Expression.Compile&lt;/a&gt; method and return a delegate that represent the lambda expression.&lt;/li&gt;
&lt;/ol&gt;
To test &lt;span style=&quot;color: #6fa8dc;&quot;&gt;GetExpression&lt;/span&gt; method we can call &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OrderBy&lt;/span&gt; extension method of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Employee&lt;/span&gt; collection or &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Department&lt;/span&gt; collection as follows&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;employees.OrderBy(GetExpression&lt;employee&gt;(&quot;Age&quot;));
departments.OrderBy(GetExpression&lt;department&gt;(&quot;Code&quot;));&lt;/department&gt;&lt;/employee&gt;&lt;/code&gt;&lt;/pre&gt;
First line will order employees by according to their ages and the second line will order departments by its codes.
&lt;br /&gt;
&lt;br /&gt;
you can download the full source code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzdERTQkVKblhMb00&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/3900874668089526688/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/04/generic-func-to-sort-collections-of_18.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/3900874668089526688'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/3900874668089526688'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/04/generic-func-to-sort-collections-of_18.html' title='Generic Lambda Expression to sort collections of different types'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>3</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-1548597024311891361</id><published>2012-04-04T17:24:00.001+02:00</published><updated>2017-05-05T17:15:48.048+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="GridView"/><category scheme="http://www.blogger.com/atom/ns#" term="GridView Events"/><category scheme="http://www.blogger.com/atom/ns#" term="Nested GridView"/><category scheme="http://www.blogger.com/atom/ns#" term="OnRowCommand"/><title type='text'>How to fire RowCommand event of nested GridView?</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
In ASP.Net you can use a Repeater or GridView controls to simply display any data collection came from any data source(database,XML file,...etc). Sometimes each item of that collection has a property that is another collection and to display it you will use another Repeater or another GridView(nested Repeater or nested GridView).
&lt;br /&gt;
&lt;br /&gt;
To edit, delete or to execute a command on any GridView row you use &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OnRowCommand&lt;/span&gt; event to handle it, but what about the commands on the child(nested) GridView rows. In case of nested Repeater you can set the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OnItemCommand&lt;/span&gt; event of the child Repeater. You can find many articles explain how to do that. The problem which my friend faced is handling the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OnRowCommand&lt;/span&gt; event of nested GridView. We googled it but we didn&#39;t find a lot of article that explain how to handle it, so I write this post to help any one facing the same issue.
&lt;br /&gt;
&lt;br /&gt;
Assume we have a set of Inventories, each Inventory have a set of products. To display All inventories with all products of each one, we will use a GridView for inventories main properties and a nest GridView to list the products of each inventory.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;class Inventory
{
    public String Name { get; set; }
    public Int32 Id { get; set; }
    public List&amp;lt;Product&amp;gt; Products { get; set; }
}
class Product
{
    public String Name { get; set; }
    public Int32 Id { get; set; }
    public Int32 Quantity { get; set; }
}&lt;/code&gt;&lt;/pre&gt;
The following image shows our GridView. Note the third column lists the products of an inventory, the forth column in the products grid is button to delete the corresponding product. This is the command that we want to execute.
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibWz7dL7NMzT0bbRXUC7pDaeDMrIQBZWsSC5QQvuBqbqYCOysOXRgYpMtMZj7P0kcncwAxnlMMtK3euxt8czAveFeopTCCMsqK-RQj5_kZWeu41E5gn-vYeLmJJhw2ZRQD8P2gqB0UMmXn/s1600/GridView.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;136&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibWz7dL7NMzT0bbRXUC7pDaeDMrIQBZWsSC5QQvuBqbqYCOysOXRgYpMtMZj7P0kcncwAxnlMMtK3euxt8czAveFeopTCCMsqK-RQj5_kZWeu41E5gn-vYeLmJJhw2ZRQD8P2gqB0UMmXn/s320/GridView.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;format=728x90_as&amp;output=html&amp;h=90&amp;w=728&amp;host=pub-1556223355139109&amp;h_ch=L0202+S0013&amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;flash=11.2.202&amp;url=http://miroprocessordev.blogspot.com/2012/04/how-to-fire-rowcommand-event-of-nested.html&amp;dt=1334674686309&amp;shv=r20100101&amp;jsv=r20100101&amp;correlator=1334674686313&amp;pv_h_ch=L0202+S0013&amp;frm=4&amp;adk=2737856453&amp;ga_vid=1910128048.1330525087&amp;ga_sid=1334674682&amp;ga_hid=81698892&amp;ga_fc=1&amp;u_tz=120&amp;u_his=6&amp;u_java=1&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=32&amp;u_nplug=15&amp;u_nmime=97&amp;biw=1440&amp;bih=785&amp;loc=http://miroprocessordev.blogspot.com/&amp;fu=0&amp;js=uds&amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;


We will bind the GridView of products inside the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OnRowDataBound&lt;/span&gt; event of the parent GridView.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;protected void inventoriesGrid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        GridView productsGrid = e.Row.FindControl(&quot;productsGrid&quot;) as GridView;
        productsGrid.DataSource = (e.Row.DataItem as Inventory).Products;
        productsGrid.DataBind();
        //productsGrid.RowCommand += new GridViewCommandEventHandler(productsGrid_RowCommand);
    }
}
&lt;/code&gt;&lt;/pre&gt;
In this event we do the following for each row of inventories GridView&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Check the&lt;span style=&quot;color: #6fa8dc;&quot;&gt; RowType&lt;/span&gt;, it must be &lt;span style=&quot;color: #6fa8dc;&quot;&gt;DataRow&lt;/span&gt;.&lt;/li&gt;
&lt;li&gt;Finding the child GridView by its &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ID&lt;/span&gt; property.&lt;/li&gt;
&lt;li&gt;Set the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;DataSource&lt;/span&gt; property of products GridView to the product list of current inventory.&lt;/li&gt;
&lt;li&gt;Call &lt;span style=&quot;color: #6fa8dc;&quot;&gt;DataBind&lt;/span&gt; method of products GridView.&lt;/li&gt;
&lt;/ol&gt;
If you uncommented the commented line, that will wire the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowCommand&lt;/span&gt; event of products GridView to&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;productsGrid_RowCommand&lt;/span&gt; event but when you will run your code this event will never be fired. &lt;span style=&quot;color: #cc0000;&quot;&gt;&lt;b&gt;Why???&lt;/b&gt;.&lt;/span&gt; To answer this question we have two scenarios :&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;If you bind the parent GridView every time you load the page, so you re-fire its &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowDataBound&lt;/span&gt; event every time and re-wire the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowCommand&lt;/span&gt; of child GridView again and again. That changes the view state of the child GridView and its &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowCommand&lt;/span&gt; will not be fired( in PostBack ASP.Net read the old view state which is changed while binding the parent grid).&lt;/li&gt;
&lt;li&gt;If you bind the parent grid in first time you request the page(the current request is not a post back) so the&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowDataBound&lt;/span&gt;&amp;nbsp;will not fired while post back. You think that will solve the problem, No that will not solve it because the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowCreated&lt;/span&gt; event of parent GridView be fired every request even if it is postback. That means you need to re-wire the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowCommand&lt;/span&gt; of child GridView again.&lt;/li&gt;
&lt;/ol&gt;
&lt;div&gt;
The best place to wire the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowCommand&lt;/span&gt; of child GridView is to write this code inside the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowCreated&lt;/span&gt; event of parent GridView because this event be fired after the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Page_Load&lt;/span&gt; and before handling post back event. This&amp;nbsp;guarantee&amp;nbsp;the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowCommand&lt;/span&gt; of child GridView is wired to the same event before handling it.&lt;/div&gt;
&lt;br /&gt;
Again you need to find the child GridView by its ID property but this time inside the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RowCreated&lt;/span&gt; event of the parent GridView.&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;protected void inventoriesGrid_RowCreated(Object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        productsGrid = e.Row.FindControl(&quot;productsGrid&quot;) as GridView;
        productsGrid.RowCommand += new GridViewCommandEventHandler(productsGrid_RowCommand);
    }
}
&lt;/code&gt;&lt;/pre&gt;
The RowCommand event of child GridView (products) its self &lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;protected void productsGrid_RowCommand(Object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == &quot;deleteitem&quot;)
    {
        //Do whatever you want
    }
}
&lt;/code&gt;&lt;/pre&gt;
you can download the full source code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzdm8yZ0loR2dsQzg&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/1548597024311891361/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/04/how-to-fire-rowcommand-event-of-nested.html#comment-form' title='16 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/1548597024311891361'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/1548597024311891361'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/04/how-to-fire-rowcommand-event-of-nested.html' title='How to fire RowCommand event of nested GridView?'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibWz7dL7NMzT0bbRXUC7pDaeDMrIQBZWsSC5QQvuBqbqYCOysOXRgYpMtMZj7P0kcncwAxnlMMtK3euxt8czAveFeopTCCMsqK-RQj5_kZWeu41E5gn-vYeLmJJhw2ZRQD8P2gqB0UMmXn/s72-c/GridView.png" height="72" width="72"/><thr:total>16</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.030745 31.2159537 30.058235 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-5450620769898317782</id><published>2012-03-26T19:26:00.000+02:00</published><updated>2012-03-26T19:32:00.432+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="AntiForgeryToken"/><category scheme="http://www.blogger.com/atom/ns#" term="Cross Site MVC Request Forgery cross site attacks ASP.Net Javascript injection ASP.Net MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="HttpOnly"/><category scheme="http://www.blogger.com/atom/ns#" term="NonAction"/><category scheme="http://www.blogger.com/atom/ns#" term="session Hijacking"/><title type='text'>Safe ASP.Net MVC application against cross site attacks - 2</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Session Hijacking:&lt;/span&gt;&lt;/b&gt;
&lt;br /&gt;
ASP.Net identifies users by session ID cookie which called &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net_SessionId&lt;/span&gt; by default, and if we use Forms Authentication, then a second cookie is used called &lt;span style=&quot;color: #6fa8dc;&quot;&gt;.ASPXAUTH&lt;/span&gt;. If an attacker can obtain these cookies, then they can include them in a request to our server and impersonate one of our users. The browser by default preventing the javascript from a site to access cookies of another site. But if the attacker has been able to inject a script into one of our pages, then the browser believes that the script is part of our application and grands access to the session cookies.&lt;br /&gt;
&lt;br /&gt;
We can protect our site by keeping a record of each client IP address when a session starts, we can deny any requests that originate from a different IP. But you should avoid this technique when you deal with the public internet.&lt;br /&gt;
&lt;br /&gt;
We can mark a cookie with the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HttpOnly&lt;/span&gt; flag, and the browser will hide its existence from javascript but will continue to send it via all HTTP requests. By default ASP.Net marks &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net_SessionId&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;.ASPXAUTH&lt;/span&gt; as &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HttpOnly&lt;/span&gt;. Of course you can apply&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;HttpOnly&lt;/span&gt; to&amp;nbsp;your session cookies when you create them.
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Cross-Site Request Forgery (CSRF):&lt;/span&gt;&lt;/b&gt;
&lt;br /&gt;
Unfortunately, anyone can mount a devastating attack by enticing our users to visit an &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HTML&lt;/span&gt; page which is hosted in external domain. When the exploit page loads, it simply sends a valid form submissions to our post-handling action method. The exploit can easily hide its actions, for example by submitting the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;POST&lt;/span&gt; request using &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Ajax&lt;/span&gt;.&lt;br /&gt;
&lt;br /&gt;
There are two main strategies to defend against &lt;span style=&quot;color: #6fa8dc;&quot;&gt;CSRF&lt;/span&gt; attacks:
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;i&gt;Validate the incoming HTTP Referrer header&lt;/i&gt;: If we check it and find it referencing an unexpected third-party domain, we know that it&#39;s a cross site attack.&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Require some user-specific token to be included in sensitive requests.&lt;/i&gt;&lt;/li&gt;
&lt;/ol&gt;
A better option is to have our server generate a secrete user-specific token, put it in hidden field and then check that the token is present and correct when the form is submitted. Fortunately, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;MVC Framework&lt;/span&gt; has a ready made implementation for this technique.
&lt;br /&gt;
&lt;br /&gt;
You can detect and &amp;nbsp;deny &lt;span style=&quot;color: #6fa8dc;&quot;&gt;CSRF&lt;/span&gt; attacks by combining &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Html.AntiForgeryToken()&lt;/span&gt;&amp;nbsp;helper and its &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ValidateAntiForgeryToken&lt;/span&gt; filter that decorate the target action method. &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Html.AntiForgeryToken()&amp;nbsp;&lt;/span&gt;will render a hidden field with name &amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;__RequestVerificationToken&lt;/span&gt; and in the same time it will give the user a cookie whose name begins with&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;__RequestVerificationToken&lt;/span&gt;. This cookie will contain the same random value as the corresponding hidden field. This value remains constant throughout the the visitor&#39;s browsing session. We must validate incoming form submissions by decorating the target action method with&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;ValidateAntiForgeryToken&lt;/span&gt;&amp;nbsp;attribute. If the values of incoming hidden field does not match the value of the cookie, The MVC Framework will throw an exception and block the request.&lt;br /&gt;
&lt;br /&gt;
The &lt;span style=&quot;color: #6fa8dc;&quot;&gt;MVC&lt;/span&gt; anti-forgery system has the following features too:
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;The cookie name has a suffix that varies according to the name of your application&#39;s virtual directory.&lt;/li&gt;
&lt;li&gt;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Html.AntiForgeyToken()&lt;/span&gt; accepts optional path and domain parameters that controls which URLs are allowed to see the cookie.&lt;/li&gt;
&lt;li&gt;The&amp;nbsp;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;__RequestVerificationToken &lt;/span&gt;hidden field value will also contain &amp;nbsp;the user name of logged user obtained from &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HttpContext.User.Identity.Name&amp;nbsp;&lt;/span&gt;(if user logged in).&amp;nbsp;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;ValidateAntiForgeryToken&lt;/span&gt;&amp;nbsp;attribute will match the random value and also will match the logged user name.&lt;/li&gt;
&lt;/ul&gt;
The &lt;span style=&quot;color: #6fa8dc;&quot;&gt;MVC&lt;/span&gt; anti-forgery system has a few limitation:&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Legitimate users&#39; browsers must accept cookies, or&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;ValidateAntiForgeryToken&lt;/span&gt;&amp;nbsp;attribute always throw an exception an block the request.&lt;/li&gt;
&lt;li&gt;It works only with forms submitted as POST requests not GET requests. That should not cause any problem because GET request must not change any data, just read.&lt;/li&gt;
&lt;li&gt;If you have any weak point in your application, XSS attackers can use it to get the random token generated by&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Html.AntiForgeyToken()&lt;/span&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Build your MVC application securely:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Don&#39;t write any public method inside a controller class that will not be an action method. By default any public method is an action method, other methods should be wrote in model section. If you have to write a method that will not be an action, make sure it will be &lt;i&gt;private &lt;/i&gt;or make it public but you must decorate it with &lt;span style=&quot;color: #6fa8dc;&quot;&gt;NonAction&lt;/span&gt; attribute.&lt;/li&gt;
&lt;li&gt;Prevent &amp;nbsp;Model Binding to change sensitive data by using &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Bind&lt;/span&gt; attribute to set up white/black list that restrict which properties model binding is allowed/not allowed to populate.&lt;/li&gt;
&lt;/ol&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;
&lt;a href=&quot;http://miroprocessordev.blogspot.com/2012/03/save-aspnet-mvc-application-against.html&quot;&gt;1&lt;/a&gt; 2&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/5450620769898317782/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/03/safe-aspnet-mvc-application-against.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5450620769898317782'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/5450620769898317782'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/03/safe-aspnet-mvc-application-against.html' title='Safe ASP.Net MVC application against cross site attacks - 2'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-1720174802463490669</id><published>2012-03-26T16:27:00.000+02:00</published><updated>2012-03-26T19:30:58.577+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net"/><category scheme="http://www.blogger.com/atom/ns#" term="ASP.Net MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="Cross Site"/><category scheme="http://www.blogger.com/atom/ns#" term="cross site attacks"/><category scheme="http://www.blogger.com/atom/ns#" term="Javascript injection"/><category scheme="http://www.blogger.com/atom/ns#" term="MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="Request Forgery"/><title type='text'>Safe ASP.Net MVC application against cross site attacks - 1</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;

Do you trust user input?!!!!!!!. If your answer is YES, stop reading and do something else. If your answer is NO, I think reading this article may help you to make your site more secure. All user&#39;s inputs can be a back door for attacker to attack your site. User&#39;s inputs that we will categorize as un-trusted inputs are : &lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;Incoming URLs including &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Request.QueryString[]&lt;/span&gt; values&lt;/li&gt;
&lt;li&gt;Form post data (&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Request.Form[]&lt;/span&gt; values including values from hidden fields and disabled fields)&lt;/li&gt;
&lt;li&gt;Cookies&lt;/li&gt;
&lt;li&gt;Data in HTTP Headers (such as &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Request.UserAgent&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Request.UrlReferrer&lt;/span&gt;).&lt;/li&gt;
&lt;/ul&gt;
Your site could be attacked by altring the query string, form values, or cookies data. The solution is not to prevent request manipulation but to check that each request is a legal request for the logged-in visitor.
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Cross-Site Scripting and HTML Injection:&lt;/span&gt;&lt;/b&gt;
&lt;br /&gt;
If an attacker can get our site to return some javascript to our visitors, then the attacker&#39;s script can take control of our visitors&#39; browsing session and by this the attackers can collect the personal information(passwords, credit card details) of our visitors. There are two main ways an attacker follow to get this:&lt;br /&gt;
&lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;&lt;i&gt;Persistently&lt;/i&gt;:&amp;nbsp;&amp;nbsp;by entering formed malicious input into some feature and hoping we will store it into our database and then issue it back to other visitors.&lt;/li&gt;
&lt;li&gt;&lt;i&gt;Non-persistently or Passively&amp;nbsp;&lt;/i&gt;: by finding a way of sending malicious data in a request to our application and having our application echo that data back in it is response. The attacker then finds a way to trick a victim into making such a request.&lt;/li&gt;
&lt;/ol&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Razor HTML Encoding:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
The Razor view engine helps protect us against &lt;span style=&quot;color: #6fa8dc;&quot;&gt;XSS&lt;/span&gt; attacks by encoding any data that we refer to using the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;@&lt;/span&gt; tag to make it safe to display as &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HTML&lt;/span&gt;. This means when we request an &lt;span style=&quot;color: #6fa8dc;&quot;&gt;URL&lt;/span&gt; with a javascript code as a query string, Razor processes the query string value and replaces the special characters and rendering javascript code as a simple text.
&lt;br /&gt;
&lt;br /&gt;
Razor view engine treats the contents of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;MvcHtmlString&lt;/span&gt; objects as if they were encoded, even when that is not the case. We can use &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Html.Raw&lt;/span&gt; helper method to include our &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HTML&lt;/span&gt; into the web page without it being encoded.
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Request Validation:&lt;/span&gt;&lt;/b&gt;
&lt;br /&gt;
The goal of request validation is to stop potentially dangerous data ever reaching the application. If the user tries to submit data that looks like it might be &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HTML&lt;/span&gt;, Then &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net&lt;/span&gt; throws an exception.This happens before the request is passed to the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;MVC Framework&lt;/span&gt;, so our application never receives the data the user has sent. But The problem with Request Validation is that it rejects any data even slightly resembling an &lt;span style=&quot;color: #6fa8dc;&quot;&gt;HTML&lt;/span&gt; tag, and this can include valid data.
&lt;br /&gt;
&lt;br /&gt;
In &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ASP.Net MVC Framework&lt;/span&gt;, request validation is enabled by default. You can disable it by decorate your controller/action method by &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ValidateInput&lt;/span&gt; attribute and passing &lt;span style=&quot;color: #6fa8dc;&quot;&gt;&lt;i&gt;false&lt;/i&gt;&lt;/span&gt; to it. If you decorate the controller with it, that means you enabled/disabled request validation for all action methods within this controller(of course not recommended). If you decorate the action method by that attribute, that means you enabled/disabled request validation for all posted data/model properties. Also you can disable request validation for a specific property by decorate it with &lt;span style=&quot;color: #6fa8dc;&quot;&gt;AllowHtml&lt;/span&gt; attribute.
&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;JavaScript String Encoding and XSS:&lt;/span&gt;&lt;/b&gt;
&lt;br /&gt;
So what if we want to accept javascript code from the user, i.e post a question on &lt;a href=&quot;http://www.stackoverflow.com/&quot;&gt;stackoverflow&lt;/a&gt;. of course we don&#39;t want to refuse it or disable request validation totally. Fortunately, the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Ajax&lt;/span&gt; helper class has method called&lt;span style=&quot;color: #6fa8dc;&quot;&gt; JavaScriptStringEncode&lt;/span&gt;, which encodes a string so that it safe to display and escapes characters so that &lt;span style=&quot;color: #6fa8dc;&quot;&gt;JavaScript&lt;/span&gt; will understand it. In such case we have to use &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Html.Raw&lt;/span&gt; method around the result generated by the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Ajax&lt;/span&gt; helper method. If we don&#39;t do this, then &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Razor HTML&lt;/span&gt; encodes the result, and we are back where we started.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;text-align: center;&quot;&gt;
1 &lt;a href=&quot;http://miroprocessordev.blogspot.com/2012/03/safe-aspnet-mvc-application-against.html&quot;&gt;2&lt;/a&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/1720174802463490669/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/03/save-aspnet-mvc-application-against.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/1720174802463490669'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/1720174802463490669'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/03/save-aspnet-mvc-application-against.html' title='Safe ASP.Net MVC application against cross site attacks - 1'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-4595016816291390121</id><published>2012-03-18T16:27:00.000+02:00</published><updated>2012-03-18T16:51:43.888+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Cast"/><category scheme="http://www.blogger.com/atom/ns#" term="IEnumerable"/><category scheme="http://www.blogger.com/atom/ns#" term="Linq"/><category scheme="http://www.blogger.com/atom/ns#" term="OfType"/><title type='text'>5 tips to get started LINQ in C#</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
&lt;br /&gt;
&lt;div&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;1-LINQ is not just for Iteration :&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;div&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;&lt;br /&gt;&lt;/span&gt;&lt;/b&gt;&lt;/div&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;LINQ&lt;/span&gt; (&lt;i&gt;Language&amp;nbsp;integrated&amp;nbsp;Query&lt;/i&gt;) is not just for queries a collection of objects, but it will be better if you think about it as a data iteration engine. If you called a method that return data of some type that you needed to convert to another datatype before passing it to another method. Assume you have a method &lt;span style=&quot;color: #6fa8dc;&quot;&gt;A()&lt;/span&gt; that return Array of integers and you need to pass this array to method &lt;span style=&quot;color: #6fa8dc;&quot;&gt;B()&lt;/span&gt; that accepts array of string. You should iterate over array items, one by one, to convert it.But with with &lt;span style=&quot;color: #6fa8dc;&quot;&gt;LINQ&lt;/span&gt; you can do that with just one line of code.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Int32[] nums = {23 , 45 , 65 , 23};
String[] numbers = nums.Select(i =&amp;gt; i.ToString()).ToArray();
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;2-Use the var keyword:&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
If you are confused about the type of the sequence result of your query and want to get your code to compile use &lt;span style=&quot;background-color: white;&quot;&gt;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;var&lt;/span&gt;&lt;/span&gt; keyword. Your query will return an &lt;span style=&quot;color: #6fa8dc;&quot;&gt;IEnumerable&lt;/span&gt; sequance of some type but you don&#39;t know&amp;nbsp;exactly&amp;nbsp;what is that type so the best choice is using &lt;span style=&quot;color: #6fa8dc;&quot;&gt;var&lt;/span&gt; keyword.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;3-Use the Cast or OfType operators for legacy code:&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Before introducing &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Generics&lt;/span&gt; collections which&amp;nbsp;enforce&amp;nbsp;the collection to contain items have the same type. The legacy code used &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ArrayLists&lt;/span&gt; which need to explicit cast each item to deal with. We can cast these old collections to be queried by &lt;span style=&quot;color: #6fa8dc;&quot;&gt;LINQ&lt;/span&gt; by using &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Cast&lt;/span&gt; operator or &lt;span style=&quot;color: #6fa8dc;&quot;&gt;OfType&lt;/span&gt; operator.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Cast&lt;/span&gt; operator requires all items in the collection to be of the correct type. If any item is unable to be cast to the specified datatype, an exception will be thrown.
&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;ArrayList arrayList = new ArrayList();
arrayList.Add(&quot;Item 1&quot;);
arrayList.Add(&quot;Item 2&quot;);
arrayList.Add(&quot;Item 3&quot;);

IEnumerable&amp;lt;string&amp;gt; items = arrayList.Cast&amp;lt;string&amp;gt;().Where(n =&amp;gt; n.Length == 6);
&lt;/code&gt;&lt;/pre&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;OfType&lt;/span&gt; operator will only items with the specified type will be stored in the output IEnumerable&amp;lt;T&amp;gt; sequence and no exception will be thrown.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;IEnumerable&amp;lt;string&amp;gt; items = arrayList.OfType&amp;lt;string&amp;gt;().Where(n =&amp;gt; n.Length == 6);
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;4-Don&#39;t assume a query is Bug-Free:&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;
In &lt;span style=&quot;color: #6fa8dc;&quot;&gt;LINQ&lt;/span&gt; the query is being called, declared, or defined but not performed. The query actually will take place the first time a result from it is used. in many cases you face a bug in a code that uses the query result and you assume the bug is in that block of code not in the query itself or its result. No the case is your query result causes the bug and you should check the query result first to fix it.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;5-Take advantage of Deferred queries:&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;
As we mentioned in tip #4, the query will not performed till you use its result so you can make a query initialization method that get gets called once for the lifetime of the scope and to construct all the queries there. Then you could enumuerate over a&amp;nbsp;particular&amp;nbsp;sequence to get the latest version of the query results as well</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/4595016816291390121/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/03/5-tips-to-get-started-linq-in-c.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4595016816291390121'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4595016816291390121'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/03/5-tips-to-get-started-linq-in-c.html' title='5 tips to get started LINQ in C#'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-798057753516655822</id><published>2012-02-26T12:59:00.001+02:00</published><updated>2012-02-26T13:54:30.047+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="pattern catalog style"/><title type='text'>Design Patterns Series 21 - How to create your own pattern?</title><content type='html'>By this post we finish our design pattern series. This post gives you a guide for how to build your own pattern in ten easy steps. Just follow along, and you are on the route to fame and fortune.&lt;br /&gt;
&lt;br /&gt;
If you don&#39;t see an established design pattern where you think there should be one?. You can create your own design pattern, and you can publicize that pattern, getting it into design pattern repositories around the world.&lt;br /&gt;
&lt;br /&gt;
Remember, design patterns are supposed to make solutions easier. Don&#39;t create a design pattern just for the sake of creating a new pattern if it&#39;s not going to be helpful. After all, patterns are supposed to be tools, not hindrances.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Pattern Catalog Style :&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The best way to start anything is with a guide of some kind, and for design patterns, that  guide is the &lt;i&gt;Pattern Catalog Style&lt;/i&gt;. There are ten sections in a pattern catalog style : &lt;br /&gt;
&lt;ol&gt;
&lt;li&gt;Intent&lt;/li&gt;
&lt;li&gt;Motivation&lt;/li&gt;
&lt;li&gt;Applicability&lt;/li&gt;
&lt;li&gt;Structure&lt;/li&gt;
&lt;li&gt;Participants&lt;/li&gt;
&lt;li&gt;Collaborations&lt;/li&gt;
&lt;li&gt;Consequences&lt;/li&gt;
&lt;li&gt;Implementation/Sample Code&lt;/li&gt;
&lt;li&gt;Known Uses&lt;/li&gt;
&lt;li&gt;Related Patterns&lt;/li&gt;
&lt;/ol&gt;
In the &lt;i&gt;Gang Of Four&lt;/i&gt;, each of the 23 patterns is written in a catalog style, with each of these ten topics carefully covered for each pattern in the&amp;nbsp;&lt;i&gt;Gang Of Four&lt;/i&gt;&amp;nbsp;book.&lt;br /&gt;
&lt;br /&gt;

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;format=728x90_as&amp;output=html&amp;h=90&amp;w=728&amp;lmt=1327217389&amp;host=pub-1556223355139109&amp;h_ch=L0202%2BS0013&amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;flash=11.1.102&amp;url=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-21-how-to-create.html&amp;dt=1327224589741&amp;shv=r20100101&amp;jsv=r20100101&amp;correlator=1327224589859&amp;pv_h_ch=L0202&amp;frm=4&amp;adk=2737856453&amp;ga_vid=1879422280.1326271734&amp;ga_sid=1327222480&amp;ga_hid=1770073439&amp;ga_fc=1&amp;u_tz=120&amp;u_his=6&amp;u_java=1&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=32&amp;u_nplug=12&amp;u_nmime=52&amp;biw=1440&amp;bih=785&amp;ref=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-21-how-to-create.html&amp;loc=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-21-how-to-create.html&amp;fu=0&amp;js=uds&amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;

&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;1- Intent&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The Intent design pattern catalog entry describes the pattern and what it is supposed to do. This is a short overview of the pattern that someone is supposed to be able to read and understand to know if the pattern solves her problem.&lt;br /&gt;
&lt;br /&gt;
When you write the intent of a pattern, keep it simple, even if it means not including every little detail. This is an overview of your patten, sort of like the descriptions in TV guide, that lets readers know if they are going to interested in your pattern.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;2- Motivation&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The motivation section of design pattern catalog entry lists a scenario that describes the problem the pattern is supposed to solve, using a concrete scenario.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;3- Applicability&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The applicability section of pattern&#39;s catalog entry describes scenarios where a pattern can be applied. You usually provide a set of condition - and if a problem meets those conditions, your pattern is a good candidate to solve it.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;4- Structure&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The structure section usually shows a diagram indicating how the pattern works.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;5- Participants&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The participants section lists the classes and objects that take part in the pattern,as well as their roles. To create the objects, for instance, you might want to make sure they all use the same methods - so you should have an interface. And you should list the classes that implement that interface, as well as the client code that attempts to use them.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;6- Collaborations&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The collaboration section entry indicates how the participants work together.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;7- Consequences&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The consequences section lists both the good and the bad effects of the pattern. Your pattern, being the most advanced and excellent one the world has yet seen, may not have any apparent drawbacks, but think hard on this point - it would not be good if you steered someone into using your pattern if that pattern&#39;s going to cause him problems.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;8- Implementation/Sample Code&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The Implementation/Sample Code section outlines the techniques you use when implementing this pattern and/or sample code.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;9- Known Uses&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The Known Uses section gives some real-world examples where the pattern has been used.
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;10- Related Patterns&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
The related patterns sections lists other patterns that might be related to this one.&lt;br /&gt;
&lt;br /&gt;
Congratulations - you have created your own new pattern. All you have got to do now is to submit your own pattern catalog entry to a design pattern repository such as the &lt;i&gt;Portland Pattern Repository&lt;/i&gt;, as hosted by Cunningham &amp;amp; Cunningham at &lt;a href=&quot;http://www.c2.com/&quot;&gt;http://www.c2.com&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/798057753516655822/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-21-how-to-create.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/798057753516655822'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/798057753516655822'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-21-how-to-create.html' title='Design Patterns Series 21 - How to create your own pattern?'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-712317670691608038</id><published>2012-02-21T11:24:00.001+02:00</published><updated>2012-02-21T12:29:36.590+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="double buffer"/><category scheme="http://www.blogger.com/atom/ns#" term="double buffer pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Model view controller pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="MVC"/><category scheme="http://www.blogger.com/atom/ns#" term="MVC Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Observer Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="recycle bin"/><category scheme="http://www.blogger.com/atom/ns#" term="Recycle bin pattern"/><title type='text'>Design Patterns Series 20 - Double Buffer, Recycle Bin, and MVC Patterns</title><content type='html'>In this post we will explore the last three patterns in our design patterns list, &lt;i&gt;Double Buffer Pattern&lt;/i&gt;, &lt;i&gt;Recycle Bin Pattern&lt;/i&gt;, and &lt;i&gt;Model/View/Controller (MVC) Pattern.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Double Buffer Pattern :&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
Double Buffering is used to avoid screen flicker when you are displaying graphics. The idea is that you perfrom your multi-step graphics creation off-screen in a buffer and then flash the results on the screen when they&#39;re complete. The process is called &lt;i&gt;Double Buffering&lt;/i&gt;&amp;nbsp;because the screen display buffer is one buffer and the buffer in which the images are prepared is the second buffer.&lt;br /&gt;
&lt;br /&gt;
Use a &lt;i&gt;Double Buffer&lt;/i&gt;&amp;nbsp;when generating revised datasets for an asynchronous processor. When the new data is complete and self consistent, redirect the asynchronous processor to the alternate buffer.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Recycle Bin Pattern :&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
If your code uses many objects and the object-creation process is time - and resource - intensive, you might want to use the &lt;i&gt;Recycle Bin Pattern&lt;/i&gt;. The idea is that when you&#39;re done with an object, you toss it into the recycle bin, and when you need an object of the same kind again, you can grab it out of the recycle bin.&lt;br /&gt;
&lt;br /&gt;
You can store freed resources in a local bin so that subsequent requests for these resources can reuse the ones in the bin. A client requests resources through the bin. The bin will reuse an existing one if available or create a new one if necessary. The recycle bin may request&amp;nbsp;more&amp;nbsp;resource than actually needed to optimize performance. When the use of the resource is complete, it should be returned to the bin.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Model/View/Controller (MVC) :&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Model/View/Controller, &lt;/i&gt;or &lt;i&gt;MVC&lt;/i&gt;, represents a good design insight : separating the code used for presentation from that which works on and handles data.&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;
&lt;li&gt;&lt;i style=&quot;color: #6fa8dc; font-weight: bold;&quot;&gt;Model : &lt;/i&gt;Implements the data crunching of the application. This is the core code that does the application&#39;s internal work. The &lt;span style=&quot;color: #6fa8dc; font-style: italic;&quot;&gt;Model&lt;/span&gt;&amp;nbsp;does not know anything about the view or the controller - you just pass it data and it goes from there, returning its result.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;

&lt;li&gt;&lt;i style=&quot;color: #6fa8dc; font-weight: bold;&quot;&gt;View : &lt;/i&gt;Implements the presentation layer that interacts with the user. When the user starts interacting with an online application, the web page(s) they see are part of view. The&lt;i style=&quot;color: #6fa8dc;&quot;&gt;View&lt;/i&gt;&amp;nbsp;also takes data supplied to it (usually from the &lt;i&gt;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;controller&lt;/span&gt;&lt;/i&gt;) and displays it.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;

&lt;li&gt;&lt;i style=&quot;color: #6fa8dc; font-weight: bold;&quot;&gt;Controller : &lt;/i&gt;Acts as the boss of the application and it is responsible for routing data to the right model and view components. The &lt;i style=&quot;color: #6fa8dc;&quot;&gt;Controller&lt;/i&gt;&amp;nbsp;oversees the model and the view by reacting to the data the user sends.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;
&lt;/ul&gt;
The &lt;i&gt;MVC Pattern&lt;/i&gt;&amp;nbsp;is &quot;&lt;i&gt;A tried of three modules linked by &lt;span style=&quot;color: #6fa8dc;&quot;&gt;&lt;a href=&quot;http://miroprocessordev.blogspot.com/2011/12/design-patterns-series-5-observer.html&quot;&gt;Observer Pattern&lt;/a&gt;&amp;nbsp;&lt;/span&gt;, all residing within &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RepresentationLayer&lt;/span&gt;.&lt;span style=&quot;color: #6fa8dc;&quot;&gt;&amp;nbsp;&lt;/span&gt;The &lt;span style=&quot;color: #6fa8dc;&quot;&gt;View &lt;/span&gt;drives a presentation within &lt;span style=&quot;color: #6fa8dc;&quot;&gt;GUILayer&lt;/span&gt;, and elements within the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;View &lt;/span&gt;observe the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Model&lt;/span&gt;. Elements within the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Controller &lt;/span&gt;observe the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;View &lt;/span&gt;and the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Model&lt;/span&gt;, and elements within the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Model &lt;/span&gt;observe the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Controller&lt;/span&gt;. The &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Model &lt;/span&gt;fronts data objects within the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;LogicLayer&lt;/span&gt;. This pattern decouples changes to how data are manipulated from how they are displayed or stored, while unifying the code in each component.&lt;/i&gt;&quot;
&lt;br /&gt;&lt;br /&gt;
Now we explored most famous design patterns and in the next and last post in this series we will know how to create our own design pattern.</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/712317670691608038/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-20-double-buffer.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/712317670691608038'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/712317670691608038'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-20-double-buffer.html' title='Design Patterns Series 20 - Double Buffer, Recycle Bin, and MVC Patterns'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-4566039787667145874</id><published>2012-02-14T12:41:00.001+02:00</published><updated>2017-05-05T17:18:23.014+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Buffers"/><category scheme="http://www.blogger.com/atom/ns#" term="Buffers Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Circular"/><category scheme="http://www.blogger.com/atom/ns#" term="Circular Buffers"/><category scheme="http://www.blogger.com/atom/ns#" term="Circular Buffers Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Circular Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Ring Buffer"/><title type='text'>Design Patterns Series 19 - Circular Buffer Pattern</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Circular Buffer Pattern :&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;Circular Buffer&lt;/i&gt;&amp;nbsp;is perfect when one part of your code stores data and another part reads that data asynchronously. Makes very efficient use of memory.&lt;br /&gt;
&lt;br /&gt;
A &lt;i&gt;Circular Buffer&lt;/i&gt;&amp;nbsp;is a memory allocation scheme where memory is reused when an index, incremented modulo the buffer size, writes over a previously used location. A &lt;i&gt;Circular Buffer&lt;/i&gt;&amp;nbsp;makes bounded queue when separate indices are used for inserting and removing data. The queue can be safely shared between threads (or processors) without further synchronization so long as one processor&amp;nbsp;en-queues&amp;nbsp;data and the other de-queues it.&lt;br /&gt;
&lt;br /&gt;
You store data items in the various locations in a ring buffer and keep track of reading and writing operations &amp;nbsp;by labeling one location the &lt;i&gt;Head&lt;/i&gt;&amp;nbsp;and one the &lt;i&gt;Tail&lt;/i&gt;.
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;/div&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjg1kqu4zk2-OuRkGWiDFegtE_QRJDboGM-ft1aoIAiinXSo2Iph2RdWOXb-SbT1LeKdV1MB6kuqhCfw-kPaVBoPi-o5rMgkTT7zkz0idtFZChY2Ma_iBO2b11iA-2wHQ_wXDoZqerAlHmp/s1600/Circular1.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;190&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjg1kqu4zk2-OuRkGWiDFegtE_QRJDboGM-ft1aoIAiinXSo2Iph2RdWOXb-SbT1LeKdV1MB6kuqhCfw-kPaVBoPi-o5rMgkTT7zkz0idtFZChY2Ma_iBO2b11iA-2wHQ_wXDoZqerAlHmp/s320/Circular1.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
When you store an item in the &lt;i&gt;Circular Buffer&lt;/i&gt; you store the item at the tail location, and the tail advances to the next location.
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUq73xMlNrkezK-lCZBiqMe-GPnhSKhNPKIrmUpgUYQLIxT2oKs_4fVIWUnV0EIxXZQdzinAIz6TNlk6_0baGojeVmYnslQrrxPPbIWze2nGHNMo_vnIquc0BgvUBM9HsSkzEEbsxCyD8g/s1600/Circular2.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;184&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUq73xMlNrkezK-lCZBiqMe-GPnhSKhNPKIrmUpgUYQLIxT2oKs_4fVIWUnV0EIxXZQdzinAIz6TNlk6_0baGojeVmYnslQrrxPPbIWze2nGHNMo_vnIquc0BgvUBM9HsSkzEEbsxCyD8g/s320/Circular2.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
When you read an item, you read the item at the current head location, and the head advances to the next position.
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;
&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfabFm9-ea5DjSsiNAa1VlEFi_Uz5YoSHsuBY2Hd_bTSWDimh1K2BEZzlpgKB37eGbkPnLzGLp7plpGcSLvQyzzzUs4cjwsmdP0H-t7-QUl8ZS1bFFygfXSeU8UNBKK77kbMOObvhUmyPy/s1600/Circular3.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;181&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgfabFm9-ea5DjSsiNAa1VlEFi_Uz5YoSHsuBY2Hd_bTSWDimh1K2BEZzlpgKB37eGbkPnLzGLp7plpGcSLvQyzzzUs4cjwsmdP0H-t7-QUl8ZS1bFFygfXSeU8UNBKK77kbMOObvhUmyPy/s320/Circular3.png&quot; width=&quot;320&quot; /&gt;&lt;/a&gt;&lt;/div&gt;
By writing to the tail and reading from the head, two streams can store and read data from the same circular buffer at the same time.

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;format=728x90_as&amp;output=html&amp;h=90&amp;w=728&amp;lmt=1327217389&amp;host=pub-1556223355139109&amp;h_ch=L0202%2BS0013&amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;flash=11.1.102&amp;url=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-19-circular.html&amp;dt=1327224589741&amp;shv=r20100101&amp;jsv=r20100101&amp;correlator=1327224589859&amp;pv_h_ch=L0202&amp;frm=4&amp;adk=2737856453&amp;ga_vid=1879422280.1326271734&amp;ga_sid=1327222480&amp;ga_hid=1770073439&amp;ga_fc=1&amp;u_tz=120&amp;u_his=6&amp;u_java=1&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=32&amp;u_nplug=12&amp;u_nmime=52&amp;biw=1440&amp;bih=785&amp;ref=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-19-circular.html&amp;loc=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-19-circular.html&amp;fu=0&amp;js=uds&amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;


The following code sets up an array holding the number of items you pass to the constructor.&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class CircularBuffer
{
    private String[] Buffer { get; set; }
    private Int32 Head { get; set; }
    private Int32 Tail { get; set; }

    public CircularBuffer(Int32 itemsCount)
    {
        Buffer = new String[itemsCount];
        Head = 0;
        Tail = 0;
    }
    .
    .
    .
}
&lt;/code&gt;&lt;/pre&gt;
The &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Store()&lt;/span&gt; method stores an item and advances the tail.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public Boolean Store(String data)
{
    if (!BufferIsFull)
    {
        Buffer[Tail] = data;
        Tail++;
        if (Tail == Buffer.Length)
        {
            Tail = 0;
        }
        return true;
    }
    return false;
}
private Boolean BufferIsFull
{
    get
    {
        if (Tail + 1 == Head)
        {
            return true;
        }
        if ((Tail == Buffer.Length - 1) &amp;amp;&amp;amp; Head == 0)
        {
            return true;
        }
        return false;
    }
}
&lt;/code&gt;&lt;/pre&gt;
And the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Read()&lt;/span&gt; method reads the item at the head location, and advances the head.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public String Read()
{
    if (Head != Tail)
    {
        String data = Buffer[Head];
        Head++;
        if (Head == Buffer.Length)
        {
            Head = 0;
        }
        return data;
    }
    return String.Empty;
}
&lt;/code&gt;&lt;/pre&gt;
Now you implemented the &lt;i&gt;Circular Buffer&lt;/i&gt; and to test it you just want to create an instance of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;CircularBuffer&lt;/span&gt; class and call &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Store()&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Read()&lt;/span&gt; methods many times in random order.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;var buffer = new CircularBuffer(5);
Console.WriteLine(&quot;Stroing : Item0&quot;);
buffer.Store(&quot;Item0&quot;);
Console.WriteLine(&quot;Reading : {0}&quot;, buffer.Read());
Console.WriteLine(&quot;Stroing : Item1&quot;);
buffer.Store(&quot;Item1&quot;);
Console.WriteLine(&quot;Stroing : Item2&quot;);
buffer.Store(&quot;Item2&quot;);
Console.WriteLine(&quot;Reading : {0}&quot;, buffer.Read());
Console.WriteLine(&quot;Stroing : Item3&quot;);
buffer.Store(&quot;Item3&quot;);
Console.WriteLine(&quot;Reading : {0}&quot;, buffer.Read());
Console.WriteLine(&quot;Stroing : Item4&quot;);
buffer.Store(&quot;Item4&quot;);
Console.WriteLine(&quot;Reading : {0}&quot;, buffer.Read());
Console.WriteLine(&quot;Reading : {0}&quot;, buffer.Read());
Console.WriteLine(&quot;Stroing : Item5&quot;);
buffer.Store(&quot;Item5&quot;);
Console.WriteLine(&quot;Stroing : Item6&quot;);
buffer.Store(&quot;Item6&quot;);
Console.WriteLine(&quot;Reading : {0}&quot;, buffer.Read());
Console.WriteLine(&quot;Reading : {0}&quot;, buffer.Read());
&lt;/code&gt;&lt;/pre&gt;
Note we passed 5 as an argument of the constructor and stored 7 items that means we stored two items more than the capacity of our buffer but actually we overwrote the first two items. So the out put will become: 
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;&lt;b&gt;Stroing : Item0&lt;/b&gt;
Reading : Item0
&lt;b&gt;Stroing : Item1&lt;/b&gt;
&lt;b&gt;Stroing : Item2&lt;/b&gt;
Reading : Item1
&lt;b&gt;Stroing : Item3&lt;/b&gt;
Reading : Item2
&lt;b&gt;Stroing : Item4&lt;/b&gt;
Reading : Item3
Reading : Item4
&lt;b&gt;Stroing : Item5&lt;/b&gt;
&lt;b&gt;Stroing : Item6&lt;/b&gt;
Reading : Item5
Reading : Item6&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
you can download the full source code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzUER2enFrV3o4ZTQ&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/4566039787667145874/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-19-circular.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4566039787667145874'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/4566039787667145874'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-19-circular.html' title='Design Patterns Series 19 - Circular Buffer Pattern'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjg1kqu4zk2-OuRkGWiDFegtE_QRJDboGM-ft1aoIAiinXSo2Iph2RdWOXb-SbT1LeKdV1MB6kuqhCfw-kPaVBoPi-o5rMgkTT7zkz0idtFZChY2Ma_iBO2b11iA-2wHQ_wXDoZqerAlHmp/s72-c/Circular1.png" height="72" width="72"/><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-1058079311514889348</id><published>2012-02-08T14:42:00.001+02:00</published><updated>2012-02-08T14:44:13.625+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Abstract factory"/><category scheme="http://www.blogger.com/atom/ns#" term="Bridge"/><category scheme="http://www.blogger.com/atom/ns#" term="Bridge pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Composite"/><category scheme="http://www.blogger.com/atom/ns#" term="Composite Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Factory"/><category scheme="http://www.blogger.com/atom/ns#" term="Factory Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="interpreter"/><category scheme="http://www.blogger.com/atom/ns#" term="Interpreter pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Momento pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Prototype"/><category scheme="http://www.blogger.com/atom/ns#" term="Prototype pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Visitor pattern"/><title type='text'>Design Patterns Series 18 - More Design Patterns</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
This Post will discover more than one design pattern. They are all good patterns, but some are not used these days. And some are just plain hard to implement, like the &lt;i&gt;Interpreter Pattern&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Abstract Factory Pattern :&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Abstract Factory Pattern&lt;/i&gt; describes a factory of factories, or, more properly thought of, an abstract specification for an actual object &lt;a href=&quot;http://miroprocessordev.blogspot.com/2011/11/design-patterns-series-4-factory.html&quot;&gt;factory&lt;/a&gt;. Here&#39;s the problem: sometimes you might need more than one &lt;a href=&quot;http://miroprocessordev.blogspot.com/2011/11/design-patterns-series-4-factory.html&quot;&gt;factory &lt;/a&gt;to create objects of a similar nature.&lt;br /&gt;
&lt;br /&gt;
An &lt;i&gt;Abstract Factory&lt;/i&gt;&amp;nbsp;is usually implemented as an abstract class that real, concrete factories extend. That unifies what the concrete factories do, while allowing leeway to fit differing requirements.&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Abstract Factory Pattern&lt;/i&gt;&amp;nbsp;should &quot;&lt;i&gt;provide an interface for creating families of related or dependent objects without specifying their concrete classes.&lt;/i&gt;&quot;&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;Prototype Pattern :&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Prototype Pattern&lt;/i&gt;&amp;nbsp;says that when it takes a lot of resources, or a lot of code, to create an object, you should consider simply copying an existing object and customizing it instead.&lt;br /&gt;
&lt;br /&gt;
In code, all you have to do is set up a prototypical object and keep calling the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Clone&lt;/span&gt; method on it - no need to create your object from scratch in your code every time &amp;nbsp;- and then add some customization to the new object as needed.&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Prototype Pattern&lt;/i&gt;&amp;nbsp;should &quot;&lt;i&gt;Specify the kinds of objects to create using a prototypical instance, and &amp;nbsp;create new objects by copying this prototype.&lt;/i&gt;&quot;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Bridge Pattern :&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The inspiration here is that when you have an abstraction that can vary, and that&#39;s tied to an implementation that can also vary, you should decouple the two.&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Bridge Pattern&lt;/i&gt;&amp;nbsp;should &quot;&lt;i&gt;Decouple an abstraction from its implementation so that the two can vary independently&amp;nbsp;.&lt;/i&gt;&quot;

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;format=728x90_as&amp;output=html&amp;h=90&amp;w=728&amp;lmt=1327217389&amp;host=pub-1556223355139109&amp;h_ch=L0202%2BS0013&amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;flash=11.1.102&amp;url=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-18-more-design.html&amp;dt=1327224589741&amp;shv=r20100101&amp;jsv=r20100101&amp;correlator=1327224589859&amp;pv_h_ch=L0202&amp;frm=4&amp;adk=2737856453&amp;ga_vid=1879422280.1326271734&amp;ga_sid=1327222480&amp;ga_hid=1770073439&amp;ga_fc=1&amp;u_tz=120&amp;u_his=6&amp;u_java=1&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=32&amp;u_nplug=12&amp;u_nmime=52&amp;biw=1440&amp;bih=785&amp;ref=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-18-more-design.html&amp;loc=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-18-more-design.html&amp;fu=0&amp;js=uds&amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;

&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Interpreter Pattern :&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
This is heavy-duty pattern. It is all about &amp;nbsp;putting together your own programming language, or handling an existing one, by creating an interpreter for that language.&lt;br /&gt;
&lt;br /&gt;
To use this pattern, you have to know a fair bit about formal grammars to put together a language. As you can imagine, this is one of those patterns that doesn&#39;t see a lot of everyday use because creating your own language is not something many people do.&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Interpreter Pattern&lt;/i&gt;&amp;nbsp;should &quot;&lt;i&gt;Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.&lt;/i&gt;&quot;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Momento Pattern :&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Here is the problem. The client code has total access to the database, so if someone flubs an operation, the database is in danger.&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Memento Pattern&lt;/i&gt;&amp;nbsp;is designed to &quot;&lt;i&gt;Without violating encapsulation, capture and externalize an object&#39;s internal state so that the object can be restored to this state later.&lt;/i&gt;&quot;&lt;br /&gt;
&lt;br /&gt;
More than just a save-state undo command, the idea here is to &quot;capture and externalize an object&#39;s internal state&quot; for backup. You might do that with a save-state object accessible from both the client code and the database.&lt;br /&gt;
&lt;br /&gt;
The solution, however violates the database&#39;s encapsulation, and the &lt;i&gt;Memento Design Pattern&lt;/i&gt;&amp;nbsp;starts off by saying, &quot;without violating encapsulation...&quot;. So What do you do? You make the save-state object private to the database.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;Visitor Pattern :&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
With&amp;nbsp;the &lt;i&gt;Visitor&amp;nbsp;Pattern&lt;/i&gt;&amp;nbsp;, you can add a new operation to a structure of objects, like a &lt;a href=&quot;http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-14-compsite.html&quot;&gt;Composite&lt;/a&gt; structure, without changing the objects in the structure. A &lt;i&gt;visitor&lt;/i&gt;&amp;nbsp;object moves from object to object in the structure, visiting each one and capturing its state. When the visitor has captured all the data it needs from the objects in the structure it&#39;s visiting, you can call the methods of the visitor.&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Visitor Pattern&lt;/i&gt;&amp;nbsp;should &quot;&lt;i&gt;Represent an operation to be preformed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.&lt;/i&gt;&quot;&lt;br /&gt;
&lt;br /&gt;
In practice, you usually use a traverser object of some kind that can move around the object structure whose &amp;nbsp;data you want, feeding data to the &lt;i&gt;Visitor&lt;/i&gt;&amp;nbsp;object. The Traverser moves the &lt;i&gt;Visitor&lt;/i&gt;&amp;nbsp;object from item to item in the &lt;a href=&quot;http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-14-compsite.html&quot;&gt;Composite&lt;/a&gt;.</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/1058079311514889348/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-18-more-design.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/1058079311514889348'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/1058079311514889348'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-18-more-design.html' title='Design Patterns Series 18 - More Design Patterns'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-2971750157468175060</id><published>2012-02-01T15:51:00.000+02:00</published><updated>2017-05-05T17:20:29.989+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="Mediator"/><category scheme="http://www.blogger.com/atom/ns#" term="Mediator Pattern"/><title type='text'>Design Patterns Series 17 - Mediator Pattern</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;The Mediator Pattern :&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Mediator Pattern &lt;/i&gt;supports coordination between objects. it makes the coupling looser by having all objects report state changes to the mediator and take commands from the mediator.&lt;br /&gt;
&lt;br /&gt;
When you use a mediator, you are encapsulating the interaction between objects. Each object no longer has to know in detail how to interact with the other objects. The coupling between objects goes from tight and brittle to loose and agile.&lt;br /&gt;
&lt;br /&gt;
You can use the &lt;i&gt;Mediator Pattern &lt;/i&gt;to &quot;&lt;i&gt;define an object that encapsulate how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.&lt;/i&gt;&quot;&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;&amp;nbsp;Mediator Pattern&lt;/i&gt;&amp;nbsp;should your first choice as a possible solution any time you have a set of objects that are tightly coupled. If every one of a series of objects has to know the internal details of the other objects, and maintaining those relationships becomes a problem, think of the &lt;i&gt;Mediator Pattern.&lt;/i&gt;&amp;nbsp;Using a mediator means the interaction code has to reside in only one place, and that makes it easier to maintain.&lt;br /&gt;
&lt;br /&gt;
Using a mediator can hide a more series problem: If you have multiple objects that are too tightly coupled, your encapsulation may be faulty. Might be time to rethink how you have broken your program into objects.&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Mediator Pattern&lt;/i&gt;&amp;nbsp;is something like a multiplexed &lt;i&gt;&lt;a href=&quot;http://miroprocessordev.blogspot.com/2011/12/design-patterns-series-10-facade.html&quot;&gt;Facade Pattern&lt;/a&gt;&amp;nbsp;&lt;/i&gt;where, instead of supplanting the interface of a single object, you are making the multiplexed interface among multiple objects easier to work with.&lt;br /&gt;
&lt;br /&gt;
Suppose we are working on a e-booking site, the site consists of four pages, home page, availability page, booking page,and exit page. The user can go form one page to another page without be restricted by certain path. He may go from availability page to exit page or from home page to exit page directly.&lt;br /&gt;
&lt;br /&gt;
For example, The home page asks the user if he wants to book or exit,when the user do his selection, passes the matching state change to the mediator object to decide which page will be displayed. To give each page access to the mediator, we pass the mediator object to its constructor.&lt;br /&gt;
&lt;br /&gt;
Each page should know its mediator and the user response(action) and have a &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Go()&lt;/span&gt; method to go to the next page, So we will create a base class, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Page&lt;/span&gt; class, for all pages to inherit.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Page &lt;/span&gt;Class&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public abstract class Page
{
    public Page(Mediator mediator)
    {
        Mediator = mediator;
        Response = &quot;n&quot;;
    }
    protected Mediator Mediator { get; set; }
    protected String Response { get; set; }

    public abstract void Go();
}

&lt;/code&gt;&lt;/pre&gt;

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;format=728x90_as&amp;output=html&amp;h=90&amp;w=728&amp;lmt=1327217389&amp;host=pub-1556223355139109&amp;h_ch=L0202%2BS0013&amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;flash=11.1.102&amp;url=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-17-mediator.html&amp;dt=1327224589741&amp;shv=r20100101&amp;jsv=r20100101&amp;correlator=1327224589859&amp;pv_h_ch=L0202&amp;frm=4&amp;adk=2737856453&amp;ga_vid=1879422280.1326271734&amp;ga_sid=1327222480&amp;ga_hid=1770073439&amp;ga_fc=1&amp;u_tz=120&amp;u_his=6&amp;u_java=1&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=32&amp;u_nplug=12&amp;u_nmime=52&amp;biw=1440&amp;bih=785&amp;ref=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-17-mediator.html&amp;loc=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-17-mediator.html&amp;fu=0&amp;js=uds&amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;

Note, we passes the mediator object to the constructor and instantiate &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Response&lt;/span&gt; property with &quot;n&quot; for No. Now we will create four classes, one for each page. Each class will inherit &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Page&lt;/span&gt; class and implement its own &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Go()&lt;/span&gt; method.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Home&lt;/span&gt; Class&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class Home : Page
{
    public Home(Mediator mediator)
        : base(mediator)
    { }

    public override void Go()
    {
        Console.Write(&quot;Do You want to get Avaialability [y/n]?&quot;);
        try 
        {
            Response = Console.ReadLine();
        }
        catch
        {}
        if (Response.Equals(&quot;y&quot;, StringComparison.CurrentCultureIgnoreCase))
        {
            Mediator.Handle(&quot;Home.Availability&quot;);
        }
        else
        {
            Mediator.Handle(&quot;Home.Thanks&quot;);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
Inside the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Go()&lt;/span&gt; method we ask the user what he want to do. This question will differ from one page to another, in the home page it may go to availability page or to exit page so according to his response we call the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Handle()&lt;/span&gt; method of mediator object and pass it the state or the path that user selected.&lt;br /&gt;
&lt;br /&gt;
In the availability page he/she will choose to go to booking page or to exit page.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Availability&lt;/span&gt; Class&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public override void Go()
{
    Console.Write(&quot;Are you ready to book [y/n]?&quot;);
    try 
    {
        Response = Console.ReadLine();
    }
    catch
    {}
    if (Response.Equals(&quot;y&quot;, StringComparison.CurrentCultureIgnoreCase))
    {
        Mediator.Handle(&quot;Availability.Booking&quot;);
    }
    else
    {
        Mediator.Handle(&quot;Availability.Thanks&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
In the booking page he/she will choose to book and exit or exit without booking.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Booking&lt;/span&gt; Class&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public override void Go()
{
    Console.Write(&quot;Do You want to book Now[y/n]?&quot;);
    try 
    {
        Response = Console.ReadLine();
    }
    catch
    {}
    if (Response.Equals(&quot;y&quot;, StringComparison.CurrentCultureIgnoreCase))
    {
        Console.WriteLine(&quot;Thanks for your booking&quot;);
    }
    Mediator.Handle(&quot;Booking.Thanks&quot;);
}
&lt;/code&gt;&lt;/pre&gt;
Now there is no any pages to go so we will ask him to visit our site again.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Exit&lt;/span&gt; Class&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public override void Go()
{
    Console.WriteLine(&quot;Please visit us again&quot;);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;format=728x90_as&amp;output=html&amp;h=90&amp;w=728&amp;lmt=1327217389&amp;host=pub-1556223355139109&amp;h_ch=L0202%2BS0013&amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;flash=11.1.102&amp;url=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-17-mediator.html&amp;dt=1327224589741&amp;shv=r20100101&amp;jsv=r20100101&amp;correlator=1327224589859&amp;pv_h_ch=L0202&amp;frm=4&amp;adk=2737856453&amp;ga_vid=1879422280.1326271734&amp;ga_sid=1327222480&amp;ga_hid=1770073439&amp;ga_fc=1&amp;u_tz=120&amp;u_his=6&amp;u_java=1&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=32&amp;u_nplug=12&amp;u_nmime=52&amp;biw=1440&amp;bih=785&amp;ref=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-17-mediator.html&amp;loc=http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-17-mediator.html&amp;fu=0&amp;js=uds&amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;

Now we will create our &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Mediator&lt;/span&gt; class and its &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Handle()&lt;/span&gt; method but the mediator should have a method that will take the user to home page so we will add another method beside &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Handle&lt;/span&gt; method call &lt;span style=&quot;color: #6fa8dc;&quot;&gt;GetHome()&lt;/span&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Mediator&lt;/span&gt; Class&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class Mediator
{
    private Page Page { get; set; }

    public void Handle(String path)
    {
        switch (path)
        {
            case &quot;Home.Availability&quot;:
                Page = new Availability(this);
                Page.Go();
                break;
            case &quot;Availability.Booking&quot;:
                Page = new Booking(this);
                Page.Go();
                break;
            case &quot;Home.Exit&quot;:
            case &quot;Availability.Exit&quot;:
            case &quot;Booking.Exit&quot;:
                Page = new Exit(this);
                Page.Go();
                break;
        }
    }
    public Page GetHome()
    {
        return new Home(this);
    }
}
&lt;/code&gt;&lt;/pre&gt;
As you see the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Handle&lt;/span&gt; method accepts the path selected by the user and set the page object with the appropriated page object to go to. To test our mediator just we will create an instance of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Mediator&lt;/span&gt; class and go to the home page.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Mediator mediator = new Mediator();
Page homepage = mediator.GetHome();
homepage.Go();
&lt;/code&gt;&lt;/pre&gt;
Just the user went to home page, he will be asked if he want to get availability or not.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Do You want to get Avaialability [y/n]?&lt;/code&gt;&lt;/pre&gt;
Here&#39;s a user who doesn&#39;t want to get availability.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Do You want to get Avaialability [y/n]?n
Please visit us again&lt;/code&gt;&lt;/pre&gt;
Here&#39;s a user who really want to get availability.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Do You want to get Avaialability [y/n]?y
Are you ready to book [y/n]?&lt;/code&gt;&lt;/pre&gt;
Here&#39;s a user who&#39;s not ready to make booking.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Do You want to get Avaialability [y/n]?y
Are you ready to book [y/n]?n
Please visit us again&lt;/code&gt;&lt;/pre&gt;
Here&#39;s a user who&#39;s ready to make booking.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Do You want to get Avaialability [y/n]?y
Are you ready to book [y/n]?y
Do You want to book Now[y/n]?&lt;/code&gt;&lt;/pre&gt;
Here&#39;s a user who&#39;s will not book now.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Do You want to get Avaialability [y/n]?y
Are you ready to book [y/n]?y
Do You want to book Now[y/n]?n
Please visit us again&lt;/code&gt;&lt;/pre&gt;
Here&#39;s a user who made a booking.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Do You want to get Avaialability [y/n]?y
Are you ready to book [y/n]?y
Do You want to book Now[y/n]?y
Thanks for your booking
Please visit us again&lt;/code&gt;&lt;/pre&gt;
As you can see, the mediator is able to coordinate all the pages. When something happens, a page lets the mediator know, and the mediator takes the appropriate next step.&lt;br /&gt;
&lt;br /&gt;
you can download the full source code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzenZEUHg0eDdXZWs&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/2971750157468175060/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-17-mediator.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/2971750157468175060'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/2971750157468175060'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/02/design-patterns-series-17-mediator.html' title='Design Patterns Series 17 - Mediator Pattern'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-365606064450508598</id><published>2012-01-31T15:32:00.000+02:00</published><updated>2017-05-05T17:22:28.329+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Command"/><category scheme="http://www.blogger.com/atom/ns#" term="Command Pattern"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><title type='text'>Design Patterns Series 16 - Command Pattern</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;
Today we will discover another pattern from our design patterns list, &lt;i&gt;The Command Pattern&lt;/i&gt;&amp;nbsp;
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: blue;&quot;&gt;&lt;b&gt;The Command Pattern :&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Command Pattern&lt;/i&gt;&amp;nbsp;lets you package complex commands into a single one. Rather than having to preform the multiple steps needed to execute each command every time, you can create a bunch of ready-to-use command objects, each of which can handle multiple steps internally. Each command is already configured with &amp;nbsp;its target and the action it&#39;s supposed to perform, so a set of command objects can act as a ready-made toolkit, already configured and all set to operate on the target objects they&#39;re supposed to handle.
&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;Command Pattern&lt;/i&gt;&amp;nbsp;says you should encapsulate all the separate actions into objects configured for specific targets. This gives you a number of objects that act like a set of tools, ready to be used.
&lt;br /&gt;
&lt;br /&gt;
In other words, the idea here is &lt;i&gt;encapsulation.&lt;/i&gt;&amp;nbsp;You are encapsulating a set of complex actions, targeted at a particular target, into an easily handled object. When you want to execute a command, you no longer have to take all the separate steps.You just use the specific prebuilt, preconfigured command object, and it does the work.
&lt;br /&gt;
&lt;br /&gt;
You use the &lt;i&gt;Command Pattern&lt;/i&gt;&amp;nbsp;to &quot;&lt;i&gt;Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undo-able operations.&lt;/i&gt;&quot;&lt;br /&gt;
&lt;br /&gt;
In simple terms, the target of a command object is called its &lt;i&gt;receiver&lt;/i&gt;. When you create a command object, you typically pass it the receiver it&#39;s supposed to work on so it can access that receiver. When you want to execute a command, typically you pass it to an object that acts as an &lt;i&gt;invoker&lt;/i&gt;. The invoker calls the methods of the command object or undo action.&lt;br /&gt;
&lt;br /&gt;
You use the &lt;i&gt;Command Pattern&lt;/i&gt;&amp;nbsp;when you have got a complex set of commands that get annoying. When the interface to those commands is so complex that it gets in the way, it makes sense to encapsulate those commands.&lt;br /&gt;
&lt;br /&gt;
The inspiration behind this design pattern is that it takes encapsulation to another level. Programmers often use encapsulation to extract a set of methods and data and wrap them in an object to simplify their code. But you don&#39;t usually think of encapsulating commands. By preconfiguring those commands to handle the receiver of their actions and bundling complex steps into single, easy-to-handle objects, you end up with a prebuilt toolkit, ready to use.

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;format=728x90_as&amp;output=html&amp;h=90&amp;w=728&amp;lmt=1327217389&amp;host=pub-1556223355139109&amp;h_ch=L0202%2BS0013&amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;flash=11.1.102&amp;url=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html&amp;dt=1327224589741&amp;shv=r20100101&amp;jsv=r20100101&amp;correlator=1327224589859&amp;pv_h_ch=L0202&amp;frm=4&amp;adk=2737856453&amp;ga_vid=1879422280.1326271734&amp;ga_sid=1327222480&amp;ga_hid=1770073439&amp;ga_fc=1&amp;u_tz=120&amp;u_his=6&amp;u_java=1&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=32&amp;u_nplug=12&amp;u_nmime=52&amp;biw=1440&amp;bih=785&amp;ref=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html&amp;loc=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html&amp;fu=0&amp;js=uds&amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;

To best understand how we create a &lt;i&gt; Command Pattern&lt;/i&gt; and how it works, Suppose our company has three servers in Asia, in Europe, and in USA. We have to monitor these three servers and fix any issue as soon as possible. Assume the commands we run are shutting down the server, run diagnostics tools, and reboot the server. Before running any command we should connect to the server first and after running it we should disconnect.
&lt;br /&gt;
&lt;br /&gt;
First thing we will do is, creating the receiver that is what a command object works on. In our example that is one of the three servers. Each server acts as a receiver of the command object&#39;s actions. We will create an &lt;span style=&quot;color: #6fa8dc;&quot;&gt;IReceiver&lt;/span&gt; interface which will be implemented by each receiver(each server).
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;IReciever&lt;/span&gt; interface
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public interface IReciever
{
    void Connect();
    void Diagnostics();
    void Reboot();
    void Shutdown();
    void Disconnect();
}
&lt;/code&gt;&lt;/pre&gt;
Now we will create three classes for our three receivers, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;AsiaServer&lt;/span&gt; class, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;EuroServer&lt;/span&gt; class, and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;USAServer&lt;/span&gt; class. All classes will implement &lt;span style=&quot;color: #6fa8dc;&quot;&gt;IReciever&lt;/span&gt; interface methods, that for simplicity will print out a message.
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;AsiaServer&lt;/span&gt; class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class AsiaServer : IReciever
{
    public void Connect()
    {
        Console.WriteLine(&quot;You are connect to Asia Server.&quot;);
    }

    public void Diagnostics()
    {
        Console.WriteLine(&quot;The Asia server dignostics check out OK.&quot;);
    }

    public void Reboot()
    {
        Console.WriteLine(&quot;Rebooting The Asia Server.&quot;);
    }

    public void Shutdown()
    {
        Console.WriteLine(&quot;Shutting down The Asia Server.&quot;);
    }

    public void Disconnect()
    {
        Console.WriteLine(&quot;You are disconnected from Asia Server.&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;EuroServer&lt;/span&gt; and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;USAServer&lt;/span&gt; classes will be as &lt;span style=&quot;color: #6fa8dc;&quot;&gt;AsiaServer&lt;/span&gt;&amp;nbsp;class with changing the messages that will print correspondingly. you can download the full source from &lt;a href=&quot;http://db.tt/gg8WtN3g&quot;&gt;here&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Commands are preconfigured to perform various actions. To make them do their thing, you typically call an &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Execute()&lt;/span&gt; method. In our example we have three commands so we will create a class for each command, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;ShutdownCommand&lt;/span&gt; class, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RebootCommand&lt;/span&gt; class, and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RunDiagnosticsCommand&lt;/span&gt; class. Each of these can perform the action corresponding to its name, and each of these can be configured to work with a specific receiver.

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;format=728x90_as&amp;output=html&amp;h=90&amp;w=728&amp;lmt=1327217389&amp;host=pub-1556223355139109&amp;h_ch=L0202%2BS0013&amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;flash=11.1.102&amp;url=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html&amp;dt=1327224589741&amp;shv=r20100101&amp;jsv=r20100101&amp;correlator=1327224589859&amp;pv_h_ch=L0202&amp;frm=4&amp;adk=2737856453&amp;ga_vid=1879422280.1326271734&amp;ga_sid=1327222480&amp;ga_hid=1770073439&amp;ga_fc=1&amp;u_tz=120&amp;u_his=6&amp;u_java=1&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=32&amp;u_nplug=12&amp;u_nmime=52&amp;biw=1440&amp;bih=785&amp;ref=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html&amp;loc=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html&amp;fu=0&amp;js=uds&amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;

First we will create a base class contains two methods, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Execute()&lt;/span&gt; method to execute the command, and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Undo()&lt;/span&gt; method to undo the command, and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;IReceiver&lt;/span&gt; object that is the receiver will be handled.
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Command&lt;/span&gt;&amp;nbsp;class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public abstract class Command
{
    protected IReciever Receiver { get; set; }

    public abstract void Execute();
    public abstract void Undo();
}
&lt;/code&gt;&lt;/pre&gt;
Now will create our commands classes that inherit &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Command&lt;/span&gt; class. We will pass the receiver that it will work on into its constructor.
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;ShutdownCommand&lt;/span&gt;&amp;nbsp;class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class ShutdownCommand : Command
{
    public ShutdownCommand(IReciever receiver)
    {
        Receiver = receiver;
    }
    public override void Execute()
    {
        Receiver.Connect();
        Receiver.Shutdown();
        Receiver.Disconnect();
    }
    public override void Undo()
    {
        Console.WriteLine(&quot;Undoing......&quot;);
        Receiver.Connect();
        Receiver.Reboot();
        Receiver.Disconnect();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;RunDiagnosticsCommand&lt;/span&gt;&amp;nbsp;class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class RunDiagnosticsCommand : Command
{
    public RunDiagnosticsCommand(IReciever receiver)
    {
        Receiver = receiver;
    }
    public override void Execute()
    {
        Receiver.Connect();
        Receiver.Diagnostics();
        Receiver.Disconnect();
    }
    public override void Undo()
    {
       Console.WriteLine(&quot;Can&#39;t Undo....&quot;);
    }
}
&lt;/code&gt;&lt;/pre&gt;
Note the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Undo()&lt;/span&gt; Method, it just displays a message because actually we can&#39;t undo the diagnostics process just we run it.
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;RebootCommand&lt;/span&gt;&amp;nbsp;class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class RebootCommand : Command
{
    public RebootCommand(IReciever receiver)
    {
        Receiver = receiver;
    }
    public override void Execute()
    {
        Receiver.Connect();
        Receiver.Reboot();
        Receiver.Disconnect();
    }
    public override void Undo()
    {
        Console.WriteLine(&quot;Undoing......&quot;);
        Receiver.Connect();
        Receiver.Shutdown();
        Receiver.Disconnect();
    }
}
&lt;/code&gt;&lt;/pre&gt;
That gives you the receivers and the command classes that act on those receivers.

&lt;iframe width=&quot;728&quot; height=&quot;90&quot; frameborder=&quot;0&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;format=728x90_as&amp;output=html&amp;h=90&amp;w=728&amp;lmt=1327217389&amp;host=pub-1556223355139109&amp;h_ch=L0202%2BS0013&amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;flash=11.1.102&amp;url=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html&amp;dt=1327224589741&amp;shv=r20100101&amp;jsv=r20100101&amp;correlator=1327224589859&amp;pv_h_ch=L0202&amp;frm=4&amp;adk=2737856453&amp;ga_vid=1879422280.1326271734&amp;ga_sid=1327222480&amp;ga_hid=1770073439&amp;ga_fc=1&amp;u_tz=120&amp;u_his=6&amp;u_java=1&amp;u_h=900&amp;u_w=1440&amp;u_ah=870&amp;u_aw=1440&amp;u_cd=32&amp;u_nplug=12&amp;u_nmime=52&amp;biw=1440&amp;bih=785&amp;ref=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html&amp;loc=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html&amp;fu=0&amp;js=uds&amp;eid=37464000&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;visibility: visible; &quot;&gt;&lt;/iframe&gt;

Now we will create the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Invoker&lt;/span&gt; class that actually puts the commands to work. You typically load a command object into the invoker and tell the invoker to run it. Sometimes you may not need to use the invoker and want to dispense with the invoker altogether and just call the execute method. But the invoker can also keep track of multiple commands in a log or a queue, which make undoing a sequence of commands possible.&lt;br /&gt;
&lt;br /&gt;
The &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Invoker&lt;/span&gt; class starts with a collection of commands to be available when undoing, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;AddCommand()&lt;/span&gt; method for add a new command to the command collection, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Run()&lt;/span&gt; method that will call the execute method of the command, and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Undo()&lt;/span&gt; method to call the undo method of the command.
&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Invoker&lt;/span&gt;&amp;nbsp;class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class Invoker
{
    private List&lt;command&gt;&lt;/command&gt; Commands { get; set; }
    private Int32 Position { get; set; }

    public Invoker()
    {
        Commands = new List&lt;command&gt;&lt;/command&gt;();
        Position = -1;
    }

    public void AddCommand(Command command)
    {
        Commands.Add(command);
        Position++;
    }
    public void Run()
    {
        Commands[Position].Execute();
    }
    public void Undo()
    {
        if (Position &amp;gt;= 0)
        {
            Commands[Position].Undo();
        }
        Position--;
    }
}
&lt;/code&gt;&lt;/pre&gt;
To test our command pattern we need to prepare the receivers objects, servers objects in our example.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;AsiaServer asia = new AsiaServer();
EuroServer euro = new EuroServer();
USAServer usa = new USAServer();
&lt;/code&gt;&lt;/pre&gt;
Then prepare the commands 
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;ShutdownCommand shutdownasia = new ShutdownCommand(asia);
RunDiagnosticsCommand diagnosticeuro = new RunDiagnosticsCommand(euro);
RebootCommand rebootusa = new RebootCommand(usa);
ShutdownCommand shutdowneuro = new ShutdownCommand(euro);
&lt;/code&gt;&lt;/pre&gt;
Note we pass the recevier object to the command that will work on it.&lt;br /&gt;
&lt;br /&gt;
Create the invoker object ,add commands to invoker, and call run method of invoker object or undo method
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;invoker.AddCommand(shutdownasia);
invoker.Run();
Console.WriteLine(&quot;***********************************************&quot;);
invoker.AddCommand(rebootusa);
invoker.Run();
Console.WriteLine(&quot;***********************************************&quot;);
invoker.AddCommand(shutdowneuro);
invoker.Run();
Console.WriteLine(&quot;***********************************************&quot;);
invoker.AddCommand(diagnosticeuro);
invoker.Run();
&lt;/code&gt;&lt;/pre&gt;
Note we add a command and call run method directly, because the run method will run the last command we added.The result of these commands will be
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;You are connect to Asia Server.
Shutting down The Asia Server.
You are disconnected from Asia Server.
***********************************************
You are connect to USA Server.
Rebooting The USA Server.
You are disconnected from USA Server.
***********************************************
You are connect to Euro Server.
Shutting down The Euro Server.
You are disconnected from Euro Server.
***********************************************
You are connect to Euro Server.
The Euro server dignostics check out OK.
You are disconnected from Euro Server.&lt;/code&gt;&lt;/pre&gt;
If we call the undo method of the invoker it will undo the last action, but we will call it twice to undo the last two actions
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;invoker.Undo();
Console.WriteLine(&quot;***********************************************&quot;);
invoker.Undo();
&lt;/code&gt;&lt;/pre&gt;
And the result will be&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Can&#39;t Undo....
***********************************************
Undoing......
You are connect to Euro Server.
Rebooting The Euro Server.
You are disconnected from Euro Server.&lt;/code&gt;&lt;/pre&gt;
Note the fisrt line of the output that because the last command we run was &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RunDiagnosticsCommand&lt;/span&gt;.
&lt;br /&gt;
&lt;br /&gt;
That is what the &lt;i&gt;Command Pattern&lt;/i&gt;&amp;nbsp;is all about - encapsulating commands. As mentioned earlier, this encapsulation is a little different from the usual, where you end up with an object that you can think of as a noun. Here, you think of the resulting object more as a verb. And when you use an invoker, you can handle whole sequences of commands and undo them if needed.&lt;br /&gt;
&lt;br /&gt;
you can download the full source code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzYll6VGh0cDFyNm8&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/365606064450508598/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/365606064450508598'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/365606064450508598'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-16-command.html' title='Design Patterns Series 16 - Command Pattern'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>0</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8395299768708339226.post-3154651861661790697</id><published>2012-01-23T19:10:00.002+02:00</published><updated>2017-05-05T17:23:26.865+02:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="C#"/><category scheme="http://www.blogger.com/atom/ns#" term="Design Patterns"/><category scheme="http://www.blogger.com/atom/ns#" term="State"/><category scheme="http://www.blogger.com/atom/ns#" term="State Pattern"/><title type='text'>Design Patterns Series 15 - State Pattern</title><content type='html'>&lt;style type=&quot;text/css&quot;&gt;
pre.source-code {
  font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; 
  color: #000000;
  background-color: #cfe2f3;
  font-size: 12px;
  border: 1px dashed #999999;
  line-height: 14px;
  padding: 5px;
  overflow: auto;
  width: 100%
}
&lt;/style&gt;

This Post will be about &lt;i&gt;The State Pattern&lt;/i&gt; where an object keeps track of its internal state, and can change its behavior based on that state.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: blue;&quot;&gt;The State Pattern :
&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
The &lt;i&gt;State Design Pattern&lt;/i&gt; will &quot;&lt;i&gt;Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.&lt;/i&gt;&quot; In other words your code should keep track of an internal state. Any part of the code can check what the current state is and react accordingly.&lt;br /&gt;
&lt;br /&gt;
When you use the &lt;i&gt;State Pattern&lt;/i&gt;, any part of your code can check what state is current. That clarify and centralize the workings of very large pieces of code because you have control over what far-flung code segments do, just by changing the current state.&lt;br /&gt;
&lt;br /&gt;
In general, The &lt;i&gt;State Pattern&lt;/i&gt; is useful when you have got a lot of code that&#39;s getting more and more murky and complex. If you can compartmentalize the working of what you are trying to do into a set of independent states, you can&amp;nbsp;compartmentalize your code.&lt;br /&gt;
&lt;br /&gt;
To use &lt;i&gt;State Pattern&lt;/i&gt; in your code, instead of giving each state its own constant, it&#39;s better idea to give each state its own class. That way, you can call all methods on a state object anywhere in your code. All you have to do is load the correct state object into a generic variable and call various methods of that variable.&lt;br /&gt;
&lt;br /&gt;
To imagine how the &lt;i&gt;State Pattern&lt;/i&gt; can help us and when we can use it, Assume we want to make a system for car renting agency. The renting process contains four steps(states), Request a car, Check available cars, Make a rent, and give the car to the client. So the action will be taken depending on which step(state) of the renting process.&lt;br /&gt;
&lt;br /&gt;
To Start building our system using &lt;i&gt;State Pattern&lt;/i&gt; we will create an abstract class(&lt;span style=&quot;color: #6fa8dc;&quot;&gt;RentCar&lt;/span&gt;) with all methods we need in renting process.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;RentCar&lt;/span&gt; class&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public abstract class RentCar
{
    public abstract void RequestCar();
    public abstract void CheckRequest();
    public abstract void CarRental();

    public abstract void SetState(State state);

    public abstract State GetWaitingState();
    public abstract State GetRequestCarState();
    public abstract State GetCarRentedState();
    public abstract State GetNoAvailableCarsState();

    public Int32 AvailableCars { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;iframe frameborder=&quot;0&quot; height=&quot;90&quot; marginheight=&quot;0&quot; marginwidth=&quot;0&quot; scrolling=&quot;no&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;amp;format=728x90_as&amp;amp;output=html&amp;amp;h=90&amp;amp;w=728&amp;amp;lmt=1327217389&amp;amp;host=pub-1556223355139109&amp;amp;h_ch=L0202%2BS0013&amp;amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;amp;flash=11.1.102&amp;amp;url=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html&amp;amp;dt=1327224589741&amp;amp;shv=r20100101&amp;amp;jsv=r20100101&amp;amp;correlator=1327224589859&amp;amp;pv_h_ch=L0202&amp;amp;frm=4&amp;amp;adk=2737856453&amp;amp;ga_vid=1879422280.1326271734&amp;amp;ga_sid=1327222480&amp;amp;ga_hid=1770073439&amp;amp;ga_fc=1&amp;amp;u_tz=120&amp;amp;u_his=6&amp;amp;u_java=1&amp;amp;u_h=900&amp;amp;u_w=1440&amp;amp;u_ah=870&amp;amp;u_aw=1440&amp;amp;u_cd=32&amp;amp;u_nplug=12&amp;amp;u_nmime=52&amp;amp;biw=1440&amp;amp;bih=785&amp;amp;ref=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html&amp;amp;loc=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html&amp;amp;fu=0&amp;amp;js=uds&amp;amp;eid=37464000&quot; style=&quot;visibility: visible;&quot; width=&quot;728&quot;&gt;&lt;/iframe&gt;

The first three methods for renting process, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;SetState()&lt;/span&gt; method for changing the current state, the next four methods to get corresponding state object, and the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;AvailableCars&lt;/span&gt; property to hold the number of available car in the agency.&lt;br /&gt;
&lt;br /&gt;
Now it&#39;s time to create the renting process itself by create a class that inherit &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RentCar&lt;/span&gt; class and implement its methods.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;Rent&lt;/span&gt; Class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class Rent : RentCar
{
    private State waitingState;
    private State requestCarState;
    private State carRentedState;
    private State noAvailableCarsState;
    private State myState;

    public Rent(Int32 carsCount)
    {
        AvailableCars = carsCount;
        waitingState = new WaitingState(this);
        requestCarState = new RequestCarState(this);
        carRentedState = new CarRentedState(this);
        noAvailableCarsState = new NoAvailableCarsState(this);
        myState = waitingState;
    }
}
&lt;/code&gt;&lt;/pre&gt;
Note the constructor accepts the number of availabe cars, instantiates four state objects, one for each state, and set the current state,&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;myState&lt;/span&gt;,&amp;nbsp;to &lt;span style=&quot;color: #6fa8dc;&quot;&gt;WaitingState&lt;/span&gt; object.
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public override void RequestCar()
{
    Console.WriteLine(myState.GotCarRequest());
}
public override void CheckRequest()
{
    Console.WriteLine(myState.CheckRequest());
}
public override void CarRental()
{
    Console.WriteLine(myState.CarRental());
    Console.WriteLine(myState.ReceiveCar());
}

public override void SetState(State state)
{
    myState = state;
}

public override State GetWaitingState()
{
    return waitingState;
}
public override State GetRequestCarState()
{
    return requestCarState;
}
public override State GetCarRentedState()
{
    return carRentedState;
}
public override State GetNoAvailableCarsState()
{
    return noAvailableCarsState;
}
&lt;/code&gt;&lt;/pre&gt;
We override methods of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RentCar&lt;/span&gt; class and implements all required methods to complete the rental process, setting current state, and getting current state of the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Rent&lt;/span&gt; object.&lt;br /&gt;
&lt;iframe frameborder=&quot;0&quot; height=&quot;90&quot; marginheight=&quot;0&quot; marginwidth=&quot;0&quot; scrolling=&quot;no&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;amp;format=728x90_as&amp;amp;output=html&amp;amp;h=90&amp;amp;w=728&amp;amp;lmt=1327217389&amp;amp;host=pub-1556223355139109&amp;amp;h_ch=L0202%2BS0013&amp;amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;amp;flash=11.1.102&amp;amp;url=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html&amp;amp;dt=1327224589741&amp;amp;shv=r20100101&amp;amp;jsv=r20100101&amp;amp;correlator=1327224589859&amp;amp;pv_h_ch=L0202&amp;amp;frm=4&amp;amp;adk=2737856453&amp;amp;ga_vid=1879422280.1326271734&amp;amp;ga_sid=1327222480&amp;amp;ga_hid=1770073439&amp;amp;ga_fc=1&amp;amp;u_tz=120&amp;amp;u_his=6&amp;amp;u_java=1&amp;amp;u_h=900&amp;amp;u_w=1440&amp;amp;u_ah=870&amp;amp;u_aw=1440&amp;amp;u_cd=32&amp;amp;u_nplug=12&amp;amp;u_nmime=52&amp;amp;biw=1440&amp;amp;bih=785&amp;amp;ref=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html&amp;amp;loc=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html&amp;amp;fu=0&amp;amp;js=uds&amp;amp;eid=37464000&quot; style=&quot;visibility: visible;&quot; width=&quot;728&quot;&gt;&lt;/iframe&gt;


As we mentioned earlier,&amp;nbsp;&amp;nbsp;it&#39;s better to give each state its own class. We will create an abstract class, &lt;span style=&quot;color: #6fa8dc;&quot;&gt;State&lt;/span&gt;, to be the base for all states objects.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;State&lt;/span&gt; Class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public abstract class State
{
    protected State(RentCar rentcar)
    {
        RentCar = rentcar;
    }
    public abstract String GotCarRequest();
    public abstract String CheckRequest();
    public abstract String CarRental();
    public abstract String ReceiveCar();

    public RentCar RentCar { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;
The constructor accepts an instance of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RentCar&lt;/span&gt; that its state changes and we have four methods for four different states. The implementation of these four methods will differ from one state to another, so We will create four classes for our four states.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;color: #6fa8dc;&quot;&gt;WaitingState&lt;/span&gt; Class
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;public class WaitingState : State
{
    public WaitingState(RentCar rentcar)
        :base(rentcar)
    {
    }
    public override String GotCarRequest()
    {
        RentCar.SetState(RentCar.GetRequestCarState());
        return &quot;We have recieved your request&quot;;
    }
    public override String CheckRequest()
    {
        return &quot;You have to submit a request&quot;;
    }
    public override String CarRental()
    {
        return &quot;You have to submit a request&quot;;
    }
    public override String ReceiveCar()
    {
        return &quot;You have to submit a request&quot;;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;iframe frameborder=&quot;0&quot; height=&quot;90&quot; marginheight=&quot;0&quot; marginwidth=&quot;0&quot; scrolling=&quot;no&quot; src=&quot;http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-5399953879255109&amp;amp;format=728x90_as&amp;amp;output=html&amp;amp;h=90&amp;amp;w=728&amp;amp;lmt=1327217389&amp;amp;host=pub-1556223355139109&amp;amp;h_ch=L0202%2BS0013&amp;amp;alternate_ad_url=http://img2.blogblog.com/img/blogger_ad.html&amp;amp;flash=11.1.102&amp;amp;url=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html&amp;amp;dt=1327224589741&amp;amp;shv=r20100101&amp;amp;jsv=r20100101&amp;amp;correlator=1327224589859&amp;amp;pv_h_ch=L0202&amp;amp;frm=4&amp;amp;adk=2737856453&amp;amp;ga_vid=1879422280.1326271734&amp;amp;ga_sid=1327222480&amp;amp;ga_hid=1770073439&amp;amp;ga_fc=1&amp;amp;u_tz=120&amp;amp;u_his=6&amp;amp;u_java=1&amp;amp;u_h=900&amp;amp;u_w=1440&amp;amp;u_ah=870&amp;amp;u_aw=1440&amp;amp;u_cd=32&amp;amp;u_nplug=12&amp;amp;u_nmime=52&amp;amp;biw=1440&amp;amp;bih=785&amp;amp;ref=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html&amp;amp;loc=http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html&amp;amp;fu=0&amp;amp;js=uds&amp;amp;eid=37464000&quot; style=&quot;visibility: visible;&quot; width=&quot;728&quot;&gt;&lt;/iframe&gt;


This class represents the waiting state of our object so the client can only make a request to rent a car, just he made that request we set the current state to &lt;span style=&quot;color: #6fa8dc;&quot;&gt;RequestCarState&lt;/span&gt;. If the client called another method first, the system must refuse his action because the current state is &lt;span style=&quot;color: #6fa8dc;&quot;&gt;WaitingState&lt;/span&gt; and the only allowed action is making a request.&lt;br /&gt;
&lt;br /&gt;
The same thing with the other three states that will be represented by three classes,&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;RequestCarState&lt;/span&gt; class,&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;CarRentedState&lt;/span&gt; class, and &lt;span style=&quot;color: #6fa8dc;&quot;&gt;NoAvailableCarsState&lt;/span&gt; class. You can refer to &lt;a href=&quot;http://db.tt/gcWPrrO7&quot;&gt;source code&lt;/a&gt; to see their implementation.&lt;br /&gt;
&lt;br /&gt;
To test our car rental system, we just need to instantiate an instance of &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Rent&lt;/span&gt; class passing it the total number of available cars then call&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;RequestCar()&lt;/span&gt;,&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;CheckRequest()&lt;/span&gt;, and&amp;nbsp;&lt;span style=&quot;color: #6fa8dc;&quot;&gt;CarRental()&lt;/span&gt; methods respectively.&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;Rent _rent = new Rent(10);
_rent.RequestCar();
_rent.CheckRequest();
_rent.CarRental();
&lt;/code&gt;&lt;/pre&gt;
The result we be according to the available cars in the agency(in the example we assumed the total available car is 10). If there is available cars to be rent the output will be
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;We have recieved your request
Your request was approved
Renting you a car...
Here are your car&lt;/code&gt;&lt;/pre&gt;
If there is no available cars to be rent the output will be
&lt;br /&gt;
&lt;pre class=&quot;source-code&quot;&gt;&lt;code&gt;We have recieved your request
Sorry, your request wasn&#39;t approved
You have to submit a request
You have to submit a request&lt;/code&gt;&lt;/pre&gt;
You have simplified the code in the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Rent&lt;/span&gt; dramatically by offloading it to &lt;span style=&quot;color: #6fa8dc;&quot;&gt;State&lt;/span&gt; objects. The code in the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;Rent&lt;/span&gt; doesn&#39;t have to change to handle different states; only the &lt;span style=&quot;color: #6fa8dc;&quot;&gt;State&lt;/span&gt; object itself changes. And each new &lt;span style=&quot;color: #6fa8dc;&quot;&gt;State&lt;/span&gt; object has its own built-in methods to handle any requests made of it, appropriately, for the state it represents. By encapsulating how you handle each state in separate &lt;span style=&quot;color: #6fa8dc;&quot;&gt;State&lt;/span&gt; objects, the code is easier to modify and maintain.&lt;br /&gt;
&lt;br /&gt;
you can download the full source code &lt;a href=&quot;https://drive.google.com/open?id=0B8yEdXzvvaQzN0FhaHZlbUFXc0U&quot;&gt;here&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://miroprocessordev.blogspot.com/feeds/3154651861661790697/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/3154651861661790697'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8395299768708339226/posts/default/3154651861661790697'/><link rel='alternate' type='text/html' href='http://miroprocessordev.blogspot.com/2012/01/design-patterns-series-15-state-pattern.html' title='Design Patterns Series 15 - State Pattern'/><author><name>Amir Ismail</name><uri>http://www.blogger.com/profile/14854622422742609715</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgzWClvKaNwWk83eEsbgw5BT_Tv8GXl51tkJy-EaETN0MTnR0zPzXlr5D-Gx2tgbIyIxmqvCqtl6X6b8yn8c0Gy54je6PgFGMNh7boCranDwLOWYRV1uz1vMySXcSb4Zw/s220/myAvatar.png'/></author><thr:total>2</thr:total><georss:featurename>Cairo, Egypt</georss:featurename><georss:point>30.04449 31.2356947</georss:point><georss:box>30.0307475 31.2159537 30.0582325 31.2554357</georss:box></entry></feed>