Fremus.co.za

Demistifying Life and Web Development

Archive for the 'C#' Category

Daily Code – Day 3 – A great reason to use interfaces

Any class that inherits an interface is considered of that type, so it makes it easy to create implementations that do different things. More importantly it makes it easier to test. Lets say you have an Interface called IMyInterface:

    public interface IMyInterface
    {
        void PrintMessage(string message);
    }

You can then create two different classes that both implement the interface:

    public class ConcreteClassA : IMyInterface
    {
        public void PrintMessage(string message)
        {
            Console.WriteLine("My implementation here: " + message);
        }
    }
    class MyConcreteClassB : IMyInterface
    {
        public void PrintMessage(string message)
        {
            Console.WriteLine("My other implementation here: " + message);
        }
    }

This means that when I implement the code like this:


    class Program
    {
        static IMyInterface myInterface;
        static void Main(string[] args)
        {
            myInterface = new ConcreteClassA();
            myInterface.PrintMessage("hello");
            myInterface = new MyConcreteClassB();
            myInterface.PrintMessage("good day");
        }
    }

I dont create a dependency for class Program on either ConcreteClassA or MyConcreteClassB. If I make any subsequent changes to either of these classes then it doesnt affect class Program because it only deals with the interface. Its a great way to abstract your code, and its something I did not realise after reading up on it. Can an abstract class provide the same type of “abstraction”? Not really, and for a several reasons, the first being that you cannot create an instance of an abstract class and secondly you would have to expose the implementation details of the classes that inherit the abstract class.

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

Daily Code – Day 2 – Difference between an abstract class and an interface

I got asked this the other day and its one of those things that devs just have to know I guess, apart from the other fundamental C# stuff. I think of interfaces as thin classes or thinned out classes with no implementations of its methods, only signatures. Its the responsibility of the class that implements that interface to provide the implementation specifics. An abstract class on the other hand cannot be instantiated but rather acts as a base class for other classes. The responsibility lies with the class that implements it to override any methods, if the methods within the abstract class are declared as abstract. Another key difference between interfaces and abstract classes is that the members within an interface are implicitly abstract, in other words the class inheriting the Interface MUST create implementations of the inherited interface, whereas an abstract class may have non abstract members.

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

Dealing with Circular References in EF4/JSON

I like the many-to-many mapping EF4 provides you simply because it allows such great navigation between entities and its easy to shape the query from one side to other and vice verse. The only issue is that it causes issues with JSON serialization, because the serializer does not know how to handle circular references, it can only serialize one way. Initially I dealt with this issue by creating “view classes” but it seemed rather tedious and pointless, so instead I started using the enumerable Select() method. It provides a very easy way to construct “anonymous objects”. So in my controller I would have a JSON Result and I would do something like this:

Json(courses.Courses.Select(t => new { CourseTitle = t.CourseTitle, CourseCode = t.CourseCode, CourseId = t.Id }));

Pretty damn neat, considering that Courses is a EF4 entity and I dont have to go and change or adapt it to play nicely with the JSON serializer.

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

What are extension methods?

I was looking for questions that a Senior .NET developer could expect and one of the questions I would ask is to explain what extension methods are. If I am not mistaken ASP.NET MVC 2.0 uses extension methods to create HTML Helpers, which would make perfect sense since ASP.NET MVC might not have all the functionality baked in, that you may require.

Extension methods essentially provide a developer with a mechanism to extend the base functionality of a particular class. So lets say you want ToString() for a class to return a date in a particular format, then you could write an extension method that transforms the ToString() representation of that object into the DateTime format you desire. Creating an extension method requires that you create a static class with a static method, like:

    static class Extensions
    {
        public static string ToString(this Concept concept, DateTime startDate)
        {
            return startDate.ToString("dddd MMMM yyyy");
        }
    }

Where concept is an arbitrary class I created. If I create an instance of Concept and call ToString() I get the overload:

            Concept concept = new Concept();
            Console.WriteLine(concept.ToString(new DateTime()));
  • Share/Bookmark
Tags: ,
posted by fr3dr1k in C# and have No Comments

Building a CMS with ASP.NET MVC 3 Razor – Conceptualisation

I have been working with ASP.NET MVC 2.0 for the last couple of months, 6 or so and the thing that I love the most about ASP.NET MVC is the fine grained control you have over the bits of your website, and it all feels like you are still working on a website. Lets be honest here for a moment, developing web applications with webforms feels unnatural and unwieldy and you always have this sense of it not being a “real” web application but rather some leaky abstraction of Windows Forms. ASP.NET MVC changed this perception a bit, by first dumping the whole page-life cycle and then by removing the whole page behind architecture. Instead you now have a very clear separation of concerns, with html being kept in views and your code is defined inside controllers and models. Controllers are small pieces of code that give views their content and you can specify whether a view is strongly typed or not, in which case when you use the Model keyword you gain access to a particular model’s properties or methods. The general rule is that controllers should be skinny and models should be fat. Models are the business logic of the application and contain items such as your interfaces and classes. Enough about what ASP.NET MVC is for now.

ASP.NET MVC 2 uses the Webform rendering engine and ASP.NET MVC 3 uses the Razor rendering engine. You can read more about the Razor view engine on Scott Gu’s blog, but essentially it boils down to is the way in which dynamic content and html is rendered and how your view engine deals with it.

Today I started reading up on ASP.NET MVC 3 and Razor, starting here because I wanted to get a better understanding of how layouts work in Razor and also how I could leverage some of its cool functionality specifically for a CMS. Before I continue discussing how I could see myself building a CMS using Razor, I want to define what I would want from a CMS and what I would want it to do. Consider this my requirement statement, my way of defining the nature and functionality of the CMS.

I want a CMS that is flexible enough to handle multiple page layouts without having to create static pages. In other words I want to create a CMS that allows me to add pages from scratch without having any static views in place. I just want to be able to create pages using different templates. So if my only view is the home view, then every subsequent page that I add will essentially be part of a ViewResult within the HomeController, and if pages are nested the ViewResult should reflect that. A page can have a parent or child page, nth levels deep. The basic workflow for adding a page to a CMS could be:

  1. Select a page Template
  2. Select a layout
  3. Populate regions within layout with content
  4. Save the page

Apart from this basic functionality the CMS should provide a way to integrate “datasets” or strongly typed data items into a page, style the data items and provide cascading pages if required without the CMS having to know anything about the data item it is cascading. If you have a product and it has several entities associated to it then you might want to create separate pages based on those entities, but then it means you have to specify the page and page layouts for the cascading items. It also depends on what type of layout that data item has.

  • Share/Bookmark
posted by fr3dr1k in ASP.NET MVC,C# and have No Comments

Ajax in the .NET environment…

Ajax is not new, its not revolutionary, but it has changed the way I view web development. Javascript no longer comes as a might-have, instead it comes as a critical part of any website application. These days I use JavaScript as the UI scripting tool of choice, and I try to steer away from doing to much UI lifting in my server side code. jQuery makes dealing with UI quite pleasant.

I have also, in the last year and a half or so, been coding without MS Ajax. I have let go of things like the UpdatePanel and the Script Manager and have instead come to do direct Ajax calls to .ashx, default.aspx and web services. It feels that when you follow this approach that you have much tighter control over the quality of the UI. So what are your options for making Ajax calls in a .NET environment? I would like to think that there are a few options that stand out:

  • Direct page ajax calls – you can use jQuery’s ajax function to call .ashx and .aspx pages. I have recently started using the [WebMethod] attribute in my .aspx files to make calls, and what I like about it is that you can tell the page to output JSON, which automatically serializes the method’s return type. I have also used ashx files to do ajax calls and this worked well
  • SOAP-based web services – an approach I learned last year was to use a javascript soap parser to parse soap-based web services. These were mainly .asmx services. You can configure .asmx services to return JSON as well
  • WCF-services can be configured for SOAP or JSON but also use a REST-like approach

What other options are there for .NET developers when making Ajax calls?

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

Logging frameworks for C#

I find myself going to StackOverflow a lot recently if I need to search for an opinion on something related to C# or ASP.NET. Strangely you will find that in the first 10 results of a Google search you will find one, maybe two, pointing to StackOverflow. I digress, and the reason I am writing this particular blogpost is to make a list of logging frameworks available to .NET (C#) developers.

Before I go into identifying a few possible solutions I need to try and understand what my need is and what it is I want to achieve. I am going to be tackling various ASP.NET MVC projects within the next two to three months, and I cannot possibly see myself knowing where all the exceptions in my application will happen, or even try and code in such a way that all my try{}catch{} statements catch the correct exception. At the same time there is no excuse to overlook an exception if it happens more than once, you have to handle it. Having noticed how many exceptions a WCF service can throw I know for a fact that I cannot know all the exceptions beforehand either, so I need something, a tool that allows me to see the exceptions, and add it to my code so I can catch them. So the basic need is simple, have a mechanism in place that allows exceptions in my system to be caught.

You might be going, OMW you don’t log? Well I have been with several development teams and I can tell you that not a lot of development teams log system errors. And there is a host of other things they also don’t do, but that is not a part of this blog post.

I searched StackOverflow, and to me it seems there are a couple of choices available for logging in the .NET world:

Maybe I need to consider all the features offered and decide on the best alternative, which would be:

  • Ease of installation
  • Ease of getting to the exception logs

My intention is to start looking at each one of these this week, and make a decision by the end of the week.

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

What are the data types available in C#?

Types in C# and the .NET framework are the fundamental building block of program design, and in C# they are divided into built-in, primitive types, and user-defined types. Generally speaking the user-defined types refer to classes, and classes are essentially made up of built-in types and other user-defined types themselves. Primitive types can also be seen as value types, that is a type that has a value in memory, usually called the stack. This is in contrast to reference types that are on the heap, but actually have pointers to themselves on the stack. C# offers the following built-in types:

  • Byte
  • Char
  • Int16
  • UInt16
  • Int32
  • UInt32
  • Long
  • ULong
  • Short
  • UShort
  • Decimal
  • Double
  • Float
  • SByte
  • Single
  • Boolean
  • Int64
  • UInt64
  • Share/Bookmark
Tags:
posted by fr3dr1k in C# and have No Comments

Springbok Selector App

You all love the Springboks right? Those men in green who do South Africa proud? Well I guess the Kiwis or Aussies or Pommies or…err wait ok dont like the Springboks that much. But I love em and the other night I started thinking about writing an app that will allow me to select a Springbok squad (or two or three) from the Super 14 teams that are currently playing. So what I did is I honestly collected some player and squad information and put it into a database, and the way I did this was to use HtmlAgility to screen scrape player information from www.sarugby.net, and I did it quite easily and successfully got some information and managed to store it. You can see on this page, albeit it might be a bit slow in coming through, that you can search for rugby players here and once you have found a rugby player you can also get the rest of his team mates in his squad. Scary what you can do with a good HTML parser. I then took the information and created a few objects with properties and methods, and then I stored the information. Note that my intention is not to make money! I just liked the code that went into it. And the data that I stored I made available through an incomplete interface here. You can click on the squads to the right, which displays the players for that squad and if you click on a player you see their information displayed. My next idea was to assign each player to one or more positions and then in the left hand pane create icons that represent rugby jerseys, and then make the players you select “addable” to the left until you reach the maximum number of players allowed.

I enjoyed doing it anyway, and I’m trying to do small projects at night to keep me motivated.

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

Doing some C#/CLR stuff

I am busy doing a CBT course with the idea of writing MCTS exams and I started by doing some stuff on C# and the .NET framework that focuses specifically on types. The .NET framework is a strongly typed framework and what we mean by strongly typed is that each variable (or type) that you define or create in you’re code must be assigned to a type. C# in particular is a statically, manifestly and strongly typed language. The .NET framework uses the Common Type System (CTS) which means that the type int in C# and the type Integer in VB.NET refer to the same Int32 type in the CLR. It makes sense therefore that in C# you can define types of int as Int32, which means int is just an alias for Int32. Basic/intrinsic types refer to int’s, bools, long, char, unsigned int, unsigned long, byte, short, sbyte, unsigned short, float and decimal. Its important to understand this because memory in the .NET framework is divided into data structures, named the heap and stack respectively. The basic types are seen as value types that are stored on the stack in a Last In First Out basis. Enumerations, structs and constants are also seen as value types. In contrast user-defined types (objects) are stored on the heap. References to the objects are stored on the stack. If for instance you have an instance of StringBuilder called strb1 and another instance called strb2 and you instantiate strb2 be setting it to strb1 then both instances will point to the same reference on the stack. If you then set the value of strb1 it will have the same value as strb2, and vice verse.

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