Monday, July 16, 2012

Adding Attributes to Generated Classes


ASP.NET MVC 2 adds support for data annotations, implemented via attributes on your model classes.  Depending on your design, you may be using an OR/M tool like Entity Framework or LINQ-to-SQL to generate your entity classes, and you may further be using these entities directly as your Model.  This is fairly common, and alleviates the need to do mapping between POCO domain objects and such entities (though there are certainly pros and cons to using such entities directly).
As an example, the current version of the NerdDinner application (available on CodePlex atnerddinner.codeplex.com) uses Entity Framework for its model.  Thus, there is a NerdDinner.edmx file in the project, and a generated NerdDinner.Models.Dinner class.  Fortunately, these generated classes are marked as partial, so you can extend their behavior via your own partial class in a separate file.  However, if for instance the generated Dinner class has a property Title of type string, you can’t then add your own Title of type string for the purpose of adding data annotations to it, like this:
public partial class Dinner 
{
   [Required] 
   public string Title { get;set; }
}
This will result in a compilation error, because the generated Dinner class already contains a definition of Title.  How then can we add attributes to this generated code?  Do we need to go into the T4 template and add a special case that says if we’re generated a Dinner class and it has a Title property, add this attribute?  Ick.
MetadataType to the Rescue
The MetadataType attribute can be used to define a type which contains attributes (metadata) for a given class.  It is applied to the class you want to add metadata to (Dinner), and it refers to a totally separate class to which you’re free to add whatever methods and properties you like.  Using this attribute, our partial Dinner class might look like this:
[MetadataType(typeof(Dinner_Validation))] 
public partial class Dinner 
{} 
 
public class Dinner_Validation 
{ 
   [Required] 
   public string Title { get; set; } 
}
In this case the Dinner_Validation class is public, but if you were concerned about muddying your API with such classes, it could instead have been created as a private class within Dinner.  Having the validation attributes specified in their own class (with no other responsibilities) complies with the Single Responsibility Principle and makes it easy for you to test that the validation rules you expect are in place via these annotations/attributes.

Friday, June 29, 2012

Serializing just about anything in C# using extensions


I was recently interested in getting C# objects to serialize into XML so that I could save and load a configuration out of a file. Sadly, C# support for XML and serialization is far from the best stuff I’ve seen in programming. But anyway, here’s what this post is about: using DataContract with a bit of extension magic to get anything to be serializable into XML!
One small problem when you use the Serializable attribute of C# is that you cannot serialize dictionary directly and we all know dictionaries are a VERY useful structure to have serialized. One easy way to have serializable dictionaries is to use the DataContract attribute instead. It implies a bit more code compared to the version where you use the Serializable attribute, but not that much more (mostly the WriteObject and ReadObject lines).
I haven’t coded any of this, so thanks to user Loudenvier fromStackoverflow.com! This solution allows you to turn ANY object into an XML string representation. It also allows you to turn that string back into an object representation. Very useful.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static class SerializationExtensions
{
    public static string Serialize<T>(this T obj)
    {
        var serializer = new DataContractSerializer(obj.GetType());
        using (var writer = new StringWriter())
        using (var stm = new XmlTextWriter(writer))
        {
            serializer.WriteObject(stm, obj);
            return writer.ToString();
        }
    }
    public static T Deserialize<T>(this string serialized)
    {
        var serializer = new DataContractSerializer(typeof(T));
        using (var reader = new StringReader(serialized))
        using (var stm = new XmlTextReader(reader))
        {
            return (T)serializer.ReadObject(stm);
        }
    }
}
How to use example
1
2
3
4
5
6
7
8
9
// dictionary to serialize to string
Dictionary<string, object> myDict = new Dictionary<string, object>();
// add items to the dictionary...
myDict.Add(...);
// serialization is straight-forward
string serialized = myDict.Serialize();
...
// deserialization is just as simple
Dictionary<string, object> myDictCopy = serialized.Deserialize<Dictionary<string,object>>();

Monday, May 7, 2012

Software Design Principles



There are many design principles that have become best practices over the years. Using these principles we can develop scalable and maintainable enterprise application with time tested approaches.
  1. Keep It Simple Stupid (KISS)
    The main goal here is keep things simple. Avoiding unnecessary complexity will help to keep it clear and easy to understand. Also this principle will help in maintenance; if it is simple then also easy to modify. Usually the simplest solution is the best solution.
  2. Don’t Repeat Yourself (DRY)
    This principle states to not repeat things. We can abstract out repeated things and keep it at some common place where everybody can access it. We can also make common (repeating) things as general, so that it is available to all.
  3. Separation of Concerns (SoC)
    Separating things into discrete responsibilities increases reusability, maintenance and also testability. Here concerns refer to specific features or behavior of the system.
    For example, Object Oriented programming languages such as C++, C# and Java (to name a few) can separate concerns into objects. A Design Pattern like MVC (Model-View-Controller) can separate content from presentation and data processing (model) from content. Service Oriented design can separate concerns into services. Procedural programming languages such as C can separate concerns into procedures. Aspect Oriented programming languages can separate concerns into aspects and objects.
  4. The Pareto Principle
    The famous pareto principle states that 80% of effects comes from 20% of causes, i.e. 80% of sales comes from 20% of customers. The principle is named after Italian economist Vilfredo Pareto, who observed in 1906 that 80% of land in Italy is owned by 20% of the population. It can help to resist efforts to correct and optimize designs beyond critical 20%. So 80% focus is on 20% part of the stuff.
    In software engineering Pareto principle can be applied to optimization efforts. For example, Microsoft noted that by fixing the top 20% of the most reported bugs, 80% of the errors and crashes would be eliminated.
  5. The Robustness Principle
    The Robustness Principle states that, “Be liberal in what you accept, and be conservative in what you send”. In other words, code that sends commands or data to other parts of the system should conform completely to the specifications, but code that receives input should accept non-conformant input as long as the meaning is clear.
    For example, TCP implementation follows the principle.
  6. You Ain’t Gonna Need It (YAGNI)
    It is the principle in extreme programming, states that programmers should not add functionality until it is necessary. It tells programmers that always implement things when you actually need them, never when you just foresee that you need them. Even if you are sure that you will need it later on, do not implement it now. The principle is actually emerged from “Extreme Programming” methodologies.
  7. Loose Coupling and High Cohesion
    Coupling means links between separate units of a program. In OOPs, if two classes depend closely on many details of each other, we say they are tightly coupled.
    Coupling is a measure of the interdependence between types/entities. If every object has a reference to every other object, then there is tight coupling, which is undesirable. Because there’s potentially too much information flow between objects. Loose coupling is desirable. It means that objects work more independently of each other. Loose coupling minimizes the “ripple effect” where changes in one class cause necessity for changes in other classes
    Cohesion refers to the number and diversity of tasks that a class is designed for. If a class is responsible for a few related logical tasks, we say it has high cohesion.
    Cohesion is a measurement of strengths of the association of variables and methods within a class. High cohesion is desirable because it means the class does one job well. Low cohesion is undesirable because it indicates that there are elements in the class which have little to do with each other. Modules whose elements are strongly and genuinely related to each other are desired. Each method should also be highly cohesive. Most methods have only one function to perform. Don’t add extra instructions into methods that cause it to perform more than one function
    Loose Coupling has following advantages:
    • We can understand concerned class without reading other classes
    • We can change one class without affecting other classes
    • Loose Coupling improves maintainability
    High Cohesion has following advantages:
    • We can easily understand what is the purpose of class or method
    • High Cohesion makes it easier to use descriptive names
    • We can easily reuse classes or methods
  8. SOLID Principles
    • Single Responsibility Principle (SRP)
      The Principle states that every object should have single responsibility, and the responsibility (reason to change) should be entirely encapsulated by the class. So a class or module should have one and only one reason to change.
      For example, we have a print report module. There are utmost two reasons to change the module. First is content of report is changed. Second is format of report is changed.
    • Open Closed Principle (OCP)
      Software entities (i.e. classes, functions or modules) should be open for extension but closed for modification. Normally we close entities modification for providing backward compatibility (regression testing) and open entities extension for extending existing entities with new functionalities.
      For example, we can implement this principle by using Abstract classes, and thus enforcing concrete classes extend abstract classes rather than changing it. Some of the design patterns that supports this principle is template pattern and strategy pattern.
      In .NET Framework Microsoft has further supported this principle by providing partial classes/methods and extension methods. You can extend existing code by using these two new features in .NET.
    • Liskov’s Substitution Principle (LSP)
      The principle states that derived types must be completely substitutable for their base types. It is just an extension of Open Closed Principle in terms of behavior. Meaning that the derived types must extend without changing behavior of base types, so that derived types is replaceable with base types (No need to change code).
      For example, we have method called StoreAddress(Address address) which accepts type “Address” as input parameter and stores it into the data store. Now if we make derived type from the “Address” type named “HomeAddress” then I should be able to call the same method by passing type “HomeAddress” and it stores correctly into the data store.
    • Interface Segregation Principle (ISP)
      In nutshell, the principle states that “Clients should not be forced to depend upon interfaces that they don’t use”. When we simplify it states that when interface is too heavy, just break it down to the smaller and more specific interfaces which is client oriented so that clients should only worry about their concerned part.
      For example if we have <> interface which has “fly()” method and is implemented by Duck class. Now if we have wooden duck?
    • Dependency Inversion Principle (DIP) [also known as Inversion of Control or Hollywood Principle: Don’t call us, we’ll call you or Dependency Injection]
      The Dependency Inversion principle refers to specific form of decoupling where conventional dependency relationship established from high level. The principle states two things.
      1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
      2. Abstractions should not depend upon details. Details should depend upon abstractions.
      The main goal of dependency inversion principle is to decouple high-level components from low-level components in such a manner that reuse of low-level component implementations become possible.
      For example Adapter Pattern does the same thing. The high-level class defines its own adapter interface which is the abstraction that the high-level class depends on. The adaptee implementation also depends on the adapter interface abstraction. The high-level has no dependency to the low-level module since it only uses low-level indirectly through the adapter interface by working polymorphic methods to the interface which are implemented by the adaptee and its low-level module.


Friday, May 4, 2012

Add javascript from codebehind C#

this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ScriptName", "<script language=JavaScript>window.print();</script>");

Run Process in background / hidden


// Run Process in background / hidden
//txtRebuildFolderBrowser.Text stands for a specific folder ex: C:\thedirectory
//rebuildFileName stands for a specific file eX: the.exe or the.bat

System.Diagnostics.ProcessStartInfo i = new
System.Diagnostics.ProcessStartInfo(txtRebuildFolderBrowser.Text + "\\" + rebuildFileName);
i.CreateNoWindow = true;
i.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(i); // inicia o processo do rebuild
p.WaitForExit(); //aguarda o processo terminar
MessageBox.Show("Process Complete","Process Info:");

Converting from string to type


//Converting from string to type
//Generic code for converting a string to a specific type

public static T FromString<T>(string text)
        {
            try
            {
                return (T)Convert.ChangeType(text, typeof(T), CultureInfo.InvariantCulture);
            }
            catch
            {
                return default(T);
            }
        }

public static T FromXmlAttribute<T>(XmlNode node, string attributeName)
        {
            if(node == null)
                throw new ArgumentNullException("node");

            if(String.IsNullOrEmpty(attributeName))
                throw new ArgumentException("Cannot be null or empty", "attributeName");

            XmlAttribute attribute = node.Attributes[attributeName];
            if(attribute == null)
                return default(T);

            return FromString<T>(attribute.Value);
        }

public static T FromXAttribute<T>(XElement element, string attributeName)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            if (String.IsNullOrEmpty(attributeName))
                throw new ArgumentException("Cannot be null or empty", "attributeName");

            XAttribute attribute = element.Attribute(attributeName);
            if (attribute == null)
                return default(T);

            return FromString<T>(attribute.Value);
        }

Call a command line function from C#



            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.FileName = "cmd";
            p.StartInfo.Arguments = "/C ipconfig /all";
            p.Start();
            StreamReader sr = p.StandardOutput;
        
            while ((sr.ReadLine()) != null)
            {
                Console.WriteLine(sr.ReadLine());
            }