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)