The ramblings of web developer Beau Brownlee

Posts Tagged ‘ C# ’

 
Thursday, March 24th, 2011

Let me start out by saying (for all the test driven devs out there who are going to pick this apart lol) that catching bugs through testing is far better than debugging and catching bugs through error logs. However, that does not mean that test driven development has brought Utopia to earth and that any software that implements proper testing doesn’t have bugs. They still have bugs,,, just a lot fewer bugs.

Scenario

So I’ve been working on a windows service as of late that does a lot of database calls, emails etc. So a lot of external things could happen to cause exceptions and I wanted to be able to quickly look up in a log file to see what errors were occuring. Here’s a quick little class to get an exception and ouput a formatted error message that points to where the problem originates:

class ExceptionFormatter
    {
        StringBuilder format = new StringBuilder();
        public ExceptionFormatter(Exception exception)
        {
            StackTrace stacktrace = new StackTrace(exception, true);
 
            var stackframes = stacktrace.GetFrames();
 
            format.Append("********* Error ************\r\n");
            format.Append("Message: " + exception.Message + "\r\n");
            format.Append("Inner Message: " + (exception.InnerException != null ? exception.InnerException.Message : "") + "\r\n");
 
            foreach (StackFrame frame in stackframes)
            {
                if (frame.GetFileLineNumber() != 0 && !string.IsNullOrEmpty(frame.GetFileName()))
                {
                    format.Append("File Name: " + frame.GetFileName() + "\r\n");
                    format.Append("Line Number: " + frame.GetFileLineNumber() + "\r\n");
                    format.Append("Column Number: " + frame.GetFileColumnNumber() + "\r\n");
                    format.Append("Method Name: " + frame.GetMethod() + "\r\n");
                }
            }
 
            format.Append("****************************");
        }
 
        public override string ToString()
        {
            return format.ToString();
        }
    }

This is really simple to use. Just pass the exception into the construct and then call the .ToString() method and you get your formatted error. This iterrates through the stackframe to get the location of the errors on top of what the errors are. Hope this helps!


Get Microsoft Silverlight

This is a great video from Silverlight TV. One of the powerful things you can do with silverlight is more robust client side error handling than most web applications. Kyle McClellan walks us through some great techniques on how to do this. He also gives some useful tips on data binding for comboboxes as well as walking us through metadata and how it can be used in validation.

 
Saturday, September 11th, 2010

Just messing around with my new FEZ Domino board and I thought I’d post up a quick tutorial on how to use a motion sensor with your board. First thing you will want to understand is interrupt ports. An interrupt port is a port that is listening and waiting for something to happen. For instance voltage levels going up or going down. In this tutorial I use a motion sensor that I got from parallax here. This is a very basic sensor that has voltage tolerance of 3-5v and has one pin that outputs high or low voltage levels. High means its sensed motion. The next part of this project involves a small speaker that outputs a tone to let you know its sensed motion. Nothing loud or anything but just for demonstration purpose. You can get the driver for the tone generation here: http://www.tinyclr.com/downloads/Component/FEZ_Components_Piezo.cs. So here’s the code:

#region motion sensor
            Thread.Sleep(30000);
 
            tone = new FEZ_Components.Piezo(FEZ_Pin.PWM.Di5);
            InterruptPort motion = new InterruptPort((Cpu.Pin)FEZ_Pin.Interrupt.Di1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeHigh);
            motion.OnInterrupt += new NativeEventHandler(motion_OnInterrupt);
 
            Thread.Sleep(-1);
#endregion
 
 
static void motion_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            tone.Play(400, 1000);
        }

To see more about how to hook the hardware up check out the video:

There needs to be about a thirty second ‘warm up’ time as the sensor gets to know its surroundings and after that the sensor will be ready to be connected to the interrupt port. The interrupt port will listen for the voltage levels to go up and when they do it will play the tone.

 
Thursday, September 9th, 2010

So the issue that I ran into recently is that I’m getting data in an observable object list and then getting an updated list. I need to be able to compare each object in the list to see if it has been updated or not. The problem is that I have a lot of properties in each object and I had several object lists which I needed to compare. The solution I wanted involves IComparable. This is a very simple interface that implements CompareTo method only. CompareTo receives an object and returns an integer. This interface is used for comparing and doing things like sorting in arrays but in this case all I need to check for is if the CompareTo returns 0 (equals) or anything but 0 (not equal).

Another problem is that to implement this function you have to write all the checking code yourself and if you have alot of properties to check you have to do that manually somehow. I wanted something to simply check to see if all properties in the current object and the object passed in through CompareTo function were equal. Here is some code to do that:

// Implement IComparable interface and use this as your function
#region IComparable Members
            public int CompareTo(object obj)
            {
                int return_value = 0;
 
                if (obj.GetType() == this.GetType())
                {
                    Type t = this.GetType();
 
                    foreach (PropertyInfo p in t.GetProperties())
                    {
                        Type t2 = obj.GetType();
 
                        object prop1_value = p.GetValue(this, null);
                        object prop1_name = p.Name;
 
                        foreach (PropertyInfo p2 in t2.GetProperties())
                        {
                            object prop2_value = p2.GetValue(obj, null);
                            object prop2_name = p2.Name;
 
                            if (prop1_name == prop2_name)
                            {
                                if (prop1_value != null && prop2_value != null)
                                {
                                    if (!prop1_value.Equals(prop2_value))
                                    {
                                        return_value++;
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                else
                {
                    return_value++;
                }
                return return_value;
            }
            #endregion

This uses system.reflection to iterate through the properties in both objects comparing the values using the ‘Equals’ method to validate the values are the same. If the properties are not the same the return_value is incremented and more than 0 is returned. This is pretty generic and should work with most classes you build. You may need to add in an if statement to filter out properties you do not wish to include in this comparison as this just checks all properties in the object.

 
Wednesday, June 2nd, 2010

One of the things I needed recently is a simple way to have a textbox that had a watermark in it. Apparantly SilverLight 4 provides it,,, and it doesn’t provide it. Check this post out. I really couldn’t help but laugh when I saw this. ‘Do not use in a Silverlight 4 application.’ and at the same time the supported version is only Silverlight 4. Aaah yes, well the only other solution is to use a watermark textbox someone else has created or to make your own. I opted to make my own. Before we get into the code here it is:

This just gives you a basic idea of what you can do. The first textbox is the user control that has watermark capabilities. If you click on the water marked textbox it will clear it out and be ready for input. If you do not type in any text and leave it blank and click on the second textbox it will replace the watermark. If you click the ‘Get Text’ button it will show blank because you do not want the watermark to count as valid text. If you click ‘Set Text’ it will programatically set the text in the textbox and you will notice that the watermark disappears.

(more…)

 
Thursday, May 27th, 2010

Reading an xml file is something that every developer has to do at some point (if not regularly). XML protocol is extremely prevalent across all technologies which makes it important to understand how to parse it. Sivlerlight exposes System.XML.Linq namespace that has all the needed classes to use Linq to query your XML to get the node/s that you need.

Always Starts with the Document

As with every XML reader you start out by creating an instance of the document and then filling it with the XML file’s data. In this case Silverlight provides ‘XDocument’ class to instantiate the document object and then the ‘Load’ method to read the data into the object. Then once we’ve loaded the object with data then we can run a traditional Linq query on the data.

Test Case

So lets run through a test case. Lets say we have a configuration file in which we want to determine what logo to display based on the url that called it. So here is our example xml:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <Logos>
    <Logo url="url1">
      <LoginWindowLogo>/namespace;path/img1.png</LoginWindowLogo>
    </Logo>
    <Logo url="url2">
      <LoginWindowLogo>/namespace;path/img2.png</LoginWindowLogo>
    </Logo>
  </Logos>
</configuration>

And here is the C# code to read it:

XDocument document = XDocument.Load("Config.xml");
 
            var images = (from e in document.Descendants("Logo")
                          where e.Attribute("url").Value == App.Current.Host.Source.Host
                          select new
                          {
                              LoginWindowLogo = e.Element("LoginWindowLogo").Value,
                          }).FirstOrDefault();
 
            if (images != null)
            {
                loginwindowlogopath = images.LoginWindowLogo;
            }

App.Current.Host.Source.Host is the property that gives you the current apps domain, the function ‘FirstOrDefault’ get the results and turn it into an object that just has the properties selected.

 
Wednesday, May 26th, 2010

An advantage of using Silverlight is the fact that the entire app is cached locally. While this may take a while to download initially, after everything is downloaded the app runs very very fast and only requires you download information asynchronously from a web service. The only problem is, what if you make changes? Since the app is cached those changes are sometimes not downloaded automatically. So what to do? Lars Holm Jensen wrote a nifty little post that shows how you can determine when the last time the silverlight package was was deployed by reading the datetime stamp on the ‘xap’ file. Just in case you didn’t click on the link, here’s the code:

<object id="Xaml1" data="data:application/x-silverlight-2," type="application/x-silverlight-2"
width="100%" height="100%">
<%
string orgSourceValue = @"ClientBin/SilverlightApp.xap";
string param;
 
if (System.Diagnostics.Debugger.IsAttached)
param = "<param name=\"source\" value=\"" + orgSourceValue + "\" />";
else
{
string xappath = HttpContext.Current.Server.MapPath(@"") + @"\" + orgSourceValue;
 
DateTime xapCreationDate = System.IO.File.GetLastWriteTime(xappath);
param = "<param name=\"source\" value=\"" + orgSourceValue + "?ignore="
+ xapCreationDate.ToString() + "\" />";
}
 
Response.Write(param);
%>
 
<param name="onError" value="onSilverlightError" />

The ‘if’ statement checks to see if your debugging. If you are, then grab the latest/greatest. If not, then it’s assumed that you are in production mode and then it checks to see if you have the latest and greatest. If you don’t, then download the latest version. Thanks Lars!

 
Wednesday, May 26th, 2010

One very important task you have as a developer is to keep track of errors. Errors you ask? ‘Errors’? ‘Not me, I write bug free code!’. Ok Mr. Programming God, but for the rest of us mortals, we have to do something to keep track of all the human errors that get embedded into our code. There are many different ways to store these errors, some people do it in flat files, others in databases. We won’t be talking about where to store these errors, just how to get them from silverlight.

The problem

Web applications have always presented a particular problem when it comes to catching errors and logging them in a central place. First, with Javascript it is difficult to know when an error has occurred and hasn’t been caught already and if so, it’s difficult to do anything after that as many javascript errors will break the app entirely and not run anymore code.

The Solution… A Solution

Silverlight attempts to simplify this process by having a central place to catch any unhandled exceptions and then do something with them. You can catch them in the App.xaml.css file. Here is an example:

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
      //Ignores logging if your debugging
      if (!System.Diagnostics.Debugger.IsAttached)
      {
        /*TODO: Some method to save the 
           the error to a file or database by using
           e.ExceptionObject.Message, e.ExceptionObject.StackTrace
        */
        e.Handled = true;
        ChildWindow errorWin = new ErrorWindow("Error", "An Error has been logged"));
        errorWin.Show();
      }
    }

Does this mean that we don’t need to do any try/catches? No, we still need to handle errors and do something with them, but in the event that we miss an error, it will be caught here and logged so that we can more easily debug the released code.

 
Monday, May 24th, 2010

The Problem

I’ve recently been working on a Silverlight project that connects to WCF services asynchronously (as all Sivlerlight apps do). The issue that no one understood was the fact that these services are not secured in any way. Silverlight is simply a client asking for some information by sending an request with XML and then receiving the XML back. So any programming language that has classes to handle SOAP could easily utilize those web services as they were not authenticated.

The Solution

As an asp.net developer you learn to use asp.net sessions as a way to authenticate and to keep track of that authentication. This works for web services as well. You just have to make sure you have a couple things. First, in your web service you must include ‘System.ServiceModel.Activation’ with the ‘using’ clause and at the top of your web service class implementation you must include the following:

namespace mynamespace
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class mywebservice
{
 
}
}

Once you’ve done this you can include your methods and utilize your session classes:

public void Login(string username, string password)
{
    // check username/password against the database and validate yes or no
 
    if (isLoggedIn)
    {
        System.Web.HttpContext.Current.Session["IsLoggedIn"] = "yes";
    }
}

The last thing that would be needed is to secure the transmissions with SSL. Without this, anyone could sniff the packets to and from a laptop using a public wifi hotspot.

 
Friday, May 21st, 2010

Quick and Easy

A quick and easy way to spawn threads and update the UI from those threads is the following:

new Thread(() =>
               {
 
                   try
                   {
                       Thread.Sleep(3000);
                   }
                   finally
                   {
                       this.Dispatcher.BeginInvoke(() =>
                       {
                           label1.Content = "testing within a thread";
                       });
                   }
               }).Start();

This code starts a new thread and runs it asynchronously to the main thread. The key here is the fact that there is no way to affect the main thread (that the UI is running on) directly from a spawned thread so you have to reference the parent (dispatcher) and call the ‘BeginInvoke’ method and pass it an anonymous function that runs on the same thread that the UI is running on.

Passing Parameters

Sometimes you need to get information in the function you are running. You can do this by passing in parameters into the anonymous function. For example:

new Thread((a) =>
               {
                   try
                   {
                       Thread.Sleep(3000);
                   }
                   finally
                   {
                       this.Dispatcher.BeginInvoke(() =>
                       {
                           label1.Content = (string)a;
                       });
                   }
               }).Start("test");

You have to remember to cast your parameter as it always comes in as an object and requires ‘un-boxing’.

Running external Functions

You can also start a thread on an external void method:

// The code starting the thread
Thread thr = new Thread(new ParameterizedThreadStart(this.test));
            thr.Name = "testthread";
            thr.Start("1");
 
 
       //The void method (object only parameters)
        public void test(object a)
        {
            while (runthread)
            {
                Thread.Sleep(3000);
                this.Dispatcher.BeginInvoke(() =>
                {
                    label1.Content += (string)a;
                });
            }
        }

Notice that in the external method you can only have generic ‘object’ as the parameter and must then cast the data into the appropriate type afterwards.

cheap software