Archive for August, 2008

Using LINQ to write to XML File

Hello all so sorry I have been offline for so long.

What have I been up to? Well KJM Solutions site is up and running again (http://www.kjmsolutions.com ). It is a site that will be devoted mostly to development of my own skills but also will offer custom development of .NET software if you should be interested :). Right now just the default page for the provider is there but finding a host and getting it going is a real challenge. I won’t be hosting my own servers anymore and i will miss that but had to make some choices. m6.net is the provider I chose if anyone is interested.

In addition, I am in the process of reforming Jericho, the Christian parody rock band I had in Sheboygan. So that is taking a lot of time. Also playing with some other churches, but really just trying to get in the groove of playing keyboards again after a long time of not playing.

Anyway, today’s topic is writing to a XML file using LINQ. Make it a great day!

Lets say you have a XML file called Settings.xml that looks like this

<?xml version="1.0" encoding="utf-8"?>
<Network>
<Host url="123.14.54.01">
   <Location>New York City</Location>
   <Administrator>John Smith</Administrator>
   <System>Windows 2003 Advance Server</System>
</Host>
<Host url="223.41.45.10">
   <Location>Florida</Location>
   <Administrator>Jonathan Plush</Administrator>
   <System>Windows 2005 Server</System>
</Host>
</Network>

The following code will open the XML file and add a Host node with children to the end of the  Host node list.

Dim xml As XDocument = XDocument.Load("Settings.xml")

Dim Network As XElement = xml.Root
Dim newHost As New XElement("Host", New XAttribute("url", txtURL.Text), _
                          New XElement("Location", txtLocation.Text), _
                          New XElement("Administrator", txtAdministrator.Text), _
                          New XElement("System", txtSystem.Text))
Network.Add(newHost)
xml.Save("Settings.xml")

If you want to load it to the very first node just after Network node then replace this line of code:

Network.Add(newHost)

With this line of code:

Network.AddFirst(newHost)

 

2 Comments

The Church Betrays The Great Commission

Therefore go and make disciples of all nations, baptizing them in the name of the Father and of the Son and of the Holy Spirit, and teaching them to obey everything I have commanded you. And surely I am with you always, to the very end of the age.(Matthew 28:18-20 NIV) 

It seems a simple enough directive. Jesus, prior to ascending into heaven, gave this simple yet straightforward command to the apostles.

Yet, it seems the evangelical church leadership (disclosure: of which I am a member of said group) focus on this has been lost.

At no point, did Jesus command us to build expensive churches, political parties, dominate governments, or legislate morality. At no point did he seem to want us to energize the faithful with political issues related to the economy or get them all enrolled on a particular candidates or party’s mailing list so they could be asked for donations. Does God really want us to care about who is in the white house? Do you not think he is big enough that his will be accomplished regardless of who is running the government?

In my opinion, God never wanted his Word to be used as a tool to justify any social position either. Take capital punishment.  Many in the church have been taught that this is something God commands. Not so! The apostle Paul encouraged us to submit to the authorities because it was common sense to do so since they "do not bear the sword for nothing." He didn’t say we should embrace the death penalty. Granted it was used in the Old Testament but first if we are to live by that law then we must place ourselves under the whole of that law. Second, God was directly involved in their justice system when that law was written. So unless you think that God somehow speaks to the juries and judges involved, you had best rethink your position on this if you are in fact one of those who think this way.

What he did command, was to reach the world with his Gospel – the freedom from sin that makes a person’s heart captive to it. They are to preach Christ and him crucified – no other message is relevant to this mission. By allowing other missions to be our focus, we lose our credibility with the world that we are in fact a true force of change that can revolutionize how a person lives now and in the hereafter. We do it on an individual basis, one heart at a time. We don’t do it via letter campaigns, voter registration drives or political party platforms.

When Jesus returns and asks for an accounting of our lives as Christians, will God look at our activities to further our political party’s goals, moral causes, and such as evidence of the furtherance of his kingdom? I don’t believe he will. Instead he would have wanted our time, treasure and talents to go toward what counts – the saving and deliverance of souls from sin and a certain spiritual death.

 

3 Comments

Copy a CSV file to another CSV File with vb.net

Good Morning! Hope all is well in your part of the world.

I myself was informed yesterday that we would be moving to another building at GE Healthcare. Of course there will not be a cafeteria or coffee shop (we have been so spoiled) so we are all kind of bummed about that. But other than that I am fine.

So what I needed to do was copy a CSV file to an empty CSV file. Not overly complicated but it was something that needed to be done. Hope it don’t bore you. Make it a great day!

Public Class Form1
    Private WithEvents tmr As New Timer
    Private sr As System.IO.StreamReader
    Private sw As System.IO.StreamWriter
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        tmr.Interval = 1000
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button1.Enabled = False
        TextBox1.Enabled = False
        TextBox2.Enabled = False
        Try           
            sr = New System.IO.StreamReader(TextBox1.Text)
            sw = New System.IO.StreamWriter(TextBox2.Text, False)
            tmr.Start()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Button1.Enabled = True
            TextBox1.Enabled = True
            TextBox2.Enabled = True
        End Try
    End Sub
    Private Sub tmr_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmr.Tick
        If (Not sr Is Nothing) AndAlso (Not sw Is Nothing) Then
            Try
                Dim line As String = sr.ReadLine
                If Not line Is Nothing Then
                    sw.WriteLine(line)
                    Debug.Print(line)
                Else
                    tmr.Stop()
                    sr.Close()
                    sw.Close()
                    Button1.Enabled = True
                    TextBox1.Enabled = True
                    TextBox2.Enabled = True
                End If
            Catch ex As Exception
                tmr.Stop()
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                If Not sr Is Nothing Then
                    sr.Close()
                End If
                If Not sw Is Nothing Then
                    sw.Close()
                End If
                Button1.Enabled = True
                TextBox1.Enabled = True
                TextBox2.Enabled = True
            End Try
        End If
    End Sub
End Class

 

 

Windows Live Tags: vb.net,.NET,csv,copy,streamwriter,timer

 

6 Comments

Read Serial Port with vb.net

Good Morning all! Sorry its been a few days.

For several reasons I needed to read a serial port yesterday. Here is the code below. Make it a great day!


Join me on Facebook

Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        ‘This event will Receive the data from the selected COM port..
        If e.EventType = SerialData.Chars Then
            thRec = New Thread(AddressOf ReceiveData)
            thRec.IsBackground = True
            thRec.Priority = ThreadPriority.Highest
            thRec.Start()
            Thread.Sleep(2)
        End If
    End Sub
Private Sub ReceiveData()
        ‘Sub to Receive Data from the Serial Port, Will Run in a Thread
        Dim lstItem As ListViewItem
        Dim bRead, nRead As Integer
        Dim returnStr As String = ""
        Dim ascStr As String = ""
        bRead = SerialPort1.BytesToRead ‘Number of Bytes to read
        Dim cData(bRead – 1) As Byte
        SerialPort1.Encoding = Encoding.GetEncoding(65001)
        nRead = SerialPort1.Read(cData, 0, bRead)  ‘Reading the Data
        For Each b As Byte In cData
            ascStr += Chr(b)        ‘Ascii String
            returnStr += Hex(b).PadLeft(2, "0")     ‘Hex String (Modified Padding, to intake compulsory 2 chars, mainly in case of 0)
        Next
    Debug.WriteLine (returnStr)
End Sub


Join me on Facebook

Consulting Requests

Feedback

Blog Front Page

Windows Live Tags: vb.net,serial port,.NET

 
Technorati Tags: ,,

 

Leave a comment

Eliminate Duplicate Rows From DataSet in vb.net

Hello all.

My oldest daughter is suppose to go to court Friday. It might possibly be delayed, but I got to tell you nothing pains a parent more than watching one’s child suffer needlessly. We struggle, we beg, we plead but to no avail. Is it a reflection on myself as a parent? This is the question I struggle with most. I know I could have done some things better. I know there were some things I have done that were right. But I can’t save her anymore and that part just drives me crazy.

Anyway, wrote this little routine to remove duplicate rows from a dataset that has no primary key. How did I end up with a dataset without a primary key? Well that I can’t answer because I didn’t have any control over it.

Make it a great day! And I will try, really I will try, to do that.


Join me on Facebook

Sub EliminateDuplicates(ByVal dt As DataTable)
        Dim ssort As String = ""
        Dim col As DataColumn
        Dim scol As DataColumn
        For Each scol In dt.Columns
            If ssort <> "" Then ssort &= ","
            ssort &= scol.ColumnName
        Next

        dt.DefaultView.Sort = ssort
        Dim i As Integer, bEquals As Boolean, c As Integer, ccount As Integer
        ccount = dt.Columns.Count
        For i = dt.Rows.Count – 1 To 1 Step -1
            bEquals = True
            For c = 0 To ccount – 1
                If dt.DefaultView(i)(c).ToString() <> dt.DefaultView(i – 1)(c).ToString() Then
                    bEquals = False
                    Exit For
                End If
            Next c

            If bEquals Then
                dt.DefaultView(i).Delete()
            End If
        Next

    End Sub

Technorati Tags: ,,,,,,,,,,,

Windows Live Tags: vb.net,.NET Framework,csharp,rows,Eliminate,Duplicate,DataSet,DataTable,DataColumn,DefaultView,Sort,Delete

 

4 Comments

Log Off Inactive Windows User with vb.net

Good Morning All! The family returned from Minnesota safe and sound and happy to see their beds. I of course busied myself with cleaning the house prior to the wife’s return. :).

Okay yesterday I was looking at how to log off a user after a certain period of inactivity, which includes a warning for the user that this is going to occur. I suppose my solution is not elegant but it worked I guess. This is a 2.0 Framework or above app. Make it a great day!


Join me on Facebook

Public Class Form1
    ‘
    ‘setup the class to reboot the computer
    Private Declare Function ExitWindowsEx Lib "user32.dll" ( _
       ByVal uFlags As Long, _
       ByVal dwReserved As Long) As Long

    Private Const EWX_FORCE = 4         ‘const for a forced logoff

    Dim intTimerCount1 As Integer = 0   ‘var for timer1 and setting it to 0
    Dim intTimerCount2 As Integer = 0   ‘var for timer2 and setting it to 0
    Dim oktoreboot As String

    ‘set var for first mouse cords
    Dim MousePosX1 As Integer
    Dim MousePosY1 As Integer
    Dim Mousepos1 As Integer = 0

    ‘set var for second mouse cords
    Dim MousePosX2 As Integer
    Dim MousePosY2 As Integer
    Dim Mousepos2 As Integer = 0

    ‘
    ‘Procedures and Functions
    ‘

    ‘warning sound procedure
    Private Sub WarnWave()
        Try
            My.Computer.Audio.Play("C:\WINDOWS\Media\Windows XP Battery Critical.wav")
        Catch ex As IO.FileNotFoundException

        End Try
    End Sub

    ‘logoff procedure
    Private Sub Command1_Click()

        ‘command to force close apps and logoff user
        ExitWindowsEx(EWX_FORCE, 4)

    End Sub

    ‘
    ‘End Procedures

    Private Sub Form14_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Timer1.Enabled = True           ‘this will start the first timer once the program is fist launched

    End Sub

    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick

        intTimerCount2 = intTimerCount2 + 1 ‘setup count for timer2
        Label2.Visible = True               ‘turn on label2 to show the countdown timer
        Label2.Text = intTimerCount2

        ‘
        ‘Set the time in seconds for the countdown timer before computer is loffed off
        If intTimerCount2 = 60 Then         ‘sets a 60 second countdown timer before the computer reboots
            ‘

            Timer2.Enabled = False          ‘shuts off timer2 since the computer will now log off
            Call Command1_Click()           ‘calls the logoff command to log user off

        End If

        Select Case Label2.Text             ‘sets up a beep sound every 5 seconds until the computer is logged off or the user presses cancel
            Case "5"
                Call WarnWave()
            Case "10"
                Call WarnWave()
            Case "15"
                Call WarnWave()
            Case "20"
                Call WarnWave()
            Case "25"
                Call WarnWave()
            Case "30"
                Call WarnWave()
            Case "35"
                Call WarnWave()
            Case "40"
                Call WarnWave()
            Case "45"
                Call WarnWave()
            Case "50"
                Call WarnWave()
            Case "55"
                Call WarnWave()

        End Select

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Timer2.Enabled = False              ‘shuts timer2 off since the user canceled the logoff
        Timer1.Enabled = True               ‘restarts timer1
        intTimerCount2 = 0                  ‘reset the countdown timer since user has pressed cancel
        Label2.Text = 0                     ‘set counter label back to 0
        Me.WindowState = FormWindowState.Minimized  ‘minimize the program
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        ‘get first mouse cords
        MousePosX1 = (Control.MousePosition.X – Me.Left)
        MousePosY1 = (Control.MousePosition.Y – Me.Top)
        Mousepos1 = (MousePosX1 + MousePosY1)

        ‘
        ‘Set You inactivty time here in milaseconds
        ‘currently set to 20 min or 1200000 milli seconds
        ‘This means the workstation could log off in 20 min with no mouse activity or
        ‘it might be up to 40 min depending on when the last check was done.

        System.Threading.Thread.Sleep(1200000)

        ‘

    End Sub

    Private Sub Timer3_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer3.Tick

        ‘get second mouse cords
        MousePosX2 = (Control.MousePosition.X – Me.Left)
        MousePosY2 = (Control.MousePosition.Y – Me.Top)
        Mousepos2 = (MousePosX2 + MousePosY2)

        ‘compare the two cords to see if the mouse has moved
        If Mousepos1 = Mousepos2 Then   ‘if = then mouse has not moved durring sleep time
            intTimerCount2 = 0

            Timer2.Enabled = True                       ‘start timer2 (shutdown timer)
            Timer1.Enabled = False                      ‘stops timer1 since timer 2 has been started
            Me.WindowState = FormWindowState.Normal     ‘brings program form to the desktop
            Timer3.Enabled = False
        End If

        Timer1.Enabled = True
        Timer3.Enabled = False

    End Sub
End Class

 

2 Comments

Brett Favre: How to destroy a legacy in 30 Days

Yes I know off my usual topic. I have avoided mentioning this for some time now. Living and having been raised mostly in Wisconsin it is hard not to become a fan of the Green Bay Packers. My earliest memories of watching the Packers play was in 1976. In 1977 a new quarterback had arrived named David Whitehurst and we all thought happy days were here again and the losing was behind us after the 1978 season. Yet it was not to be. 1983 offered another mirage of hope that was quickly dashed followed by the Majik Man campaigns in 1989. Yet the losing continued. This once proud franchise couldn’t seem to do anything right.

In 1991, Ron Wolf arrived and that all changed. Green Bay fans, so hungry for a winner after 2 decades of losing, embraced him enthusiastically. He brought in a quarterback named Brett Favre. I admit I lived and died with this guy on each throw.

To be honest, I never bought the "awe shucks good old boy" routine. One obvious example was in the Super Bowl against the Patriots. It was clear he was coached to take off his helmet and run with it so the cameras could see his face. It was a way to pick up endorsements. To be honest, though I found it annoying and yeah the guy always came across as an egomaniac I set that aside because….hey we had just won a super bowl! So those concerns were set aside. The following year the league imposed the rule that says you cannot take off your helmet on the playing surface.

The retirement talk started 4 years ago. What you have to understand is this was a button Brett knew he could push with the Green Bay fans. Fans remember pre 1992 losing ways and in no way want to go back to that. So this drama only intensified the relationship between Favre and the fans. Truth is, he played us like a fiddle and while this summer has gone by, the Packers as an organization were burning.

Favre seemed to want Ted Thompson to feel the need to kiss his ass and jump at the chance to be told what to do by him. Ted Thompson did an outstanding job rebuilding this team. But because that never happened, we are in the position we are in today.

Talk to fans these days, talks of a 32 million dollar personal services contract after retirement (a shameless bribe attempt by the Packers – the single mistake they made in all of this. Do they not think we have brains??) , talk of Brett in a Vikings uniform because Brett wants to play against the Packers, the tearful press conference, and then change of mind(I think Brett did it soley to spite Thompson – you won’t kiss my ass I am gonna make your life difficult) and when it is all said and done we look at Brett differently today. Sure, if we go and win the Super Bowl with him under center we will all cheer. But no one will cry when he leaves next time. We’ve have all had our fill of being played and used as a pawn by Brett. And that my friends, is so far away from where we were 30 days ago even it is just unbelievable. He destroyed his legacy over the course of the last few months. And in the last 30 days he really showed his true colors.

Anyway, make it a great day! And Go Pack!

 

2 Comments

Kill Remote Computer Process in vb.net

Good Morning All! Everyone was gone this weekend which meant I had a very quiet weekend. Did some WPF study but not whole lot of other things.

Anyway what we want to do is kill a process on a remote PC using WMI. It actually was pretty challenging. Don’t forget you will need to allow permissions for this! But anyway, make it a great day!

Private Sub cmdKill_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdKill.Click
        strComputer = txtPC.Text
        strDomain = <Domain>
        strProcessKill = "’" & listProcess.SelectedItem & ".exe’"
        objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
        colProcess = objWMIService.ExecQuery("Select * from Win32_Process Where Name = " & strProcessKill)
        For Each objProcess In colProcess
            objProcess.Terminate()
        Next
    End Sub

 

Technorati Tags: ,,,,,,,,,,,,,,,,,,,,,,

Windows Live Tags: vb.net,.NET Framework,csharp,cimv2,root,impersonate,impersonationLevel,winmgmts,WMI,process,Kill,Remote,Computer,Object,Text,Domain,SelectedItem,GetObject,ExecQuery,Select,Where,Name,Terminate

5 Comments