Friday, April 24, 2009

Count Character Occurances In a String

In a string occurance of particular character can be found easily by using the function 'InStr()' which returns the location of the character in the string. But if we want to count the number of occurances of particular character in the string then I've found the following three ways to get the

Private Function countOccurance1(ByVal hayStack As String,ByVal needle As Char) As Integer
If String.IsNullOrEmpty(hayStack) Then Return 0
Dim chars() As Char = hayStack.ToCharArray
Dim count As Integer = 0
For Each ch As Char In chars
If ch = needle Then count += 1
Next
Return count

End Function

Private Function countOccurance2(ByVal hayStack As String, ByVal needle As String) As Integer
Return (Len(hayStack) - Len(Replace(hayStack, needle, ""))) / Len(needle)
End Function

Private Function countOccurance3(ByVal hayStack As String, ByVal needle As String) As Integer
Dim i As Long, sHayStack As String : sHayStack = hayStack
Do Until InStr(sHayStack, needle) = 0
sHayStack = Replace(sHayStack, needle, "", 1, 1) : i += 1
Loop
Return i

End Function

I've not tested which is more effiecient, but all provides the similar results for many number tests.

Wednesday, April 22, 2009

Open XML Format SDK 2.0

Open XML documents provides strongly typed part and content classes for use

Open XML is an open ECMA 376 standard and is also approved as the ISO/IEC 29500 standard that defines a set of XML schemas for representing spreadsheets, charts, presentations, and word processing documents. Microsoft Office Word 2007, Excel 2007, and PowerPoint 2007 all use Open XML as the default file format.

The Open XML file formats are useful for developers because they use an open standard and are based on well-known technologies: ZIP and XML.

The Open XML Format SDK 2.0 is built on top of the System.IO.Packaging API and provides strongly typed part classes to manipulate Open XML documents. The SDK also uses the .NET Framework Language-Integrated Query (LINQ) technology to provide strongly typed object access to the XML content inside the parts of Open XML documents.

  • Requirements:

    Supported Operating Systems: Windows Server 2003; Windows Vista; Windows XP Service Pack 2

This download requires the following:

  • The Microsoft .NET Framework version 3.5.
  • Up to 120 MB of available disk space.

“Be aware that it’s a 90MB download (about 120MB installed). About 100MB of it is documentation. The library itself (DocumentFormat.OpenXml.dll) is 3.5MB” as specified in windowsclientdevelopment.

The Open XML Format SDK 2.0 went live on April 7, 2009, and is now up for grabs via the Microsoft Download Center. The SDK, and the underlying System.IO.Packaging API enables developers to leverage a simplified manipulation process involving OpenXML packages. And when it comes down to manipulation of OpenXML packages, version 2.0 of the SDK brings to the table support for strongly typed part and content classes.

“In version 1 of the Open XML SDK we released the Open XML Packaging API, which allows you to create, open and manipulate Open XML files at the package and part level. In the first CTP of version 2 we released the Open XML Low Level DOM and Stream Reading/Writing components, which allow you to create and manipulate objects within xml parts contained in an Open XML package. In the second CTP of version 2 we are providing schema level validation functionality,” revealed Brian Jones, Office program manager.

In addition, the April 2009 CTP of Open XML Format SDK 2.0 permits OpenXML documents to be validated. The validation functionality added to the latest version of the SDK is designed to permit developers to perform validation of Open XML docs in relation to variations of the Open XML Format. Essentially what validation support is designed to do is to help reduce the possibility of invalid or corrupt Open XML files.

“Manipulating Open XML Formats by using the Open XML Base layer makes it much easier for you to work on the Open XML files, but doing so does not guarantee the production of valid Open XML files. The new Schema Level Validation component provides a mechanism to help you discover Open XML errors within files and in your code. This component assists you in debugging and validating Open XML files based on the schemas,” Jones added.

This release includes a high-level DOM (document object model) for Open XML development, as well as several tools to streamline Open XML development:

* The OpenXmlDiff utility identifies differences in the markup in two Open XML documents.

* The Open XML Class Explorer helps you determine which strongly typed class to use for a specific task, and includes the text of the relevant section of the ECMA-376 spec for each class.

* The Open XML Document Reflector takes a target document as input, and with a few clicks it shows you the C# code needed to generate that document (or a section of it) with the Open XML SDK.

Sample code that supports the scenarios described in the series of articles titled Creating Documents by Using the Open XML Format SDK 2.0 (Community Technology Preview)

The first article is located at:
http://msdn.microsoft.com/en-us/library/dd440953.aspx

Some brief overview can be seen from the link

Thursday, April 16, 2009

Filling the DataGridView with all the files(upto deepest level) in specified directory

In case we need to fill a DataGridView in our form with all the files in the specified directory, no matter how deep many files exists, all the files are retireved from the directory and the related information is displayed in the DataGridView.

The steps to get the result as below:
1. Get the collection of FileInfo for each file in the directory/drive by using function explained in "Retrieve All Files Info in the specified Folder (Using LINQ To Object)" blog
2. Add the DataGridView component in the form name it anything say DataGridView1
3. Add the following string in the action corresponding to which data grid is needed to be filled with the file information:

       Dim arrList as New ArrayList
       getCompleteFileList1(directoryName, arrList)
       dataGridView1.DataSource= arrList

Or If only specific list of attributes for each file is needed to be displayed the the following lines can be considered:

       Dim arrList As New ArrayList
       getCompleteFileList1(directoryName, arrList)
        Dim filesInfo = From file As IO.FileInfo In arrList _
                       Select file.Name, file.DirectoryName, file.Length, file.LastWriteTime
        dataGridView1.DataSource = filesInfo.ToList


Retrieve All Files Info in the specified Folder (Using LINQ To Object)


        Public Sub getCompleteFileList1(ByVal rootDir As String, ByRef arrFileList As ArrayList) 
            If My.Computer.FileSystem.GetDirectoryInfo(rootDir).Name = "System Volume Information" Then
                Return
            End If

            For Each recursiveDir As String In My.Computer.FileSystem.GetDirectories(rootDir)
                Call getCompleteFileList1(recursiveDir, arrFileList)
            Next

            Dim files = From file In My.Computer.FileSystem.GetFiles(rootDir, FileIO.SearchOption.SearchTopLevelOnly) _
                        Order By file _
                        Select My.Computer.FileSystem.GetFileInfo(file)
            arrFileList.AddRange(files.ToList)

        End Sub

This function return a collection of System.IO.FileInfo objects that can be used to retrieve all files and their corresponding information with same list that can be used depending on the requirement.

If  only the specific attribute is desired for each file, then we can specify the needed attribute under the Select Key

Retrieve All Files in the specified Folder

Private Sub getCompleteFileList(ByVal rootDir As String, ByRef arrFileList As ArrayList)
If My.Computer.FileSystem.GetDirectoryInfo(rootDir).Name = "System Volume Information" Then
Return
End If
For Each recursiveDir As String In My.Computer.FileSystem.GetDirectories(rootDir)
Call getCompleteFileList(recursiveDir, arrFileList)
Next
For Each foundFile As String In My.Computer.FileSystem.GetFiles(rootDir,FileIO.SearchOption_
.SearchTopLevelOnly)
arrFileList.Add(foundFile)
Next
End Sub

rootDir can be root drive or some specific directory. arrFileList is the final list of files in rootDir' all subDir,Sub-SubDir,Sub-Sub-SubDir................ means all the existing files, no matter how much deeper, are added in th earrFileList that can be used for any needed purpose requiring all the list of files in some dir.

Tuesday, April 14, 2009

XML Operations: Create XML, Insert Data, Modify Data and Delete Data in XML File

    • Create XML File
    Private Sub CreateXmlFile()
            Dim xw As New XmlTextWriter("C:\mySampleXml.xml", System.Text.Encoding.UTF8)
            xw.WriteStartDocument()
            xw.WriteStartElement("nodes", "")

            xw.WriteStartElement("node", "")
            xw.WriteStartAttribute("id", "")
            xw.WriteString("1")
            xw.WriteEndAttribute()
            xw.WriteStartElement("child")
            xw.WriteString("sample10")
            xw.WriteEndElement()
            xw.WriteStartElement("child")
            xw.WriteString("sample11")
            xw.WriteEndElement()
            xw.WriteEndElement()


            xw.WriteStartElement("node", "")
            xw.WriteStartAttribute("id", "")
            xw.WriteString("2")
            xw.WriteEndAttribute()
            xw.WriteStartElement("child")
            xw.WriteString("sample20")
            xw.WriteEndElement()
            xw.WriteStartElement("child")
            xw.WriteString("sample21")
            xw.WriteEndElement()
            xw.WriteEndElement()

            xw.WriteStartElement("node", "")
            xw.WriteStartAttribute("id", "")
            xw.WriteString("3")
            xw.WriteEndAttribute()
            xw.WriteStartElement("child")
            xw.WriteString("sample30")
            xw.WriteEndElement()
            xw.WriteStartElement("child")
            xw.WriteString("sample31")
            xw.WriteEndElement()
            xw.WriteEndElement()

            xw.WriteEndElement()
            xw.Flush()
            xw.Close()
            Process.Start("C:\mySampleXml.xml")
        End Sub


    • Insert Data in XML File
    Private Sub InsertDataToXmlFile()
            Dim xDoc As New XmlDocument
            xDoc.Load("C:\mySampleXml.xml")
            Dim sourceRootNode As XmlNode = xDoc.SelectSingleNode("/nodes/node[@id=2]") 'Slects the root 'nodes'
            Dim newChildNode As XmlNode = xDoc.CreateNode(XmlNodeType.Element, "child", "")
            newChildNode.InnerText = "New Sample 22"

            'Child with attribute
            Dim newChildNode1 As XmlNode = xDoc.CreateNode(XmlNodeType.Element, "child", "")
            Dim atr As XmlAttribute = xDoc.CreateAttribute("childID")
            atr.Value = "ch1"
            newChildNode1.InnerText = "New Sample 23"
            newChildNode1.Attributes.Append(atr)
            sourceRootNode.AppendChild(newChildNode)
            sourceRootNode.AppendChild(newChildNode1)
            xDoc.Save("C:\mySampleXml.xml")
            Process.Start("C:\mySampleXml.xml")

        End Sub


    • Modify Data in XML File
        Private Sub ModifyDataInXmlFile()
            Dim xDoc As New XmlDocument
            xDoc.Load("C:\mySampleXml.xml")
            Dim desiredNode As XmlNode = xDoc.SelectSingleNode("/nodes/node[@id=2]")
            Dim childNodes As XmlNodeList = desiredNode.SelectNodes("./child") ''.' specifies the current node and '/child' specifies child nodes
            For Each curNode As XmlNode In childNodes
                If curNode.HasChildNodes = True Then
                    If curNode.Attributes.Count > 0 Then
                        If curNode.Attributes("childID").Value = "ch1" Then
                            curNode.InnerText = "Updated Sample 23"
                        End If
                    End If
                End If
            Next
            xDoc.Save("C:\mySampleXml.xml")
            Process.Start("C:\mySampleXml.xml")

        End Sub


    • Delete Data in XML File
        Private Sub RemoveDataFromXmlFile()
            Dim xDoc As New XmlDocument
            xDoc.Load("C:\mySampleXml.xml")
            Dim desiredNode As XmlNode = xDoc.SelectSingleNode("/nodes/node[@id=2]")
            Dim childNodes As XmlNodeList = desiredNode.SelectNodes("./child") ''.' specifies the current node and '/child' specifies child nodes
            For Each curNode As XmlNode In childNodes
                If curNode.HasChildNodes = True Then
                    If curNode.Attributes.Count > 0 Then
                        If curNode.Attributes("childID").Value = "ch1" Then
                            curNode.ParentNode.RemoveChild(curNode)
                        End If
                    End If
                End If
            Next
            Dim anotherDesiredNode As XmlNode = xDoc.SelectSingleNode("/nodes/node[@id=2]")
            anotherDesiredNode.ParentNode.RemoveChild(anotherDesiredNode)
            xDoc.Save("C:\mySampleXml.xml")
            Process.Start("C:\mySampleXml.xml")

        End Sub

    Please give any suggestions for better coding. Also add code for other possible cases that can be  possible for other various situations.

Monday, April 13, 2009

Convert Bitmap picture to Byte() and back to picture

[Not tested Code]

Let pic be the picture as
Dim pic as Bitmap

and Let bytes() be the required converted picture into byte.
Dim bytes() As Byte

Then the code to convert the picture to bytes as below:

If picture IsNot Nothing Then
Dim BitmapConverter As System.ComponentModel.TypeConverter = System.ComponentModel.TypeDescriptor.GetConverter(picture.[GetType]())
bytes= DirectCast(BitmapConverter.ConvertTo(picture, GetType(Byte())), Byte())
Else
bytes= Nothing
End If

Also to get picture back to bitmap format from the byte object the code will be like as below:

If bytes IsNot Nothing Then
pic= New Bitmap(New MemoryStream(value))
Else
pic = Nothing
End If
Uses:
The picture can't save directly in XML file and is required to be converted to like bytes only then can be saved to XML file. Similarly later it can be retrieved back to picute in bitmap format by using the above procedure.