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.

Thursday, March 12, 2009

SendKys

In an application sometimes we may face to send a key to the application or environment after some event occures. VB.Net provides a way to send keys to window forms by using

System.Windows.Forms.SendKeys.Send("your key comes here")

there are various codes for various keys. The list of syntax of all the keys is given below:


Key Code
BACKSPACE {BACKSPACE}, {BS}, or {BKSP}
BREAK {BREAK}
CAPS LOCK {CAPSLOCK}
DEL or DELETE {DELETE} or {DEL}
DOWN ARROW {DOWN}
END {END}
ENTER {ENTER}or ~
ESC {ESC}
HELP {HELP}
HOME {HOME}
INS or INSERT {INSERT} or {INS}
LEFT ARROW {LEFT}
NUM LOCK {NUMLOCK}
PAGE DOWN {PGDN}
PAGE UP {PGUP}
PRINT SCREEN {PRTSC}
RIGHT ARROW {RIGHT}
SCROLL LOCK {SCROLLLOCK}
TAB {TAB}
UP ARROW {UP}
F1 {F1}
F2 {F2}
F3 {F3}
F4 {F4}
F5 {F5}
F6 {F6}
F7 {F7}
F8 {F8}
F9 {F9}
F10 {F10}
F11 {F11}
F12 {F12}
F13 {F13}
F14 {F14}
F15 {F15}
F16 {F16}

To specify keys combined with any combination of the SHIFT, CTRL, and ALT keys, precede the key code with one or more of the following codes:

Key Code
SHIFT +
CTRL ^
ALT %

Tuesday, February 17, 2009

Getting String object as Stream IO.Stream object

let myString be the String object that is needed to be converted into

Dim msObj As MemoryStream = New MemoryStream(System.Text.Encoding.ASCII.GetBytes(myString))

MyObjThatNeedsStreamObj.Load(CType(msObj , Stream))

Tuesday, January 27, 2009

Opening a Form by Type or Name

Opening a Form by Type or Name
You have a class that is able to trap an event, say the doubleclick of a textbox, and has to open a form when it occurs. If it's always the same form, that's easy, but what if you want it to be determined during runtime? This is a quite common story: doubleclick on article opens the detail form of that article, doubleclick on supllier opens that particular form. If you use a form variable, how do you say to the class which form should be opened? This will not work

Code:
Dim FormToOpen as Form 'you don't want to open it right away, you want to know when the time comes what form to open
FormToOpen = Form1

You could say FormToOpen = new Form1, but then 1. an instance would be immediately created, even if it never will be used: memory leak. 2. you can never close the form, you'll always have to use the same instance created when setting the form. Consequently, you can never open more than 1 instance using this way.

The solution: use the type. If you know the type, the Activator class will enable you to open (and return) an instance of that form at any time and as much times as you like. (The Activotor class exposes the function CreateInstance which returns an instance of the specified object)
The following code creates an instance of the type form1 and shows it.

Code:
CType(Activator.CreateInstance(GetType(Form1)), Form).Show()
. . . . . . . .. . . . . . . .. . . . . . . .


WMI Scripting

WMI (Windows Management Instrumentation) - Home

Introduction to WMI

Who will benefit from learning about WMI (Windows Management Instrumentation) commands? Here are the people who I had in mind as I wrote this section. Network managers who want to collect specific data from one (or more) server. IT professionals who what to know precisely what's happening in their Microsoft operating system. Those techies who love remote control without hassle. . . . . . . . . . . . . . . . . . . . . . . . . . .

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

WMI Scripting can be used to retrieve many useful information related to running machine in a very easy way.


Tutorial Learning Points

1) Sometimes simple phrases have a beauty all of their own. Yet, often simple phrases hide all the hard work, what you do not see is all the experiments that did not work and all the extra code that you don't need. Perhaps the best way to re-enforce this theme is to point what NOT to put in the WQL clause.

2) ("Select * from Win32_LogicalDisk where objItem.FreeSpace > 10000"). No need for objItem, just the pure property name. As with all scripting learn to apply the punctuation correctly.

Example 2 - Select only File Systems that are NTFS.

The key WQL clause is where FileSystem = 'NTFS'")

("Select * from Win32_LogicalDisk where FileSystem = 'NTFS'")

Tutorial Learning Points

1) In truth, text filters are harder than numeric filters. The greatest problems are with the speech marks.

("Select * from Win32_LogicalDisk where FileSystem = 'NTFS'"). Again looks easy, but here are some mistakes. Where FileSystem = ' NTFS '". It is outrageous that blank spaces should cause problems - but they do.

2) Here is another error, note the wrong type of speech marks. where FileSystem = "NTFS"". The spacing is correct but NTFS should be bracketed by a pair of single speech marks, the double quotes draws an error message.

. . . . . .. . . . . .. . . . . .. . . . . .. . . . . .. . . . . .. . . . . .. . . . . .


Monday, January 19, 2009

Saving all the images from ImageList to Disk

Public Sub saveImageListToDisk()
Dim img As Image
Dim iCnt As Integer
For Each img In ImagList1.Images
iCnt = iCnt + 1
img.Save("C:\MyImages\" & iCnt & ".png")
Next
End Sub