Posts Tagged ‘.net’

Learning About .NET Web Access Classes

Thursday, May 15th, 2008

I mentioned about wanting to start a business in my previous post. Well it looks like I might have my chance. While it isn’t exactly what I was thinking of in my previous post, I foresee many opportunities to flex my programming muscle in this endeavor. Plus, I will be starting up with a good friend, so there is a good chance our motivation will actually produce some results.

A piece of software I am starting to research/design/create will be an internal application we will use to automatically extract some government provided public data. The current issue is time. With the amount of data and the requirement of using their web interface, it is not worth the time needed to do it by hand. The only other option would be to buy the data from the government, but that’s just an unnecessary cost seeing as there is a free option available.

So I will be writing a program in C# to automatically access a few websites and download the needed data in chunks. I have never delt with .NET’s web access objects, so I started looking at what they have to offer today…. which looks like a lot.

I modified an example from here:

http://msdn.microsoft.com/en-us/library/456dfw4f.aspx

To do a simple test to see how reading a web page works in .NET.

My revised code below:
Take note of the two windows form controls (webBrowser1) and (textbox1).

//due to the finally statement, these variables need to be created outside the try block
WebRequest request = null;
WebResponse response = null;
Stream dataStream = null;
StreamReader reader = null;
try
{
    // Create a request for the URL.
    request = WebRequest.Create("http://page_to_access");

    // If required by the server, set the credentials.
    request.Credentials = CredentialCache.DefaultCredentials;

    // Get the response.
    response = request.GetResponse();

    // Display the status.
    textBox1.Text = ((HttpWebResponse)response).StatusDescription;

    // Get the stream containing content returned by the server.
    dataStream = response.GetResponseStream();

    // Open the stream using a StreamReader for easy access.
    reader = new StreamReader(dataStream);

    // Read the content.
    string responseFromServer = reader.ReadToEnd();

    // Display the content.
    webBrowser1.DocumentText = responseFromServer;
}
catch (Exception error)
{
    Console.Write(error.ToString());
}
finally
{
    // Clean up the streams and the response.
    if (reader != null)
    {
        reader.Close();
    }
    if (response != null)
    {
        response.Close();
    }
}

All it does is just request a webpage (only with get data) and then stream the response to a string. After that it takes the string and inserts it into the standard WebBrowser control.

Next up I will setup/research:
- Searching the results from a web request.
- POSTing data to a page as apposed to using the get string
- Downloading files that are available from a webpage

Should be interesting!

DLL Files And .NET ClickOnce Deployment

Saturday, March 1st, 2008

I want to deploy one of my .NET apps as a ClickOnce application. The issue is that I am connecting to Oracle (see previous posts here and here). Connecting to Oracle requires at least, 4 DLL files that generally have to be in the same directory as the EXE file. The issue is that when the program is published, the DLLs are not referenced in any way, so the program won’t work.

Then I read about adding the files to the project, so that ClickOnce and the Publish processor will figure out that the DLLs are required and add them to the manifest.

Here is the process in Visual Studio 2005:
1. Put the 4 DLL files in their own directory in your solution directory (for ease of use mostly).
2. Add all four files to your project by going to “Project->Add Existing Item…”
3. Click on each DLL file in the solution explorer and then change their property: “Copy To Output Directory” to “Copy Always”.

That’s it! Now when I publish or even run the application I don’t have to worry about if the DLL files are where they should be.

C# .NET Programming Tip: Oracle Connection Revised

Saturday, March 1st, 2008

Take not that Microsoft will discontinue support for System.Data.OracleClient in .NET 4.0. This method should still work, but it will be depreciated…

Now that I have had more time to work with Oracle, I found a better way to connect then described in my previous post. With this new method you can connect to multiple instances in one program by getting rid of that tnsnames file.

*Remember that a project reference to System.Data.OracleClient must be added:

OracleConnection dbConnection;

string connectionString = "Server=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = *******)(PORT = 1521))(CONNECT_DATA = (SID = *****)));Persist Security Info=true;User Id=*****;Password=*****;";

dbConnection = new OracleConnection(connectionString);

It’s really that simple. The key here is that the connection string must use the “Server” attribute instead of the “Data Source” one. I ran upon that while looking at the specification on Microsoft’s MSDN documentation site.

It’s basically a tnsnames string with a few more attributes like user id and password. Just remember that:
host is the name of your server or ip address, sid is the name of your database meaning the *** part of ***.world, and of course the user id and password are your login credentials.

There is another helpful step that I will be posting about. It relates to ClickOnce and the 4 DLL files that you need to connect to Oracle.

C# .NET Programming Tip: Using the Tag property of controls

Saturday, February 16th, 2008

I’ve been doing C# programming at my job lately. Throughout the process I’ve hit a few little walls that were difficult to find answers for and thought writing down the solutions here would be good for myself any anyone who happens to find this by-way-of search engine. So as I come upon these little bits of useful harder-to-find information, I’ll write something here about it.

Creating windows form controls programmatically and passing data between class instances was one such issue. I did a number of searches on Google and didn’t really find much help. The main suggestion was to create an EventArgs class that passes events or some such thing. That was a really involved process that didn’t seem like it was worth the effort to implement.

I then created my own static global event class where anything in the program could pass an unlimited number of parameters. Once the parameters were accessed, they were deleted from the static Dictionary that stored everything. Well actually it was a Dictionary inside a Dictionary (parameterSetName -> (Dictionary that holds all parameters)). So it was a one shot wonder.

Let me give a little background information about why I needed to implement it:
I had a number of classes that generate their own windows controls to select or edit themselves. For example, A “checklist container” created controls to allow the user to select one specific checklist. The function was called with a reference to a FlowLayoutPanel. Then when the user clicked a button to select one specific checklist, the container class would call a function inside the selected checklist instance to tell it to display edit controls for itself. The problem was passing that FormLayoutPanel reference to the checklist function from an event function that I linked to the buttons that were dynamically generated.

There was really no easily noticeable way to do it. Every button the Container class created was all linked up into one Event function. The way .NET works is that you can create your own event function, but only two specific parameters are passed (one is the control itself, in the sender parameter).

So that is why I created that static global parameter class. The thing is I ran into another roadblock that made the global parameter class useless. They way I designed it is that the parameters were deleted from the Dictionary object once some function accessed them, but what if I wanted a form that did a similar process, but did not completely replace the current controls with something new (eg: the single checklist edit controls needed to perform actions like reading data from textboxes that were created at runtime. The function that would take events from the buttons on the edit form had no way of accessing textboxes at this point.

I go back on Google and Yahoo! and do a few more searches. This time I come upon the Tag property of Windows Form Controls. It’s an object variable that you can put anything into and it works perfectly for what I was trying to do.

By this point you probably are having a hard time understanding what I am talking about. So here are a few code examples to help you out:

The way my program works is that checklist has multiple checklist items and each checklist item has a few windows form buttons that should do things.

This is a button that would fire off a request to update a database data from a textbox:

Button btnNotesChance = new Button();
btnNotesChance.Text = "Update Notes";
btnNotesChance.AutoSize = true;
pnlTxtBoxes.Controls.Add(btnNotesChance);
btnNotesChance.Name = "clintsbx-" + i.ToString(); //save a name so we can know who calls the event handler
btnNotesChance.Tag = txtNotes; //save the handle to the notes textbox into the button's "tag" variable
btnNotesChance.Click += new EventHandler(displayChecklistAsControls_Event);

Notice the Name property. I give it a unique identifier clintsbx-#, so that way I can know which “Update Notes” button was clicked in the function displayChecklistAsControls_Event. I’ll get to the event function later. Also notice the Tag property. That stores the handle to the button’s related TextBox “txtNotes” object (windows form textbox). So now when the button is clicked we will know who called the update and what textbox to take the information from!

Here is an excerpt from the event function:

private void displayChecklistAsControls_Event(Object sender, EventArgs e) //event handler for the checklist selector buttons
{
    //fetch the calling control
    Control senderControl = (Control)sender;

    //take the calling control's name and split it up into two parts, one means the type of control and the other means
    //the index of the control (eg: ollststatu-4 means the 4th listbox for checklistitem status)
    string [] nameData = senderControl.Name.Split(Convert.ToChar("-"));

    //turn the second array value into an integer
    int itemSelected = Convert.ToInt32(nameData[1]);

As you can see there the sender variable is key. We can use that to get access to the button that called the event. Then we can take the Name of the control and the Tag of the control and do what we need to do.

I perform a Switch on the first nameData item to decide which set of controls called the event. Here is some code below for “update notes” I have been talking about.

case "clintsbx":
//take the notes textbox data and save it to the corresponding checklistitem notes field
//utilizes the button's tag element to save a reference to the corresponding textbox
string selectedItemText = ((TextBox)((Button)senderControl).Tag).Text;
//only update if the user made some type of change
if (checkListItems[itemSelected].Notes.Equals(selectedItemText) == false)
{
    //update the instance and database with this text data
    checkListItems[itemSelected].Notes = selectedItemText;
}
break;

It takes the button’s Tag property and turns that into a reference to the textbox. Then it is able to access the Text property of the textbox and then update the database.

Problem solved!




The Way Of Coding



 
Scott J. Waldron Photography
Stock Photo Website
Tech Learning Site

Popular Article Tags

Archives

Pages