Software Architecture – Debugging in Silverlight+WCF

June 30, 2010

Story of Debugging in Silverlight+WCF

Environment: Silverlight + WCF + NHibernate

Normally, you will get error as:

“silverlight [Async_ExceptionOccurred]\Arguments: \Debugging resource strings are unavailable.”

So solution is to install Silverlight Developer Runtime, which is different from normal silverlight run time. Basically Silverlight Developer Runtime provides better debugging/resources information, so highly suggested for Silverlight debugging.

So now the most common error thrown by WCF will be as:
“the remote server returned an error notfound”

Actually, it is general statement that something has gone wrong in WCF.
Possible reasons are be any of the following:
• Connection string is wrong for DB Connection.
• Any configuration file like Configuration.cfg.xml (Used for NHibernate) is missing.
• Any dependency file like LinFu.DynamicProxy.dll ( Used for NHibernate) is missing.
• Entities have circular references.
• Any other thing.

So it is very hard to figure out actual reason.

Beside Fiddler2, solution is to configure Service log for WCF Service.
Make sure to have following piece of tags in web.config of Sliverlight Web project.

<system.serviceModel>
	<diagnostics>  
		<messageLogging   
  		logEntireMessage="true"   
             logMalformedMessages="false"  
             logMessagesAtServiceLevel="true"   
             logMessagesAtTransportLevel="false"  
             maxMessagesToLog="3000"  
            maxSizeOfMessageToLog="2000"/>  
      </diagnostics> 
      <bindings>
        <basicHttpBinding>
          <binding name="Binding1"            
          maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
        </basicHttpBinding>
      </bindings>
      <behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                  <dataContractSerializer maxItemsInObjectGraph="500000" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
    </system.serviceModel>


    <system.diagnostics>       
	     <sharedListeners>   
          <add name="WcfListener"   
                  type="System.Diagnostics.XmlWriterTraceListener"   
                  initializeData="d:\logs\wcfLog.svclog"  />   
      </sharedListeners>       
      <sources>         
       <!-- switchValue attribute has no impact on MessageLogging -->   
      <source name="System.ServiceModel.MessageLogging">  
            <listeners>  
              <add name="WcfListener" />  
            </listeners>  
         </source>        
        <source name="System.ServiceModel"  
                        switchValue="Warning, ActivityTracing"  
                      propagateActivity="true" >  
          <listeners>  
           <add name="WcfListener" />  
         </listeners>  
        </source>        
       </sources>      
   </system.diagnostics>  

This configuration will create a log at d:\logs\wcfLog.svclog. It is a very messy log file, so WCF/SVC log viewer is required to read and analyzed the log data.
Install the WCF/SVC log viewer using web installation of Windows SDK
from following location. As size of SDK is very big(In GBs), so you can install selected features.

http://www.microsoft.com/downloads/details.aspx?FamilyId=0BAF2B35-C656-4969-ACE8-E4C0C0716ADB&displaylang=en

The Service Trace Viewer supports three file types:
• WCF Tracing File (.svcLog)
• Event Tracing File (.etl)
• Crimson Tracing File
Service Trace Viewer enables you to open any supported trace file, add and integrate additional trace files, or open and merge a group of trace files simultaneously.

The Service Trace Viewer provides the following different views. They are displayed as tabs on the left pane of the Viewer, and can also be accessed from the View menu.
• Activity View
• Project View
• Message View
• Graph View


Trace for exception will look like as:


On Clicking the red colored exception, details will be displayed in the below panel as:


Graph view of trace will look like as:

Reference:
http://msdn.microsoft.com/en-us/library/ms732023.aspx


Software Architecture – Tips for Development Model with Microsoft Visual Studio 2010+ .Net Framework 4.0 + Sliverlight 4.0

June 27, 2010

Environment:
Microsoft Visual Studio 2010+ .Net Framework 4.0 + Sliverlight 4.0
WCF + Nhibernate + Sliverlight

Assumption: This document assumes that you have initial understanding of WCF and NHibernate.

Tips:
1. Entities will be shared b/w NHibernate and WCF, so sample entity will look like as:

[DataContract]    
    public class City
    {
        public City() { }

        [DataMember]
        public virtual int CityID { get; set; }

        [DataMember]
        public virtual string CityCode { get; set; }

        [DataMember]
        public virtual string Description { get; set; }
             
    }

Corresponding HBM will look like as:

<class name="SilerverlightTest.Web.City, SilerverlightTest.Web" table="GeneralCityMaster" lazy="false" >
      <id name="CityID" column="CityID">
        <generator class="native" />
      </id>
      <property name="CityCode" column="CityCode" />
      <property name="Description" column="Description" />
       </class>

2. Incase there are circular references between the entities of Data contract, all entities must be marked as IsReference = true. See below:

 [DataContract(IsReference = true)] 
public class CurrencyRate : ParentClass<CurrencyRate>
{
 }

Search goolge with keywords “WCF + NHibernate + circular reference” for more details and see top 5 links for theory related to it.

3. As lazy loading can’t work across the WCF wire, so all entities must be marked as lazy=”false” in HBM file. See Below.

<class name="Pegasus.BusinessObjects.General.Main.Company, PCMS-SL.Web" table="GeneralCompanyMaster" lazy="false" >

4. Incase of ManyToOne relationship in class of HBM files, make sure to add option not-found=”ignore” so that if relation is missing then exception is not thrown.

<many-to-one name="ModifiedBy" column="ModifiedBy" class="Pegasus.BusinessObjects.General.Administration.Employees, PCMS-SL.Web" cascade="none"   lazy="false" not-found="ignore"/>

5. In all *.svc.cs, services must be marked as [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
See Blow:

 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AccountsManager : IAccountsManager
    {
}

6. For many issues, WCF Service will show following error as:
{System.TimeoutException: The HTTP request to ‘http://localhost/PCMS-SL.Web/businessmanagers/MastersManager.svc&#8217; has exceeded the allotted timeout. The time allotted to this operation may have been a portion of a longer timeout. —> System.Net.WebException —> System.Net.WebException
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.c__DisplayClass5.b__4(Object sendState)
at System.Net.Browser.AsyncHelper.c__DisplayClass2.b__0(Object sendState)

That is general error, possible error can be anything that is specified above.So try to investigate the root cause of this error.

7. In order to see the exception generated in WCF Service enble error in web.config of ASP Project as:

<behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                </behavior>
            </serviceBehaviors>
        </behaviors>

8. Copy ClientAcessPolicy.xml at the root of ASP .net Project, with content as:

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from>
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Otherwise following error will occur:

An error occurred while trying to make a request to URI “http://localhost:1498/SecurityManager.svc&#8221;. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.

Search google with this exception and see top 5 urls for theory related to it.

9. NHibernate will list for IList for collection definition. But WCF Look for List so a trick is to use properties as :

<bag name="InstrumentList" cascade="all" inverse="true" lazy="false">
        <key column="Cityid" />
        <one-to-many class="SilerverlightTest.Web.Instrument, SilerverlightTest.Web"  />
      </bag>

Code for collection will be as:

public virtual IList<Instrument> InstrumentList {get;set;}

        [DataMember(Name = "InstrumentList")]
        public  List<Instrument> InstrumentListPrivate
        {
            get { return  new List<Instrument>(this.InstrumentList) ; }
            set { this.InstrumentList = value; }
        }  

For reference see the link below:
http://stackoverflow.com/questions/1538811/nhibernate-and-wcf-ilist-conflict

10. Exception as:
{System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. —> System.Net.WebException: The remote server returned an error: NotFound. —> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.c__DisplayClass5.b__4(Object sendState)
at System.Net.Browser.AsyncHelper.c__DisplayClass2.b__0(Object sendState)
— End of inner exception stack trace —
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)

That is general error, possible error can be anything that is specified above. So try to investigate the root cause of this error.


Communication Gaps – Joke

June 27, 2010

Programmer to Team Leader:

“We can’t do this proposed project. **CAN NOT**. It will involve a major
design change and no one in our team knows the design of this legacy system.
And above that, nobody in our company knows the language in which this
application has been written. So even if somebody wants to work on it, they
can’t. If you ask my personal opinion, the company should never take these
type of projects.”

Team Leader to Project Manager :

“This project will involve a design change. Currently, we don’t have any
staff that has experience in this type of work. Also, the language is
unfamiliar to us, so we will have to arrange for some training if we take
this project. In my personal opinion, we are not ready to take on a project
of this nature.”

Project Manager to 1st Level Manager :

“This project involves a design change in the system and we don’t have much
experience in that area. Also, not many people in our company are
appropriately trained for it. In my personal opinion, we might be able to do
the project but we would need more time than usual to complete it.”

1st Level Manager to Senior Level Manager :

“This project involves design re-engineering. We have some people who have
worked in this area and others who know the implementation language. So they
can train other people. In my personal opinion we should take this project,
but with caution.”

Senior Level Manager to CEO :

“This project will demonstrate to the industry our capabilities in
remodeling the design of a complete legacy system. We have all the necessary
skills and people to execute this project successfully. Some people have
already given in house training in this area to other staff members. In my
personal opinion, we should not let this project slip by us under any
circumstances. ”

CEO to Client :

“This is the type of project in which our company specializes. We have
executed many projects of the same nature for many large clients. Trust me
when I say that we are the most competent firm in the industry for doing
this kind of work. It is my personal opinion that we can execute this
project successfully and well within the given time frame.


Software Architecture – Case Study – Why and Why not SQL Server Replication

June 7, 2010

 Cases Study Related To Replication

                                                             By: Shahzad Sarwar

                                                            To: Dubai Office

                                                            Dated: 7th June 2010

Problem Definition:

Ships of shipping companies move around in sea, which have a system where check list (as Questions/answer) are supposed to be saved. These check list identify the health, safety and operational status of ship and its different components. On regular intervals, these checklists are filled in ships.

There will be one centralized server, where data of these check lists from different ships will be pushed. So central server will have consolidated view of data from all the ships moving in the Sea.

Solutions:

Lets first analyze what are the objective of replication, Why to use and Why to not use replication in eyes of MSDN-the most valid source of information.

1         Objectives of Replication:

Replication can be used effectively for many different purposes, as discussed in the following sections.

1.1      Separating Data Entry and Reporting

If you have worked in an environment in which the same database is used for data entry and reporting, you probably know that things aren’t always rosy. Constantly reading and modifying data in the same set of tables just doesn’t work very well if you care about data integrity. Transactions that run against a set of tables prevent reading the locked data rows and pages, or perhaps prevent even an entire table from being read by a report. In such an environment, you are bound to see blocking locks. Although there are ways to avoid blocking (please see my earlier article about transactions and locking), it is best to separate data entry and reporting databases. Transactional replication works well by delivering data changes from the data entry server to the reporting server.

1.2      Distributing Load Across Servers

As your organization grows, you might find yourself in a situation in which a single database server is utilized by too many users. If CPU utilization on your database servers is constantly over 80 percent and you have tuned database design and queries appropriately, chances are you could benefit by spreading the user base over multiple servers. For instance, a server named South could serve all employees working in the southern United States, and a server called North could serve all Northerners. If you need to combine all data for reporting, you could use replication to move transactions from North and South to a server named Central_Reporting.

1.3      Providing High Availability

Occasionally, you might consider using replication for high availability; that is, to replicate transactions from the main server to a standby server. If the main server fails, you can then point your data sources to the standby server. Be aware that using replication for high availability takes careful planning and testing. Replication does not provide any sort of automatic fail-over. SQL Server supports other methods of providing high availability, such as clustering and log-shipping, which might be more appropriate for your environment.

1.4      Transporting Data

Another common use for replication is to simply move data changes from publishers to subscribers. This method is particularly useful for moving transactional data to a data warehousing server, in which it is transformed and aggregated for OLAP reporting. SQL Server provides other ways of transporting data: DTS, BCP, BULK INSERT statements, and others. Be sure to carefully consider the alternatives before implementing replication because other solutions might be cheaper or even faster than replication.

2         Why and Why not Replication

2.1      Why Use Database Replication?

Imagine that a client has asked you to develop a contact-management solution that the company’s field sales staff can use to monitor sales and orders. Each sales representative has a laptop computer that can be connected to the company’s network.

A traditional approach to building this solution is to separate the tables from the other objects in the database so that the data can reside in a back-end database on a network server, or on the Internet or an intranet, while the queries, forms, reports, macros, and modules reside in a separate front-end database on the user’s computer. The objects in the front-end database are based on tables that are linked to the back-end database. When sales representatives want to retrieve or update information in the database, they use the front-end database.

Database replication enables you to take a new approach to building this solution by creating a single database that contains both the data and objects, and then making replicas of the database for each sales representative. You can make replicas for each user and synchronize each replica with the Design Master on a network server. Sales representatives update the replicas on their computers during the course of a work session, and users synchronize their replicas with the Design Master on the server as needed.

In addition, you can choose to replicate only a portion of the data in the Design Master, and you can replicate different portions for different users by creating partial replicas. In the scenario involving sales representatives who use replica databases, each individual salesperson typically needs only the sales data related to his or her own territory. Replicating all sales data for all sales representatives would involve unnecessary processing and duplication of data. By using partial replicas, you can duplicate only the data that each salesperson actually needs. A complete set of data is still contained in the Design Master, but each replica handles only a subset of that data.

2.2      When Database Replication Should Not Be Used?

Although database replication can solve many of the problems inherent in distributed-database processing, it is important to recognize that there are situations in which replication is less than ideal. You may not want to use replication if:

2.2.1      There are large numbers of record updates at multiple replicas. 

Solutions that require frequent updates of existing records in different replicas are likely to have more record conflicts than solutions that simply insert new records in a database. Record conflicts occur when any changes are made to the same record by users at different locations at the same time. Solutions with many record conflicts require more administrative time because the conflicts must be resolved manually. This is true even if different fields are updated within the same record.

2.2.2      Data consistency is critical at all times. 

Solutions that rely on information being correct at all times, such as funds transfers, airline reservations, and the tracking of package shipments, usually use a transaction method. Although transactions can be processed within a replica, there is no support for processing transactions across replicas. The information exchanged between replicas during synchronization is the result of the transaction, not the transaction itself.

3         Solution points:

 

  • As consolidation of all ships data to central database is primary objective, so general case supports implementation as replication.

 

  • With reference to point 2.2.1, as all ships have separate records of data of checklist, so we don’t have multiple updates of same record by different replicas.  So we are on safe side for replication.

 

  • With reference to point 2.2.2, as we don’t have data consistency issues with data, as logically data from different ships don’t have relationship between them.

 

  • Point under query is, “Is data really worth transferring via replication?” or simple Import or export via XML file and transfer by ftp will serve the purpose. Volume of data and frequency of data transfer will be a deciding factor.

 

References:

                 Microsoft MSDN

                 Google


Software Architecture – New features of Microsoft Visual Studio 2010 Part 1 ( Editor and C# only)

June 5, 2010

Presentation: New features of Microsoft Visual Studio 2010 Part 1 ( Editor and C# only)

By: Shahzad Sarwar

To: Development Team

Dated: 5th June 2010

Microsoft Visual Studio 2010 has been released to market for a month now and our company is one of the few first companies in Pakistan who have adopted this new technoglogy.  Lets explore new features of Microsoft Visual Studio 2010 / .Net framework 4.0

There is a very long list of features added by Microsoft in Visual Studio 2010.This presentation will cover only features of Visual studio Editor 2010 and C# language. •Separate presentations will be required to touch features in WPF,LINQ,WCF, Windows workflow and other elements of .Net framework 4.0