Fremus.co.za

Demistifying Life and Web Development

Using yield to stream database results

I have been looking for a way to stream database results for a while now, and has as yet not come to a fitting solution. That is until today and after I did some reading on the yield keyword. The yield keyword can be used inside a function that implements the IEnumerable interface and what it seems to do is force a loop to return a result even though its not finished. Lets say for instance you have a function like this:

    public static IEnumerable Power(int number, int exponent)
    {
        int counter = 0;
        int result = 1;
        while (counter++ < exponent)
        {
            result = result * number;
            yield return result;
        }
    }

And you implement it like this:


         //Display powers of 2 up to the exponent 8:
        foreach (int i in Power(2, 9))
        {
            Console.Write("{0}", i + "\n");
            Thread.Sleep(2000);
        }

You will see that the results in the command line are delayed. If you take that same logic and you translate it to a function that queries a database like this:

    public static IEnumerable GetData()
    {
        DataTable table = new DataTable();
        using (SqlConnection sqlConnection = new SqlConnection("connectionstring"))
        {
            string commandText = "select chattext from Chat";
            using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
            {
                sqlCommand.CommandType = CommandType.Text;
                SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
                dataAdapter.Fill(table);
            }

        }
        foreach (DataRow row in table.Rows)
        {
            yield return row["chattext"].ToString();
        }
    }

Then the implementation is similar to the first example's:


        foreach (string s in GetData())
        {
            Console.WriteLine(s + "\n");
            Thread.Sleep(2000);
        }

And the result is the same. Read about the yield keyword on MSDN and check out this StackOverflow article, on which the database example is based.

  • Share/Bookmark
posted by fr3dr1k in C# and have No Comments

Understanding what the difference is between Convert.ToInt32 and Int32.Parse

One thing I have come to look upon in a critical way is when a fellow developer tells you something and expects you to just take his word for it. Its like a developer saying “I would do it this way” but not give a reason why, or even asking another developer why he does not do it the same way. I have found this situation yesterday and decided to make sure I knew the difference, and specifically it applies to Convert.ToInt32() and Int32.Parse(). What is the difference? Well simply put Convert.ToInt32() will not throw a FormatException if the value you pass is null or not, whereas Int32.Parse will. It means that for Int32.Parse you have to use some try catch logic. With Convert.ToInt32 you do not have to do this.

On this topic I read here and here that you could also use Int32.TryParse, which will try to convert the value to an integer and return true if it succeeds and false if it fails. It uses an out variable to return the result of the conversion. You can check it out on MSDN here.

  • Share/Bookmark
Tags:
posted by fr3dr1k in C# and have No Comments

Some thoughts on Windows Forms Development

Yesterday I posted about Making static content more dynamic. I actually started developing a small C# windows forms application in combination with a MS Access database. The windows forms application will, for now, generate all the HTML needed for the website and the MS Access database will be used to centralise information. This is not the most modern or flashiest approaches but it does lend itself to saving some money and if the marketing strategy is good and accurate might even deliver good results. Obviously as soon as the customer changes hosting plans the need for static HTML content might go out the window altogether. You can still, however, incorporate the same Windows forms application, through WCF services.

Windows forms seemed so strange, because the domain is so different to web-based apps, seeing that I havent done any in a very long time. But the C# code remains very much the same, which is awesome.

  • Share/Bookmark
posted by fr3dr1k in Application Development,C# and have No Comments

Making static content more dynamic

I was helping some with their website yesterday and the hosting package they have does not allow for dynamic languages, such as PHP or Python, and there is no database either. So basically you have a situation where you can only upload static HTML pages, which is limiting yes, but not such an entirely bad thing. Managing the content for such a website only has two or three realistic options:

  • Use IDE such as Dreamweaver, which also implies more costs
  • Manually edit the HTML pages yourself, which can become nightmarish
  • Create some managed (C#) code that can automate HTML generation

All three approaches involve content being uploaded, which is not the worst thing ever, but it does mean that updates do not occur immediately. Also remember that a budget constraint is the biggest factor here. The idea is that you do not incur any additional monthly costs. I also think you can build content updates to social networks as well.

  • Share/Bookmark
Tags:
posted by fr3dr1k in Application Development and have No Comments

Understanding Delegates

So one of the topics I have been telling myself to understand a bit better is delegates, and I think tonight I understand a bit more. Firstly a delegate can be described in simple terms as a type that references a method. So for instance you would have a class with a method that you would like to maybe re-use in another class without having implement it again. In this instance you might want to use a delegate. A delegate must have the same signature as the method it references, and you use the Delegate keyword for that. I created a very basic example to illustrate its use:

    delegate string Del(string myString);
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Del d = p.Myname;
            d += p.MySurname;

            Console.WriteLine(d("Fredrik"));
            Console.WriteLine(d("Erasmus"));
        }
        string Myname(string myString)
        {
            return myString;
        }
        string MySurname(string myString)
        {
            return myString;
        }
    }
  • Share/Bookmark
Tags: ,
posted by fr3dr1k in C# and have No Comments

Linq to XML and DataSet to XML

On Monday I started working through some LINQ to XML and it got me so excited that I misunderstood some project requirements that ended up being quite wrong. It did not, however, diminish my enthusiasm. I ended up using a small part of the code in the end anyway, even though it was not in a production environment.

Lets say you have a collection of XML documents and you would like to know what elements appear in all of them, so at the end of it all you have a single of list of elements that appear between all of them. This is how I did it:

            DirectoryInfo di = new DirectoryInfo(ConfigurationManager.AppSettings["XMLDirectory"].ToString());
            Dictionary values = new Dictionary();
            FileInfo[] fi = di.GetFiles();
            Response.Write("
");
            Response.Write("
");
            foreach (FileInfo file in fi)
            {
                //Response.Write(@"


");
            }
            Response.Write("

");
            Response.Write("
");
            Response.Write(@"


");
            Response.Write("

");
            Response.Write("
"); //Response.Write("" + file.Name + "
"); XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; settings.IgnoreComments = true; settings.ConformanceLevel = ConformanceLevel.Fragment; //Console.WriteLine(file.Name); XmlReader reader = XmlReader.Create(file.Directory + @"\" + file.Name, settings); XDocument document = XDocument.Load(reader); IEnumerable elems = from items in document.Descendants("Bond") select items; foreach (XElement elem in elems) { IEnumerable childElems = from items in elem.Descendants() select items; foreach (XElement xelem in childElems) { //Response.Write(xelem.Name.ToString() + " " + xelem.Parent.Name.ToString() + "
"); if (!values.ContainsKey(xelem.Name.ToString())) { values.Add(xelem.Name.ToString(), xelem.Parent.Name.ToString()); } } } //Response.Write("
"); Response.Write("Combined"); var combined = values .OrderBy(kv => kv.Value); foreach (KeyValuePair kvp in combined) { Response.Write(kvp.Key + " " + kvp.Value + ""); } Response.Write("
");

I use the DirectoryInfo class on a directory, XMLPath in this instance. I then declare an array of type FileInfo, which I then use in a foreach (Enumerate) loop using the FileInfo class. I then use the XMLReader class to read the XML document that is represented through the FileInfo class to read the XML. Inside the foreach loop I create an enumerable instance of XElement called elems which uses LINQ to XML to select all the items. I then create a second enumerable instance of XElements called childElems. I then iterate (enumerate) through the childElems instance and add the Name of the element as the key and the parent as a value to a dictionary of type string,string which I declared earlier. This will loop through all files in the directory and generate a dictionary with combined values. Once its in a dictionary you can simply enumerate through it. I ordered it first by using the OrderBy extension method. Once it has been ordered I enumerate through it with a KeyValuePair and display the combined list. This approach has apparent weaknesses in that it uses the name of a node as a key and the parent as the value. What if two nodes are equal but have different parents? It served a purpose for me though.

The second piece of code I would like to show is an example of converting a dataset to xml and returning the raw XML. Let’s say you have an arbitrary function and you want to return the raw XML of a dataset, you could use:

            StringWriter writer = new StringWriter();
            transactionDS.WriteXml(writer);
            xmlizedString = writer.ToString();

            return xmlizedString;
  • Share/Bookmark
posted by fr3dr1k in Application Development,C# and have No Comments

Growing into Learning LINQ to XML

So I forced myself last night to spend time learning LINQ to XML, both from a technical perspective and a theoretical perspective. My aim is to not only know what LINQ to XML is but also to understand why and how. My goal for the next six months is to not skim over source code, but to actually spend time going through it and trying to understand it, and the same applies to LINQ to XML.

I started off with the MSDN article, and my goal is to go through all of the material and to get a good overview of the technology as well as knowing the code that goes with it. So I will try and learn as much of code as possible.

From what I read last night I found a few facts about LINQ to XML interesting:

  • It is a built-in language feature. I already knew this actually. And because it is a built-in language feature it gets to use debugging features as well as be strongly typed
  • LINQ to XML is equivalent to a redesigned XML DOM. You write query expressions that are equivalent to XQuery and XPath in functionality (not syntax).
  • It uses something called functional construction
  • You can create and manipulate XML by saving it, serializing it or sending it over the net
  • The query expression are SQL-like:
    IEnumerable items = from items in purchaseOrder.Descendants(“Items”)
    where (int)items.Element(“Quantity”) * (decimal)items.Element(“USPrice”) > 100
    orderby (string)items.Element(“PartNumber”)
    select items;
    The above sample is taken directly from MSDN
  • Share/Bookmark
posted by fr3dr1k in C#,LINQ to XML and have No Comments

More code vs less code vs readability vs efficiency

After my blog post yesterday on File.ReadAllLines() vs StreamReader I have been thinking that more code does not necessarily mean more, or does it? I mean syntactically the first one is a one liner and the second one is a few lines, but I do feel that the latter adds more value. Why? Well firstly because streams seem to be an important part and concept in the .NET framework and secondly the streamreader class seems to dispose of resources a bit better. It also seems as if my implementation of the streamreader class deals with something the first option has still to deal with. I mean you have to assign a string array and then somewhere you have to iterate through the content of the array, whereas with the streamreader you can do all of that once. Looping through the contents that gets read by the streamreader class instance can be achieved by either appending the results to a stringbuilder instance or by using a function that implements the IEnumerable interface and uses the yield keyword. Using a function that implements IEnumerable means that you can run a foreach against it. I do honestly find this approach a lot more expressive. Its also interesting to note that the streamreader class performs better in some cases.

  • Share/Bookmark
Tags:
posted by fr3dr1k in Application Development and have No Comments

File.ReadAllLines() vs StreamReader

A couple of days ago I forced myself to memorize the C# code for reading from a file (text, html), and for it I used the StreamReader class (on MSDN):

try
{
    using(StreamReader reader = new StreamReader('filename'))
    {
            string s;
            while((s = reader.ReadLine()) != null)
            {
                   Console.WriteLine(s);
            }
     }
}
catch(Exception ex)
{
      Console.WriteLine(ex.Message);
}

This is in comparison to the File class which has a method called ReadAllLines, and its biggest benefit is that it results in less code. Is less more? I’m not sure yet. With the StreamReader class you can create a method that implements IEnumerable which allows you to use the foreach on it. I found the sample for this on http://stackoverflow.com/questions/286533/filestream-streamreader-problem-in-c.

public static IEnumerable ReadLines(string path)
    {
        using (StreamReader reader = File.OpenText(path))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                yield return line;
            }
        }
    }

foreach(string line in ReadLines(file))
{
    Console.WriteLine(line);
}

It is also mentioned that the StreamReader approach works nicely with Linq. Another thing that was mentioned is that the StreamReader uses a concept called lazy evaluation and this increases performance.

Does the less code option result in better performance just because it uses less lines of code? I’m a bit undecided. Maybe I will have a better opinion in the future.

  • Share/Bookmark
Tags:
posted by fr3dr1k in Application Development,C# and have No Comments

Sites that use Silverlight, updated

Last year July I wrote a blog post that listed some sites that use Silverlight to power rich application content. Twelve months later and I have found a few more cool ones, although the Hardrock Memorabilia site still remains my favourite.

ShineDraw still remains a great site for checking out the same things done in either Flash or Silverlight. And its updated regularly, which is always great.

In the meantime though I have found two other cool examples of Silverlight:

  • Share/Bookmark
posted by fr3dr1k in Silverlight and have No Comments
Get Adobe Flash playerPlugin by wpburn.com wordpress themes