Monday, April 14, 2014

Generate Sample XML from XSD using Visual Studio 2012

There was a question on how to generate sample XML from an XSD without using C# or VB.NET Code. I did some googling for a few hours and then stumbled upon a tutorial from Code project which is the reference of this post. Since, Im using Visual Studio 2012, I replicated the steps based from the article.
1. Add a new XSD file to Visual Studio. In my case, I reused the example from MSDN:
 <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://tempuri.org" targetNamespace="http://tempuri.org" elementFormDefault="qualified">  
  <xsd:element name="PurchaseOrder" type="tns:PurchaseOrderType"/>  
  <xsd:complexType name="PurchaseOrderType">  
  <xsd:sequence>  
   <xsd:element name="ShipTo" type="tns:USAddress" maxOccurs="2"/>  
   <xsd:element name="BillTo" type="tns:USAddress"/>  
  </xsd:sequence>  
  <xsd:attribute name="OrderDate" type="xsd:date"/>  
  </xsd:complexType>  
  <xsd:complexType name="USAddress">  
  <xsd:sequence>  
   <xsd:element name="name"  type="xsd:string"/>  
   <xsd:element name="street" type="xsd:string"/>  
   <xsd:element name="city"  type="xsd:string"/>  
   <xsd:element name="state" type="xsd:string"/>  
   <xsd:element name="zip"  type="xsd:integer"/>  
  </xsd:sequence>  
  <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>  
  </xsd:complexType>  
 </xsd:schema>  
2. Open the file using XML Schema Explorer.
3. Right click on the XML Element which is PurchaseOrder and select Generate Sample XML:
4. Here's a sample generated XML File:
 <?xml version="1.0" encoding="utf-8"?>  
 <PurchaseOrder OrderDate="1900-01-01" xmlns="http://tempuri.org">  
  <ShipTo country="US">  
   <name>name1</name>  
   <street>street1</street>  
   <city>city1</city>  
   <state>state1</state>  
   <zip>1</zip>  
  </ShipTo>  
  <ShipTo country="US">  
   <name>name2</name>  
   <street>street2</street>  
   <city>city2</city>  
   <state>state2</state>  
   <zip>-79228162514264337593543950335</zip>  
  </ShipTo>  
  <BillTo country="US">  
   <name>name1</name>  
   <street>street1</street>  
   <city>city1</city>  
   <state>state1</state>  
   <zip>1</zip>  
  </BillTo>  
 </PurchaseOrder>  

Reference using Visual Studio 2010: Generate Sample XML from XSD

Tuesday, April 8, 2014

Apply LINQ Grouping and Sum aggregate to a Datatable Object (VB.NET)

There's a question on vb forums on how to apply LINQ grouping and aggregate function sum to a datatable object. This can be achieved by familiarizing on IGrouping which is a key/value pair interface. Here's how i did it.
VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
Dim dt As New DataTable("tblEntTable")
dt.Columns.Add("ID", GetType(String))
dt.Columns.Add("amount", GetType(Decimal))
dt.Rows.Add(New Object() {"1", 100.51})
dt.Rows.Add(New Object() {"1", 200.52})
dt.Rows.Add(New Object() {"2", 500.24})
dt.Rows.Add(New Object() {"2", 400.31})
dt.Rows.Add(New Object() {"3", 600.88})
dt.Rows.Add(New Object() {"3", 700.11})

Dim result = (From orders In dt.AsEnumerable
    Group orders By ID = orders.Field(Of String)("ID") Into g = Group
    Select New With { Key ID,
        .Amount = g.Sum(Function(r) r.Field(Of Decimal)("amount"))
    }).OrderBy(Function(tkey) tkey.ID).ToList()

dgvSum.DataSource = result

Output:
See C# Version here: Apply LINQ Grouping and Sum aggregate to a Datatable Object (C#)

Simple Array Manipulation using Knockout.js (Add, Remove All, Remove Item, Show)

Most of KnockoutJS features involves binding of a viewmodel object to the a view. But there are special cases where in you want to manipulate ordinary arrays without using ko.observableArray(). So to expound more on this post, here's a sample code below:
KnockoutJS code:
 $(document).ready(function () {  
       function ProductViewModel() {  
         //product array  
         this.Products = [{ id: '1', name: 'Wax' },  
                { id: '2', name: 'Cotton Buds' },  
                { id: '3', name: 'Nova' },  
                { id: '4', name: 'Milo' }  
         ];  

         //insert product
         this.Add = function () {  
           console.log('Insert Activity');  
           this.Products.push({  
             id: '5',  
             name: 'Test'  
           });  
           console.log('Total products: ' + this.Products.length);  
         };  

         //show custom method  
         this.Show = function () {  
           console.log('Display Activity');  
           console.log('Products in array:');            
           ko.utils.arrayForEach(this.Products, function (v) {  
             console.log(v.id + ' ' + v.name);  
           });  
         };  

         //delete product item  
         this.Delete = function() {  
           console.log('Remove Item Activity');  
           var product;  
           if (this.Products.length > 0) {  
             ko.utils.arrayForEach(this.Products, function (item) {  
               //remove last item  
               if (item.id == '4') {  
                 console.log('Item deleted: ' + item.id + ':' + item.name);  
                 product = item;  
               }  
             });  
             ko.utils.arrayRemoveItem(this.Products, product);  
             console.log('Total products: ' + this.Products.length);  
           }  
           else {  
             alert('No Products to remove!');  
           }  
         };  

         //clear array  
         this.DeleteAll = function()  
         {  
           console.log('Remove All Items Activity');  
           if (this.Products.length > 0) {  
             this.Products = [];  
             console.log('Total products: ' + this.Products.length);  
           }  
           else {  
             alert('No Products to remove!');  
           }  
         };  
       }  
       ko.applyBindings(new ProductViewModel());  
     });  
Html markup:
 <button data-bind='click: Add'>Add Item</button>  
 <button data-bind='click: Show'>Show Items</button>  
 <button data-bind='click: Delete'>Delete Item</button>  
 <button data-bind='click: DeleteAll'>Delete All Items</button>  
Sample output using console.log() statements from the Knockout array script:

Friday, April 4, 2014

Unable to get value of the property 'nodeType': object is null or undefined (Knockout JS)

After completing a simple binding using Knockout Javascript framework, I decided to transfer the script tags to the header section of the page. Upon running my code, I stumbled upon an error as stated on the title. I believe, the DOM elements have not been initialized when the binding occurs. One solution I came up was to transfer the view model script inside the document ready function.
 <head runat="server">  
   <title>Integrate jQuery with Knockout!</title>  
   <script type="text/javascript" src="Scripts/knockout-3.1.0.js"></script>  
   <script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>  
   <script type="text/javascript">  
     $(document).ready(function() {  
       var myViewModel = {  
         personName: 'PsychoGenes',  
         personAge: 33  
       };  
       ko.applyBindings(myViewModel);  
     });  
   </script>  
 </head>  

Simple Knockout.js example in ASP.NET Webform

Intrigued with emerging Javascript framework called knockout, I decided to try a simple example myself.
As defined by Wikipedia:
Knockout is a standalone JavaScript implementation of the Model-View-ViewModel pattern with templates. The underlying principles are therefore:
1. A clear separation between domain data, view components and data to be displayed
2. The presence of a clearly defined layer of specialized code to manage the relationships between the view components

The features of Knockout are based on Declarative bindings:
A. Automatic UI refresh (when the data model's state changes, the UI updates automatically)
B. Dependency tracking
C. Templating (using a native template engine although other templating engines can be used, such as jquery.tmpl)


I come to a conclusion that this has similar approach to WPF MVVM.

So, to get started with, download the latest Knockout.js framework here: Knockout Home Page and add reference to your html or aspx markup:
Code:
 <!DOCTYPE html>  
 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head runat="server">  
   <title>Simple Knockout JS</title>    
 </head>  
 <body>  
   <form id="form1" runat="server">  
   <h2>My First KnockoutJS example</h2>  
   <div>  
     My name is: <span data-bind="text: personName"></span><br />  
     My Age is: <span data-bind="text: personAge"></span>  
   </div>  
   <script type="text/javascript" src="Scripts/knockout-3.1.0.js"> </script>  
   <script type="text/javascript">  
     var myViewModel = {  
       personName: 'PsychoGenes',  
       personAge: 33  
     };  
     ko.applyBindings(myViewModel);  
   </script>  
   </form>  
 </body>  
 </html>  
Running aspx page:

Cheers! :)

Thursday, April 3, 2014

Loop through HTML Elements using GeckoFX WebBrowser

C#:
1
2
3
4
5
//Note: this.DomDocument is a class which inherits the GeckoWebBrowser control
foreach (GeckoElement element in this.DomDocument.GetElementsByTagName("span"))
{
   //some codes here
}

VB.NET:
1
2
3
4
'Note: this.DomDocument is a class which inherits the GeckoWebBrowser control        
For Each element As GeckoElement In Me.DomDocument.GetElementsByTagName("span")
    'some codes here
Next

Tuesday, April 1, 2014

Predicate Wrapper Custom Class in C#

Based from this post: Predicate Wrapper Custom Class in VB.NET, here's the equivalent classes in C#.

FindTrack class:
Code:
 public class SystemTrack
    {
        public int ID { get; set; }
        public string Author { get; set; }
        public string Title { get; set; }
        public static bool FindIndexTrackNumber(SystemTrack systrac, int searchArg)
        {
            return systrac.ID.Equals(searchArg);
        }
    }
Predicate Class:
Code:
public delegate bool PredicateWrapperDelegate<T, A>(T item, A argument);
    
    public class PredicateWrapper<T, A>
    {
        private A _argument;

        private PredicateWrapperDelegate<T, A> _wrapperDelegate;

        public PredicateWrapper(A argument, PredicateWrapperDelegate<T, A> wrapperDelegate)
        {
            _argument = argument;
            _wrapperDelegate = wrapperDelegate;
        }

        private bool InnerPredicate(T item)
        {
            return _wrapperDelegate(item, _argument);
        }

        public static implicit operator Predicate<T>(PredicateWrapper<T, A> wrapper)
        {
            return new Predicate<T>(wrapper.InnerPredicate);
        }
    }
Sample usage:
Code:
static void Main(string[] args)
        {
            int SearchNumber = 456;
            int Index;

            List<SystemTrack> SystemTracks = new List<SystemTrack>();
            SystemTracks.Add(new SystemTrack() { ID = 111, Title = "Help Me", Author = "Greg Phil" });
            SystemTracks.Add(new SystemTrack() { ID = 222, Title = "Help Me1", Author = "James Nelson" });
            SystemTracks.Add(new SystemTrack() { ID = 456, Title = "Help Me2", Author = "Tom Enigma" });
            SystemTracks.Add(new SystemTrack() { ID = 12, Title = "Help Me3", Author = "Lord Brown" });
            
            Index = SystemTracks.FindIndex(new PredicateWrapper<SystemTrack,int>(SearchNumber,SystemTrack.FindIndexTrackNumber));

            if(Index != -1)
                Console.WriteLine("Sytem Track has been found at: " + Index);
            else
                Console.WriteLine("System Track not found! ");

            Console.ReadLine();
        }