Dailycode.info

Short solution for short problems

Opening a window with ShowDialog in a window that is opened with ShowDialog.

I had a simple form that opened a search form. From this search form it was possible to open a sub search form. What happened was when you opened the sub search form, and found a value, selected it and returned to the (parent)search form, it ended up in the close handler of this form and closed it. After some searching around, Ii found out that the Dialog Result of the sub search form was effecting the dialog result of the search form. The solution I found was to explicitly set the dialog result of the search form to none after the sub search form returned its result.

For example: Lets say my search form is called from a main form using the ShowDialog. In this search form we call a second search form of type SearchSubForm.

Dim frmSubSearchForm As SearchSubForm = new SearchSubForm()

If frmSubSearchForm.ShowDialog = DialogResult.OK Then

'Do something 

End If

 

This code could generate the problem. So to solve this, you can set the dialog result of the search form to none like this:

Dim frmSubSearchForm As SearchSubForm = new SearchSubForm()

If frmSubSearchForm.ShowDialog = DialogResult.OK Then

       Me.DialogResult = DialogResult.None

'Do something 

End If

This solves the problem. I did not had the time to look into this problem in dept. It could be that it has something to do with the main page state or some other problem, but unfortunately I will not have time to investigate it.


How to write a simple Splash Screen

Just a quick post to guide you to write a good and very simple splash screen.
First create a simple screen with useful information and some visual indication the system is loading. Then come a simple trick. Op the Splash screen in a separate thread and close the thread when the loading is done. It’s that Simple:
'Show Splash Screen 
Dim myWorkerThread As Thread
myWorkerThread = New Thread(New ThreadStart(AddressOf StartUp))
myWorkerThread.Name = "Splash screen startup"
myWorkerThread.Start()
Then there is the simple function that will open the splash screen:
    Private Shared Sub StartUp()
        Dim frmStartUp As frmGalvaClientSplash
        frmStartUp = New frmGalvaClientSplash()
        frmStartUp.ShowDialog()
    End Sub
 
Then Simply close the plash with the following command:
myWorkerThread.Abort()
 

Setting the property of a control from a seperate thread using an extension method.

In this post you can find a solution that implements an extension method to change the properties of a Windows Forms Control. It’s a large improvement for my previous post: http://www.dailycode.info/Blog/post/2011/04/18/Multi-Threading-and-accessing-controls-from-seperate-threads-in-WPF.aspx

Now this extension will provide the functionality on any control of your form. This is the function that does the magic:

/// <summary>  

/// Executes the Action asynchronously on the UI thread, does not block execution on the calling thread.  

/// </summary>  

/// <param name="control"></param>  

/// <param name="code"></param>  

public static void UIThread(this Control @this, Action code)

{

    if (@this.InvokeRequired)

    {

        @this.BeginInvoke(code);

    }

    else

    {

        code.Invoke();

    }

}

 

Can it be more simpler? This can save a lot of developer time and is one of my latest high impact findings thanks to: http://stackoverflow.com/questions/661561/how-to-update-gui-from-another-thread-in-c

 

Here are some examples on  how to implement this:

Setting some text in a textbox from a separate thread:

this.UIThread(() => lblSubAction.Text = @"Reading Records...");

 

Changing the value of a progressbar:

 

this.UIThread(() => pgbSub.Value = pgbSub.Value + pgbSub.Step);

 

Setting a property of a third party control:

this.UIThread(() => numRecordsFound.EditValue = countForLambda);

 


Degree symbol gets converted into a strange symbol.

I was developing an application to read the html from a given URL and get some text out of it. The application was for temperature (using degree Celsius) meters that post their findings on a simple html page. Since the structure is configurable, we had to look for a dynamic solution. So we get the html and look for a string that is between 2 given tags.

All went well until I had some troubles with the WebClient.DownloadString method. It works the first time, but hangs the second time. So I decided to use a streamreader on the webresponse.

This works good, you can close the connections and read as much as you like. But then I figured out that the degree sign: ° was converted into some weird symbol.

The reason was that if you do not use a specific encoding for the stream reader, it uses utf-8 encoding, which replaces the degree sign. The solution is simple, but it took me a while to find out which encoding did the trick. At the end it was the Default encoding that worked for me!

He is the code example:

    Private Function GetHTML() As String

        Dim urlCheck As Uri = New Uri(txtUrl.Text)

        Dim request As HttpWebRequest = CType(WebRequest.Create(urlCheck), HttpWebRequest)

        'Timeout is set to 3 seconds.

        request.Timeout = 3000

        Dim sb As StringBuilder = New StringBuilder

        Dim response As HttpWebResponse

        Try

            'If the url doesn't exist the exeption will be thrown after 2 seconds.

            'This will prevent your system from hanging.

            response = CType(request.GetResponse(), HttpWebResponse)

            If response.StatusCode = HttpStatusCode.Found Or response.StatusCode = HttpStatusCode.OK Then

                 Dim receiveStream As Stream = response.GetResponseStream()

                Dim encode As Encoding = System.Text.Encoding.Default

                ' Pipes the response stream to a higher level stream reader with the required encoding format.

                Dim readStream As New StreamReader(receiveStream, encode)

                Dim read(256) As [Char]

                ' Reads 256 characters at a time.   

                Dim count As Integer = readStream.Read(read, 0, 256)

                While count > 0

                    ' Dumps the 256 characters to a string and displays the string to the console.

                    Dim str As New [String](read, 0, count)

                    sb.Append(str)

                    count = readStream.Read(read, 0, 256)

                End While

                ' Releases the resources of the Stream.

                readStream.Close()

                ' Releases the resources of the response.

                response.Close()

            End If

            'request.EndGetResponse(response)

            Return sb.ToString

        Catch ex As Exception

            'If the site is not found, then an exception will be trown

            Return "No response"

        End Try

    End Function

 


SAP ALV: Field symbol has not yet been assigned.

I'm also involved in a little SAP development, yes you read it well, not only ASP but also SAP ;-)

I got a course to help out with the internal development and debugging. So my first real mission was to create a simple ALV. In the course it took me 1 hour and it was fixed. But now I was facing this great error and couldn't find what was wrong. At the end it appeared to be a copy paste mistake. I forgot to change the structure name of the fieldcategory structure. This was also because the ALV template had some confusing text above it, it said to change the name if the include. But imho it is better to call it structure because that what it is!

 *!TODO! - change this to your include - make sure to use capital letters!

changed this to:

 *!TODO! - change this to your structure - make sure to use capital letters!

That offcourse dind't solved the problem but will prevent this from occurring once more. Now I just had to set the correct structure name:

 *!TODO! - change this to your structure - make sure to use capital letters!
  PERFORM fieldcat_build_single
          USING 'ZMRDALVGOODSSTR' p_buffer.
*          USING 'ZMRDTESTSTRUCT2'  p_buffer.
  PERFORM change_fieldcatalog.

  PERFORM get_data.

 Below an outprint of the error:


Clear the controls from a .Net panel of container.

If you are working a lot with usercontrols and dynamlically adding them to the GUI, you might end up with the error saying that there are no more window handlers.

One of the reasons could be that you clear controls from your screen but they do not get discposed. Most of the time its just to many usercontrols, so add some paging or something.

But always try the following solution first. In stead of using the clear call to the panel, dispose each object in the panel. You can use this code:

    Private Shared Sub DisposeObjectsInPanel(ByVal pnl As Panel)

        For iCounter As Integer = 1 To pnl.Controls.Count Step 1

            If Not pnl.Controls(0) Is Nothing Then

                pnl.Controls(0).Dispose()

            End If

        Next

    End Sub


Read html from an url using VB.Net

 

If you are planning on reading html from a given url, you can have the problem that the system hangs when the url is not found. Especially when the url is a local url on the network. It tends to hang. To resolve this, you can use the HttpWebRequest. I created a simple implementation that will check if the url exists and reads the html to a text field:

        Dim urlCheck As Uri = New Uri(txtUrl.Text)

        Dim request As HttpWebRequest = CType(WebRequest.Create(urlCheck), HttpWebRequest)

        'Timeout is set to 2 seconds.

        request.Timeout = 2000

        Dim response As HttpWebResponse

        Try

            'If the url doesn't exist the exeption will be thrown after 2 seconds.

            'This will prevent your system from hanging.

            response = CType(request.GetResponse(), HttpWebResponse)

            If response.StatusCode = HttpStatusCode.Found Or response.StatusCode = HttpStatusCode.OK Then

                Try

                    If Not String.IsNullOrEmpty(txtUrl.Text) Then

                        sUrl = txtUrl.Text

                        Dim webClient As System.Net.WebClient = New System.Net.WebClient()

                        Dim result As String = webClient.DownloadString(sUrl)

                        result = result.Replace(vbCrLf, "")

                        webClient.Dispose()

                        txtResult.text = result

                    Else

                        MessageBox.Show("Url is required!")

                        Return ""

                    End If

                Catch ex As Exception

                    MessageBox.Show("Error: " & ex.Message)

                End Try

            End If

        Catch ex As Exception

            'If the site is not found, then an exception will be trown

        End Try

After some testing and debugging work I came up with an even more stable solution, since the DownloadString method can give trouble. I decided to use the StreamReader solution directly on the response. It also saves an extra WebRequest. I implemented here in an extensions method for a string (c# this time):

public static class Extensions

{

    public static string GetHTMLForURL(this String s)

    {

        HttpWebRequest webRequest = WebRequest.Create(s) as HttpWebRequest;

        webRequest.Timeout = 2000; 

        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

        if (response.StatusCode == HttpStatusCode.Found || response.StatusCode == HttpStatusCode.OK)

        {

            using (StreamReader sr = new StreamReader(response.GetResponseStream()))

            {

                //This is an arbitrary size for this example.

                char[] c = null;

                StringBuilder sb = new StringBuilder();

                while (sr.Peek() >= 0)

                {

                    c = new char[5];

                    sr.Read(c, 0, c.Length);

                    //The output will look odd, because

                    //only five characters are read at a time.

                    sb.Append(c);

                }

                return sb.ToString();

            }

        }

        else

        {

            return s;

        }

    }

}


Then implement the method like this:

txtResult.Text = txtUrl.Text.GetHTMLForURL();

More info on this you can find here: http://nevmehta.blogspot.com/2006/11/controlsclear-doesnt-dispose-in-win.html

A simple extension example can be found here:  http://dotnetbyexample.blogspot.com/2007/11/string-extension-methods.html