Kuzhikkattil

Just another WordPress.com weblog

silverlight page navigation

Dim strPath As String = App.Current.Host.Source.OriginalString
        Dim strActualPath As String = strPath.Substring(0, strPath.IndexOf(“ClientBin”))
        Dim sourceURI As New Uri(strPath)
        Dim querystring As String = sourceURI.Query
        Dim objuri As New Uri(strActualPath & “test.aspx”)
        HtmlPage.Window.Navigate(objuri)

 

June 27, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

dependency injection

Public Interface IUserInfoProvider

    Function IsValidUser(ByVal domain As String, ByVal username As String, ByVal pwd As String) As Boolean
    Function GetUserList(ByVal domain As String, ByVal matchPattern As String) As System.Data.DataSet
    Function GetUserInfo(ByVal domain As String, ByVal matchPattern As String) As DataSet

End Interface
==================================

Public Class ActiveDirectoryUserInfo
    Implements IUserInfoProvider
    Dim objActiveDirectoryUserInfo As New ActiveDirectoryProvider.ActiveDirectoryProvider

    Public Function GetUserInfo(ByVal domain As String, ByVal matchPattern As String) As System.Data.DataSet Implements IUserInfoProvider.GetUserInfo
        Dim dsUserList As New System.Data.DataSet()
        dsUserList = objActiveDirectoryUserInfo.GetUserInfo(domain, matchPattern)
        Return dsUserList
    End Function

    Public Function GetUserList(ByVal domain As String, ByVal matchPattern As String) As System.Data.DataSet Implements IUserInfoProvider.GetUserList
        Dim dsUserList As New System.Data.DataSet()
        dsUserList = objActiveDirectoryUserInfo.GetUserList(domain, matchPattern)
        Return dsUserList
    End Function

    Public Function IsValidUser(ByVal domain As String, ByVal username As String, ByVal pwd As String) As Boolean Implements IUserInfoProvider.IsValidUser
        Return objActiveDirectoryUserInfo.IsValidUser(domain, username, pwd)
    End Function
End Class
===================================
<CONFIG>
    <Key>USER_INFO_SOURCE</Key>
    <Value>SQLeAudItClient.ActiveDirectoryUserInfo, SQLeAudItClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</Value>
  </CONFIG>
=========================================

Public Class UserInfoClassSetter

    Public Shared Function GetCorrectDependency() As IUserInfoProvider
        Dim objUtil As New Utility()
        Dim userInfoSource As String = objUtil.GetConfiguration(“USER_INFO_SOURCE”)

        ‘Dim classToCreate As String = objUtil.GetConfiguration(“USER_INFO_SOURCE”)
        ‘Dim type As Type = type.[GetType](classToCreate)
        Dim type As Type
        If userInfoSource = “ActiveDirectory” Then
            type = GetType(ActiveDirectoryUserInfo)
        ElseIf userInfoSource = “SQLSERVER” Then
            type = GetType(SQLServerUserInfo)
        End If

        Dim dependency As IUserInfoProvider = CType(Activator.CreateInstance(type), IUserInfoProvider)
        Return dependency

    End Function

  class continue………………………
==========================================

June 27, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

ExecBatFile [Process] process.startinfo

ExecBatFile [Process]

Private Function ExecBatFile(ByVal BatchFilePath As String, ByVal ScriptFile As String, ByVal userid As String, ByVal password As String, ByVal strSqlServerInstanceName As String) As Boolean

        Try

            ” Delete the log file before executing the batch file

            If (File.Exists(Path.Combine(BatchFilePath, TEMP_LOG_FILE_NAME))) Then

                File.Delete(Path.Combine(BatchFilePath, TEMP_LOG_FILE_NAME))

            End If

 

            Dim objProc As New Process

            objProc.StartInfo.UseShellExecute = True

            objProc.StartInfo.FileName = Path.Combine(BatchFilePath, BATCH_FILE_NAME)

            objProc.StartInfo.WorkingDirectory = BatchFilePath

            objProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

            objProc.StartInfo.Arguments = String.Format(” “”{0}”" “”{1}”" “”{2}”" “”{3}”" “, userid, password, strSqlServerInstanceName, ScriptFile)

            objProc.Start()

            objProc.WaitForExit()

            objProc = Nothing

            Try

                ‘Delete the temp script file

                File.Delete(ScriptFile)

            Catch ex As Exception

            End Try

 

        Catch ex As Exception

            Return False

        End Try

 

        Return True

    End Function

Public Function ExecBatSnapshot(ByVal BatchFilePath As String, ByVal ScriptFile As String, ByVal userid As String, ByVal password As String, ByVal strSqlServerInstanceName As String, ByVal StrDatabaseName As String, ByVal StrPublicationName As String) As Boolean

        Try

            Dim CmdEx As New SqlCommand

            Dim filepath As String = BatchFilePath

 

 

            Dim testconn As New SqlConnection(BuildConnectionString(userid, password, strSqlServerInstanceName, “master”))

            Dim strCommand As String = String.Concat(New String() {” EXEC xp_cmdshell ‘”, Path.Combine(BatchFilePath, ScriptFile), ” “”", strSqlServerInstanceName, “”" “”", StrDatabaseName, “”" “”", StrPublicationName, “”"‘”})

 

            Try

                testconn.Open()

                CmdEx.Connection = testconn

                CmdEx.CommandType = CommandType.Text

                CmdEx.CommandText = strCommand

                CmdEx.ExecuteNonQuery()

            Catch ex As Exception

                Return False

            End Try

 

 

        Catch ex As Exception

            Return False

        End Try

 

        Return True

    End Function

 

Private Function CreateNewScriptFile(ByVal BatchFilePath As String, ByVal strScript As String) As String

        Dim strScriptFile As String = String.Empty

        Try

            strScriptFile = Path.Combine(Path.GetTempPath(), TEMP_SCRIPT_FILE_NAME)

            ‘ ” Delete the temp script file before writing

            If (File.Exists(strScriptFile)) Then

                File.Delete(strScriptFile)

            End If

 

            ” declaring a FileStream and creating a sql file named file with access mode of writing

            Dim fs As New FileStream(strScriptFile, FileMode.Create, FileAccess.Write)

 

            ” creating a new StreamWriter and passing the filestream object fs as argument

            Dim writer As New StreamWriter(fs)

 

            ” the seek method is used to move the cursor to next position to avoid text to be overwritten

            writer.BaseStream.Seek(0, SeekOrigin.End)

 

            ” writing text to the file

            writer.Write(strScript)

            writer.Flush()

 

            ” closing the file

            writer.Close()

 

            writer = Nothing

        Catch ex As Exception

            Return “”

        End Try

 

        Return strScriptFile

    End Function

June 27, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

NetworkAvailable

Public Function NetworkAvailable() As Boolean

        Dim objPing As New System.Net.NetworkInformation.Ping

        Dim objPingReply As System.Net.NetworkInformation.PingReply

        Dim status As Boolean = False

        Try

            objPingReply = objPing.Send(“www.google.com”, 200)

            If (objPingReply.Status = Net.NetworkInformation.IPStatus.Success) Then

                status = True

            Else

                status = False

            End If

        Catch ex As Exception

            status = False

        End Try

        Return status

    End Function

June 27, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

serialize,deserialize xml

SerializeObjectToXML DeserializeXMLToObject For webservice

  Public Function DeserializeXMLToObject(ByVal input As String, ByVal type As System.Type) As Object

        Dim result As Object = Nothing

        Dim serializer As New XmlSerializer(type)

        Try

            result = serializer.Deserialize(New XmlTextReader(New StringReader(input)))

        Catch ex As Exception

            Debug.WriteLine(ex.Message)

        End Try

        Return result

    End Function

 

    ”’ <summary>

    ”’ Serializes Object To XML

    ”’ </summary>       

    Public Function SerializeObjectToXML(ByVal input As Object, ByVal type As System.Type) As String

        Dim returnXML As String = String.Empty

        Dim serializer As New XmlSerializer(type)

        Dim writer As New StringWriter

        Try

            serializer.Serialize(New XmlTextWriter(writer), input)

            returnXML = writer.ToString()

 

        Catch ex As Exception

            Debug.WriteLine(ex.Message)

        Finally

            writer.Close()

        End Try

        Return returnXML

    End Function

SerializeIVObject (for encryption)

 

”’ <summary>

    ”’ Serializes the IV object and stores it in IV file.

    ”’ </summary>

    ”’ <param name=”objIV”>Instance of IVInfo object.</param>

    ”’ <param name=”filePath”>Full file path where serialized file to be stored.</param>

    Public Function SerializeIVObject(ByVal objIV As IVInfo, ByVal filePath As String) As Boolean

        Return SerializeObject(objIV, filePath)

    End Function

 

    ”’ <summary>

    ”’ Deserializes the IV file and returns an object of InvoteInfo.

    ”’ </summary>

    ”’ <param name=”filePath”>Full file path of IV file.</param>

    Public Function DeserializeIVObject(ByVal filePath As String) As IVInfo

        Dim objIV As New IVInfo

        objIV = DirectCast(DeserializeObject(filePath), IVInfo)

        Return objIV

    End Function

 

    ”’ <summary>

    ”’ Serializes the object and stores it in file using file path.

    ”’ </summary>

    ”’ <param name=”obj”>Object instance to be serialized.</param>

    ”’ <param name=”filePath”>File path to store serialized object.</param>

    Private Function SerializeObject(ByVal obj As IVInfo, ByVal filePath As String) As Boolean

        Try

            Dim fileStream As Stream = File.Create(filePath)

            Dim binaryFormatter As New BinaryFormatter()

            binaryFormatter.Serialize(fileStream, obj)

            fileStream.Close()

            Return True

        Catch

            Return False

        End Try

    End Function

 

    ”’ <summary>

    ”’ Deserializes the file and returns an object.

    ”’ </summary>

    ”’ <param name=”filePath”>Full file path of file.</param>

    Private Function DeserializeObject(ByVal filePath As String) As Object

        Try

            Dim obj As New Object

            Dim fileStream As Stream = File.Open(filePath, FileMode.Open)

            Dim binaryFormatter As New BinaryFormatter

            obj = binaryFormatter.Deserialize(fileStream)

            fileStream.Close()

            Return obj

        Catch

            Return Nothing

        End Try

    End Function

June 27, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

Datatable ,.SetValue,IO.DirectoryInfo,rowfilter

Public Function SetTestRecord(ByVal strUserID As String, ByVal strDomain As String, ByVal strWebServer As String, ByVal strSqlserver As String, ByVal strIVId As String, ByVal StrEngId As String) As Boolean

 

        ‘Adds/Updates an IV record to IVFile

        Dim Ds As New DataSet

 

        Ds = GetIVDataSet()

 

        If Ds.Tables.Count > 0 Then

            With Ds.Tables(0).Select(“IVId = ‘” & strIVId & “‘”)

                If .Length = 1 Then

                    Dim dr As DataRow = .GetValue(0)

                    dr(“UserID”) = strUserID

                    dr(“Domain”) = strDomain

                    dr(“IVId”) = strIVId

                    dr(“TesttId”) = StrEngId

                    dr(“WebServer”) = strWebServer

                    dr(“SQLSERVER”) = strSqlserver

                    .SetValue(dr, 0)

                Else

                    If .Length = 0 Then

                        Dim drow As DataRow

                        drow = Ds.Tables(0).NewRow()

                        drow(“UserID”) = strUserID

                        drow(“Domain”) = strDomain

                        drow(“IVId”) = strIVId

                        drow(“TesttId”) = StrEngId

                        drow(“WebServer”) = strWebServer

                        drow(“SQLSERVER”) = strSqlserver

                        Ds.Tables(“Config”).Rows.Add(drow)

 

                    Else

                        Return False

                        Err.Raise(1234, , “More than one value found for requested key.”)

                    End If

 

                End If

            End With

        Else

            Return False

            Err.Raise(1234, , “Incorrect format of Configuration file.”)

        End If

        Ds.WriteXml(strpath)

        Return True

        Ds = Nothing

    End Function

IO.DirectoryInfo, DATATABLE CREATION

Try

            di = New IO.DirectoryInfo(strFolderpath)

            aryFi = di.GetFiles(“*.inv”)

 

            For Each fi In aryFi

                objIV = objutil.DeserializeIVObject(fi.FullName)

                If objIV.TesttId = EngId Then

                    Dim drow As DataRow

                    drow = ds.Tables(0).NewRow()

                    drow(“UserID”) = objIV.UserId

                    drow(“EmailId”) = objIV.EmailId

                    drow(“IVTime”) = objIV.IVTime

                    drow(“SQLSERVER”) = objIV.SQLServer

                    ds.Tables(“Record”).Rows.Add(drow)

                End If

            Next

            Return ds

        Catch ex As Exception

 

DefaultView and rowfilter

dsData.ReadXml(Server.MapPath(“Data\TEST.xml”))

            dsData.Tables(“Account_Test”).DefaultView.RowFilter = “TestId = ‘” & TestId & “‘”

            LstAC.DataSource = dsData.Tables(“SignificantAccountMatrix”).DefaultView.ToTable

            LstAC.DataBind()

June 27, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

xml — insert after a key ,Get node value ,update

Insert after a key and delete duplicates

—————————————–

 

            xmldoc.Load(strpath)

            Dim Node As XmlNode = xmldoc.SelectSingleNode(“//configuration/appSettings”).FirstChild

            nNode = Node.Clone

            PNode = Node.ParentNode

            nNode.Attributes.GetNamedItem(“value”).Value = Strvalue

            nNode.Attributes.GetNamedItem(“key”).Value = StrKey

            PNode.InsertAfter(nNode, PNode.LastChild)

            xmldoc.Save(strpath)

 

            xmldoc.Load(strfullPath)            xmldoc.SelectSingleNode(“//configuration/appSettings”).RemoveChild(xmldoc.SelectSingleNode(“//add[@value='" & StrValue & "']“))

            xmldoc.Save(strfullPath)

Private Sub Updatekey(ByVal StrKey As String, ByVal Strvalue As String, ByVal strPath As String)

       

        Dim xmldoc As New XmlDocument()

        Try

            xmldoc.Load(Strpath)

            For Each Node As XmlNode In xmldoc.Item(“configuration”).Item(“appSettings”)

                If Node.Name = “add” Then

                    If Node.Attributes.GetNamedItem(“key”).Value = StrKey Then

                        Node.Attributes.GetNamedItem(“value”).Value = Strvalue

                    End If

                End If

            Next Node

            xmldoc.Save(Strpath)

        Catch ex As Exception

            MsgBox(ex.Message)

        Finally

            xmldoc = Nothing

        End Try

    End Sub

Private Function GetNodeValue(ByVal StrKey As String, ByVal strPath As String) As String()

        Dim xmldoc As New XmlDocument()

        Try

            Dim strVal As String = String.Empty

            xmldoc.Load(Strpath)

            For Each Node As XmlNode In xmldoc.Item(“configuration”).Item(“appSettings”)

                If Node.Name = “add” Then

                    If Node.Attributes.GetNamedItem(“key”).Value = StrKey Then

                        strVal &= Node.Attributes.GetNamedItem(“value”).Value & “,”

                    End If

                End If

            Next Node   

 

            Dim separators As String = “,”

            Dim XmlVal() As String = strVal.Split(separators.ToCharArray)

 

            Return XmlVal

 

        Catch ex As Exception

        Finally

            xmldoc = Nothing

        End Try

    End Function

June 27, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

Accept CommandLineArgs in exe

Public Sub New(ByVal StrArgs As String)

        Dim str() As String

        str = GetCommandLineArgs(StrArgs)

……………………………….

………………………………

………………………….

 

Function GetCommandLineArgs() As String()

        Dim separators As String = “,”

        Dim commands As String = Microsoft.VisualBasic.Command()

        Dim args() As String = commands.Split(separators.ToCharArray)

        Return args

    End Function

June 27, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

Silverlight ,xml related,linq

<UserControl x:Class=”SilverlightApplication1.InherentRisk”    xmlns=”http://schemas.microsoft.com/client/2007″     xmlns:my=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data”    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”     Width=”Auto” Height=”Auto”>    <Grid x:Name=”LayoutRoot” Background=”White”>        <Grid.RowDefinitions>            <RowDefinition  Height=”*” />            <RowDefinition  Height=”*” />            <RowDefinition  Height=”*” />        </Grid.RowDefinitions>        <Grid.ColumnDefinitions>            <ColumnDefinition   Width =”50″/>            <ColumnDefinition  Width=”1900″ />            <ColumnDefinition  Width=”*” />        </Grid.ColumnDefinitions>          <StackPanel Orientation=”Vertical”  HorizontalAlignment=”Left” Grid.Row=”1″ Background=”White” Grid.Column=”1″>            <StackPanel Orientation=”Vertical” >             <TextBlock Text=”Impact on Audit strartegy”  HorizontalAlignment=”Left” Style=”{StaticResource TBSubTitleStyleWithoutUnderline}” ></TextBlock>            <my:DataGrid  x:Name=”dgStrategy” ColumnWidth=”105″ RowHeight=”32″ RowDetailsVisibility=”VisibleWhenSelected” HorizontalAlignment=”Left” Grid.Column=”0″ Grid.ColumnSpan=”2″ Height=”150″ Width=”600″>                <my:DataGrid.Columns>                    <my:DataGridTextBoxColumn   DisplayMemberBinding=”{Binding id}” Header=”id” Width=”0″ Visibility=”Collapsed” ></my:DataGridTextBoxColumn>                    <my:DataGridTextBoxColumn DisplayMemberBinding=”{Binding Description}” Header=”Description of impact”></my:DataGridTextBoxColumn>                     <my:DataGridTemplateColumn Header=”Section Impacted” Width=”340″>                        <my:DataGridTemplateColumn.CellTemplate>                            <DataTemplate>                                <StackPanel Orientation=”Horizontal”>                                    <ListBox x:Name=”lstStrat” Width=”330″  ItemsSource=”{Binding Section , Mode=TwoWay}” SelectionChanged=”lstChange” />                                </StackPanel>                            </DataTemplate>                        </my:DataGridTemplateColumn.CellTemplate>                        <my:DataGridTemplateColumn.CellEditingTemplate>                            <DataTemplate>                                <StackPanel Orientation=”Horizontal”>                                    <ListBox  x:Name=”lstStrat” Width=”330″ ItemsSource=”{Binding Section}” SelectedItem=”{Binding SelectedSection , Mode=TwoWay}” SelectionChanged=”lstChange” />                                </StackPanel>                            </DataTemplate>                        </my:DataGridTemplateColumn.CellEditingTemplate>                    </my:DataGridTemplateColumn>                                    </my:DataGrid.Columns>            </my:DataGrid>        </StackPanel> <StackPanel Orientation=”Vertical”  HorizontalAlignment=”Left” Grid.Row=”1″ Background=”White” Grid.Column=”1″>            <StackPanel Orientation=”Horizontal” Grid.Row=”2″ Grid.Column=”2″>                <TextBlock Width=”500″ x:Name=”placeholder”></TextBlock>                <Button Width=”150″ x:Name=”Next” HorizontalAlignment=”Center” Content=”Save” Height=”35″ ></Button>            </StackPanel>        </StackPanel>    </Grid></UserControl>  Public Class ClsTest         Private m_id As String        Private Sections As List(Of String)        Private m_Description As String        Private m_SelectedSection As String                 Public Property Section() As List(Of String)            Get                Return Sections            End Get            Set(ByVal value As List(Of String))                Sections = value            End Set        End Property         Public Property Description() As String            Get                Return m_Description            End Get            Set(ByVal value As String)                m_Description = value            End Set        End Property        Public Property id() As String            Get                Return m_id            End Get            Set(ByVal value As String)                m_id = value            End Set        End Property        Public Property SelectedSection() As String            Get                Return m_SelectedSection            End Get            Set(ByVal value As String)                m_SelectedSection = value            End Set        End Property    End Class

 Dim RskMgrSoapClient As New BizLogic.DataServiceSoapClient()’’webservice – BizLogic.Dim StrategyLst As New List(Of ClsTest)()RskMgrSoapClient.RetrieveTestFunctionAsync(“0″)’’function in webservice – BizLogic.         AddHandler RskMgrSoapClient.RetrieveTestFunctionCompleted, AddressOf RskMgrSoapClient_RetrieveTestFunctionCompleted

 Public Sub RskMgrSoapClient_RetrieveTestFunctionCompleted(ByVal sender As Object, ByVal e As Bizlogic.RetrieveTestFunctionCompletedEventArgs)        Try             Dim objRsk As ClsTest            Dim strxml As String = e.Result            Dim xmlProducts As XDocument = XDocument.Parse(strxml)            Dim products = From product In xmlProducts.Descendants(“Strat”)’’’linq            For Each p In products                objRsk = New ClsTest()                objRsk.Section = New List(Of String)                objRsk.Section.Add(“Team assignments including kpmg specialists”)                objRsk.Section.Add(“involvement of others”)                objRsk.Section.Add(“Timing of Audit activities”)                objRsk.Section.Add(“Communication with reviewers”)                objRsk.Section.Add(“meteriality”)                objRsk.id = p.Element(“ID”).Value.ToString                objRsk.Description = p.Element(“Desc”).Value.ToString                StrategyLst.Add(objRsk)            Next        Catch ex As Exception         End Try                Me.dgStrategy.ItemsSource = StrategyLst‘’binding datagrid (also having a list box “Section” in grid)    End Sub

‘’’editStrategyLst = dgStrategy.ItemsSourceFor Each objStrategy In StrategyLst            Dim strselectditem As String = IIf(objStrategy.SelectedSection Is Nothing, objStrategy.Section(0).ToString, objStrategy.SelectedSection)            RskMgrSoapClient.SaveTestFunctionAsync(objStrategy.id, objStrategy.Description, strselectditem, “False”) Next            

 XmlReader

Dim settings As XmlReaderSettings = New XmlReaderSettings()Dim reader As XmlReader = XmlReader.Create(“DocManifest.xml”)While reader.Read()      Select Case reader.NodeType           Case XmlNodeType.Element                 output.Append(reader.Name)            Case XmlNodeType.Text                output.Append(reader.Value + Environment.NewLine)       End SelectEnd WhileOutputTextBlock.Text = output.ToString

 ‘’’latest

Dim nodeX As XNode        Dim output As StringBuilder = New StringBuilder()         Dim xdoc As XElement = XElement.Load(“DocManifest.xml”)        Dim products = From product In xdoc.Elements(“DocumentControlService”).Elements(“Current”).Elements(“Item”).Elements(“DateTime”)        For Each p In products            p.Value = “206-555-0168″            ‘nodeX = p.FirstNode ‘products.First            nodeX = p            output.Append(nodeX.ToString)        Next        OutputTextBlock.Text = output.ToString        Dim Xadd As XElement = New XElement(“DateTime”, “206-555-0168″)        Dim xdoc1 As XElement = xdoc.Elements(“DocumentControlService”).Elements(“Current”).Elements(“Item”).First        xdoc1.Add(Xadd)        xdoc1.RemoveNodes()        products = Nothing        Return nodeX

June 27, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet

SQL select case in where condition

create table MyTable

 (  mydata int

      , mycompare1 char(1)

      , mycompare2 char(1)

 )

go

insert MyTable select 1, ‘A’, ‘B’

insert MyTable select 2, ‘A’, ‘C’

insert MyTable select 3, ‘D’, ‘G’

insert MyTable select 4, ‘E’, ‘B’

GO

select *

 from MyTable

 where 1 = CASE

             WHEN mycompare1 = ‘A’ then 1

             ELSE 0

           END

GO

————————————————————————————-

 

  Declare @x varchar(2)

  set @x=‘D’

   select * from TBLTEST order by case  when  @x=‘D’ then  -1*id   else  id     end

June 2, 2008 Posted by kuzhikkattil | Uncategorized | | No Comments Yet