Monday, May 13, 2013

Error: A call to SSPI failed

If you are configuring your client application to use WCF net TCP binding, you may come across the following error.

A call to SSPI failed, see inner exception.The target principal name is incorrect

So you will find yourself stumped as what is wrong with it, how to fix it.

 

Problem:  The basic issue is the user name or principal name, as stated in the exception. You have to make sure that it should use the user to communicate under the account the service is running. So here is an example as how to fix this issue

 

First check the WSDL of the service you are using, it will look like following towards the end of WSDL file

 

<wsdl:port name="netTcpEndpoint_IMyService" 
binding="tns:netTcpEndpoint_IMyService">     
<soap12:address location="net.tcp://MyDomain.net/MyService.svc" />     
<wsa10:EndpointReference>       
<wsa10:Address>net.tcp://MyDomain.net/MyService.svc</wsa10:Address>       
<Identity xmlns="http://schemas.xmlsoap.org/ws/2006/02/addressingidentity">         
<Upn>testUser@MyDomain.net</Upn>       
</Identity>    
 </wsa10:EndpointReference>   
</wsdl:port> 
 
Resolution: Ensure in your client side config file that the following information is there.

<
endpoint address="net.tcp://MyDomain.net/MyService.svc"
binding="netTcpBinding" bindingConfiguration="netTcpEndpoint_IMyService"  
contract="MyService.IMyService" name="netTcpEndpoint_IMyService">     
<identity>       
<dns value="MyDomain.net"/>       
<userPrincipalName value="testUser@MyDomain.net" />     
</identity>   
</endpoint> 
 
So Make sure both identities or user name are same.If you are using the client under same application domain, you may not need to provide user principle name or dns info, as by default it will use the same.

Wednesday, April 10, 2013

Redirect non-www to www using rewrite

There are multiple scenario in which you would like to redirect your domain to always to a standard address possibly www.domain.com

 

If you’re using IIS 7 or higher, URL Rewrite is a valuable tool, well worth installing and using.

 

One common use of URL Rewrite is redirecting http://domain.com to http://www.domain.com .   Many people are doing this for search engine optimization (SEO) so that search engines only see the one site, rather than two sites.

 

Some people may have multiple blog hosted on the same account with different domain names. And you do not want the end-user landing to a wrong domain if he or she did not provide www along with domain name. So what is the solution.

 

One solution is open IIS Manager and double-click on the “URL Rewrite” icon and then add rules. Well, this may not be very user friendly.

 

The other solution is much simpler, just open the web.config file and then …In the <system.webServer> section, add the following:

 

If you like Wildcards

 
<rewrite>
   <rules>
     <rule name="Redirect domain.com to www" patternSyntax="Wildcard" stopProcessing="true">
       <match url="*" />
       <conditions>
         <add input="{HTTP_HOST}" pattern="domain.com" />
       </conditions>
       <action type="Redirect" url="http://www.domain.com/{R:0}" />
     </rule>
   </rules>
   </rewrite> 


If you like Regular Expressions

<rewrite>
    <rules>
      <rule name="Redirects to www.domain.com" patternSyntax="ECMAScript" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAny">
          <add input="{HTTP_HOST}" pattern="^domain.*(com|net)$" />
          <add input="{HTTP_HOST}" pattern="^(www.)?mydomain2.(com|net)$" />
          <add input="{HTTP_HOST}" pattern="^www.domain.net$" />
        </conditions>
        <action type="Redirect" url="http://www.domain.com/{R:0}" />
      </rules>
    </rules>
  </rewrite>

Tuesday, March 05, 2013

Error: The application attempted to perform an operation not allowed by the security policy.

You may come across this error. It will appear that there is something wrong with your code, but solution is very simple.

Security Exception may look like following


Description: The application attempted to perform an operation not allowed by the security policy.  To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

 

Stack Trace:
[SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
   System.Security.CodeAccessSecurityEngine.SpecialDemand(PermissionType whatPermission, StackCrawlMark& stackMark) +0
   System.Security.CodeAccessPermission.Demand(PermissionType permissionType) +28

 

Resolution:

Add or ensure the following setting in your web.config

<system.web>

<trust level="Full"/>

</system.web>

Wednesday, February 06, 2013

How to create SSRS Reports with Dynamic Connection

If you had multiple databases and would like to dynamically use the connection string for SQL Server Reporting Services, how would you do it? Here are some steps

1. Open Visual Studio, if Report Server project does not exist, create it

2. DO NOT Create any Shared Data Sources and Shared Datasets

3. Go to Reports, right click, then click on Add—>New Item—>Report

4. Click on Newly Created Report, then from left side of the pane (Report Data), right click on Data Source—>Add Data Source

a. Give a Name to Data Source: SQLConnection

b. Choose Embedded connection, type : Microsoft SQL Server

c. Provide a Connection string either pasting or building through Edit

d. Test Connection

5. Right click on Datasets, then click on Add Dataset

a. Give a dataset name

b. Choose : use a dataset embedded in my report

c. Choose a data source, This will be SQLConnection by default

d. Choose Query type, stored procedure is recommended

e. Click on OK

6. Once Report is created, go to parameters and add a new parameter called DataSourceName of Data type text and visibility must be hidden

  • Before deploying the report go into Data Sources—>SQLConnection, and in place of connection string, replace the connection string with “[@DataSourceName]”

7. Deploy the above report

8. Now go to SSRS Report Manager, select the above report, click the option to manage, go into Data Sources, select Credentials stored securely in the report server, provide User Name and Password and Click on Apply.

9. Run the report from UI

You are all set.

Wednesday, January 09, 2013

Pros & Cons of Designing Application using OOA vs. SOA

In many organization, it is asked how would we benefit by taking this particular approach of Designing and Developing Application. It can be a brand new application or porting a legacy code. In most cases organization wants a quick solution to address the immediate need, some may come back later and rework in a phased approach but some just keep moving with quick and dirty solutions until a situation demand for real upgrade or rewrite.

 

As we all know, there are different application design patterns evolved over period of time, no one pattern is best in every situation but some of them stood out and consistently used even today. I would focus mainly on three different designs, which indicates an era in its own. However they are being still used today. They are – Procedural, Object Oriented and Service Oriented Designs. Many people would ask what would be the pros and cons of using one over the other, so I thought to come up with comparison chart, and here it goes.

 

Area

Design and Development

 

Procedural

Object Oriented

Service Oriented

1. Reuse of code

&

Resource

Limited to None

(Localized to Page, method, process or stored procedure, generally customized according to respective requirement)

Highly reusable but limited to internal consumers only(closely coupled with application)

a. Business Objects are Centralized

b. Business Process and Logics may be Centralized

c. Generally same cached data can be used by the respective server consumers only

Highly reusable and can be used by Internal and External consumers by design

a. Business Objects are Centralized

b. Business Process and Logics are Centralized

c. Standard communication Channels with diverse options become available to ensure the respective change or new capability of the service to get uniformly distributed to its consumers

d. Same cached data is shared among different consumers calling from different platforms

2. Interoperability

None

None or Limited to same technology

(e.g. Even within Microsoft Platform a .NET Component cannot be reused in Classic ASP)

Highly interoperable by design and technology neutral, thus it can be used by diverse technology platforms

3. Organizational Agility

None

(Any new business change will require refactor of the code completely)

Medium

(Any new business change will require, modification or extension of objects)

High

(Services capability can be composed, extended or concurrent capability can be provided to address new requirements while keeping the old one as it is)

4. Security

Lowest

(Tightly coupled with application)

Low to Medium

(Coupled with application but also logically abstracted in objects)

High

(Can be customized as per need, decoupled from application and service security can be independently governed as needed)

5. Scalability

Lowest

(Only allows Vertical scalability without redundant install )

Low to Medium

(Mostly allows vertical scalability without redundant install or Business objects designed to be used over network)

High

(Allows both vertical and scalability with or without redundant install)

6. Performance

Low for Complex Application

High for Simple Application

(As it depends on several factors – usually applications are tightly coupled from UI, Business Logic and Database which makes it difficult to abstract & individually optimize certain part of the process)

Medium for both Simple of Complex Application

(Since major objects, functionality and data layer are usually abstracted, it is easier to optimize for better performance)

High for complex Application

 

(A Process is centralized and reused by different consumer consistently)

Low for Simple Application

(A Process has to unnecessarily pass through several steps and perform data transfer to do a simple task

7. Development Time

Fastest(X)

Generally 1.5 to 2X depending on size & complexity of project

Generally 2 to 2.5X depending on size & complexity of project

8. Development & Infrastructure Cost

Low

(No specialized skillset required for this type of development, application can be deployed on just one box)

Medium

(Specialized skillset is to implement object orientation principles and application may be deployed on more than one machine)

High

(Very specialized skillset required to understand the service oriented principles to implement the design appropriately. Multiple machines are usually involved as it is naturally fall under distributed application architecture)

9. ROI

Highest in short term

 

(Usually in 1st Year because immediate business needs were quickly addressed)

Lowest in long term

 

(Usually after a year the value starts going down due to lack of reuse and rework to redeliver new business needs)

Moderate

The value always stays in the middle due to internal reuse of the components

Lowest in the Short Term

 

(Usually in 1st year due to more time and money spend to develop a functionality, centralized logic and process)

Highest in the Long Term

(As time passes by and more and more service operations and processes are reutilized, the cost of development time is saved

10. Interruption in application uses during deployment

Users will be always kicked off

Users will be kicked out if Business objects deployed along with application.

Users will less likely to be affected

Wednesday, December 12, 2012

Convert JSON to XML

You may come across situation when you receive data in JSON and would like to convert into XML. JSON (JavaScript Object Notation) is a text-based open standard designed for human-readable data interchange.

 

The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.

 

Following example is a function which converts a JSON data string into XML Document.

 

Private Shared Function JsonToXml(ByVal json As String) As XmlDocument
        Dim newNode As XmlNode = Nothing
        Dim appendToNode As XmlNode = Nothing
        Dim returnXmlDoc As XmlDocument = New XmlDocument
        returnXmlDoc.LoadXml("<Document />")
        Dim rootNode As XmlNode = returnXmlDoc.SelectSingleNode("Document")
        appendToNode = rootNode
 
        json = json.Replace(",", "," & vbLf)
        json = json.Replace("{", "{" & vbLf)
        json = json.Replace("}", vbLf & "}" & vbLf)
        json = json.Replace("[", "[" & vbLf)
        json = json.Replace("]", vbLf & "]" & vbLf)
 
        Dim arrElements() As String = json.Split(CChar(vbLf))
        For Each element As String In arrElements
            Dim processElement As String = element.Replace(vbLf, "").Replace(vbCr, "").Replace(vbTab, "").Trim()
            If processElement.Trim <> "" Then
                If (processElement.IndexOf("}") > -1 Or processElement.IndexOf("]") > -1) And Not (appendToNode Is rootNode) Then
                    appendToNode = appendToNode.ParentNode
                ElseIf (processElement.IndexOf("[") > -1) Then
                    processElement = processElement.Replace(":", "").Replace("[", "").Replace("""", "").Trim()
                    If processElement.Trim = "" Then
                        processElement = "Square"
                    End If
                    newNode = returnXmlDoc.CreateElement(processElement)
                    appendToNode.AppendChild(newNode)
                    appendToNode = newNode
                ElseIf (processElement.IndexOf("{") > -1) Then
                    processElement = processElement.Replace(":", "").Replace("{", "").Replace("""", "").Trim()
                    If processElement.Trim = "" Then
                        processElement = "Element"
                    End If
                    newNode = returnXmlDoc.CreateElement(processElement)
                    appendToNode.AppendChild(newNode)
                    appendToNode = newNode
                Else
                    Dim FoundAt As Integer = processElement.IndexOf(":")
                    If (FoundAt > -1) Then
                        Dim NodeName As String = processElement.Substring(0, FoundAt - 1).Replace("""", "")
                        Dim NodeValue As String = processElement.Substring(FoundAt + 1, processElement.Length - FoundAt - 1).Trim
                        If NodeValue.StartsWith("""") Then
                            NodeValue = NodeValue.Substring(1, NodeValue.Length - 1).Trim
                        End If
                        If NodeValue.EndsWith(",") Then
                            NodeValue = NodeValue.Substring(0, NodeValue.Length - 1).Trim
                        End If
                        If NodeValue.EndsWith("""") Then
                            NodeValue = NodeValue.Substring(0, NodeValue.Length - 1).Trim
                        End If
                        newNode = returnXmlDoc.CreateElement(NodeName)
                        newNode.InnerText = NodeValue
                        appendToNode.AppendChild(newNode)
                    End If
                End If
            End If
        Next
        Return returnXmlDoc
    End Function

Monday, November 26, 2012

Reading XML with Namespace

If your XML contains Namespace information, then following example illustrates as how to read the data

Let’s consider following XML saved as TestResp.xml

This example contains elements and attribute.

<ResponseData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Result xmlns="http://TestInfo.com/GetData">
<Data>
<Id>3260</Id>
<StatusCode>0</StatusCode>
<StatusValue>NA</StatusValue>
<Values>
    <Value Type="A">1</Value>
    <Value Type="B">1</Value>
</Values>
</Data>
</Result>
</ResponseData>

Now, let’s read the info

Dim xmlString As String = ""
If File.Exists("C:\Test\TestResp.xml") Then xmlString = File.ReadAllText("C:\Test\TestResp.xml")
 
If String.IsNullOrEmpty(xmlString) = False Then
    xmlDoc = New Xml.XmlDocument
    xmlDoc.LoadXml(xmlString)
    Dim ns1 As New Xml.XmlNamespaceManager(xmlDoc.NameTable)
    ns1.AddNamespace("t", "http://TestInfo.com/GetData")
 
    If xmlDoc.SelectSingleNode("//t:Result/t:Data/t:Id", ns1) IsNot Nothing AndAlso _
                   IsNumeric(xmlDoc.SelectSingleNode("//t:Result/t:Data/t:Id", ns1).InnerText) Then
        Dim id As String = xmlDoc.SelectSingleNode("//t:Result/t:Data/t:Id", ns1).InnerText
    End If
 
    If xmlDoc.SelectSingleNode("//t:Result/t:Data/t:Values/t:Value", ns1) IsNot Nothing Then
        Dim xmlnodes As Xml.XmlNodeList = xmlDoc.SelectNodes("//t:Result/t:Data/t:Values/t:Value", ns1)
        For Each nod As Xml.XmlNode In xmlnodes
            If nod.Attributes("Type").Value = "A" Then
                Dim valueTypeA As String = nod.InnerText
            End If
        Next
    End If
End If

Saturday, October 06, 2012

Error: The underlying connection was closed

This is one of the most interesting error you may come across specially when using WCF Services. It will give you no detail, just go figure out - The underlying connection was closed: The connection was closed unexpectedly. So what to do? Most likely you have dataset size issue which is going back and forth between different tiers. For the security and performance reasons you should always limit the size. But if you are required to pass big chunk of data, you have to change the size to it’s maximum. So how do we do it?

 

You have to change the configuration on both side (client and service).

 

On the WCF Service side: ensure that you have

 

<dataContractSerializer maxItemsInObjectGraph="2147483647" />

 

2GB is the maximum size you can send data at once using WCF Service, so please be careful, you can adjust to a lower value as needed

 

<behaviors>
       <serviceBehaviors>
          <behavior name="serviceBehavior_Name">             
            <dataContractSerializer maxItemsInObjectGraph="2147483647" />
          </behavior>
       </serviceBehaviors>
</behaviors>

On the Client Side: Make sure that Binding and behavior info are set correctly

e.g. Binding

<binding name="wsHttpEndpoint_ITestService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
         <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
         <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
         <security mode="Message">
           <transport clientCredentialType="None" proxyCredentialType="None" realm=""/>
           <message clientCredentialType="Windows" negotiateServiceCredential="true" establishSecurityContext="true"/>
         </security>
</binding>

Client Behavior

<behaviors>
     <endpointBehaviors>
       <behavior name="endpointBehavior_Common">
         <dataContractSerializer maxItemsInObjectGraph="2147483647" />
       </behavior>
     </endpointBehaviors>
   </behaviors>

Finally, Client where you refer the actual service

<client>
    <endpoint address="http://www.test.com/TestService.svc" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpoint_ITestService" contract="TestService.ITestService" name="wsHttpEndpoint_ITestService"  behaviorConfiguration="endpointBehavior_Common" />            
</client>

This should fix the above problem.

Thursday, September 06, 2012

WCF Diagnostics

Have you seen weird error messages while using WCF Services and unable to figure out easily as what’s going on? Add the following diagnostics configuration in you config file under configuration section, may be at the bottom. It will generate a file named “App_tracelog.svclog”, you can open as XML file and read the info and may be able to trace the problem easily.

<system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
        <listeners>
          <add name="ServiceModelTraceListener"/>
        </listeners>
      </source>
 
      <source name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
        <listeners>
          <add name="ServiceModelTraceListener"/>
        </listeners>
      </source>
      <source name="System.Runtime.Serialization" switchValue="Verbose,ActivityTracing">
        <listeners>
          <add name="ServiceModelTraceListener"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="App_tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="Timestamp"/>
    </sharedListeners>
  </system.diagnostics>

The file will be generated on the same level where config file is available. Make sure to either comment or remove this configuration once you resolved the issue else it may impact the performance and use unnecessary disk space.

Monday, April 09, 2012

Abstract Factory Design Pattern

It is one of the highly used Creational Pattern from Gang of Four patterns. It provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the theme.

 

The client does not know (or care) which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage.

 

When and where to use it

You may wonder why you want to create objects using another class (called Abstract Factory) rather than calling constructors directly. Here are some reasons:

  1. Constructors are limited in their control over the overall creation process. If an application needs more control, using Factory is best option. E.g. sharing and re-using objects like object caching, or applications that maintain object and type counts.
  2. There are times when the client does not know exactly what type to construct to use. It is easier to code against a base type or an interface and then let a factory make the decision. ADO.NET objects such as DBConnection, DBCommand etc. are the examples.
  3. Constructors don’t communicate their intention very well because they must be named after their class. Having numerous overloaded constructors may make it hard for the developer to decide which constructor to use. Replacing constructors with intention-revealing creation methods are frequently preferred. 

 

Steps to Create Abstract Factory

  1. First Create Abstract Objects Interfaces (e.g. IAbstractProduct1, IAbstractProduct2) – It is like making of group of objects which will implement the set of same interfaces
  2. Create an Abstract Factory Interface (e.g. IAbstractFactory) which defines the Abstract Object Interfaces created in step 1
  3. Ensure actual concrete object (e.g. Product11 , Product12, Product21 and Product22) implements one of the Abstract Object Interface as defined in step1
  4. Finally Create Concrete Factories(e.g. ConcreteFactory1, ConcreteFactory2) which implements Abstract Factory Interface defined in step 2

 

Sample Code

Step 1.

''' <summary>
''' Abstract Product 1 (Group)
''' </summary>
''' <remarks></remarks>
Public Interface IAbstractProduct1
 
End Interface
 
''' <summary>
''' Abstract Product 2 (Group)
''' For example Here Abstract Product 2 Group is using AbtractProduct1 
''' </summary>
Public Interface IAbstractProduct2
    Function Status(ByVal ab1 As IAbstractProduct1) As String
End Interface

 

Step 2.

''' <summary>
''' Highest Level of Abstraction
''' The Abstract Factory
''' It defines two Abstract Product Groups (1 and 2)
''' </summary>
''' <remarks></remarks>
Interface IAbstractFactory
    Function CreateABF1() As IAbstractProduct1
    Function CreateABF2() As IAbstractProduct2
End Interface

 

Step 3.

''' <summary>
''' Product11 is part of AbstractProduct1 Group
''' </summary>
''' <remarks></remarks>
 
Public Class Product11
    Implements IAbstractProduct1
 
End Class
 
Public Class Product12
    Implements IAbstractProduct1
 
End Class
 
Public Class Product21
    Implements IAbstractProduct2
 
    Public Function SendStatus(ab1 As IAbstractProduct1) As String Implements IAbstractProduct2.Status
        Dim msgString As String = Me.GetType().Name & " is using " & CType(ab1, Object).GetType().Name
        Return msgString
    End Function
End Class
 
Public Class Product22
    Implements IAbstractProduct2
 
    Public Function SendStatus(ab1 As IAbstractProduct1) As String Implements IAbstractProduct2.Status
        Dim msgString As String = Me.GetType().Name & " is using " & CType(ab1, Object).GetType().Name
        Return msgString
    End Function
End Class

 

Step 4

''' <summary>
''' Abstract Factory gets implemented using the Concrete Factory
''' These methods finally gets implemented to return the respective product or object
''' </summary>
''' <remarks></remarks>
Public Class ConcreteFactory1
    Implements IAbstractFactory
 
    Public Function CreateABF1() As IAbstractProduct1 Implements IAbstractFactory.CreateABF1
        Return New Product11()
    End Function
 
    Public Function CreateABF2() As IAbstractProduct2 Implements IAbstractFactory.CreateABF2
        Return New Product21()
    End Function
End Class
 
''' <summary>
''' Abstract Factory gets implemented using the Concrete Factory
''' These methods finally gets implemented to return the respective product or object
''' </summary>
''' <remarks></remarks>
 
Public Class ConcreteFactory2
    Implements IAbstractFactory
 
    Public Function CreateABF1() As IAbstractProduct1 Implements IAbstractFactory.CreateABF1
        Return New Product12
    End Function
 
    Public Function CreateABF2() As IAbstractProduct2 Implements IAbstractFactory.CreateABF2
        Return New Product22
    End Function
End Class

 

Client to Test this Design Pattern

'You can use either ConcreateFactory for this test - Using a Windows app client
        'Dim factory As New ConcreteFactory1
        Dim factory As New ConcreteFactory2
        Dim prod1 = factory.CreateABF1
        Dim prod2 = factory.CreateABF2
        MsgBox(prod2.Status(prod1))