The ramblings of web developer Beau Brownlee

Archive for the ‘ C# ’ Category

 
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.

 
Tuesday, December 1st, 2009

Jumploader is a very cool very powerful uploading agent. It is a java applet that runs in your browser that allows you to upload very large files by breaking them up into ‘partitions’ (small sections of a file). It has other neat features such as drag and drop files, image editing, meta data forms and file compression. The responsibility on the developers side is handling the file uploads with server side scripting of some kind. It works with pretty much any server side language such as PHP, .net, Python etc… Anything that can run in a web server and write to a file stream. I’ve worked with this recently in .net. There is an open source example of how to use Jumploader with C# on their website originally written by Michael Wright. It isn’t updated however and it was missing some key features that I needed such as examples on how to handle the ‘resume’ feature, allowing for the meta data forms and a few other things. I made several updates to the original code and have started an open source project on Google Project. You can visit the project at http://code.google.com/p/jlnetwrapper/. I will be updating this periodically and am always happy for other contributions to this project as well.

 
Thursday, November 12th, 2009

I have recently been using LINQ to accomplish much of my data abstraction and have found it very useful for building a robust ASP.Net application. Ultimately what LINQ to SQL does is it translates your C# code into a SQL query and returns an object or an object list instead of a dataset. This can be much easier to deal with than a dataset. I have run into a couple things that I didn’t expect so I thought I’d share. (more…)

cheap software