Wednesday, April 20, 2016

Copy single element of an array to another array without using loop

Simple solution is to use Array.Copy() method.
C# Code
1
2
3
int[] sourceArray = {1,2,3,4,5,6,7,8,9,10};
int[] destinationArray = new int[1];
Array.Copy(sourceArray,3,destinationArray,0,1);

VB.NET Code
1
2
3
Dim sourceArray As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Dim b As Integer() = New Integer(1) {}
Array.Copy(sourceArray, 3, destinationArray, 0, 1)

Saturday, April 16, 2016

WPF DataGrid Column Resize Event

Windows Forms DataGridView has a built-in event when the DataGridViewCell is resized but missing in WPF. To add an event for the DataGridCell when it is resized, a solution is to add an EventSetter to the DataGridCell style and then set the values of Handler and Event respectively.
1
2
3
4
5
<DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
        <EventSetter Event="SizeChanged" Handler="Cell_SizedChanged" />
    </Style>
</DataGrid.CellStyle>
In your code behind, add definition to the Handler based from the defined style.
1
2
3
4
5
private void Cell_SizedChanged(object sender, SizeChangedEventArgs e)
{
    DataGridCell cell = (DataGridCell)sender;
    //TODO: Add your code here....
}

Thursday, April 14, 2016

WebBrowser click html element with data-id attribute

Here's how you click an <li> element with data-id attribute. Given that the element's behavior includes navigating to another page.
VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
If webBrowser1.Document IsNot Nothing Then
    Dim elems As HtmlElementCollection = 
webBrowser1.Document.GetElementsByTagName("li")
    For Each elem As HtmlElement In elems
        Dim nameStr As String = elem.GetAttribute("data-id")
        If ((nameStr IsNot Nothing) And (nameStr.Length <> 0)) Then
            If nameStr = "5" Then
                elem.InvokeMember("click")
            End If
        End If
    Next
End If

C#
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
if (webBrowser1.Document != null)
{
    HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("li");
    foreach (HtmlElement elem in elems)
    {
        String nameStr = elem.GetAttribute("data-id");
        if (nameStr != null && nameStr.Length != 0)
        {
            if (nameStr == "5")
            {
                elem.InvokeMember("click"); 
            }
        }
    }
}

Test Page: Gumtree.co.za

Wednesday, April 13, 2016

Get latest order for each customer using LINQ to SQL

Given the task that my client requires me to retrieve all customers and their recent orders made for their report, the solution for this using LINQ is to join two tables namely Customers and Orders. Then the script retrieves the latest order code in the subquery with the condition that it should match with the customer id in the outer query. The subquery also applies arranging the orders made according to recent date and then select the latest using FirstOrDefault() which is the equivalent to Top 1.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var results = (from order in _context.Orders
               join cus in _context.Customers
               on order.CustomerID equals cus.CustomerID
               where (order.OrderID == (
                  from subOrder in _context.Orders
                  where subOrder.CustomerID == order.CustomerID
                  orderby subOrder.OrderDate descending
                  select subOrder.OrderID).FirstOrDefault())
               select new
               {
                   ContactName = cus.ContactName,
                   OrderID = order.OrderID,
                   OrderDate = order.OrderDate
               }).OrderBy(e => e.ContactName).ToList();

Tuesday, April 12, 2016

Apply LINQ Grouping and Sum aggregate to a Datatable Object (C#)

Here's the C# version of this post. Apply LINQ Grouping and Sum aggregate to a Datatable Object (VB.NET)
Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
DataTable dt = new DataTable("tblEntTable");
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("amount", typeof(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
});
 
var results = (from orders in dt.AsEnumerable()
            group orders by orders.Field<string>("ID") into g
            select new{
                ID = g.Key,
                Amount = g.Sum(r => r.Field<decimal>("amount"))
            }).OrderBy(tkey => tkey.ID).ToList();
 
dgvSum.DataSource = results;

Output:

Saturday, April 9, 2016

Get Microsoft Excel cell value using C#

In this article, I'll show you two options to get the cell value of excel using C#. Given that you are using VSTO and have referenced the assembly Microsoft.Office.Interop.Excel.

1
2
3
var cellValue = (string)(xlWorkSheet.Cells[3, 6] as Excel.Range).Value2;
//or this
var cellValue = xlWorkSheet.get_Range("F3", Type.Missing).Value2;

Note: xlWorkSheet is an Excel Worksheet object.

Wednesday, April 6, 2016

Implement IEnumerable<T> interface in C# and VB.NET

Hello, According to MSDN, IEnumerable<T> Interface exposes the enumerator, which supports a simple iteration over a collection of a specified type. Collections such as List<T> implements this interface. For this demo, I created a simple class that implements IEnumerable<string>. You can use concrete types instead of string or ordinary data types. Presented are two classes in different languages (C# and VB.NET) that implements the interface. Notice that in VB.NET, the yield functionality is applied in an Iterator function.

C#.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
namespace IEnumerableExample
{
    class Program
    {
        static void Main(string[] args)
        {
            MessagingApp myObject = new MessagingApp();
 
            foreach (string item in myObject)
            {
                Console.WriteLine(item);
            }
            
            Console.ReadLine();
        }
    }
 
    public class MessagingApp : IEnumerable<string>
    {
        string[] Messages = { "Test", "C#Program", "Testing" };
 
        public IEnumerator<string> GetEnumerator()
        {
            foreach (var item in Messages)
            {
                if (item == null)
                {
                    break;
                }
 
                yield return item;
            }
        }        
 
        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }       
    }
}

VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Module Module1
   
    Sub Main()
        Dim myObject As New MessagingApp
        For Each item As String In myObject
            Console.WriteLine(item)
        Next
        Console.ReadLine()
    End Sub
 
    Public Class MessagingApp
        Implements IEnumerable(Of String)
        Dim Messages As String() = {"Test", "VBProgram", "Hello"}
 
        Public Iterator Function GetEnumerator() As IEnumerator(Of String) _
        Implements IEnumerable(Of String).GetEnumerator
            For Each item As String In Messages
                If item = Nothing Then
                    Exit For
                End If
 
                Yield item
            Next
        End Function
 
        Private Function GetEnumerator1() As IEnumerator _ 
        Implements IEnumerable.GetEnumerator
            Return Me.Messages.GetEnumerator()
        End Function
 
    End Class
    
End Module

References:
Walkthrough: Implementing IEnumerable(Of T) in Visual Basic
IEnumerable Interface

Monday, April 4, 2016

How to wrap text in a DataGridViewColumn

Given that you have data such as comments/notes/description/address that would comprise at least hundreds of characters and you want to show them on the DataGridView control, you will notice that the text is concatenated and replaced with ellipses.


In order to achieve wrapping of text in a DataGridView cell, I achieved it using these steps.
1. Change the WrapMode value to True of a DataGridViewTextBoxColumn's DefaultCellStyle. 2. In my DataBindingComplete event of the DataGridView, set the AutoSizeRowsMode of the DataGridView to AllCells.
C# Code
private void dgvFormat_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
 dgvFormat.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
}

That's it.. :-)

Return Top 3 largest values in an array using LINQ

Sample snippet on getting the three largest values in an array using LINQ.

VB.NET
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Dim rand As New Random()
Dim numbers As New List(Of Int32)
For index = 1 To 20 Step 1
    ' add a list item which is a number from 1 through 100 
    numbers.Add(rand.Next(1, 100))
Next
 
Dim topThreeLargest = numbers.OrderByDescending(Function(t) t).Take(3)
Console.WriteLine("Top three largest elements in the array: ")
 
For Each item As String In topThreeLargest
    Console.WriteLine(item)
Next

Set url parameter of $.getJSON() method using @Url.Action() in ASP.NET MVC

Here's how you set the first parameter of $.getJSON() which is url using @Url.Action() where GetProductDetails is the action name and Product is the controller name. Make sure to surround it with single quotes.

Javascript Code:
1
2
3
4
5
function GetProductData(event) {
    $.getJSON('@Url.Action("GetProductDetails","Product")', function (prod) {
        alert(prod);
    });
}

Saturday, April 2, 2016

Append QueryString to PostBackUrl attribute in LinkButton Control

There was a question raised in the forum on how to append query string to a PostbackUrl attribute in an ASP.NET LinkButton inside the template field of a GridView control.

To answer that, one possible solution is to set the PostBackUrl with String.Format() method where you can include the desired query string of that url.
1
2
3
4
<asp:LinkButton ID="lnkProductPage" runat="server" 
    PostBackUrl='<%# String.Format("ProductPage.aspx?Id={0}", Eval("ID"))%>' 
    CausesValidation="false" Text='<%# Eval("ID")%>'>
</asp:LinkButton>