Wednesday, January 13, 2010

Transformation and Validation of XML

Some common Xml operation in .Net might be transforming,Validating or writing a XML file to a specific folder location. This can be done easily as explained below step by step.

How to Validate a Xml:

private bool _ValidationResult = true;
private string _ErrorMsg = string.Empty;

///
/// Method to validate XML using XSD
///

/// Source XmlReader object
/// XSD as string
/// Error
/// 'true' if validation succeeds, 'false' if validation fails
public ValidateXmlReturnType ValidateXml(XmlReader xmlReader, string xsdString)
{
_ValidationResult = true;
_ErrorMsg = string.Empty;
string validationErrorMsg = string.Empty;

// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

//Add the XML schema to an XmlSchemaSet and add to XmlReaderSettings.
XmlSchemaSet schemas = new XmlSchemaSet();

try
{
using (XmlReader schemaReader = XmlReader.Create(new StringReader(xsdString)))
{
schemas.Add("", schemaReader);
}
settings.Schemas.Add(schemas);
using (XmlReader newXmlReader = XmlReader.Create(xmlReader, settings))
{
while (newXmlReader.Read())
{
if (!string.IsNullOrEmpty(_ErrorMsg))
break;
}
}
}
catch (System.Xml.XmlException xmlException)
{
OnValidationFailed(xmlException.Message);
}

return new ValidateXmlReturnType(_ValidationResult, _ErrorMsg);

}

//Event handler to execute the validation and return the result.
void ValidationCallBack(object sender, ValidationEventArgs e)
{
OnValidationFailed(e.Message);

}
private void OnValidationFailed(string exceptionMessage)
{
if (_ValidationResult != false)
{
_ValidationResult = false;
}
if (!string.IsNullOrEmpty(_ErrorMsg) && !string.IsNullOrEmpty(exceptionMessage))
{
_ErrorMsg += System.Environment.NewLine;
}
_ErrorMsg += exceptionMessage;
}







How to Transform a Xml:

TrandformXMLReturnType Entity class definition

public class TransformXmlReturnType
{
bool _IsTransformed;
Stream _OutputXmlStream;

public TransformXmlReturnType(bool isTransformed, Stream outputXmlStream)
{
this._IsTransformed = isTransformed;
this._OutputXmlStream = outputXmlStream;
}
public bool IsTransformed
{
get
{
return _IsTransformed;
}
}

public Stream OutputXmlStream
{
get
{
return _OutputXmlStream;
}
}

}


Method to Do call transformation:

TransformXmlReturnType transformationResult = null;

using (XmlReader xmlReader = XmlReader.Create(this.SourceDataFilePath.ToString()))
{
this.WriteInformation("Attempting to transform source XML using XSLT");

try
{
transformationResult = TmEaiXmlProcessor.TransformXml(xmlReader, Xslt);
}
catch (System.Xml.Xsl.XsltException xsltException)
{
this.LogFatalException(xsltException, "Failed to transform XML", methodName);

}
catch (System.ArgumentNullException argumentNullException)
{
this.LogFatalException(argumentNullException, "Failed to transform XML: " +
argumentNullException.ParamName + " is null", methodName);
}
catch (Exception exp)
{
this.LogFatalException(exp, "Failed to transform XML", methodName);
}
}

if (transformationResult != null &&
transformationResult.IsTransformed && transformationResult.OutputXmlStream != null)
{
this.WriteInformation("Transformed XML successfully");
}
TranformXML Method:
///
/// Method to transform Source XML to Target XML using
/// XSL transformation
///

/// Source XmlReader object
/// XSLT as string
/// Transformed target XML XDocument object
public static TransformXmlReturnType TransformXml(XmlReader xmlReader, string xsltString)
{
bool isTransformed = true;

Stream outputXmlStream = new MemoryStream();
XslCompiledTransform xslt = new XslCompiledTransform();

try
{
// Load the style sheet.
xslt.Load(XmlReader.Create(new StringReader(xsltString)));
XPathDocument doc = new XPathDocument(xmlReader);
//Transform using IXPathNavigable input
xslt.Transform(doc, null, outputXmlStream);

}
catch (Exception exp)
{
isTransformed = false;
outputXmlStream = null;
throw exp;
}

outputXmlStream.Flush();
outputXmlStream.Seek(0, SeekOrigin.Begin);

return new TransformXmlReturnType(isTransformed, outputXmlStream);
}




How to Write a Xml to a destination path:

Input will xml Data and the destionation file path for writing a xml file in a specific location.
///
/// Writes XML data to destination file.
///

/// input XML data
/// destination File path
public static void WriteXmlToFile(XmlReader inputXmlReader, string destinationFilePath)
{
bool isEmptyElement = false;
using (FileStream fs = new FileStream(destinationFilePath, FileMode.Create))
{

XmlWriterSettings ws = new XmlWriterSettings();
ws.Indent = true;
using (XmlWriter writer = XmlWriter.Create(fs, ws))
{
// Parse the file and write each of the nodes.
while (inputXmlReader.Read())
{
switch (inputXmlReader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(inputXmlReader.Name);
isEmptyElement = inputXmlReader.IsEmptyElement;

while (inputXmlReader.MoveToNextAttribute()) // Read attributes.
writer.WriteAttributes(inputXmlReader, false);

if (isEmptyElement)
{
writer.WriteFullEndElement();
isEmptyElement = false;
}

break;
case XmlNodeType.Text:
writer.WriteString(inputXmlReader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(inputXmlReader.Name, inputXmlReader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(inputXmlReader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}

}
}
}

Thursday, February 26, 2009

Some Xml Stuff's

Serializing A Entity Class To String:
Dim commandResult As Object
commandResult = commandObject.Execute(inputValue) ‘Command Result is list of Some Entity class
Dim xmlSerializer As XmlSerializer xmlSerializer = New XmlSerializer(commandResult.GetType())
Dim memStream As MemoryStream = New MemoryStream()
xmlSerializer.Serialize(memStream, commandResult)
Dim xdoc As System.Xml.XmlDocument = New System.Xml.XmlDocument() 'Set the pointer to begining of the stream memStream.Position = 0
xdoc.Load(memStream)
Dim strResult As String = xdoc.OuterXml
Return (strResult)

Reading from XML String Using Linq to XML:
xmlContent is of String format.Using Linq u can get each Xml Element or Attribute in order to get the data in Entity Class format.
Dim xmlDocument As XDocument = XDocument.Parse(xmlContent)
Dim Claims = New ClaimUI WITH _ { _ .ID = ClaimUI.Element("ClaimID"), _ .Reference = ClaimUI.Element("ClaimReference") _ } End With _ In Dim FoundNames As IEnumerable(Of String) = From Name In AllNames Where Name.StartsWith("G") 'When this statement has been executed, FoundNames will now contain a collection of names that starts with the letter "G." It this case, it returns "Gabriel."
You can now add the names to a ListBox control:
For Each PeopleName In FoundNames

ListBox1.Items.Add(PeopleName)
Next
'To Find a author Where author.Field(Of String)("State") = "CA" _
Dim C As ClaimUI = New ClaimUI()
Dim Claims = From Claim In xmlDocument.Descendants("ClaimEntity") _
Select New ClaimUI With { .ID = Claim.Element("ClaimID"), _ .Reference = Claim.Element("ClaimReference")} .LastName = ClaimUI.Field(Of String)("au_lname".) }
ProductList.ItemsSource = Claims
ClaimList.ItemsSource = Claims

Handling Or Converting Entire Record Set in Form of XML In Stored Procedure Level:
Declare @XML VARCHAR(MAX)
SET @XML ='Root Tag'
SET @XML = @XML + (SELECT * FROM tblCaseReg for XML Path('Records'))
SET @XML = @XML + 'Root Tag'
SELECT @XML
Creating or Forming Xml using XML Document:
Dim Doc As New XmlDocument()

Dim newAtt As XmlAttribute
Dim TempNode As XmlElementTrypropertiesList = New PropertiesEntityList
powerStationDataReader = CType(ReportingDAL.Sample(), SqlDataReader) 'which wil return me datareader
Dim dec As XmlDeclaration = Doc.CreateXmlDeclaration("1.0", _Nothing, Nothing)

Doc.AppendChild(dec)
Dim DocRoot As XmlElement = Doc.CreateElement("Root")

Doc.AppendChild(DocRoot)
list = New List(Of Object)Dim x As Integer
Dim colname1 As String = powerStationDataReader.GetName(x).ToString()
Dim columncount1 As Integer = powerStationDataReader.FieldCount
For x = 0 To columncount1 - 1
Dim pv1 As XmlNode = Doc.CreateElement("Column")
newAtt = Doc.CreateAttribute("colname")
DataValue = colname1
newAtt.Value = DataValue.ToString()
pv1.Attributes.Append(newAtt)
DocRoot.AppendChild(pv1)
NextWhile (powerStationDataReader.Read())
Dim SqlReader As SqlClient.SqlDataReader = powerStationDataReader
Dim columncount As Integer = powerStationDataReader.FieldCount
For x = 0 To columncount - 1
Dim colname As String = SqlReader.GetName(x).ToString()

Dim pv As XmlNode = Doc.CreateElement("NodeItem") ' Creating Each Node for xml
newAtt = Doc.CreateAttribute(colname)
DataValue = powerStationDataReader(x) 'Data For the Attribute
newAtt.Value = DataValue.ToString()
pv.Attributes.Append(newAtt)
DocRoot.AppendChild(pv) 'Adding Node to the Doc Root
Next
End While
stringXML = Doc.OuterXml 'Finally u can have it in string format.

Extracting XML Data:
Dim xmlReaderForSettings As XmlReader = xmlReaderForSettings.Create(New StringReader(XmlStringData))
While (xmlReaderForSettings.Read()) 'Reading Each Xml Node
If (xmlReaderForSettings.HasAttributes) Then 'Now for Attributes if it has Gor then Find for the Elements Key NameIf (xmlReaderForSettings.IsStartElement("Settings")) Then
While (xmlReaderForSettings.MoveToNextAttribute()) 'Similarly move to all Attributes
If (xmlReaderForSettings.Name = "ID") Then
_Id= xmlReaderForSettings.Value
ElseIf (xmlReaderForSettings.Name = "Name") Then

_Name=xmlReaderForSettings.Value
End While
End If
End If
End While

Sunday, February 15, 2009

Facade Design Pattern


Facade Design Pattern Provides a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.


Best Example for facade is a Telephone operator or a receptionist. Its responsible for routing of the operation. Facade also means entry point.

Example:Business Operations For me might be ClaimTransaction,EstimateTransation,BillingTransaction. So the business methods for my application will look like this.

In Facade Class:

---------------------------------------------------------------------------------

Function ClaimsTransaction(ByVal Operation As BusinessOperation, ByVal Input As Object, ByVal Output As Object)

Function UserTransaction(ByVal Operation As BusinessOperation, ByVal Input As Object, ByVal Output As Object)

Function AppSetUpTransaction(ByVal Operation As BusinessOperation, ByVal Input As Object, ByVal Output As Object)

Public Enum BusinessOperation

  • Add
  • Update
  • Delete
  • List
  • Validate
  • GetDetails

End Enum

Select Case [Operation]

Case BusinessOperation.Add

Dim claim As Claims = New Claims() --This will call respective Business operations

claim.Add()

Case BusinessOperation.List

Dim claim As Claims = New Claims()

Return claim.GetList()

Case BusinessOperation.Update

Dim claim As Claims = New Claims()

claim.Update()

End Select

---------------------------------------------------------------------------------

My Call to the Facade will be of this sort:

Dim BL As BusinessLayer.BusinessFacade = New BusinessLayer.BusinessFacade() BL.ClaimsTransaction(BusinessOperation.List, Nothing, Nothing)

----------------------------------------------------------------

Thursday, February 12, 2009

Command Design Patterns


Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
The classes and/or objects participating in this pattern are:
Command (Command) :declares an interface for executing an operation
ConcreteCommand (CalculatorCommand) :defines a binding between a Receiver object and an action
implements Execute by invoking the corresponding operation(s) on Receiver
Client (CommandApp) :creates a ConcreteCommand object and sets its receiver
Invoker (User) :asks the command to carry out the request
Receiver (Calculator) :knows how to perform the operations associated with carrying out the request.
Sample Code:

#Region "Service Client Definition"
'''
''' Service Client is responsible for routing the request from UI to different services.
'''

''' Decorated with AspNetCompatibilityRequirements attribute to ALLOW the service to participate in HttpContext
_
Public Class ServiceClient
Implements IServiceClient

Public Sub New()
System.Net.ServicePointManager.ServerCertificateValidationCallback = AddressOf TrustAllCertificatesCallback
End Sub



'''
''' This method is used to submit a command to the CommandManager from the UI.
'''

''' Name of the command that needs to executed
''' The session Id for the login
''' CommandResult which is result of the command execution
''' Used when there are no input parameters
Public Function SubmitRequest(ByVal commandName As String, ByVal sessionID As String) As CommandResult Implements IServiceClient.SubmitRequest
Return CommandManager.SubmitCommand(commandName, String.Empty, sessionID)
End Function
'''
''' This method is used to submit a command to the CommandManager from the UI.
'''

''' String: Name of the command that needs to executed
''' String: Input value for the command
''' The session Id for the login
''' CommandResult which is result of the command execution
''' Used when there are input parameters to be passed
Public Function SubmitRequestWithInput(ByVal commandName As String, ByVal commandInput As Object, ByVal sessionID As String) As CommandResult Implements IServiceClient.SubmitRequestWithInput
Return CommandManager.SubmitCommand(commandName, commandInput, sessionID)
End Function
'Public Function DelegateRequest(ByVal commandName As String, ByVal sessionID As String) As CommandResult Implements IServiceClient.DelegateRequest
' Dim CM As ContextMgrService = New ContextMgrService()
' Dim siteConfigContextValue As Object = CM.GetSessionData("SITECONFIGINFO")
' Dim siteConfigList() As AdminService.SiteConfigEntity = CType(siteConfigContextValue, AdminService.SiteConfigEntity())
' Dim cmdResult As CommandResult = New CommandResult()
' Dim remoteServiceClientURL As String = String.Empty
' Dim userID As String
' Dim password As String
' For Each siteConfig As AdminService.SiteConfigEntity In siteConfigList
' If siteConfig.linkType = "SVCCLIENT" And siteConfig.siteID = "UKIDER01" Then
' remoteServiceClientURL = siteConfig.linkURI
' userID = siteConfig.userID
' password = siteConfig.password
' Exit For
' End If
' Next
' Dim baseAddress As Uri = New Uri(remoteServiceClientURL)
' Dim bind As BasicHttpBinding = New BasicHttpBinding()
' Dim endPoint As EndpointAddress = New EndpointAddress(baseAddress)
' Dim channel As ChannelFactory(Of IServiceClient) = New ChannelFactory(Of IServiceClient)
' Dim remoteClient As IServiceClient = channel.CreateChannel(bind, endPoint)
' cmdResult = remoteClient.HandleRemoteRequest(commandName, "1", userID, password)
' Return cmdResult
'End Function
'''
''' This method is used to handle a remote request from another instance of ServiceClient
'''

''' String: Name of the command that needs to executed
''' String: Input value for the command
''' String: UserId provided to the remote client to connect
''' String: Password provided to the remote client to connect
''' CommandResult which is result of the command execution
''' Used when there are input parameters to be passed
Public Function HandleRemoteRequest(ByVal commandName As String, ByVal commandInput As String, ByVal userID As String, ByVal password As String) As CommandResult Implements IServiceClient.HandleRemoteRequest
Dim sessionID As String
Dim input As String = userID + "@" + password
Dim cmdResult As CommandResult = New CommandResult()
cmdResult = CommandManager.SubmitCommand("LoginCmd", input, String.Empty)
If cmdResult.ErrorCode = String.Empty Then
sessionID = cmdResult.OutputList(0)
Return CommandManager.SubmitCommand(commandName, commandInput, sessionID)
Else
Return cmdResult
End If
End Function


'''
''' Requried to handle any errors raising out of trust certification in SSL.
'''

'''
'''
'''
'''
'''
'''
Private Function TrustAllCertificatesCallback(ByVal sender As Object, ByVal cert As X509Certificate, ByVal chain As X509Chain, ByVal errors As SslPolicyErrors) As Boolean
Return True
End Function
End Class
#End Region
#Region "Command Manager Definiton"
'''
''' This class represent the invoker in the command design pattern.
''' Responsible for associating concrete commands with different requests.
'''

'''
Public Class CommandManager
'''
''' This method enables the Service Client class to submit the request to the Command manager.
'''

''' String: Name of the command to be executed.
''' Object: Input value to be processed
''' The session Id for the login
''' Returns the object value after executing the command
'''
Public Shared Function SubmitCommand(ByVal commandName As String, ByVal inputValue As Object, ByVal sessionID As String) As Object
Dim submitCommandResult As Object = New Object()
Dim cmd As Command
'Dim inputString As Object = inputValue.ToString()
Dim currAssembly As System.Reflection.Assembly
currAssembly = System.Reflection.Assembly.GetExecutingAssembly()
cmd = currAssembly.CreateInstance(commandName)
If (sessionID <> String.Empty) Then
Dim contextManagerService As ContextMgrService = New ContextMgrService()
Dim currentUser As Object = contextManagerService.GetCurrentUser(sessionID)
Dim loginDetail As UserService.UserEntity = CType(currentUser, UserService.UserEntity)
'cmd.LoginUserID = loginDetail.LoginID
'cmd.LoginPassword = loginDetail.Password
cmd.LoginUserID = "Site01@Admin"
cmd.LoginPassword = 1
End If
cmd.LoginUserID = "Site01@Admin"
cmd.LoginPassword = 1

submitCommandResult = ExecuteCommand(cmd, inputValue, sessionID)
Return submitCommandResult
End Function
'''
''' This method is responsible for executing the concrete command and serializing the result to be returned.
'''

''' Command: Instance of the concrete command object to be executed
''' String: Input value to be processed by the command
''' The session Id for the login
''' Object value which is the result of command execution
''' inputValue would be 'Nothing' when SubmitRequest() is used to submit the command from UI
Private Shared Function ExecuteCommand(ByVal commandObject As Command, ByVal inputValue As Object, ByVal sessionID As String) As Object
Dim executeCommandResult As CommandResult = New CommandResult()
Dim commandResultForReturn As CommandResultList = New CommandResultList()
executeCommandResult = commandObject.Execute(inputValue)
Return executeCommandResult
End Function
End Class
#End Region
#Region "Command Definitions"
'''
''' Base command class which must be inherited by all the concrete command classes.
'''

''' All distinct requests are represented by a command
Public MustInherit Class Command
Public Sub New()
loginDetail = New UserService.UserEntity()
End Sub
Public MustOverride Function Execute(ByVal input As Object) As Object
Private loginDetail As UserService.UserEntity
Public Property LoginUserID() As String
Get
Return loginDetail.LoginID
End Get
Set(ByVal value As String)
loginDetail.LoginID = value
End Set
End Property
Public Property LoginPassword() As String
Get
Return loginDetail.Password
End Get
Set(ByVal value As String)
loginDetail.Password = value
End Set
End Property
End Class






#End Region
CLASS CODE:

Public Class DeleteTeamDiaryEntryCmd
Inherits Command
Public Overrides Function Execute(ByVal input As Object) As Object
End Function
End Class
PROXY CODE:

_ServiceClientProxy = New ServiceClient.ServiceClientClient()
AddHandler _ServiceClientProxy.SubmitRequestWithInputCompleted, AddressOf Localization
_ServiceClientProxy.SubmitRequestWithInputAsync(" PPG.Leapfrog.Commands.CommonCommands.GetLocalizedControlValueCmd", "VehicleAvailabilityForecast", _SessionID)

Monday, June 23, 2008

Database Logging with Enterprise Library 4.0

Hi All,
I am a begginer in Microsoft technologies.
I was trying enterprise library for Logging Past three days.Here is a quick walk through of what i have done in my application hope it helps at least one who is new to Enterprise library..
I had a typical scenario in which i was supposed to log the LogCategory and LogMessage in the Database(SQL Server) Using Enterprise Library 4.0.
First of All we should be careful with the .dll's while playing around.We should refer to the Dll's only in the Bin folders else will through type error and create lot of problems when u debug the application.

Add references to Logging,Logging Database and Enterprise Library Shared Assembly from Bin of the program files folder.

using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Database;


LogEntry dblog = new LogEntry();
dblog.Message = "DB Log Message";
dblog.Categories.Add("Error");
dblog.EventId = 1;
Logger.Write(dblog);

Open the web Config File using configration tool which is available in the Bin folder.
Which will give a good graphical user interface than using the ugly Xml's in the web config.
Now Add the Logging Application Block and specify the Connection String to your need.Add trace listners corresponding to your need.Save the Web Config file.Also be careful with the Text formatter if you not specifing it in Web Config file corresponding to the DatabaseTraceListner with out which runtime it will throw you BuildFailedException(The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter, null]) failed: The value can not be null or string or empty. Parameter name: name (Strategy type Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.ConfiguredObjectStrategy, index 2) )Enterprise library will take care the remaining for you in logging your information into the database!!