Thursday, December 23, 2010

SqlCacheDependency

following Steps those are required are given below:

Prepare the database:
In order to use the SqlCacheDependency class, the database has to be configured to use the service broker (notification services).
First check if the service broker is enabled:

SELECT is_broker_enabled FROM sys.databases WHERE name = 'Northwind'

When this query returns 1 the broker is enabled and we are done with SQL Server.
If not, enable the broker by using this alter table statement:

ALTER DATABASE Northwind SET ENABLE_BROKER

Two problems I have encountered using this statement:
1. It keeps running.
2. It returns error 9772: The Service Broker in database 'Northwind' cannot be enabled because there is already an enabled Service Broker with the same ID.

This problems can be solved by using resp.:
1. Change the statement to ALTER DATABASE Northwind SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE
2. First execute statement ALTER DATABASE Northwind SET NEW_BROKER and then again try to enable the broker.

Prepare the web application:
In the Global.asax file add the following statement to the Application_Start subroutine:
System.Data.SqlClient.SqlDependency.Start("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True")
And allmost the same statement in Application_Stop:
System.Data.SqlClient.SqlDependency.Stop("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True")

Using the Cache:
1) in Global.asax file under Application_Start method
SqlDependency.Start(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
2) in Global.asax file under Application_Stop method
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
3)Code

DataSet objDS = new DataSet();

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
SqlCommand cmd = new SqlCommand("select top 100 ID,CRN_ID from C1", con);
cmd.Notification = null;
cmd.NotificationAutoEnlist = true;
SqlCacheDependencyAdmin.EnableNotifications(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
if(!SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString).Contains("C1"))
{ SqlCacheDependencyAdmin.EnableTableForNotifications(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString, "C1");
}

SqlCacheDependency dependency = new SqlCacheDependency(cmd);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(objDS);

_cache.Insert("C1", objDS, dependency);


for more information please visit:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=263&AspxAutoDetectCookieSupport=1

.NET,ASP.NET: Application level data caching (File dependency) with callbacks

state management(cache management)

Now let's discuss different aspects of cache management (or state management) in ASP.NET.

Although cache management is not an issue in Windows applications, it has always been a challenge in the web environment. Since HTTP is a stateless protocol and a web server doesn't recognize users between different requests, it becomes very important for us to recognize a particular user between different requests and also store data so that it can be re-used between different requests. ASP.NET provides many features for storing data both in the client (browser) and the server (web server) sides, but sometimes we get confused with when to use what. In ASP.NET we come across features like Session, Application and Cache objects, but it is important for us to understand the difference between them in order to effectively use them in web applications.

Caching helps us to achieve three important aspects of QoS (Quality Of Service):

•Performance - Caching improves application performance by minimizing data retrieval and formatting operations.
•Scalability - Since caching minimizes data retrieval and formatting operations, it reduces the load on server resources thus increasing the scalability of the application.
•Availability - Since the application uses data from a cache, the application will survive failures in other systems and databases.

Server side cache management

ASP.NET session state is used to cache data per user session. It means that the data cannot be shared across multiple users and the data usage is limited to the user session it is created in. ASP.NET Session object is used for this purpose.

ASP.NET session state can be managed in three different ways:

•InProc - Stored in the aspnet_wp.exe process area. The session data is lost when the process or the application domain is recycled.
•StateServer - Session state is stored in a separate process (aspnet_state.exe) which can be stored in a different machine. Since it can be stored in a different machine, this option will work in a web farm scenario.
•SQLServer - Session state is stored in a SQL Server database. This option will also work in a web farm scenario.

ASP.NET application object
ASP.NET provides an object called Application object to store data that is accessible to all user requests. The life span of this object is tied to the application and it is re-created every time the application starts. Unlike ASP.NET Session object this object is accessible to all user requests. Since this storage is created and maintained in an application domain space, this should not be used for data storage in a web farm scenario. This option is very useful to store data like the application metadata (CONFIG files data) that can be loaded to the Application object during application start up and can be used during the life of the application without reloading it every time for each user request. But if there is a requirement to invalidate the cached data whenever there is any change to the CONFIG files while the application is running, this option should not be used as it doesn't provide any feature to expire the cached data. So in this case other options like the ASP.NET Cache object should be used, which is explained below.

ASP.NET cache object
ASP.NET provides a key-value pair object - the Cache object which is available in the System.Web.Caching namespace. The scope of it is the application domain and the life span is tied to the application. Unlike the ASP.NET Session object, this object is accessible to all user requests.

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.

Let us discuss the different expiration policies and the dependencies that are supported.

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

•File dependency - This provides an option to remove an item automatically from the cache whenever a disk file changes. Let's say in my application I am using an XML file to store error details (error number and error message mapping) which is used to retrieve an error message for a given error number at runtime. So instead of reading the file from the disk each time I need an error message, let's say I decide to load it once at application startup and store it in the ASP.NET cache for further use. So, if I need to change the CONFIG file to add new error messages or change some of the existing error messages while the application is running, then what will happen to my cached data? Do I need to stop the application and start it again to reflect the file changes in the application? The answer is no. The cache data can be invalidated whenever the file changes by using the File dependency option.

Example: in Global.asax file
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
//Common.ServiceManger.constant.LoadConstants();
_cache = HttpContext.Current.Cache;
FillConstantCache();
}

private void FillConstantCache()
{
//if (errorconstant == null)
//{
DataSet objDS = new DataSet();
string constantFile = string.Empty;
constantFile = "D:/DOTNETPROJECTS/TFSPROJECTS53/Test/AppConstants.xml";
CacheDependency dependency = new CacheDependency(constantFile);
objDS.ReadXml(constantFile);

//SqlConnection con = new SqlConnection("connectionString");
//SqlCommand cmd = new SqlCommand("select key,value from table", con);
//SqlCacheDependency dependency = new SqlCacheDependency(cmd);
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//da.Fill(objDS);

errorconstant = new Hashtable();
foreach (DataRow dr in objDS.Tables[0].Rows)
{
if (!errorconstant.Contains(dr[0].ToString()))
errorconstant.Add(dr[0].ToString(), dr[1].ToString());
}
_cache.Insert("appconstant", objDS, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, new CacheItemRemovedCallback(this.CacheItemRemoved));
//}

}

//this method used for callBack when you modified an AppConstants.xml
private void CacheItemRemoved(string key, object val, CacheItemRemovedReason reason)
{
FillConstantCache();
}

You call this from any web page like that:
lblname.Text = Global.errorconstant["keyname"].ToString();

for more information visit the following links:
http://weblogs.asp.net/kwarren/archive/2004/05/20/136129.aspx
http://www.codeproject.com/KB/web-cache/cachemanagementinaspnet.aspx

Monday, December 6, 2010

Difference between Implicit and Explicit Interface

There are 4 basic difference between Implicit and Explicit interface. To understand all four of them see the below example first:

There is a class C1 which implements two interfaces I1 and I2. and Both the class have method with same name i.e. sum().

public class C1 : I1, I2
{
//Explicit Implementation of interface
void I2.sum()
{
}

//Implicit Implementation of interface
public void sum()
{
}
}

public interface I1
{
void sum();
}
public interface I2
{
void sum();
}

The Interface I1 is implemented implicitly and I2 is explicitly. Below are the difference based on above example.

1) In Implicit implementation, no need to specify Interface name with its method.
e.g. public void sum() { }
Where as in Explicit implementation, you need to specify Interface name with its method
e.g. void I2.sum() { }

2) In implicit, access specifier is required with method name and it must be public, even protected will not work.
Where as in Explicit, no access specifier will be required.

3) You can not make virtual method in explicit implemention and same will work in implicit implemention.

4) You can not make abstract method in explicit implemention and same will work in implicit implemention.

Practical Example

Now you wonder, by considering above scenario, what is the use of these two implementation because only Implicit implementation will also work for all type of method then why these two has been introduced by Microsoft. or what should be the practical scenario where we need to use either Implicit or Explicit.

Suppose you need to implement 2 interface and both interface will have method with same name. At that time you can not create one method in your class for both interfaces, rather you must implement one interface Implicit and one Explicit (or both Explicit) for showing two different method in your class. (Check above example).

Hiding Interface Details:

If you implement interface explicitly then it will not show in class Intellisense list. So, if you want to hide your method name to display when creating object of class then you need to go for Explicit interface implementation and in this case you need to create object of your interface to know the method name.

E.g.: In our above example if I want to invoke method of I2 interface:
I2 obj = new C1();
obj.sum();

NOTE: for more please click http://developerssolutions.wordpress.com/2010/07/22/difference-between-implicit-and-explicit-interface/

Is it possible to declare multiple Interfaces with same name and method?

Yes, You can have same name for all the interfaces if you declare with partial keyword.

But they can have same method but with different signature.

partial interface AAA
{
void TestAAA();
}

partial interface AAA
{
string TestAAA(parameter);
}

Implementing Two interface having the same method signature in the same class

There can be scenario when we would have two interface with the same method name and same type of arguments, same number of arguments and even the return type can be same and we need to implement both the interface in the same class. How to implement the interface in our class? Most of you will be thinking whats so tough in this, just implement the interface and the method and move on. If the signature of the methods in the interface were different then there would have been no problem but here the signature of the methods in two different interface are same and both the interfaces are gonna be implemented in the same class. The two interface are as below.
public interface IA
{
string PrintName();
}
public interface IB
{
string PrintName();
}

From the above code we can infer that we have two interface with names IA and IB and both have a single method named “PrintName”. The signature of both the methods are same and we need to implement the interfaces in our class say “A”. One way of impelementing the interface is as shown below i.e. just having a “public” implementation of the interface method only once.
public class A : IA, IB
{
public A()
{
}
public string PrintName()
{
return this.GetType().Name;
}
}

The above implementation has got a limitation i.e the method “PrintName” is considered to be a common method for all i.e commong method for the class, and for the interfaces IA and IB. If you are writing a code shown below
A a = new A();
IA ia = new A();
IB ib = new A();
Console.WriteLine(a.PrintName());
Console.WriteLine(ia.PrintName());
Console.WriteLine(ib.PrintName());

all the calls to method “PrintName” will give you the same result, the name of the class i.e. “A”. This is because all call to the method goes to the same definition. Now if you want to give different implementation to the methods in interface IA and IB, what will you do? Its also simple, just have two impelementation of the same method and prefix the method names with the interface name as shown below.
public class A : IA, IB
{
public A()
{
}
string IA.PrintName()
{
return “IA PrintName Method”;
}
string IB.PrintName()
{
return “IB PrintName Method”;
}
}

Now the below code will give you different output.
IA ia = new A();
IB ib = new A();
Console.WriteLine(ia.PrintName());// Will print "IA PrintName Method"
Console.WriteLine(ib.PrintName());// Will print "IB PrintName Method"

So this is how two interfaces having the same method signature can be given different implementation in the same class.

For more information please visit : http://sandblogaspnet.blogspot.com/2008/05/implementing-two-interface-having-same.html

Saturday, November 20, 2010

Convert a Dynamic Entity to a System Entity

This sample code shows how to convert a dynamic entity instance into a strongly typed account entity instance. The code first creates a dynamic entity, populates its properties with account attributes and values, and then converts the dynamic entity to an account entity.
using System;
using System.Reflection;

using CrmSdk;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
public class ConvertDynamicToCore
{
static void Main(string[] args)
{
// TODO: Change the server URL and organization to match your Microsoft
// Dynamics CRM Server and Microsoft Dynamics CRM organization.
ConvertDynamicToCore.Run("http://localhost:5555", "CRM_SDK");
}

public static bool Run(string crmServerUrl, string orgName)
{
// Create an account dynamic entity.
DynamicEntity accountDynamicEntity = new DynamicEntity();

//Set a few account properties.
StringProperty name = new StringProperty();
name.Name = "name";
name.Value = "Fabrikam Inc.";

StringProperty accountnumber = new StringProperty();
accountnumber.Name = "accountnumber";
accountnumber.Value = "AZ1200";

Picklist plist = new Picklist();
plist.name = "UPS";
plist.Value = 2;

PicklistProperty shippingmethodcode = new PicklistProperty();
shippingmethodcode.Name = "address1_shippingmethodcode";
shippingmethodcode.Value = plist;

accountDynamicEntity.Properties = new Property[] { name, accountnumber, shippingmethodcode };
accountDynamicEntity.Name = EntityName.account.ToString();

//Create a strongly typed account entity to copy the dynamic entity into.
account coreAccount = new account();

//Convert the dynamic entity to a strongly typed business entity.
coreAccount = (account)Convert(accountDynamicEntity);

Console.WriteLine("\n|Core Account Attributes\n|=======================");
Console.WriteLine("|name: {0}", coreAccount.name);
Console.WriteLine("|accountnumber: {0}", coreAccount.accountnumber);
Console.WriteLine("|address1_shipmethodcode: {0}", coreAccount.address1_shippingmethodcode.Value);

return true;
}

///
/// Convert a dynamic entity into a strongly typed business entity.
///

public static BusinessEntity Convert(DynamicEntity entity)
{
string coreEntityName = entity.Name;

Type entType = (new account()).GetType();
ConstructorInfo init = entType.GetConstructor(new Type[] { });
object ent = init.Invoke(new object[] { });

foreach (Property p in entity.Properties)
{
PropertyInfo entProp = entType.GetProperty(p.Name);
if (null == entProp)
{
Console.WriteLine("Could not find attribute {0} on entity {1}.", p.Name, coreEntityName);
}
else
{
entProp.SetValue(ent, GetAttribute(entity, p.Name), null);
}
}
return (BusinessEntity)ent;
}

///
/// This method returns the value of a dynamic entity attribute.
///

public static object GetAttribute(BusinessEntity entity, string attribute)
{
if (entity.GetType() == typeof(DynamicEntity))
{
DynamicEntity de = (DynamicEntity)entity;
foreach (Property prop in de.Properties)
{
if (prop.Name == attribute)
{
PropertyInfo propInfo = prop.GetType().GetProperty("Value");
return propInfo.GetValue(prop, null);
}
}
return null;
}
else
{
PropertyInfo propInfo = entity.GetType().GetProperty(attribute);
return propInfo.GetValue(entity, null);
}
}
}
}

PublishXml Message (CrmService)

Publish the customizations for the specified entities.
The relevant classes are: 1) PublishXmlRequest 2) PublishXmlResponse
Remarks
To use this message, pass an instance of the PublishXmlRequest class as the request parameter in the Execute method.
For a list of required privileges, see PublishXml Privileges.
Example
The following code example shows how to use the PublishXml message.
// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the request.
PublishXmlRequest request = new PublishXmlRequest();

request.ParameterXml = @"<importexportxml>
<entities>
<entity>account</entity>
<entity>contact</entity>
</entities>
<nodes/>
<securityroles/>
<settings/>
<workflows/>
</importexportxml>";

// Execute the request.
PublishXmlResponse response = (PublishXmlResponse)service.Execute(request);

Split the String values with a special character in MS Flow to convert this into Array

 Many times we have a requirement to prepare the Mailing address for some of the documents, suppose there are Address Line1, Address Line2, ...