johanvw's blog

johanvw's blog

This is a blog about .NET and other fun stuff :)
datetime formatting c#

found this awesome article on datetime formatting in c# .. was busy working on something the other day where I needed to find the time for a specific DateTime object. Question was, do I need to be concerned about 'AM' or 'PM'? Answer was: 'Not if you use the .TimeOfDay property' (it give 24 hour time) ..

The other day someone also asked me something along the lines of "what's the formatting again to display the date in 'such' format?" .. I'm gonna browse to my own blog the next time :p

http://www.daniweb.com/code/snippet184.html#

 

Posted: Jul 07 2009, 11:48 AM by johanvw | with no comments
Filed under:
sadev presentation : SOLID design

Earlier this week I was honored to form part of the team presenting at this month's SADEV meeting .. we covered a very interesting topic, the design principles commonly referred to as the S.O.L.I.D principles for software design.

"Robert C. Martin, also known as "Uncle Bob", compiled a list of 5 principles of class design that became known as the SOLID Principles of Class Design.  In this first session of a two part series we take a look at the first three principles:  Single Responsibility Principle, Open Closed Principle and Liskov Substitution Principle.  Join us as we take a look at these principles and discuss their application. "

I'm posting both the code and presentation file together with this article. To everyone that was there and could make it, thank for a wonderful time and I hope it was as much fun as it was for me... :) Rock on !!

Johan 

Gridview: no select button

Here's a handy code-snippet to replace the functionality provided by a select button in a gridview. Clicking anywhere on the row will select the row.

Place this code in the 'RowDataBound' event for the gridview:

   1:  if (e.Row.RowType == DataControlRowType.DataRow)
   2:  {
   3:      e.Row.Attributes.Add("onclick",
   4:      ClientScript.GetPostBackEventReference(GridView1, "Select$" +
   5:      e.Row.RowIndex.ToString()));
   6:      e.Row.Style.Add("cursor", "pointer");
   7:  }

and replace on LOC 4 'GridView1' with the id of your own gridview ..

Exploring the Abstract Factory Design Pattern

The patterns described in the book 'Design Patterns: Elements of Reusable Object-Oriented Software" written by the 'Gang of Four' (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides)  are generally considered the foundation for all other patterns.

These patterns can be categorized into three groups:

  • Creational
  • Structural
  • Behavioral

In this post we'll be focusing on one of the Creational Patterns:

THE ABSTRACT FACTORY

Purpose

The Abstract Factory provides an interface that can delegate object creation calls to one or more concrete classes with the purpose to deliver specific objects.

More simply put, it provides an interface for creating a family of related objects without having to specify the object's concrete class.

Characteristics

  • An object maker that can typically produce more than one type of object.
  • Each object produced by the factory is known to the receiver of the created object only by that object's interface, not by the object's concrete implementation.
  • The different types of objects that can be produced are related, meaning they are from a common family.

Why to use this pattern

  • Easy to switch between product families
  • It's easy to extend upon the range of products and their families.

When to use this pattern

  • The creation of the objects should be independent of the client utilizing them.
  • The client should be capable of using multiple families of objects
  • Families of objects must be used together (enforcing the constraint)
  • Libraries must be published without exposing implementation details, or when there is a need to abstract from the products' implementation details.
  • Concrete classes should be decoupled from clients.

How does it look like?

There'd be an interface defining all the methods that any of the Factory classes can do. Typically something like IFactory.cs. Remember, a Factory is responsible for creating / 'manufacturing' specific types of objects.

So, these methods would return an object implementing from a specific object interface, like IProduct for example.

   1:  public interface IFactory
   2:  {
   3:      IProduct CreateProduct();
   4:  } 

Next, you would create a factory class implementing that factory interface. The method implementation would create an instance of a specific object, like ProductA, and then return that object after perhaps performing some logic on it as well.

Since the factory method "return an interface" (please forgive me for putting it like that) and not a specific object type, you can return any kind of object as long as it implements the expected interface.

So an implemented method inside FactoryA.cs (implementing interface IFactory) could look like this:

   1:  public class FactoryA : IFactory
   2:  {    
   3:      public IProduct CreateProduct()
   4:      {
   5:          // ProductA implements the IProduct interface
   6:          return new ProductA;
   7:      }
   8:  }

and another factory class, FactoryB, would look almost identical:

   1:  public class FactoryB : IFactory
   2:  {
   3:      public IProduct CreateProduct()
   4:      {
   5:          // ProductB implements the IProduct interface
   6:          return new ProductB;
   7:      }
   8:  } 

For a simple example, you'd have 2 separate interfaces: one for the factory (IFactory.cs) and one for the products being created (IProduct.cs)

AbsFactory3

From there on, things get a bit easier: you have the factories all set up and ready to produce specific objects. To create a specific object (product), you need to create an instance of the factory that can produce the kind of product you're looking for, and then call the method to produce it.

In our example, we can do that as follow:

   1:  IFactory factory1 = new FactoryA();
   2:   
   3:  // create a 'ProductA' object
   4:  IProduct product1 = factory1.CreateProduct();


Since we know that 'FactoryA' can only produce 'ProductA' objects, we can be confident that product1 will behave as a 'ProductA' object, meaning that any method being called on product1 will ultimately execute the code defined in ProductA.cs.

Note that no matter if we created a 'ProductA' object or a 'ProductB' object, it will have the same method contract as defined in the IProduct interface.

That corresponds with the second characteristic we mentioned earlier:

Each object produced by the factory is known to the receiver of the created object only by that object's interface, not by the object's concrete implementation.

Please let me know if you want a copy of this article's code and feel free to comment!

Scott Hanselman - Cape Town

Scott Hanselman is comming to Cape Town, South Africa on 17 December 2008 to speak about 'Building a Real Website with ASP.NET MVC: Suffering and Pain and Joy' at the sadeveloper.net event.

I can't wait - please remember to RSVP here by adding a comment for the event!

New .NET Logo

There's a brand new .NET logo out:

ndotnetlogo

"We needed a logo that was in sync with the key values that we want .NET to stand for: consistency, robustness and great user experiences.

We also wanted a logo that conformed to the design principles that are driving Microsoft’s brand identity evolution and is reflected in newer brands such as Silverlight, Surface and more. 

Finally, we needed a logo that is more strongly aligned with the portfolio of brands that .NET is most strongly aligned with: Silverlight, Visual Studio and our server products."

- source

Posted: Oct 27 2008, 10:02 AM by johanvw | with no comments
Filed under:
Find objects in Generic List using Nullable Types

There's quite a few ways to find an object inside a Generic List, but we'll focus on one specific method List<T>.Find() and investigate it's behavior when working with value types and reference types.

List<T>.Find Method - Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.

A simple example is a generic list consisting of integers:

   1:  List<int> intList1 = new List<int>(new int[] {1,2,3,4});
   2:  int intResult = intList1.Find
(
delegate(int intpar1){return intpar1 == 3}
);

which would basically return the integer if it was found in the list.

However, consider the response when the integer wasn't found:

When searching a list containing value types, make sure the default value for the type does not satisfy the search predicate. Otherwise, there is no way to distinguish between a default value indicating that no match was found and a list element that happens to have the default value for the type. If the default value satisfies the search predicate, use the FindIndex method instead.

- extract from MSDN help

so, be carefull when using .Find() when your search criteria is literally the default value for the type. (This is especially relevant when using value types.)

One way of handling this, is to turn your value types into nullable types. That way you can avoid 0 being returned when your integer wasn't found in the list:

        List<Nullable<int>> intListTemp2 = new List<int?>
(
new int?[] { 1, 2, 3, 4 }
);
        int? intFoundAnon = intListTemp2.Find
(
delegate(int? intInput1){return intInput1 == 5;}
);

instead of 0, null is returned if the value wasn't found in the list of value types.

This can be very usefull when working with database null values being used in columns that have types such as int or DateTime.

*** There's another thing to keep in mind when searching for a reference type inside a list.

Rerence equality vs value equality.

Value equality is the generally understood meaning of equality: it means that two objects contain the same values. For example, two integers with the value of 2 have value equality.

Reference equality means that there are not two objects to compare. Instead, there are two object references and both of them refer to the same object.

When your doing a .Find() on a value type (such as int, bool, char, datetime, enum, decimal, ..) the elements are compared based on the value itself.  But if you do a .Find() on a reference type (like a custom class), you'd be looking for objects that have the same reference.

To explain it more: even if you compare two objects with the same values for all it's properties, it won't necessarily return true.

   1:  Patient patTemp1 = new Patient("Johan");
   2:  Patient patTemp2 = new Patient("Johan");
   3:   
   4:  // this will return false
   5:  bool blResult = patTemp1.Equals(patTemp2);

Instead, you should make sure your custom class overrides the Equals() method and define how the two objects should be compared.

   1:  class Patient : IComparable
   2:  public override bool Equals(object obj)
   3:  {
   4:      return this.Firstname == ((Patient) obj).Firstname;
   5:  }
 

And remember to make sure your custom class inherits from the interface "IComparable" as well.

If you remember to do that, you can do a Find() on your Generic List and it will play along as expected (won't return false every time)

   1:  List<Patient> PatientList = new List<Patient>
   2:  (
   3:      new Patient[] 
   4:          { new Patient("John Smith"), new Patient("Victor Matfield") 
   5:      }
   6:  );
   7:   
   8:  bool blresult = PatientList.Exists
   9:  (
  10:      delegate(Patient pTempSearch) 
  11:      { 
  12:          return pTempSearch.Equals(new Patient("John Smith")); 
  13:      }
  14:  );

The following helper method takes in an array of custom types and check if the specified object was found.

   1:  public bool ArrayContains<T>(T[] array, T value) 
   2:  {            
   3:      return array != null &&
   4:      Array.Exists(array, delegate(T tTemp) 
   5:      {
   6:          return tTemp.Equals(value);
   7:      });
   8:  } 
   9:  bool blResult = ArrayContains<Patient>(PatientArray, Patient1);

I hope this helps someone understand a bit better on what's going on when using the Find() method on a Generic List. Please post a comment if you did find this useful or have any feedback! :)

Posted: Oct 24 2008, 01:59 PM by johanvw | with 7 comment(s)
Filed under:
C# Generics when working with Enum

When working with enumerations inside the .net framework (which handles them as a value type), it can be tedious to constantly call Enum.Parse on the input to find the value.

Let's say you've got the following simple enums:

   1:  public enum Title : int {Mr, Mrs, Ms};
   2:  public enum Gender : int {Male, Female};
 
and your using 
 
   1:  Title foundTitle = (Title)Enum.Parse(typeof(Title), "Mr");
   2:  Gender foundGender = (Gender)Enum.Parse(typeof(Gender),"Male");
 
to determine the enums for the provided values "Mr" and "Male", there's a lot of casting going around.
 
By applying generics on these enumerations, you can end up with the following little helper class to hopefully make things a little easier:
 
   1:  public static class enumFinder<T>
   2:  {
   3:       public static T ParseMe(string value)
   4:      {
   5:          T foundEnum = (T)Enum.Parse(typeof(T),value);
   6:          return foundEnum;
   7:      }
   8:  }
 
You can use this helper class to achieve the same result:
 
   1:  Title foundTitle = enumFinder<Title>.ParseMe("Mr");
   2:  Gender foundGender = enumFinder<Gender>.ParseMe("Male");

You could also use Generics to write another usefull helper method that find all the values for any given enum:

   1:  public static IList<T> GetValues()
   2:  {
   3:      IList<T> ListOfValues = new List<T>();
   4:      foreach (object value in Enum.GetValues(typeof(T)))
   5:      {
   6:          ListOfValues.Add((T) value);
   7:       }
   8:       return ListOfValues;
   9:  }

You can call the method like this:

   1:  IList<Title> mytitleList = enumFinder<Title>.GetValues();
   2:  IList<Gender> mygenderList = enumFinder<Gender>.GetValues();

which will return the collection of defined values for the specified enumeration.

Hope these little helper methods will help make life a bit easier and bring the point across on how using generics can make coding (and life?) easier.

Posted: Oct 21 2008, 09:35 AM by johanvw | with 8 comment(s)
Filed under:
Generic type aliasing

When working with C# Generics, it is sometimes useful to alias a particular combination of specific types.

You can do that through the using statement:

   1:  using lRange = System.Collections.Generic.List<int>;
   2:   
   3:  lRange lrTemp = new lRange();
   4:  lrTemp.Add(1);
   5:  lrTemp.Add(2);
   6:  lblResults.Text = lrTemp[0].ToString();

Note that the scope of aliasing is the scope of the file, so you have to repeat aliasing across the project files in the same way you would with using namespaces.

Posted: Oct 09 2008, 07:53 AM by johanvw | with no comments
Filed under:
setting the path variable in Vista

When using XP and older versions of the Windows operating system, it was a case of editing the autoexec.bat file and setting the PATH variable there.

[edit: thanks to ahmeds for pointing out in his comment, this was not the only way of setting it for these products]

When using Vista tho, here's a way of doing it:

Control Panel -> System -> Advanced System Settings -> 'Environment Variables' button .. scroll down until you see path and click the edit button

hope this saves someone a few frustrating seconds or even minutes ;)

Posted: Oct 08 2008, 09:22 AM by johanvw | with 2 comment(s)
Filed under:
MSSQL - Search Trick

Found this helpful trick for searching a database's SP's that contain certain text:

   1:  SELECT ROUTINE_NAME, ROUTINE_DEFINITION 
   2:      FROM INFORMATION_SCHEMA.ROUTINES 
   3:      WHERE ROUTINE_DEFINITION LIKE '%Whatever you looking for%' 
   4:      AND ROUTINE_TYPE='PROCEDURE'

link: databases.aspfaq.com

Posted: Oct 01 2008, 09:08 AM by johanvw | with 2 comment(s) |
Filed under:
Ever wondered how to find the application based file path with asp.net?

Linking to a resource from a reusable control in different levels in your web app folder tree can be a bit more challenging than you'd expect.
There's a number of ways to go about:
Absolute Paths

Hardcoding the path to the resource
- http://www.mysite.co.za/1/page.aspx
- not acceptable for reusable components
- generally not a good idea or something I would suggest.

Relative Paths

This option allows for a more dynamic approach. You'd have less of a headache when trying to rollout to a different server (for example)
Now, there's different ways to go about and using relative paths:

  • current level based - a/b/c/page.ext - doesn't work for reusable components
  • root based - /a/b/c/page.ext - that works good in some cases but not in every 
  • app based - ~/a/b/c/page.ext - perfect when you can use it

When using root based paths
Be carefull when using root based paths.
When you work on a project you often use built-in WebServer of the Visual Studio and your app runs on http://localhost:XXXX/. Everything seems to be working fine with the root based paths. Now it's time to deploy your app on a test machine. You deploy it on http://test/myBestApp/. Now all your root based paths are pointing to http://test/Page.ext instead of http://test/myBestApp/Page.ext. That's a good reason not to use root based paths.

~ (tilde)

That's a good solution that comes out of the box and takes care finding the root of your app. Ok, but what if need to build the URL on the fly like in this example:

~/Item.ext?id=<% Request.QueryString[ "id" ] %>

This won't work if you put it in a Hyperlink like this:


<asp:HyperLink ID = "hlnkItemDetails" runat = "server" NavigateUrl = '~/Item.ext?id=<% Request.QueryString[ "id" ] %>' />

Don't think about changing the quotation marks. It won't work however you try.



The universal solution - Page.ResolveUrl

Now that's what can help you in every situation (or at least all cases I can think of). Think about this case: you have a custom control in ~/items/controls/ItemViewControl.ascx. This control is used in ~/Default.aspx and ~/items/Default.aspx. You need to link to ~/items/Item.aspx?id=<query string param> from ItemViewControl.ascx. You can't use ~ (tilde), root based, current folder relative or absolute path for some of the reasons written above. This is where Page.ResoulveUrl comes into help. You can build your link in this way:

<a href='<% String.Format( "{0}?id={1}", Page.ResolveUrl( "~/items/Item.aspx" ), Request.QueryString[ "id" ] ) %>' />

Yes, it is a bit complicated, but at least you won't be worried about broken links and they will work as expected wherever you put them.

Posted: Oct 01 2008, 08:52 AM by johanvw | with no comments
Filed under:
ie6, ie7 cookie / session and cross domain issue

Here's the scenario:

let's say you've got a website that's dropping cookies (authentication for example) onto the client's computer, but your also relying on cookies created from other domains via pages hosted in IFRAMES on your site, there's something to keep in mind.

P3P (Platform for Privacy Preferences) - Apparently, this w3c standard is is necessary to make sure your third-party cookies does get dropped correctly when using ie client. (it's mandatory for ie)

Firefox (at this moment) doesn't view this http header as mandatory, but more as optional. This explains why your cross domain cookies can be set when accessing the site via Firefox.

Per default, ie would view these 'other domain' cookies as Third-party cookies and not drop them at all if you didn't specify a P3P policy in the headers.

To check if this applies to your scenario, see if you can access these other-domain cookies after overriding the way ie handles cookies:

in ie - tools - internet options - privacy - advanced - check the 'Override automatic cookie handling' and make sure 'Accept' option is selected for 'Third-party Cookies'

image

If you can access the cookies after changing this setting, then this post applies.

Of course, you can't expect from the end-user to go and set these when using your site. That's why you'll have to include the P3P headers into your HTTP Response.

usefull links:

Marco.org

P3P Compact Policy

forums.microsoft.com

Posted: Sep 30 2008, 01:16 PM by johanvw | with 2 comment(s)
Filed under:
Data transform / mapping using .NET Attribute and Reflection

Found this really cool article on Shahed Khan's (MVP C#) blog about how to apply .NET Attributes to existing classes so you can control the Mapping of data between a source and target data structrue. Using .NET Reflection, the "source party" can analyze these classes during runtime and can request a specific transformation / mapping of the class for itself.

It's very interesting and relevant stuff..

Posted: Aug 04 2008, 09:05 AM by johanvw | with no comments
Filed under:
Cargo-cult Programming

Found this interesting post over at Scott Hanselman's Blog about the dangers of just 'understanding' what the code does, and not doing any effort in finding out 'how' it does it.

At the core - that's what cargo cult programming is about.

He mentions the following (taken from a series of articles)

During the Second World War, the Americans set up airstrips on various tiny islands in the Pacific.  After the war was over and the Americans went home, the natives did a perfectly sensible thing -- they dressed themselves up as ground traffic controllers and waved those sticks around.  They mistook cause and effect -- they assumed that the guys waving the sticks were the ones making the planes full of supplies appear, and that if only they could get it right, they could pull the same trick.  From our perspective, we know that it's the other way around -- the guys with the sticks are there because the planes need them to land.  No planes, no guys.

Isn't that how a lot of guys are developing today as well (myself included at some stage!) ..

It's important to develop with the mindset of first taking the backend (architecture .. layers, web services and how they connect with each other) into consideration and then develop a front end for that, instead of the other way round. I know it's a basic principle, but I think it's well represented by the above story. "If we develop a good front-end, the back-end will follow" :p

More Posts Next page »