Sunday 30 May 2010

Configurable WCF Service url in Silverlight project side

WCF service gets url and binding properties from “ServiceReferences.ClientConfig “ file in silverlight project (client side). When WCF service initialize, it gets all property from this file. There is no problem reading data from that file. But when web site get deployment url are change. So manually you have to change url of WCF services from that file. <endpoint/> tag address property hold WCF url address.

To get rid of this hassle, we can configure it to read the url from web.config file. We can do followings things.

Create a class as an example ServiceFactory. All the initialization related things which is take place in “ServiceReferences.ClientConfig” file, have to be ServiceFactory class. See the sample code.

BasicHttpBinding _BasicHttpBinding;

      EndpointAddress _EndpointAddress;

public ServiceFactory()

        {

    _BasicHttpBinding = new System.ServiceModel.BasicHttpBinding();

            _BasicHttpBinding.MaxReceivedMessageSize = 2147483647;

            _BasicHttpBinding.MaxBufferSize = 2147483647;

            _BasicHttpBinding.OpenTimeout = new TimeSpan(0, 20, 0);

            _BasicHttpBinding.CloseTimeout = new TimeSpan(0, 20, 0);

            _BasicHttpBinding.ReceiveTimeout = new TimeSpan(0, 20, 0);

            _BasicHttpBinding.SendTimeout = new TimeSpan(0, 20, 0);           

Now when we need to make the instance of WCF service we can create a method in ServiceFactory class. So we can bind BasicHttpBinding and EndpointAddress class property within WCF service instance. Look at sample method below.

public PCBuilderServiceClient GetPCBuilderServiceClient()

        {

            _EndpointAddress = new System.ServiceModel.EndpointAddress(ServiceUrlManager.GetValue(ConstantClass.SERVICE_SERVER_URI) + ServiceUrlManager.GetValue(ConstantClass.PC_BUILDER_SERVICE));

                _PCBuilderServiceClient = new PCBuilderServiceClient(_BasicHttpBinding, _EndpointAddress);

            return _PCBuilderServiceClient;

      }

Here PCBuilderServiceClient is the service name. _EndpointAddress object is binding service url. There are two things one is the server url and another is the exact location and name of the WCF service file in server. So both need to cocate to get the exact location of the WCF service. Initially we have kept thos information inside IDictionary object during starting of the web site. Now just fetching the value from IDictionary by key.

Saturday 29 May 2010

Silverlight project initial configuration

There are several steps to make initial configuration of any silverlight project. We can use RIA service for communication but I will describe here with WCF service. If we use VS 2008 we have to install silverlight toolkit and VS 2008 service pack 3. But for VS 2010 silverlight framework is already exist.

1.       First create an Silverlight type project. There are two types of project will automatically generate. One is web project and another is silverlight project.

2.       Silverlight works in client side so it produce a .xap file which exist in web project ClientBin folder. Being a client side application it needs service to communicate with server.  XAP file reated settings generate when we take silverlight type project. In web project there is ProjectNameTestPage.aspx file. It contains necessary settings.

3.       Now add Silverlight enabled WCF service (.svc file extension) to web project. Service file open automatically. There are few key words or class like [ServiceContract(Namespace = "")] above class name. [OperationContract] is above method name.  

4.       When we will create method in service we have to use the key word [OperationContract] above every method to introduce method publically.

5.       In web.config file there is tag <system.serviceModel/> under which few configuration code will generate. It is basically setup for service communication. In <bindings/> tag there is tag name <customBinding0/> remove the tag and its inside code and paste the following code.

<basicHttpBinding>

            <binding name="PCServicesBinding" closeTimeout="00:10:00" openTimeout="00:10:00"

              receiveTimeout="00:10:00" sendTimeout="00:10:00" maxBufferSize="2147483647"

              maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"

              transferMode="StreamedResponse">

              <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"

                maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />

            binding>

basicHttpBinding>                             

You can change the name and can configure the value of tags.

6.       Now in <endpoint/> tag under <service/> tag change the name of binding = “basicHttpBinding” and bindingConfiguration = “PCServicesBinding”. It is the name of tag.

7.       Run service (.svc) file by right click and “View in browser”. Now go to the Silverlight project add “Add Service Reference” click on discover. All the available service in web project will shown as reference in silverlight project. Try to expand service reference. Click on Advance option, uncheck “Reuse types in referenced assemblies”, click ok.

Now project is ready for coding with WCF service. We can create more configurations in this project. Basically when we deploye a web project service url also need to change along with project url. Service get this url from “ServiceReferences.ClientConfig” file. We can make a configurable file for services from where we can easily change the url of services.    

Friday 28 May 2010

DeferredLoadingEnabled options in Linq

Linq to SQL has a drawback it load data from all the available relationship of database table. So it crush or become slow that’s why if we make DeferredLoadingEnabled property false it will not load its child or parent data when we request any single row from any table. 

base.DataContext.DeferredLoadingEnabled = false;

We can specify the parent or child table name when we try to fetch any particular table data. Then it will retrieve all the related data automatically from the define table. We can do it when we make the instance of any class. 

DataLoadOptions options = new DataLoadOptions();

options.LoadWith<Builder>(m => m.SalesOffices);

options.LoadWith<SalesOffice>(m => m.ModelHomes);

options.LoadWith<ModelHome>(m => m.ModelHomeDetailImages);

options.LoadWith<SalesOffice>(m => m.SalesOfficeAds);

base.DataContext.LoadOptions = options;

In the above example we create DataLoadOptions object then assign its LoadWidth property then again assigne DataContext LoadOptions. So current DataContext instance only have above define tables relational data only.

In this way we can make faster use of Linq to SQL.

Singletone Pattern

Making one instance of a class through out the project is called singletone. To do a object singletone you could make a class instance as static. Here is the technique to declare a object as singletone.

static BuilderInformation _Instance = null;

public static BuilderInformation GetInstance()

{

if (_Instance == null)

      {

            _Instance = new BuilderInformation();

}

return _Instance;

}     

When you need the object of this class just declare like:

 BuilderInformation builderInformation = BuilderInformation.GetInstance();

We can make collection of object as singletone. Here is an example of that. If SalesOfficeOID is not in the _LiveAgentConversationList list make an object of _ InstanceLA and append it to the collection of list.

static LiveAgentConversation _InstanceLA = null;

static IList<LiveAgentConversation> _LiveAgentConversationList = new List<LiveAgentConversation>();

public static LiveAgentConversation GetInstance(string saleOfficeOID)

{

LiveAgentConversation liveAgentConversation = null;

      if (_LiveAgentConversationList.Count > 0)

      {

            for (int i = 0; i <>

            {

                  if (_LiveAgentConversationList[i]._SalesOfficeOID == saleOfficeOID)

                  {

                        return _LiveAgentConversationList[i];

                  }            

            }

            if (liveAgentConversation == null)

            {

                liveAgentConversation = new LiveAgentConversation();

                liveAgentConversation._SalesOfficeOID = saleOfficeOID;               

                _LiveAgentConversationList.Add(liveAgentConversation);

            }

            return liveAgentConversation;

        }

}

During object invokation write statement like:

LiveAgentConversation liveAgentConversation = LiveAgentConversation. GetInstance(string saleOfficeOID)

Monday 24 May 2010

appSettings in Web.onfig

It takes key and value combination.

<appSettings>

<add key="ServerURI" value="http://localhost:1643/"/>

appSettings>

To read value from web.config

string configPath = ConfigurationManager.AppSettings[key].ToString();

Connection String Settings in Web.config

1. Add following line to web.config file.

<connectionStrings>

<add name="Name" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=sa;Password=sa" providerName="System.Data.SqlClient"/>

connectionStrings>

Name = Provide any name of connection string.

Data Source = Server name. ex: SHUVRO\SQLEXPRESS

Initial Catalog = Database name. Ex: PCDB

2. Get the connection string from web.config file from cs

String ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Name"].ConnectionString;

[“Name”] is the connection string name that is in web.config tag name

Log4net Settings in Web Project

To add log4net in web project steps are below:

1. Download and log4net dll in project where you want to use it.

2. We can write log in log file or we can send mail when an error occur. For these two options we have to make setup in Web.config file. Initially add following line after in web.config file.

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

a. Write log in log file only, add following code in web.config file. You can change the log file name “PC.log.txt” is the file name here.

<log4net debug="true">

<appender name="RollingLogFileAppender

type="log4net.Appender.RollingFileAppender">

<file value="App_Data\PC.log.txt" />

<appendToFile value="true" />

<rollingStyle value="Size" />

<maxSizeRollBackups value="10" />

<maximumFileSize value="10MB" />

<staticLogFileName value="true" />

<layout type="log4net.Layout.PatternLayout">

<conversionPattern value="%d [%t] %-5p %c - %m%n" />

layout>

appender>

<root>

<level value="DEBUG" />

<appender-ref ref="RollingLogFileAppender" />

root>

log4net>


b. Send log through mail need to add following line to web.config. In tag add e-mail address inside value. In tag create an account in gmail, add that e-mail address there. From all the error mail will be send. Put a mail subject in tag. In tag you may change the name but for that you have change the name in cs file also.

<log4net debug="true">

<appender name="SmtpAppender" type="log4netExtensions.SmtpClientSmtpAppender">

<to value="e-mail,e-mail" />

<from value="e-mail" />

<subject value="subject" />

<smtpHost value="smtp.gmail.com" />

<port value="587"/>

<authentication value="Basic" />

<bufferSize value="512" />

<lossy value="true" />

<evaluator type="log4net.Core.LevelEvaluator">

<threshold value="ALL"/>

evaluator>

<layout type="log4net.Layout.PatternLayout">

<conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />

layout>

appender>

<logger name="PC.Web.Smtp">

<level value="All" />

<appender-ref ref="SmtpAppender" />

logger>

<root>

<level value="DEBUG" />

<appender-ref ref="RollingLogFileAppender" />

root>

log4net>


C. Combinly add both facility to web config add both appender in web.config file

<log4net debug="true">

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">

<file value="App_Data\PC.log.txt" />

<appendToFile value="true" />

<rollingStyle value="Size" />

<maxSizeRollBackups value="10" />

<maximumFileSize value="10MB" />

<staticLogFileName value="true" />

<layout type="log4net.Layout.PatternLayout">

<conversionPattern value="%d [%t] %-5p %c - %m%n" />

layout>

appender>

<appender name="SmtpAppender" type="log4netExtensions.SmtpClientSmtpAppender">

<to value="e-mail,e-mail />

<from value="e-mail" />

<subject value="subject" />

<smtpHost value="smtp.gmail.com" />

<port value="587"/>

<authentication value="Basic" />

<bufferSize value="512" />

<lossy value="true" />

<evaluator type="log4net.Core.LevelEvaluator">

<threshold value="ALL"/>

evaluator>

<layout type="log4net.Layout.PatternLayout">

<conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline%newline" />

layout>

appender>

<logger name="PC.Web.Smtp">

<level value="All" />

<appender-ref ref="SmtpAppender" />

logger>

<root>

<level value="DEBUG" />

<appender-ref ref="RollingLogFileAppender" />

root>

log4net>

3. Now Add below line in AssebmlyInfo.cs file of web project

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]

4. Add below line in cs file where you are going to use it.

a. To write log in log file:

protected static log4net.ILog _Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

b. To send mail:

protected static log4net.ILog _Logger = log4net.LogManager.GetLogger("PC.Web.Smtp");

Now _Logger object can be use. There are various method like Debug(), Info() etc.