Ali B's Code Log

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

  • Categories

  •  

    February 2010
    M T W T F S S
    « Jan    
    1234567
    891011121314
    15161718192021
    22232425262728

Sortable ListView

Posted by alibad on January 16, 2010

The Windows Forms ListView control doesn’t provide column sorting functionality. So if you click on a column in a ListView Details view, don’t expect the items to be sorted by the clicked column. To get this functionality, we’ll need to sort the items by the clicked column in the ListView ColumnClick event. I searched online for “Sortable ListView” and I found three MSDN articles talking about this: Sort ListView Column in Visual C#, Sorting ListView Items by Column Using Windows Forms, and How to: Sort ListView Items. None of those implementations takes into consideration the type of the column being sorted. That is, they all do string sorting. If you have dates and numbers in your list, then they’ll not be sorted properly. For example, number 2 will be considered greater than 11. Date time 9/9/1400 will be considered greater than 11/11/2020. Below is an implementation that takes into consideration string, DateTime, int and double types. It can be easily extended to handle more types.

  • Add the SortableListView control to your Windows Form
  • When adding columns to the SortableListView, set the Tag attribute to the type of the column.
sortableListView.Columns.Add("String Field").Tag = typeof(string);
sortableListView.Columns.Add("DateTime Field").Tag = typeof(DateTime);
sortableListView.Columns.Add("Int Field").Tag = typeof(int);
sortableListView.Columns.Add("Double Field").Tag = typeof(double);
  • Now, you can add the items as usual.

For example, the below list is sorted by the DateTime field.

Sortable ListView

Sortable ListView

 Click on the above image to download the SortableListView control.

Posted in .Net, csharp | Tagged: , , , , , , , | Leave a Comment »

PropertGrid Collection Events

Posted by alibad on January 12, 2010

You are using the PropertyGrid control to allow the user to edit the properties of an object at run-time from the UI. This works great and is in fact very reliable since this is the same control used by Visual Studio to display the properties of controls. Now that you are letting the user update the object directly, you’d like to get a PropertyValueChanged event whenever the user changes a property, so you can respond to the user’s action. You’ll be able to do that by adding a PropertValueChanged event to the PropertyGrid, which will get triggered every time a property is changed, unless the property is a collection. So if you have a collection inside the property grid selected object and you’d like to be notified when a property changes in that collection or when an item is added\removed, there is no way to do so with the OOB Microsoft PropertyGrid control. Clearly, the reason why the PropertyValueChanged event is not triggered when a collection is changed is because the reference to the collection object is still the same.

In order to be notified when a property changes inside a collection, follow instructions on this blog. You’ll find this very helpful. However, this solution can’t help you if you’d like to be notified when an item is removed from the collection or when it is added without any of its properties changed. A more generic solution I found was to get a notification when the collection form is closed. This way, I wouldn’t have to worry too much about the steps the user is taking in the collection editor. When the collection form is closed, I get notified and act on the collection object based on its current state.

Solution

First, add a reference to System.Design dll in your Visual Studio project. Create the following class, which represents a collection editor that triggers a MyFormClosed event when the collection editor form is closed.

using System;
using System.ComponentModel.Design;
using System.Windows.Forms;

public class MyCollectionEditor : CollectionEditor
{
    public delegate void MyFormClosedEventHandler(object sender,
                                        FormClosedEventArgs e);

    public static event MyFormClosedEventHandler MyFormClosed;

    public MyCollectionEditor(Type type) : base(type) { }
    protected override CollectionForm CreateCollectionForm()
    {
        CollectionForm collectionForm = base.CreateCollectionForm();
        collectionForm.FormClosed += new FormClosedEventHandler(collection_FormClosed);
        return collectionForm;
    }

    void collection_FormClosed(object sender, FormClosedEventArgs e)
    {
        if (MyFormClosed != null)
        {
            MyFormClosed(this, e);
        }
    }
}

To use the above collection editor for the property grid, you can simply add the following attribute above the collection Property of the object which you set to propertGrid.SelectedObject.

[Editor(typeof(MyCollectionEditor), typeof(UITypeEditor))]

The final part is to create our custom FormClosed event handler and bind it to our custom collection editor as follows:

public MyForm()
{
    InitializeComponent();

    //  Make the property grid listen to collection properties changes
    MyCollectionEditor.MyFormClosed += new MyCollectionEditor.MyFormClosedEventHandler
                                        (propertyGrid_CollectionFormClosed);
}

private void propertyGrid_CollectionFormClosed(object s, FormClosedEventArgs e)
{
    //  Code to run when collection form is closed
}

Note: the solution above is not my idea. I simply took all the changes from this blog and changed the event from PropertyValueChanged to FormClosed.

Posted in .Net, csharp | Tagged: , , , , , , , , | 1 Comment »

Xml Serialization – Tips & Tricks

Posted by alibad on December 29, 2009

Let’s say we have an XSD representing a library with a list of books and employees in it. 

<?xml version="1.0" encoding="utf-8"?>

<xsd:schema id="Lib"
           targetNamespace="http://schemas.ali.com/lib/"
           elementFormDefault="qualified"
           xmlns="http://schemas.ali.com/lib/"
           xmlns:mstns="http://schemas.ali.com/lib/"
           xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           version="1.0"
           attributeFormDefault="unqualified">

  <xsd:element name="Library" type="LibraryType" />

  <xsd:complexType name="LibraryType">
    <xsd:all>
      <xsd:element name="Books" type="BooksType" minOccurs="0" maxOccurs="1" />
      <xsd:element name="Employees" type="EmployeesType" minOccurs="0" maxOccurs="1" />
    </xsd:all>
  </xsd:complexType>

  <xsd:complexType name="BooksType">
    <xsd:sequence minOccurs="0" maxOccurs="unbounded">
      <xsd:element name="Book" type="BookType" />
    </xsd:sequence>
  </xsd:complexType>

  <xsd:complexType name="EmployeesType">
    <xsd:sequence minOccurs="0" maxOccurs="unbounded">
      <xsd:element name="Employee" type="EmployeeType" />
    </xsd:sequence>
  </xsd:complexType>

  <xsd:complexType name="BookType">
    <xsd:attribute name="Title" type="xsd:string" use="required" />
    <xsd:attribute name="Author" type="xsd:string" use="optional" />
  </xsd:complexType>

  <xsd:complexType name="EmployeeType">
    <xsd:attribute name="Name" type="xsd:string" use="required" />
  </xsd:complexType>

</xsd:schema>

Here is a sample Xml using this XSD: 

<?xml version="1.0" encoding="utf-8" ?>

<Library xmlns="http://schemas.ali.com/lib/">
  <Books>
    <Book Title="Book 1" Author="Ali"/>
    <Book Title="Book 2" Author="Sara"/>
  </Books>
  <Employees>
    <Employee Name="Ali"/>
    <Employee Name="Sara"/>
  </Employees>
</Library>

Tip 1 – Generating Code from XSD 

We’d like to have an object representation of this Xml. Thus, we’ll use the Xml Schema Definition tool to generate .Net C# code from the XSD, as follows: 

  • Start Visual Studio Command Prompt
  • Run this command: xsd “path to XSD file” -language:CS /classes /outputdir:”path to output directory”

As a result, a .cs file will be generated and copied to the output directory. Take a look at the file GeneratedLibrary.cs

Tip 2 – Using List<T> instead of array 

The <Books> and <Employees> elements are generated as arrays. So I would like to change those arrays to List<T> objects to make it easier to add items to them instead of having to worry about the size of the array and expanding it. Take a look at the modified class LibraryWithLists.cs. However, this is still not good enough because if I want to create a library with one book, I’ll have to write the following code: 

LibraryType library = new LibraryType();
library.Books = new BooksType();
library.Books.Book = new List<BookType>();
BookType newBook = new BookType();
newBook.Title = "Book 1";
newBook.Author = "Author 1";
library.Books.Book.Add(newBook);

But that doesn’t seem neat enough. I want to write something like: 

LibraryType library = new LibraryType();
library.Books = new List<BookType>();
BookType newBook = new BookType();
newBook.Title = "Book 1";
newBook.Author = "Author 1";
library.Books.Add(newBook);

Thus, I’ll need to get rid of the class BooksType and change it in the declaration from “private BooksType booksField;” to “private List<BookType> booksField;”. However, making that change only is not enough. We need to tell the serializer that the new property is an XmlArrayItem and not an XmlElement. Take a look at the resulting code in Library.cs.  

Tip 3 – Serializing Object to Xml 

Now, we should be able to write code and generate Xml from the object created. For example, writing the code below 

//  Create a library
LibraryType library = new LibraryType();

//  Create Books tag
library.Books = new List<BookType>();

//  Add 5 books to the library
for (int i = 1; i <= 5; i++)
{
    BookType book = new BookType();
    book.Title = string.Format("Book {0}", i);
    book.Author = string.Format("Author {0}", i);
    library.Books.Add(book);
}

//  Create employees tag
library.Employees = new List<EmployeeType>();

//  Add 3 employees to the library
for (int i = 1; i <= 3; i++)
{
    EmployeeType employee = new EmployeeType();
    employee.Name = string.Format("Book {0}", i);
    library.Employees.Add(employee);
}

//  Now that the object is created, serialize it and print out resulting Xml
XmlSerializer serializer = new XmlSerializer(typeof(LibraryType));
StringWriter sw = new StringWriter();
serializer.Serialize(sw, library);
Console.WriteLine("Object serialized to Xml:\n\n{0}", sw.ToString());

would result in the following Xml 

<?xml version="1.0" encoding="utf-16"?>
<Library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.ali.com/lib/">
  <Books>
    <BookType Title="Book 1" Author="Author 1" />
    <BookType Title="Book 2" Author="Author 2" />
    <BookType Title="Book 3" Author="Author 3" />
    <BookType Title="Book 4" Author="Author 4" />
    <BookType Title="Book 5" Author="Author 5" />
  </Books>
  <Employees>
    <EmployeeType Name="Book 1" />
    <EmployeeType Name="Book 2" />
    <EmployeeType Name="Book 3" />
  </Employees>
</Library>

Tip 4 – Serializing without Namespace 

If you look at the serialized Xml above, you’ll notice the extra xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance“,  xmlns:xsd=”http://www.w3.org/2001/XMLSchema”  and xmlns=”http://schemas.ali.com/lib/“. These namespaces are added by default. In my case, I only care about the  xmlns=”http://schemas.ali.com/lib/” which is the url for the XSD of my Xml file. To get rid of the above namespaces and keep the one referring to the XSD, we’ll need to pass our custom XmlSerializerNamespaces object to the Serialize() method. 

//  Create our own xml serializer namespace
//  Avoiding default xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
//  and xmlns:xsd="http://www.w3.org/2001/XMLSchema"
XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); 

//  Add lib namespace with empty prefix
ns.Add("", "http://schemas.ali.com/lib/"); 

//  Now serialize by passing the XmlSerializerNamespaces object
//  as a parameter to the Serialize() method
XmlSerializer serializer = new XmlSerializer(typeof(LibraryType));
StringWriter sw = new StringWriter();
serializer.Serialize(sw, library, ns);
Console.WriteLine("Object serialized to Xml:\n\n{0}", sw.ToString());

If you want to get rid of the namespaces altogether, you can simply write ns.Add(“”, “”) instead of ns.Add(“”, “http://schemas.ali.com/lib/“)

Tip 5 – Changing Encoding

If you look at the generated Xml above, you’ll notice in the Xml declaration that the encoding is set to utf-16. To make this UTF8 encoding, we’ll need to change the Stream object settings before we do the serialization. To do this, replace the code below

StringWriter sw = new StringWriter();
serializer.Serialize(sw, library, ns);

with

//  Serialize the object to Xml with UTF8 encoding
MemoryStream ms = new MemoryStream();
XmlTextWriter xmlTextWriter = new XmlTextWriter(ms, Encoding.UTF8);
xmlTextWriter.Formatting = Formatting.Indented;
serializer.Serialize(xmlTextWriter, library, ns);
ms = (MemoryStream)xmlTextWriter.BaseStream;
string xml = Encoding.UTF8.GetString(ms.ToArray());

To make this more generic, we can create a static method that can do serialization with any encoding.

/// <summary>
/// Serializes the object to Xml based on encoding and name spaces.
/// </summary>
/// <param name="serializer"></param>
/// <param name="encoding"></param>
/// <param name="ns"></param>
/// <param name="objectToSerialize"></param>
/// <returns></returns>
public static string Serialize(XmlSerializer serializer,
                           Encoding encoding,
                           XmlSerializerNamespaces ns,
                           object objectToSerialize)
{
    MemoryStream ms = new MemoryStream();
    XmlTextWriter xmlTextWriter = new XmlTextWriter(ms, encoding);
    xmlTextWriter.Formatting = Formatting.Indented;
    serializer.Serialize(xmlTextWriter, objectToSerialize, ns);
    ms = (MemoryStream)xmlTextWriter.BaseStream;
    return encoding.GetString(ms.ToArray());
}

Now we can write something like the below

string xml = Serialize(serializer, Encoding.UTF8, ns, library);

Tip 6 – Removing Xml Declaration

Let’s say you want to completely remove the Xml Declarartion <?xml Version=”1.0″ Encoding=”utf-8″?> from your serialized Xml. You can do so neatly by using an XmlWriterSettings class and setting its OmitXmlDeclaration property to true. Here is how the above Serialize method would change to support this:

Thus, we can do something like the below to omit the Xml declaration

/// <summary>
/// Serializes the object to Xml based on encoding and name spaces.
/// </summary>
/// <param name="serializer">XmlSerializer object (passing as param to avoid creating one every time)</param>
/// <param name="encoding">The encoding of the serialized Xml</param>
/// <param name="ns">The namespaces to be used by the serializer</param>
/// <param name="omitDeclaration">Whether to omit Xml declarartion or not</param>
/// <param name="objectToSerialize">The object we want to serialize to Xml</param>
/// <returns></returns>
public static string Serialize(XmlSerializer serializer,
                               Encoding encoding,
                               XmlSerializerNamespaces ns,
                               bool omitDeclaration,
                               object objectToSerialize)
{
    MemoryStream ms = new MemoryStream();
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = omitDeclaration;
    settings.Encoding = encoding;
    XmlWriter writer = XmlWriter.Create(ms, settings);
    serializer.Serialize(writer, objectToSerialize, ns);
    return encoding.GetString(ms.ToArray()); ;
}

Tip 7 – Deserializing Xml to Object 

string xml = Serialize(serializer, Encoding.Default, ns, true, library);

This functionality is really cool. Load Xml into an object I can understand and easily interact with. For example, you’d write the following code to read the contents of Xml file “Sample1.xml” and convert it to object LibraryType.

//  Read the first Xml file
TextReader tr = new StreamReader("Sample1.xml");

//  Deserialize the Xml file into a LibraryType object
XmlSerializer serializer = new XmlSerializer(typeof(LibraryType));
LibraryType lib1 = (LibraryType)serializer.Deserialize(tr);

If you look at the object lib1 using the debugger, you’ll see that it’s properly loaded:

LibraryType Object
LibraryType Object

We can add a new book to this object and serialize it back to Xml using the following code

if (lib1.Books == null)
{
    lib1.Books = new List<BookType>();
}

BookType newBook = new BookType();
newBook.Title = "Book 3";
lib1.Books.Add(newBook);

//  Serialize back the library type object and output Xml
StringWriter sw = new StringWriter();
serializer.Serialize(sw, lib1);
Console.WriteLine("{0}:\n\n{1}", "Sample1.xml", sw.ToString());

The resulting Xml would look something like:

<?xml version="1.0" encoding="utf-16"?>
<Library xmlns="http://schemas.ali.com/lib/">
  <Books>
    <Book Title="Book 1" Author="Ali" />
    <Book Title="Book 2" Author="Sara" />
    <Book Title="Book 3" />
  </Books>
  <Employees>
    <Employee Name="Ali" />
    <Employee Name="Sara" />
  </Employees>
</Library>

Tip 8 – Resolving Empty Lists Issue

Now, let’s try the same deserialization code above, but on xml file “Sample2.xml” which has no <Employees> tag. When we deserialize xml into an object then serialize back into Xml, we get the following:

<?xml version="1.0" encoding="utf-16"?>
<Library xmlns="http://schemas.ali.com/lib/">
  <Books>
    <Book Title="Book 1" Author="Ali" />
    <Book Title="Book 2" Author="Sara" />
  </Books>
  <Employees />
</Library>

Notice the extra <Employees/> which we really didn’t intend to have in our Xml. I guess the reason for this issue is because XmlSerializer is initializing all List<T> variables in the object on deserialization (verified that by watching the object in the debugger after deserialization) and thus we’ll get this empty tag <Employees/> when we serialize back. To resolve this issue, there are two workarounds. The first approach is definitely better, but you might find the other approach helpful based on your needs.

Approach 1

Don’t bother with the empty lists. Just clean up their corresponding empty Xml tags on serialization. The method below takes a string represenation of the Xml and removes all empty tags.

/// <summary>
/// //////////Deletes empty Xml tags from the passed xml
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static string CleanEmptyTags(String xml)
{
    Regex regex = new Regex(@"(\s)*<(\w)*(\s)*/>");
    return regex.Replace(xml, string.Empty);
}

With the method above in mind, our Serialize method would change as follows:

public static string Serialize(XmlSerializer serializer,
                               Encoding encoding,
                               XmlSerializerNamespaces ns,
                               bool omitDeclaration,
                               object objectToSerialize)
{
    MemoryStream ms = new MemoryStream();
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = omitDeclaration;
    settings.Encoding = encoding;
    XmlWriter writer = XmlWriter.Create(ms, settings);
    serializer.Serialize(writer, objectToSerialize, ns);
    string xml = encoding.GetString(ms.ToArray());
    xml = CleanEmptyTags(xml);
    return xml;
}

Approach 2

Call the deserialize as usual then set any empty instantiated lists (Count == 0) to null. Here is the static method and its helper method that does the job.


/// <summary>
/// Deserializes the passed Xml then deallocates any instantiated and empty lists.
/// </summary>
/// <param name="serializer"></param>
/// <param name="tr"></param>
/// <param name="objectNamespace"></param>
/// <returns></returns>
public static object Deserialize(XmlSerializer serializer, TextReader tr, string objectNamespace)
{
    //  Deserialize Xml into object
    object objectToReturn = serializer.Deserialize(tr);

    //  Clean up empty lists
    CleanUpEmptyLists(objectToReturn, objectNamespace);

    return objectToReturn;
}

/// <summary>
/// Sets any empty lists in the passed object to null. If the passed object itself is a list,
/// the method returns true of it's empty and false otherwise.
/// </summary>
/// <param name="o"></param>
/// <param name="objectNamespace"></param>
/// <returns></returns>
public static bool CleanUpEmptyLists(object o, string objectNamespace)
{
    //  Skip if the object is already null
    if (o == null)
    {
        return false;
    }

    //  Get the types of the object
    Type type = o.GetType();

    //  If this is an empty list, set it to null
    if (o is IList)
    {
        IList list = (IList)o;

        if (list.Count == 0)
        {
            return true;
        }
        else
        {
            foreach (object obj in list)
            {
                CleanUpEmptyLists(obj, objectNamespace);
            }
        }

        return false;
    }
    //  Ignore any objects that aren't in our namespace for perf reasons
    //  and to avoid getting errors on trying to get into every little detail
    else if (type.Namespace != objectNamespace)
    {
        return false;
    }

    //  Loop over all properties and handle them
    foreach (PropertyInfo property in type.GetProperties())
    {
        //  Get the property value and clean up any empty lists it contains
        object propertyValue = property.GetValue(o, null);
        if (CleanUpEmptyLists(propertyValue, objectNamespace))
        {
            property.SetValue(o, null, null);
        }
    }

    return false;
}

Using the above static method, you can now deserialize as follows:

//  Deserialize the Xml file into a LibraryType object
XmlSerializer serializer = new XmlSerializer(typeof(LibraryType));
LibraryType lib = (LibraryType)Deserialize(serializer, tr, typeof(LibraryType).Namespace);

If you know of a better solution, please let me know.

Source

Download full source code here. You can use it to try out the above tips one by one.

Posted in .Net, XML, csharp | Tagged: , , , , , , , , , , , , | Leave a Comment »

Casting .Net Generic Collections (List<T> Example)

Posted by alibad on December 28, 2009

Let’s say you have a class A that inherits from class P. It’s clear that you can create a new object of type A and cast it to type P

//  Create an object of type A
A a1 = new A();
a1.X = 1;
a1.Y = "test";
a1.Z = DateTime.Now; 

//  Try casting object A to P
P p1 = (P)a1;

 Now, create a List<A> object and add to it object a1. Then try to cast it to List<P>. You would expect it to work, but it doesn’t since C# doesn’t support variance for generic types.  

//  Create listA and add a1 to it
List<A> listA = new List<A>();
listA.Add(a1); 

//  Try casting listA to listP
List<P> listP = (List<P>)listA;

If you try to compile the above code, you’ll get the error message “Cannot convert type ‘System.Collections.Generic.List<A>’ to ‘System.Collections.Generic.List<P>“.  Below is a helper method that allows you to do the casting. 

public static List<T1> Cast<T1, T2>(List<T2> listToCast) where T2 : T1
{
    List<T1> listToReturn = new List<T1>(); 

    foreach (T2 item in listToCast)
    {
        listToReturn.Add(item);
    } 

    return listToReturn;
}

It can be used as follows: 

 List<P> listP = Cast<P, A>(listA);

Here is another example 

List<int> listI = new List<int>();
listI.Add(1);
listI.Add(2); 

List<object> listO = Cast<object, int>(listI); 

foreach (object o in listO)
{
    Console.WriteLine(o);
}

Let’s say we have many other classes B, C, D, E, etc inheriting from class P and for some reason we’re getting the generic list  (be it List<A>, List<B>, …) as an object obj, then it’ll not be possible to do the casting since our helper method above expects a List<T> parameter. Thus, we need a better solution to get around this issue. The helper method below resolves this issue and can be used on any .Net collection implementing the IEnumerable interface. 

Solution

public static List<T> Cast<T>(IEnumerable collection)
{
    List<T> listToReturn = new List<T>(); 

    foreach (object item in collection)
    {
        listToReturn.Add((T)item);
    } 

    return listToReturn;
}

Here is how it can be used: 

List<P> listP = Cast<P>(listA);

or in the case when we have an object passed 

object obj = listA;     //  or listB, listC, ....
if (obj is IEnumerable)
{
    IEnumerable collection = (IEnumerable)obj;
    listP = Cast<P>(collection);
}

Note that if you try to do something like if(obj is  List<P>), it will return false since it will try to do the casting from List<A> to List<P> at runtime. I have a fairly complex scenario using reflection and the above method is working great for me. Let me know if it doesn’t work in certain cases or if you have a better solution. 

Download full src for the above snippets.

Posted in .Net, csharp | Tagged: , , , , , | 2 Comments »

C# Regular Expression Helper

Posted by alibad on December 22, 2009

One component of an application I’m writing uses a lot of regular expressions. To be sure I was using the right regular expressions, I’ve created this simple tiny tool to help me learn and verify regular expressions against my input data. Nothing fancy, but it might help someone out there.

For example, it took me a little while trying to find the proper regular expression to match all comments in an Xml file.

C# Regular Expression Helper

Download exe or source.

Posted in .Net | Tagged: , , , , , | 1 Comment »

Java UPC-A Barcode Generator

Posted by alibad on June 4, 2008

Almost every item we buy or own has a barcode printed on it. We see those barcodes every day, but still we don’t understand what they really mean or how to generate them. That’s why I’ve created an article on Code Project that explains what barcoding is and details the design and implementation of a Java program that generates a barcode label from a given UPC code.

UPC-A Barcode Generator

Enjoy!
Ali B

Posted in Java | Tagged: , , , , | Leave a Comment »

SharePoint CAML IntelliSense

Posted by alibad on May 14, 2008

So you’ve been having some pain trying to put IntelliSense into your frequent CAML (Collaborative Application Markup Language) files. For every new XML file you create, you have to go to its properties and then point to the target schema located at ../TEMPLATE/XML/wss.xsd.

If you don’t know what I mean, usually, in order to display IntelliSense in an XML file opened through Visual Studio, we must link the XML file to an XSD. This is done by going to the file properties and linking to the XSD every time we open the XML file in Visual Studio.

One way to avoid having to link to the XSD every time, is to add the file(s) to a Visual Studio project. However, what if you create CAML files so frequently that you don’t want to add them to a Visual Studio project every time?

The best solution would be to load the XSD whenever a new XML file referencing it is opened; and I have the steps to do that!

Under the Schemas folder of the Visual Studio installation folder (Ex: C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas), there is a file named Catalog.xml.

Reference wss.xsd from it by adding the following tag:

Make sure that href is pointing to the correct location of the wss.xsd file.

<Schema href="C:/Program Files/Common Files/Microsoft Shared/Web Server Extensions/12/TEMPLATE/XML/wss.xsd" targetNamespace="http://schemas.microsoft.com/sharepoint/" />

Enjoy!

Ali B

Posted in .Net, SharePoint | Tagged: , , , , , , | 1 Comment »

OpenGL Geometric Primitives

Posted by alibad on March 1, 2008

The purpose of this interactive program is to make it easier to learn OpenGL Geometric Primitives. There are ten geometric primitives in OpenGL, from a point to a polygon, and all are represented by vertices. This program will give you the flexibility to add and remove vertices in a certain order, and shows you how the choice of the primitive determines how the vertices are to be combined. It can be used in the following ways:

  • Learn OpenGL Geometric Primitives through
    • Interactive Program
    • Source Code
    • Documentation
  • Learn some OpenGL functions designed to work with geometric primitives
  • Draw primitives manually and generate their corresponding OpenGL C code

Here is a view showing Monalisa drawn with lines only…

OpenGL Geoemtric Primitives

Click here to download a video showing how the program can be used.

Enjoy!
Ali B

Posted in C, OpenGL | Tagged: , , , , , , , | Leave a Comment »

C Round Function

Posted by alibad on February 13, 2008

It’s really weird that the C math library (math.h) doesn’t support the round function. It only includes the floor function which rounds down a float to an integer (can also be done by implicit or explicit casting) and the ceil function which rounds the value up.

For example,

int x;

x = floor(1.2);   //  x is set to 1
x = floor(1.8);   //  x is set to 1
x = (int)1.8;     //  x is set to 1 (Explicit Narrowing Conversion)
x = 1.8;          //  x is set to 1 (Implicit Narrowing Conversion)
x = ceil(1.2);    //  x is set to 2
x = ceil(1.8);    //  x is set to 2

The round function is supposed to round the float value to the nearest integer.

x = round(1.2);    //  x is set to 1
x = round(1.8);    //  x is set to 2

This can be done adding a 0.5 to the value and then truncating it.

x = (int)(1.2 + 0.5);  //  x is set to 1
x = (int)(1.8 + 0.5);  //  x is set to 2

We also have to take negative values into consideration by adding -0.5 and then truncating.

x = (int)(-1.2 - 0.5);  //  x is set to -1
x = (int)(-1.8 - 0.5);  //  x is set to -2

Thus, here is the resulting C function:

int round(double number)
{
    return (number >= 0) ? (int)(number + 0.5) : (int)(number - 0.5);
}

Note that you might want to use long rather than int to include support for larger numbers and avoid integer overflow.

That’s it, pretty much primitive, but fun!

Enjoy!
Ali B

Posted in Algorithms, C | Tagged: , , , , , | 4 Comments »

Generating a GUID

Posted by alibad on February 8, 2008

A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated. The term is usually referred to as GUID (Globally Unique Identifier) when working with Microsoft technologies. Otherwise, it is referred to as UUID (Universally Unique Identifier).

Here are multiple ways to generate a GUID:

Visual Studio

Run guidgen.exe. There are two ways to run guidgen:

  1. Open Visual Studio IDE, go to Tool menu, and select the Create Guid menu item. More details here.
  2. Open Visual Studio Command Prompt (from start menu) and enter the following command: guidgen. More details here.

Using any of the methods above, you get the following:

guidgen

You can use any of the 4 formats available, but usually the Registry format (currently selected) is the mostly used one. To generate a new GUID, click New GUID. To copy the GUID to the clipboard, click Copy.

.Net

You can generate a Guid using any .Net language. Here is how you can do it with C#. Click here for more details.

Guid myGuid = System.Guid.NewGuid();

SQL Server

A GUID is represented as type uniqueidentifier in T-SQL. It is generated as shown below. More details here.

SELECT newid()

Online

If none of the above methods are available for you, you can get one generated online at http://www.guidgenerator.com/.

Posted in .Net, Database | Tagged: , , , , | 3 Comments »