Fremus.co.za

Demistifying Life and Web Development

Archive for October, 2009

For and If statements without the braces

I noted a lot recently that C# developers do not use the curly braces for if and for loops, it seems that the indentation is enough. So if you write this:

                if (elemInner.HasElements)
                    foreach (XElement elemInnerInner in elemInner.Elements())
                        context.Response.Write("
" + elemInnerInner.Name + "
");

Apparently you use curly braces if you have multiple lines you should use curly braces. If you don’t use curly braces only the first line in your condition will be execute.

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

Enumerating through an XML document

I am in the process of developing some code for easily updating my CV, and one of the technologies I am using for this purpose is Linq to XML. As I have said previously on this blog, Linq to XML is an in-memory XML manipulation technology which allows you to manipulate XML as if you would use the XML DOM. So as part of my application I want to use XML because its easy to create or get the structure needed for creating the CV. I have discussed the idea of a CV Builder previously here. So part of this project involves reading XML and reading XML with LINQ to XML seems a rather straight forward process. The first thing you need to know about though is that the IEnumerable interface you need to use exists in the System.Collections.Generic namespace, not System.Collections. If you use only the latter you will get an error message saying:

The non-generic type ‘System.Collections.IEnumerable’ cannot be used with type arguments

Lets show some code that reads XML:

        XDocument document = XDocument.Load(context.Server.MapPath(@"CVTemplate.xml"));
        XElement root = document.Root;
        IEnumerable elements = from el in root.Descendants("parentsection")
                                             select el;
        foreach (XElement elem in elements)
        {
            builder.AppendLine("Element Name:\t" + elem.Name.ToString());
            builder.AppendLine("Attributes:");
            foreach (XAttribute attrib in elem.Attributes())
            {
                builder.AppendLine("\t\t" + attrib.Value);
            }
            foreach (XElement subElem in elem.Descendants())
            {
                builder.AppendLine("\t\t" + subElem.Name.ToString() + "\n\t\t\t" + subElem.Value);
            }
        }
        context.Response.Write(builder.ToString());

In the code above I use the XDocument class to read the XML from an XML file that I specified in a web.config app setting. I then create an XElement instance by assigning it to the document.Root of the XDocument instance, because its return type is XElement. I then create an enumerable variable elements of type XElement and get the enumerable result from a LINQ query that selects the elements from the XML of the nodes parentsection. I then enumerate through the XElements from the elements variable. Inside the foreach loop I enumerate twice again, once for the attributes of the XML node and the second time for the nested XElements. I just created a StringBuilder instance to write the values as the enumeration took place, its just so that I can see the values and also because I implemented this with a generic handler. Ok so what is next? Well next I need to be able to select items and move them around, but thats for another article.

  • Share/Bookmark
posted by fr3dr1k in C#,LINQ to XML and have No Comments

Getting to understand JavaScripts prototypal nature

One of the things that are quite weird to get use to, from a C# developer’s perspective, is JavaScript’s prototypical nature. Check out this basic example:


var objXMLHTTP =
{
    getXMLHTTPObject: function(url,elementName) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else {
            alert("Your browser does not support XMLHTTP!");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4) {
                document.getElementById(elementName).innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    }
};
objXMLHTTP.getXMLHTTPObject("http://localhost/YieldTester/Handler.ashx", "testDiv");

The code above creates a simple XMLHTTPRequest object, but you do not create an instance of the object, you call it directly. Note objXMLHTTP.getXMLHTTPObject. In C# you might have created an object and then you instantiate it through an instance of that object. I have taken the code as is given on W3Schools and modified it a little.

  • Share/Bookmark
posted by fr3dr1k in AJAX,Web Technologies and have No Comments

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

.NET Framework 4.0

I read a Tweet from Scott Gu, and got to the Entity Framework Team Blog, from where I did a search on .NET 4.0. The first thing I came across was the download on Microsoft’s site, but I also came across a blog entry by Brad Abrams titled .NET Framework 4 Poster which is available in PDF and a Deep Zoom Silverlight application. I opened the Silverlight object and took a look at the classes and namespaces that are new in .NET 4.0. I found it interesting that MVC now becomes a part of the framework, and all the classes that relate to MVC are under System.Web.Mvc. Charting is also now an integrated part of the framework.

Another interesting bit I read on the Entity Framework blog was that the new EF will support some extra features that seem to be in other ORM frameworks. I will definately be looking at this.

  • 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
Get Adobe Flash playerPlugin by wpburn.com wordpress themes