Saturday, June 15, 2013

Create sample application using Microsoft sync framework

The Sync Framework ships with the following three out-of-the-box synchronization providers.

·         Synchronization provider for files and folders.
·         Synchronization provider for ADO.NET-enabled data sources
·          Synchronization provider for RSS and Atom feeds


Using the built-in sync providers is very easy. The tasks can be summarized as follows:

1. Create unique Globally Unique Identifiers (GUIDs) for the source replica and
destination replica.
2. Create a source provider by creating a new instance of the built-in provider and
attaching the source provider to the source replica.
3. Create a destination provider by creating a new instance of the built-in provider
and attaching the destination provider to the destination replica.
4. Create a new instance of a sync agent and attach the source and destination
provider to it.
5. Set the direction of the synchronization by using the sync agent. The sync application
can now use the sync agent to start synchronization.

Let’s now dig into some code. Recall that the file sync provider helps to synchronize the
files, folders, and subfolders.

1.    Create a new Windows Forms application using Visual Studio 2010 and name it
SyncApp_BuiltInFileProviders as shown below screen shot.



2.    Add a reference to Microsoft.Synchronization and Microsoft.Synchronization.
Files. (The Add Reference dialog box shown in below can be launched by
right-clicking the project in Solution Explorer and clicking Add a Reference.)


3.    Place a button on form1 and name it btnSynchronize with this text: Synchronize.
Double-click the button to wire an event handler for the button.

4.  Place a label on the form with its Name as label1 and text as Click on Synchronize
button to start the synchronization.

5. Add two folders in your C drive and name them Image1 and Image2. Create a
new texts file in Image1 and name it Image1.txt. Open the file and type some
text into it.

6.In the using block at the top of the form1.cs, add the following two namespaces:

using Microsoft.Synchronization;
using Microsoft.Synchronization.Files;

7. Create two new GUIDs for the source and destination replicas, as shown in the
following code:

        Guid sourceReplicaId;
        Guid destReplicaId;
        private void Form1_Load(object sender, EventArgs e)
        {
            //Assign Unique Guid's to the Replicas
            sourceReplicaId = Guid.NewGuid();
            destReplicaId = Guid.NewGuid();
        }

8. Write the following code in the btnSynchronize_Click event (the main logic of the
code resides in this event):

       private void btnSynchronize_Click(object sender, EventArgs e)
        {

          btnSynchronize.Enabled = False;
            //Create the Source and destination Sync provider.
            //Attach the source sync provider to C:\Image1 folder and
            //assign it a unique replica guid.
            FileSyncProvider sourceProvider = new FileSyncProvider(sourceReplicaId,
            @"C:\ Image1 ");
            //Attach the destination sync provider to C:\ Image2 folder and
            //assign it a a unique replica guid.
            FileSyncProvider destProvider = new
            FileSyncProvider(destReplicaId, @"C:\ Image2");
            //syncAgent is the Sync Controller and it co-ordinates the sync session
            SyncOrchestrator syncAgent = new SyncOrchestrator();
            syncAgent.LocalProvider = sourceProvider;
            syncAgent.RemoteProvider = destProvider;
            syncAgent.Synchronize();
            label1.Text = "Synchronizing Finished...";
            btnSynchronize.Enabled = True;

        }


The code is incredibly simple. We created the source and destination sync providers
by passing the replica IDs and the folder name as a parameter. Then we
created a new instance of SyncOrchestrator (also known as the sync agent) and

attached the two providers to it. Finally we called the Synchronize method on it.
That’s it; we wrote the code to synchronize two replicas (Image1 and Image2)
using two instances of a built-in file sync provider.

Run the application and click the Synchronize button.



Introduction to Microsoft Sync Framework

Overview
Microsoft Sync Framework is a comprehensive synchronization platform that enables collaboration and offline access for applications, services, and devices. It features technologies and tools that enable roaming, sharing, and taking data offline. Using Microsoft Sync Framework, developers can build sync ecosystems that integrate any application, with any data from any store using any protocol over any network.

Benefits of Synchronization

Synchronization can be described as the process of bringing together two end points or data stores. When the contents of the two data stores are the same, they are known to be in sync with each other. For example, if you want to synchronize two databases manually,
you do the following.

1      1    Determine changes in the source database.
  2     Send the changes to the destination database.
  3      Apply the source’s changes to the destination database.
  4   Repeat the previous steps by swapping the source and destination databases.


·         Takes the application, store, or services offline: The biggest advantage of synchronization is that it enables you to take your application offline. If you build synchronization into your application, users of the application can interact with their local data stores until they need the items that are not contained in a local repository or until the application is back online.

·         Builds a faster and richer user interface: Building synchronization into the application allows you to build a richer user interface without worrying about the performance of the application. Because data is usually fetched from a local store, your application can provide faster responses.

·         Reduces the network cost: Sync-enabled applications or services upload and download only incremental changes, thereby reducing the amount of the data that needs to be sent over the network.

Now that you understand the need for synchronization, the next section examines some issues associated with synchronization and how Sync Framework can resolve them.

Life Before Sync Framework

The importance of Sync Framework can’t be understood without discussing problems
involved while implementing synchronization, including the following:

·    Storage and application errors and failover handling: Imagine that you’re synchronizing two databases, and an application error such as a connection timeout or a constraint violation occurs while changes to the destination database are applied. What happens to the record that needs to be synchronized? It is the responsibility of the Sync Framework to recover from such application and storage errors. 


   •   Network failure: Imagine the same example of synchronizing two databases. What
happens if one of the databases is downloading changes from another and suddenly
the Internet connection goes down? Sync Framework can recover the network
failures.
  •   Conflict detection: A conflict is said to occur if the same item was modified at both
end points at the same time. The Sync Framework should be able to detect the
conflicts and provide a mechanism to resolve or log the conflicts.

Installing Microsoft Sync Framework

At the time of writing, Microsoft Sync Framework 1.0 was the latest release. You can get a
copy of the Microsoft Sync Framework software development kit (SDK) in three ways:

   • Sync Framework ships with Microsoft SQL Server 2008.

  • Sync Framework ships with Microsoft Visual Studio 2008 Service Pack 1.

  • You can download the Sync Framework from the Microsoft download page:

www.microsoft.com/downloads/details.aspx?FamilyId=C88BA2D1-CEF3-4149-
B301-9B056E7FB1E6&displaylang=en.

Core Components

The Sync Framework comes with support for ADO.NET, file systems, RSS, Atom feeds,
and even custom data stores. You can divide the components of the Sync Framework into
the following three categories:

  • Microsoft Sync Framework runtime: This SDK allows developers to use the built-in
sync providers and create their own sync providers.

   • Metadata services: Provide the necessary infrastructure to store the sync metadata.
Sync metadata is used by the Sync Framework runtime during the synchronization.
The Sync Framework ships with the built-in Microsoft SQL Server Compact Edition
(CE) that can be used to store the metadata.
  • Built-in providers: The Sync Framework ships with the following three built-in
providers:

o    Synchronization services for ADO.NET provide offline and collaboration support
for ADO.NET enabled data stores.
o    Synchronization services for SSEs are the built-in providers for synchronizing RSS
and Atom feeds.
o    Synchronization services for file systems are the built-in providers for synchronizing
files and folders on Win32-compatible file systems. 




Synchronization Flow:

Synchronization providers enable you to synchronize data between different replicas.
Replicas are also known as end points or data stores. The actual data is stored in the replica. You need to have one sync provider for each replica for the replica to synchronize its data with other replicas. A replica synchronizes its data with another replica by establishing a sync session.


As shown in below screen shot, synchronization providers communicate with each other using a sync session. The two sync providers are attached to the sync agent, and the sync application initiates the communication between the two providers using the sync agent. The sync agent is responsible for establishing and managing the sync session. Sync providers can receive and apply changes to the replicas. There are two sync providers on the top of the Sync Framework runtime: the source sync provider and destination sync provider, respectively.

After being invoked by a sync agent, the destination sync provider sends its knowledge
to the source sync provider. The source provider uses this knowledge to determine the
changes and sends its knowledge to the destination. The destination provider compares
its knowledge with the source, resolves the conflicts, and then sends the request to the
source provider for changed data. The source provider sends the changes to the destination
provider, and the destination provider applies the changes to the destination replica.
Within a sync session, synchronization flow is always in one direction. What this means is
that the source provider and the destination provider cannot work simultaneously. At any
given point within a sync session, information flows between the source and destination
replicas or between destination and source replicas, but doesn’t flow simultaneously
between both.

In its simple form, a sync session contains a sync agent and two sync providers. One of the providers is a source provider that sends the changes; the other is a destination provider that receives and applies the changes. Of course, the sync agent controls this flow.

The sync providers shown in below screen shot illustrate a scenario in which the metadata is
stored in the built-in metadata store provided by the Sync Framework, which is very easy
to use and is built on top of the SQL Server.




Click here to create sample application using Microsoft sync framework.

















Monday, May 27, 2013

Aps.net Cache Concepts

Cache is the technique of persisting the data in the memory for immediate access to requesting program calls. One of the most important factors in building high-performance, scalable Web applications is the ability to store items, whether data objects, pages, or parts of a page, in memory the initial time they are requested.

Although both Application and Cache objects look the same, the key difference between them is the added features provided by the Cache object like the expiration policies and dependencies. It means that the data stored in the cache object can be expired/removed based on some predefined time limit set by the application code or when the dependent entity gets changed whereas this feature is not available in the Application object.
Caches are two different types:

·         Page Level Output Caching
·         Fragment Caching              

Page Level Output Caching:
This is at the page level and one of the easiest means for caching pages. This requires one to specify Duration of cache and Attribute of caching.

Syntax: 
<%@ OutputCache Duration="60" VaryByParam="none" %>

The above syntax specifies that the page be cached for duration of 60 seconds and the value "none" for VaryByParam* attribute makes sure that there is a single cached page available for this duration specified.

* VaryByParam can take various "key" parameter names in query string. Also there are other attributes like VaryByHeader, VaryByCustom etc.

Fragment Caching:
Even though this definition refers to caching portion/s of page, it is actually caching a user control that can be used in a base web form page. In theory, if you have used include files in the traditional ASP model then this caching model is like caching these include files separately. In ASP.NET more often this is done through User Controls. Initially even though one feels a bit misleading, this is a significant technique that can be used especially when implementing "n" instances of the controls in various *.aspx pages. We can use the same syntax that we declared for the page level caching as shown above, but the power of fragment caching comes from the attribute "VaryByControl". Using this attribute one can cache a user control based on the properties exposed.

Syntax: 
<%@ OutputCache Duration="60" VaryByControl="DepartmentId" %>

The above syntax when declared within an *.ascx file ensures that the control is cached for 60 seconds and the number of representations of cached control is dependant on the property "DepartmentId" declared in the control. 

Add the following into an *.ascx file. Please note the use of tag "Control" and the cache declaration.

<%@ Control Language="C#"%>
<%@ outputcache duration="60" varybycontrol="DepartMentId" %>

<script runat="server">
private
 int _Departmentid=0;
public int DepartMentId
{
get{return _Departmentid;}
set{_Departmentid =value;}
}
//Load event of control
void Page_Load(Object sender, EventArgs e)
{
lblText.Text = "Time is " + DateTime.Now.ToString() + " for Department id = " 
+ _Departmentid + "\n";
}
</script>
<
asp:Label id="lblText" runat="server"></asp:Label>

Add the following to an *.aspx file. Please note the way "Register" tag is used; the declaration of control using syntax <[TagPrefix]:[TagName]>; Usage of property " DepartMentId". Open the page in two browsers and closely watch the Base form timing and the User control timing. Also note that the following page results in two copies or representation of user control in the cache.
Let us discuss about different expiration polices and dependencies that are supported.

Dependency:
Dependency means that the ad item can be removed from cache when the dependent gets changed So a dependent relationship can be defined on an item whose removal from the cache will depend on the dependent. There are three types of dependencies supported in ASP.NET.

·             File dependency: - Allows you to invalidate a specific cache item when a disk
based file or files change.
 Time-based expiration: - Allows you to invalidate a specific cache item depending
on predefined time.
Key dependency:- Allows you to invalidate a specific cache item depending when
another cached item changes.

File dependency:
public void displayAnnouncement()
        {
            string announcement = string.Empty;
            if( Cache["announcement"]==null )
            {
                StreamReader file = new StreamReader(@"D:\sekhar.txt");
                announcement = file.ReadToEnd();
                file.Close();
                CacheDependency depends = new CacheDependency(@"D:\sekhar.txt");
                Cache.Insert("announcement", announcement, depends);
                Response.Write(Convert.ToString(Cache["announcement"]));
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            displayAnnouncement();
        }

Above given method displayAnnouncement() displays banner text from Announcement.txt file
which is lying in application path of the file . Above method, first checks whether the
Cache object is nothing, if the cache object is nothing then it moves further to load the cache data
from the file. Whenever the file data changes the cache object is removed and set to nothing.

Time-based expiration:
Time based expiration provides an option to expire an item in the cache at a predefined time. The expiration time can be set as absolute time like 31st October 2005 12:00 or sliding time i.e. relative to the current time when the item is accessed.

    //Absolute Expiration
            Cache.Insert("StudentName", "Anish", null, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
            ////Sliding Expiration
            Cache.Insert("StudentName", "Akarsh", null, DateTime.Now.AddDays(1),TimeSpan.FromSeconds(60));

Key dependency: Key dependency is similar to file dependency but the only difference is that instead of a file the item is dependent on another item in the cache and gets invalidated when the dependent item gets changed or removed. This option is useful when multiple related items are added to the cache and those items are to be removed if the primary item is changed. For e.g. employee number, name, address and salary are added to the cache and if the employee number is updated/removed all the related employee information are removed. In this case the employee number dependency can be used for other employee information.

string[] relatedKeys = new string[1];
            relatedKeys[0] = "EMP_NUM";
            CacheDependency keyDependency = new CacheDependency(null, relatedKeys);
            Cache["EMP_NUM"] = 5435;
            Cache.Insert("EMP_NAME", "Anish", keyDependency);
            Cache.Insert("EMP_ADDR", "Tampa", keyDependency);
            Cache.Insert("EMP_SAL", "33647", keyDependency);