Thursday, July 18, 2013

Parsing XML with multiple namespaces

You may come across a situation when you will have to read a XML document containing name spaces and assign values to it. Here is sample which includes multiple namespaces with SOAP envelope xml document.

Test.XML

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <GetRecord xmlns="http://services.sample.com">
      <Request xmlns:a="http://schemas.sample.com/2013/06/GetRecordRequest" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <LoginData>
          <UserID>UserName</UserID>
          <Password>password</Password>
          <RequestID>23232323</RequestID>
          <IPAddress>121.11.1.1</IPAddress>
        </LoginData>
        <a:RecordID>35488047</a:RecordID>
      </Request>
    </GetRecord>
  </s:Body>
</s:Envelope>

 

Function which reads and assign values 

Private Function ReadAndAssignRequestXML(ByVal recordID As String) As String
Dim xmlDoc As New XmlDocument
Dim InputSOAPXML As String = String.Empty
Dim xmlFileName As String = "C:\Test.xml"


Try
xmlDoc.Load(xmlFileName)
Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(xmlDoc.NameTable)
nsmgr.AddNamespace("a", "http://schemas.sample.com/2013/06/GetRecordRequest")
nsmgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
nsmgr.AddNamespace("l", "http://services.sample.com")

xmlDoc.SelectSingleNode("/s:Envelope/s:Body/l:GetRecord/l:Request/l:LoginData/l:UserID", nsmgr).InnerText = "myUserID"
xmlDoc.SelectSingleNode("/s:Envelope/s:Body/l:GetRecord/l:Request/l:LoginData/l:Password", nsmgr).InnerText = "PASS"
xmlDoc.SelectSingleNode("/s:Envelope/s:Body/l:GetRecord/l:Request/a:RecordID", nsmgr).InnerText = recordID

InputSOAPXML = xmlDoc.OuterXml

Catch ex As Exception
InputSOAPXML = ex.Message
End Try

Return InputSOAPXML
End Function

 

Wednesday, June 12, 2013

Error:There is no compatible TransportManager found for URI

If you are configuring WCF Service, it is possible that you may come across the following error.

There is no compatible TransportManager found for URI 'net.tcp://MyDomain.net/MyService.svc/mex'. This may be because you have used an absolute address that points outside of the virtual application, or the binding settings of the endpoint do not match those that have been set by other services or endpoints. Note that all bindings for the same protocol should have the same settings in the same application.

 

Problem: The actual problem is you have defined more than one endpoint for address=”mex”

Solution: Ensure that you have only one endpoint for meta data exchange address, preferably use http or https binding

For example

 
<service behaviorConfiguration="svcBehavior_Common" name="MyWCFService.MyService">      
<endpoint address="" binding="wsHttpBinding" 
bindingConfiguration="wsHttpBinding_Common" 
name="wsHttpEndpoint_IMyService" 
bindingNamespace="http://wcfservices.mydomain.net" 
contract="MyWCFService.IMyService" />      
<endpoint address="" binding="netTcpBinding" 
bindingConfiguration="netTcpBinding_Common" 
name="netTcpEndpoint_IMyService" 
bindingNamespace="http://wcfservices.mydomain.net" 
contract="MyWCFService.IMyService" />      
<endpoint address="mex" binding="mexHttpsBinding" 
bindingConfiguration="mexHttpsBinding_Common" 
name="mexHttpEndpoint_IMyService" bindingNamespace="http://wcfservices.mydomain.net" 
contract="IMetadataExchange" />    
</service>

 

Note: Configuration info are defined in common place if the same is used by multiple services

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