Monday, October 6, 2014

The file references an XML namespace that is inconsistent with the target framework of the project. (Entity Framework 6)

When adding an ADO.NET Entity Data Model to a ASP.NET project which connects to a certain SQL Server database, the entities (tables) do not appear on the model design view. However, the model successfully connects to the SQL DB.

Upon checking the Model design view, an error is shown which is the title of this post. After debugging and re-doing the steps in adding Entity Data Model, the error still persists.

Later, I found out that the ASP.NET project target framework was 4.0. Changing it to .NET Framework 4.5 solved the issue.

:)

Monday, September 22, 2014

ListView in WPF with alternating row colors

Here's how to change row colors for a WPF ListView control using a Converter class and Triggers.
Converter Class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class AddressTargetConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value.ToString().Equals(parameter.ToString()));
        }
 
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

XAML:
 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
<Window.Resources>
        <y:AddressTargetConverter x:Key="AddressTargetConverter" />
    </Window.Resources>
    <Grid>
        <StackPanel>
            <ListView ItemsSource="{Binding PersonCollection}">
                <ListView.ItemContainerStyle>
                    <Style TargetType="ListViewItem">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Address, Converter={StaticResource AddressTargetConverter}, ConverterParameter = Guam}" Value="True">
                                <Setter Property="Background" Value="LightBlue"></Setter>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ListView.ItemContainerStyle>
                <ListView.View>
                    <GridView>
                        <GridViewColumn Width="140" Header="Name" DisplayMemberBinding="{Binding Name}"  />
                        <GridViewColumn Width="200" Header="Address"  DisplayMemberBinding="{Binding Address}" />
                        <GridViewColumn Width="160" Header="Contact" DisplayMemberBinding="{Binding Contact}" />
                    </GridView>
                </ListView.View>
            </ListView>
        </StackPanel>
    </Grid>

Namespace declaration in XAML:
1
xmlns:y="clr-namespace:ListViewApp"
where ListViewApp is the project namespace.

KGComputers! :)

Sunday, September 21, 2014

ASP.NET GridView Control CRUD with Bootstrap

Here's a simple CRUD application using ASP.NET GridView control with Twitter Bootstrap as it's css class reference. The code sample used is in VB.NET.
Create: Update: Delete: ASPX markup:
  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
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
<div id="Container">
        <div id="GridContainer">
            <div id="LabelContainer">
                <asp:Label ID="lblHeading" runat="server" Text="ASP.NET GridView CRUD with Bootstrap (VB.NET)" >
                </asp:Label>
            </div>           
            <br />
               <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Code,Type,Gender" 
                ShowFooter="True" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound" 
                OnRowDeleting="GridView1_RowDeleting"
                OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCommand="GridView1_RowCommand" 
                CellPadding="0" ForeColor="#333333" CssClass="table table-striped table-bordered table-condensed">
                    <Columns>
                        <asp:TemplateField HeaderText="Name">
                            <EditItemTemplate>
                                <asp:TextBox id="txtName" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label id="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtNewName" runat="server" ></asp:TextBox>
                            </FooterTemplate>
                            <ItemStyle Wrap="True" />
                        </asp:TemplateField>
 
                        <asp:TemplateField HeaderText="Gender">
                            <EditItemTemplate>
                                &nbsp;           
                                <asp:DropDownList ID="cmbGender" runat="server">
                                    <asp:ListItem>Male</asp:ListItem>
                                    <asp:ListItem>Female</asp:ListItem>
                                </asp:DropDownList>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label runat="server" Text='<%# Eval("Gender")%>' id="Label2"></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:DropDownList ID="cmbNewGender" runat="server" >
                                    <asp:ListItem>Male</asp:ListItem>
                                    <asp:ListItem>Female</asp:ListItem>
                                </asp:DropDownList>
                            </FooterTemplate>
                        </asp:TemplateField>
 
                        <asp:TemplateField HeaderText="City">
                            <EditItemTemplate>
                                <asp:TextBox runat="server" Text='<%# Eval("City")%>' id="txtCity"></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label runat="server" Text='<%# Eval("City")%>' id="Label3"></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtNewCity" runat="server" ></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
 
                        <asp:TemplateField HeaderText="State">
                            <EditItemTemplate>
                                <asp:TextBox runat="server" Text='<%# Eval("State")%>' id="txtState"></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label runat="server" Text='<%# Eval("State")%>' id="Label4"></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtNewState" runat="server"></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
 
                        <asp:TemplateField HeaderText="Type">
                            <EditItemTemplate>
                                &nbsp;
                            <asp:DropDownList ID="cmbType" runat="server">
                                    <asp:ListItem>Retail</asp:ListItem>
                                    <asp:ListItem>Wholesale</asp:ListItem>
                                </asp:DropDownList>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label runat="server" Text='<%# Eval("Type") %>' id="Label5"></asp:Label>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:DropDownList ID="cmbNewType" runat="server">
                                     <asp:ListItem>Retail</asp:ListItem>
                                     <asp:ListItem>Wholesale</asp:ListItem>
                                </asp:DropDownList>
                            </FooterTemplate>
                        </asp:TemplateField>
 
                        <asp:TemplateField HeaderText="Edit" ShowHeader="False">
                                <ItemTemplate>                                    
                                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" CssClass="btn btn-primary" Text="Edit"></asp:LinkButton>  
                                </ItemTemplate>
                                <EditItemTemplate>
                                    <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="True" CssClass="btn btn-info" CommandName="Update" Text="Update"></asp:LinkButton>
                                    <asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CssClass="btn btn-info"  CommandName="Cancel" Text="Cancel"></asp:LinkButton> 
                                </EditItemTemplate>
                                <FooterTemplate>
                                    <asp:LinkButton ID="lnkAddNew" CssClass="btn btn-primary" runat="server" CommandName="AddNew">Add</asp:LinkButton>
                                </FooterTemplate>
                            </asp:TemplateField>
    
                        <asp:TemplateField HeaderText="Delete" ShowHeader="False">
                            <ItemTemplate>        
                                <span onclick="return confirm('Are you sure to Delete the record?')">                                    
                                    <asp:LinkButton ID="lnkB" runat="Server" CssClass="btn btn-primary"  Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Delete"></asp:LinkButton>
                                </span>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
            </asp:GridView>                      
        </div>    
    </div>

Source Code: http://www.vbforums.com/showthread.php?776827-ASP-NET-GridView-CRUD-with-Bootstrap-(VB-NET)
Cheers!

Saturday, September 20, 2014

ASP.NET GridView RowCommand Event Firing Twice

This issue happened when I migrated an asp.net 3.5 website to an asp.net 4.5 website. Upon clicking Add or Delete linkbuttons in the GridView, the RowCommand event fires twice. After googling for hours, I found a solution that is to remove the Handles GridView1.RowCommand in the event declaration.
The code below does not work (event fires twice)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
        Handles GridView1.RowCommand
        If e.CommandName.Equals("AddNew") Then
            Dim txtNewName As TextBox
            txtNewName = CType(GridView1.FooterRow.FindControl("txtNewName"), TextBox)
            Dim cmbNewGender As DropDownList
            cmbNewGender = CType(GridView1.FooterRow.FindControl("cmbNewGender"), DropDownList)
            Dim txtNewCity As TextBox
            txtNewCity = CType(GridView1.FooterRow.FindControl("txtNewCity"), TextBox)
            Dim txtNewState As TextBox
            txtNewState = CType(GridView1.FooterRow.FindControl("txtNewState"), TextBox)
            Dim cmbNewType As DropDownList
            cmbNewType = CType(GridView1.FooterRow.FindControl("cmbNewType"), DropDownList)
 
            Dim objCustomer As New CustomerCls()
            objCustomer.InsertCustomer(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text, cmbNewType.SelectedValue)
            FillCustomerInGrid()
        End If
 
    End Sub

The code below works (Handles GridView1.RowCommand removed)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) 
        If e.CommandName.Equals("AddNew") Then
            Dim txtNewName As TextBox
            txtNewName = CType(GridView1.FooterRow.FindControl("txtNewName"), TextBox)
            Dim cmbNewGender As DropDownList
            cmbNewGender = CType(GridView1.FooterRow.FindControl("cmbNewGender"), DropDownList)
            Dim txtNewCity As TextBox
            txtNewCity = CType(GridView1.FooterRow.FindControl("txtNewCity"), TextBox)
            Dim txtNewState As TextBox
            txtNewState = CType(GridView1.FooterRow.FindControl("txtNewState"), TextBox)
            Dim cmbNewType As DropDownList
            cmbNewType = CType(GridView1.FooterRow.FindControl("cmbNewType"), DropDownList)
 
            Dim objCustomer As New CustomerCls()
            objCustomer.InsertCustomer(txtNewName.Text, cmbNewGender.SelectedValue, txtNewCity.Text, txtNewState.Text, cmbNewType.SelectedValue)
            FillCustomerInGrid()
        End If
 
    End Sub

Friday, September 19, 2014

Find Checked Treenode in TreeView control using LINQ

Here's one way of searching through a treenode using LINQ. Assuming that the search criteria is a List or array object.
 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
Public Class Form1
    Public Shared mat As List(Of String) = Nothing
 
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
 
        mat = New List(Of String)
 
        mat.Add("Books")
        mat.Add("VB")
        mat.Add("Drinks")
        mat.Add("Food")
        mat.Add("Tea")
        mat.Add("Chod")
       
    End Sub
 
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If Not (mat Is Nothing) Then
            For Each tn As String In mat
                If (tvMat.Nodes.Find(tn, True).FirstOrDefault() IsNot Nothing) Then
                    If (tvMat.Nodes.Find(tn, True).FirstOrDefault().Checked) Then
                        MessageBox.Show(String.Format("Node Found"))
                        Me.Close()
                    End If
                End If
            Next
        End If
    End Sub
End Class

Monday, September 15, 2014

The type of one of the expression in the join clause is incorrect.Type inference failed in the call to GroupJoin (LINQ to XML)

Hi,
I just tested on grouping two collections using GroupJoin approach in LINQ to XML. In the example, the two collections are Customers and Companies. In which, companies served as grouping for the customers. In simple terms, identify a customer of which company he or she belongs. The code below produced an error The type of one of the expression in the join clause is incorrect.Type inference failed in the call to GroupJoin.
Code:
XElement companiesAndCustomers = new XElement("CompaniesAndCustomers",
   from company in companies
   join customer in customers on 
        company equals customer.CompanyName
        into groupCompany
        select new XElement("Company",
               new XAttribute("CompanyName", company.CompanyName),
               new XAttribute("Country", company.Country),
                   from subCustomer in groupCompany
                        select new XElement("Customer", subCustomer.LastName + ", " + subCustomer.FirstName
                               , new XAttribute("Age",subCustomer.Age))));
As I glanced through the code, I joined an entire company object to a customer CompanyName property. To fix that, I added a CompanyName property to company object that is of exact match with customer's CompanyName type.
Code:
XElement companiesAndCustomers = new XElement("CompaniesAndCustomers",
   from company in companies
   join customer in customers on 
        company.CompanyName equals customer.CompanyName
        into groupCompany
        select new XElement("Company",
               new XAttribute("CompanyName", company.CompanyName),
               new XAttribute("Country", company.Country),
                   from subCustomer in groupCompany
                        select new XElement("Customer", subCustomer.LastName + ", " + subCustomer.FirstName
                               , new XAttribute("Age",subCustomer.Age))));

:)

Sunday, September 14, 2014

Formatting ASP.NET Panel as Bootstrap Modal Dialog

Here's how you make use of the asp.net panel container that will serve as modal dialog. During render, panel will be converted to div elements.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<asp:Panel ID="pnlModal" runat="server" role="dialog" CssClass="modal fade">
    <asp:Panel ID="pnlInner" runat="server" CssClass="modal-dialog" >
        <asp:Panel ID="pnlContent" CssClass="modal-content" runat="server">
            <asp:Panel runat="server" class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                </button>
                <h4 class="modal-title">Bootstrap Modal Dialog in ASP.NET</h4>
            </asp:Panel>
            <asp:panel runat="server" class="modal-body">
               <p>
                    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et 
                    dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip 
                    ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu 
                    fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt 
                    mollit anim id est laborum.
               </p>
             </asp:panel>
            <asp:panel runat="server" class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </asp:panel>
        </asp:Panel>
    </asp:Panel>
</asp:Panel>

Make sure to download the bootstrap files and reference them to your asp.net project.
1
2
3
<script src="Scripts/jquery-1.11.1.min.js"></script>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Content/bootstrap.min.js"></script>

Friday, September 5, 2014

Linear Gradients in.NET 2D

Hi,
Here's a simple demo using Linear gradients (Color Manipulation) in .NET
Code:
private int _rColor = 100;
     
public int GenerateRGB(int cc)
{
 int rt = 0;
 if (cc <= 255)
 {
  rt = Information.RGB(255, cc, 0);
 }
 else if (cc < 511)
 {
  rt = Information.RGB(255 - (cc - 255), 255, 0);
 }
 else if (cc < 766)
 {
  rt = Information.RGB(0, 255, cc - 511);
 }
 else if (cc < 1022)
 {
  rt = Information.RGB(0, 255 - (cc - 767), 255);
 }
 else if (cc < 1277)
 {
  rt = Information.RGB(0, 0, 255 - (cc - 1022));
 }
 else
 {
  rt = Information.RGB(0, 0, 0);
 }
 return rt;
}

private void timer1_Tick(object sender, EventArgs e)
{
 this.Refresh();
 _rColor += 1;
 if (_rColor > 1500)
 {
  _rColor = 0;
 }
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
 Color color = new Color();
 Random m_Rnd = new Random(); 
 color = Color.FromArgb(255, m_Rnd.Next(0, 255), m_Rnd.Next(0, 255), m_Rnd.Next(0, 255));

 using (LinearGradientBrush linGrBrush = new LinearGradientBrush(new Point(0, 10), new Point(200, 10), Color.FromArgb(GenerateRGB(_rColor)), color))
 {
  using (Pen mypen = new Pen(linGrBrush, 2))
  {
   e.Graphics.DrawLine(mypen, 0, 0, this.Width, this.Height);
  }
 }
}
Form Load:
After One Second, the color changes:

Thursday, September 4, 2014

Cannot connect to WMI provider. You do not have permission or the server is unreachable (SQL Server 2012)

Hello,

When you click on SQL Server Configuration Tools after pc reboot, you might encounter an error stated by the title of this post.

Given the following details
OS: Windows 7 Enterprise 64 Bit
Software: SQL Server 2012
Network Setup: Domain Controller

The steps to resolve the issue is presented below:
1. Right click command prompt and select "Run as Administrator"
2. Type the following in the command prompt C:\
mofcomp "%programfiles(x86)%\Microsoft SQL Server\110\Shared\sqlmgmproviderxpsp2up.mof"
(where 110 is the number)

Note: For this command to succeed, the Sqlmgmproviderxpsp2up.mof file must be present in the %programfiles(x86)%\Microsoft SQL Server\number\Shared folder.

Sample Error Message:

Cheers! :)

Web Form Using Master Page not found on Visual Studio 2012 IDE

When the RTM versions of Visual Studio 2012 were updated to version 4, I noticed that when you Add a New Item in an Asp.net website or project, "Web Form Using Master Page" has gone missing.

I soon realized that Web Form Using Master Page is replaced with "Content Page" in the Add New Item Dialog.
:)

Tuesday, August 19, 2014

Webbrowser Control imitate Internet Explorer Behavior

Hi,

Lately, I was given a task from a client if I can update my VB.NET crawler scripts with a webbrowser control to show/render images of the crawled website to the control. Normally, I used the control just to obtain the web page source and then parse the necessary information. By default, the settings of the webbrowser control is IE7.

After doing some reseach, I stumbled upon a solution by Noseratio on IE Feature Control Hacks. The documentation for browser emulation can be found on MSDN: MSDN Browser Emulation.

I uploaded a sample VB.NET application here: WebBrowser Control Similar to IE Browser

Sample Result:

Cheers! :)

Sunday, August 17, 2014

List running computer processes by array names using LINQ

Here's a snippet on how to retrieve running process in your computer by array names using LINQ.
C# Code
1
2
3
4
5
6
7
8
List<Process> procs = new List<Process>();
procs = new List<string>() { "firefox", "iexplore", "ssms", "notepad++", "chrome" }
            .SelectMany(o => Process.GetProcessesByName(o)).ToList();

foreach (var item in procs)
{
        Console.WriteLine(item.ProcessName);
}

VB.NET
1
2
3
4
5
6
Dim procs As IEnumerable(Of Process) = _
        {"firefox", "iexplore", "ssms", "notepad++", "chrome"}.SelectMany(Function(proc) Process.GetProcessesByName(proc))
For Each p In procs
     Console.WriteLine(p.ProcessName)
Next
Console.ReadLine()

Saturday, August 9, 2014

WPF DataGrid Row and Cells Extension Methods

Below are extension methods in accessing WPF DataGrid Rows and Cells. These methods were based on existing C# methods and I converted them to VB.NET for VB programmers.

WPF DataGrid Extension Methods:
  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
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
Option Explicit On
Option Infer On
 
Imports System.Runtime.CompilerServices
Imports System.Windows.Controls.Primitives
 
Module DataGridExtensions
 
    ''' <summary>
    ''' Get DataGridRow using index
    ''' </summary>
    <Extension()>
    Function GetRow(ByVal grid As DataGrid, ByVal index As Integer) As DataGridRow
 
        Dim row As DataGridRow = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
        If row Is Nothing Then
            grid.UpdateLayout()
            grid.ScrollIntoView(grid.Items(index))
            row = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
        End If
 
        Return row
    End Function
 
    ''' <summary>
    ''' Return Selected Item
    ''' </summary>
    <Extension()>
    Function GetSelectedRow(ByVal grid As DataGrid) As DataGridRow
        Return DirectCast(grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem), DataGridRow)
    End Function
 
    ''' <summary>
    ''' pass datagridrow and column index
    ''' </summary>
    <Extension()>
    Public Function GetCell(grid As DataGrid, row As DataGridRow, column As Integer) As DataGridCell
        If row IsNot Nothing Then
            Dim presenter As DataGridCellsPresenter = GetVisualChild(Of DataGridCellsPresenter)(row)
 
            If presenter Is Nothing Then
                grid.ScrollIntoView(row, grid.Columns(column))
                presenter = GetVisualChild(Of DataGridCellsPresenter)(row)
            End If
 
            Dim cell As DataGridCell = DirectCast(presenter.ItemContainerGenerator.ContainerFromIndex(column), DataGridCell)
            Return cell
        End If
        Return Nothing
    End Function
 
    ''' <summary>
    ''' Pass row and column index
    ''' </summary>
    <Extension()>
    Public Function GetCell(grid As DataGrid, row As Integer, column As Integer) As DataGridCell
        Dim rowContainer As DataGridRow = grid.GetRow(row)
        Return grid.GetCell(rowContainer, column)
    End Function
 
    ''' <summary>
    ''' Return DataGrid Rows 
    ''' </summary>
    <Extension()>
    Public Function GetDataGridRows(grid As DataGrid) As List(Of DataGridRow)
        Dim rows As New List(Of DataGridRow)
        Dim itemsSource = TryCast(grid.ItemsSource, IEnumerable)
 
        If itemsSource Is Nothing Then
            Return Nothing
        End If
 
        For Each item In itemsSource
            Dim row = TryCast(grid.ItemContainerGenerator.ContainerFromItem(item), DataGridRow)
 
            If row Is Nothing Then
 
                'bring into view and get row
                grid.UpdateLayout()
                grid.ScrollIntoView(item)
                row = TryCast(grid.ItemContainerGenerator.ContainerFromItem(item), DataGridRow)
 
            End If
 
            If row IsNot Nothing Then
                rows.Add(row)
            End If
        Next
 
        Return rows
 
    End Function
 
    ''' <summary>
    ''' Set selection based on indexes
    ''' </summary>
    <Extension()>
    Public Sub SelectDataGridRowByIndexes(dataGrid As DataGrid, ByVal ParamArray rowIndexes As Integer())
        If Not dataGrid.SelectionUnit.Equals(DataGridSelectionUnit.FullRow) Then
            Throw New ArgumentException("Change selection unit of the DataGrid to FullRow.")
        End If
 
        If Not dataGrid.SelectionMode.Equals(DataGridSelectionMode.Extended) Then
            Throw New ArgumentException("Change selectionMode of the DataGrid to Extended.")
        End If
 
        If rowIndexes.Length.Equals(0) OrElse rowIndexes.Length > dataGrid.Items.Count Then
            Throw New ArgumentException("Invalid number of indexes.")
        End If
 
        dataGrid.SelectedItems.Clear()
        dataGrid.UpdateLayout()
 
        For Each rowIndex As Integer In rowIndexes
        
            If rowIndex < 0 OrElse rowIndex > (dataGrid.Items.Count - 1) Then
                Throw New ArgumentException(String.Format("{0} is an invalid row index.", rowIndex))
            End If
 
            Dim item As Object = dataGrid.Items(rowIndex)
 
            Try
                dataGrid.SelectedItems.Add(item)
            Catch ex As Exception
 
            End Try
 
            Dim row As DataGridRow = TryCast(dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex), DataGridRow)
 
            If row Is Nothing Then
                dataGrid.ScrollIntoView(item)
                row = TryCast(dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex), DataGridRow)
            End If
 
            If row IsNot Nothing Then
                Dim cell As DataGridCell = GetCell(dataGrid, row, 0)
                If cell IsNot Nothing Then
                    cell.Focus()
                End If
            End If
        Next
    End Sub
 
    ''' <summary>
    ''' Traverse Visual Tree 
    ''' </summary>
    <Extension()>
    Public Function GetVisualChild(Of T As Visual)(parent As Visual) As T
        Dim child As T = Nothing
        Dim numVisuals As Integer = VisualTreeHelper.GetChildrenCount(parent)
 
        For i As Integer = 0 To numVisuals - 1
            Dim v As Visual = DirectCast(VisualTreeHelper.GetChild(parent, i), Visual)
            child = TryCast(v, T)
            If child Is Nothing Then
                child = GetVisualChild(Of T)(v)
            End If
 
            If child IsNot Nothing Then
                Exit For
            End If
        Next
 
        Return child
    End Function
 
End Module

Sample Output(Selecting DataGrid rows using index): Source Code: Accessing-Rows-and-Cells-in-a-WPF-DataGrid

Regards,
.NET Gene/KGComputers

Friday, August 8, 2014

Show Asterisk Triangle Shapes using TSQL (SQL Server)

In programming, it's a common exercise to show triangle shapes using the asterisk character. Well, this can be achieved using TSQL as well.. :)

Script #1
 DECLARE      @Total1      INT            
 DECLARE      @ctrOuter1      INT            
 DECLARE      @ctrInner1      INT            
 DECLARE @strPrint1 VARCHAR(100)  
 SET           @Total1     = 5  
 SET           @ctrOuter1 = @Total1  
 SET           @strPrint1 = ''  
 WHILE      @ctrOuter1     >= 1 --outer loop  
 BEGIN   
      SET @strPrint1 = ''  
      SET @ctrInner1 = 0  
      WHILE     @ctrInner1 <= (@Total1 - @ctrOuter1)   
      BEGIN  
           SET @strPrint1 = @strPrint1 + '*'  
           SET @ctrInner1 = @ctrInner1 + 1  
      END       
   PRINT @strPrint1       
      SET @strPrint1 = @strPrint1 + CHAR(13)  
      SET     @ctrOuter1 = @ctrOuter1 - 1     
 END  
Output:
Script #2
 DECLARE      @Total      INT            
 DECLARE      @ctrOuter      INT            
 DECLARE      @ctrInner      INT            
 DECLARE    @strPrint VARCHAR(100)  
 SET           @Total     = 5  
 SET           @ctrOuter = @Total  
 SET           @strPrint = ''  
 WHILE      @ctrOuter     >= 1 --outer loop  
 BEGIN   
      SET @strPrint = ''  
      SET @ctrInner = 1  
      WHILE     @ctrInner <= @ctrOuter  
      BEGIN  
           SET @strPrint = @strPrint + '*'            
           SET @ctrInner = @ctrInner + 1  
      END       
   PRINT @strPrint       
      SET @strPrint = @strPrint + CHAR(13)  
      SET     @ctrOuter = @ctrOuter - 1     
 END  
Output:
Cheers! :)

Wednesday, August 6, 2014

Cannot connect to WMI provider. You do not have permission or the server is unreachable in SQL Server 2012

After installing SQL Server 2012, I installed other MS software as well. However, when I restart my pc and log in to SQL, I encountered an error as seen in this image.

Specifications:

Windows 7 Enterprise 64 Bit
Software: SQL Server 2012 64 Bit (Enterprise or Developer) editions

Solution:
1. Right click command prompt and select "Run as Administrator"
2. Type the following in the command prompt C:\
mofcomp "%programfiles(x86)%\Microsoft SQL Server\110\Shared\sqlmgmproviderxpsp2up.mof"
(where 110 is the unique instance id for SQL Server 2012)

Note For this command to succeed, the Sqlmgmproviderxpsp2up.mof file must be present in the
%programfiles(x86)%\Microsoft SQL Server\number\Shared folder.

Reference: Cannot connect to WMI provider

Monday, July 21, 2014

Databinding ASP.NET 4.5 GridView with jQuery and Ajax

Hi,

Here's a simple asp.net program that performs adding of data to GridView control through jQuery and ajax. On page load, perform databinding on dropdown list and gridview using server side and code behind. And on client side, that is a selection change occurs in dropdown list, perform binding by adding table rows and columns to GridView.

Page Load (Load All Products):


Selection Change (Load Specific Products):

The sample code is available for download here: Databinding ASP.NET 4.5 GridView with jQuery and Ajax Code

Cheers!

Thursday, July 17, 2014

GeckoFX DocumentText similar to Webbrowser Control Alternative (C#)

In this post GeckoFX DocumentText similar to Webbrowser, I presented a solution on how to retrieve the page source of a website. However, another solution was provided by a .NET guru using TextContent property:
Code:
this.Document.GetElementsByTagName("html")[0].TextContent;

Cheers!

Monday, July 14, 2014

Paint WPF DataGridCell background w/o using IValueConverter

Here's how to paint WPF DatagridCell using extension methods without using IValueConverter.
Extension Method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Module DataGridExtensions
    <Extension()>
    Function GetRow(ByVal grid As DataGrid, ByVal index As Integer) As DataGridRow
        Dim row As DataGridRow = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
        If row Is Nothing Then
            grid.UpdateLayout()
            grid.ScrollIntoView(grid.Items(index))
            row = DirectCast(grid.ItemContainerGenerator.ContainerFromIndex(index), DataGridRow)
        End If
        Return row
    End Function
End Module

MainWindow.xaml:
1
2
3
4
Dim firstRow As DataGridRow = grid1.GetRow(0) 'grid1 is your DataGrid control
Dim firstColumnInFirstRow As Controls.DataGridCell = DirectCast(grid1.Columns(0).GetCellContent(firstRow).Parent, Controls.DataGridCell)
'set background
firstColumnInFirstRow.Background = Brushes.Red

Wednesday, July 9, 2014

Split a string with multiple space as delimiter or separator (Regex or String.Split)

Given that you have a string that you want to split and the separator is two or more spaces. You can achieve using split() or Regex.
VB.NET
1
2
3
4
5
6
7
8
Dim str As String = "Rule Name:                            WhosThere-176.44.28.203"
Dim whosThereVar As String
Dim whosThereString As String

'using split
whosThereVar = str.Split(New String() {"  "}, StringSplitOptions.RemoveEmptyEntries)(1).Trim()
'using regex
whosThereString = System.Text.RegularExpressions.Regex.Split(str, "\s{2,}")(1)
C#
1
2
3
4
5
string str = "Rule Name:                            WhosThere-176.44.28.203";
//using split
string whosThereVar = str.Split(new string[] { "  " }, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
//using regex
string whosThereString = System.Text.RegularExpressions.Regex.Split(str, @"\s{2,}")[1];

Tuesday, July 1, 2014

Sorting a HashTable object using LINQ in .NET

In .NET, you can't directly sort a Hashtable object. A tip on sorting a Hashtable object is to cast it to Dictionary then apply LINQ OrderBy() method to the Hashtable object. See examples below:
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
34
35
Private Sub SortHashTableKey()
 
        hash = New Hashtable()
        hash.Add("B", 1)
        hash.Add("A", 2)
        hash.Add("C", 3)
 
        Dim dict = hash.Cast(Of DictionaryEntry)() _
                        .ToDictionary(Function(d) d.Key, Function(d) d.Value) _
                        .OrderBy(Function(e) e.Key)
 
        Console.WriteLine("Sort by Key")
        For Each item In dict.ToList()
            Console.WriteLine(String.Format("{0}, {1}", item.Key, item.Value))
        Next
 
        Console.WriteLine(Environment.NewLine)
 
    End Sub
 
    Private Sub SortHashTableValue()
        hash = New Hashtable()
        hash.Add("A", 2)
        hash.Add("B", 1)
        hash.Add("C", 3)
 
        Dim dict = hash.Cast(Of DictionaryEntry)() _
                   .ToDictionary(Function(d) d.Key, Function(d) d.Value) _
                   .OrderBy(Function(e) e.Value)
        Console.WriteLine("Sort by Value")
        For Each item In dict.ToList()
            Console.WriteLine(String.Format("{0}, {1}", item.Key, item.Value))
        Next
 
    End Sub

C#
 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
private void SortHashTableKey() {
 Hashtable hash = new Hashtable();
 hash.Add("B", 1);
 hash.Add("A", 2);
 hash.Add("C", 3);

 var dict = hash.Cast < DictionaryEntry > ()
  .ToDictionary(d => d.Key, d => d.Value)
  .OrderBy(e => e.Key);

 listBox1.Items.Add("Sort by Key");

 foreach(var item in dict.ToList()) {
  listBox1.Items.Add(String.Format("{0}, {1}",
   item.Key, item.Value));
 }

 listBox1.Items.Add(Environment.NewLine);
}

private void SortHashTableValue() {
 Hashtable hash = new Hashtable();
 hash.Add("B", 1);
 hash.Add("A", 2);
 hash.Add("C", 3);

 var dict = hash.Cast < DictionaryEntry > ()
  .ToDictionary(d => d.Key, d => d.Value)
  .OrderBy(e => e.Value);

 listBox1.Items.Add("Sort by Value");

 foreach(var item in dict.ToList()) {
  listBox1.Items.Add(String.Format("{0}, {1}",
   item.Key, item.Value));
 }
}

Output:

Cheers! :)

Saturday, June 28, 2014

Update ASP.NET Label control value using continuous mouse down click

Starting today, I'm going to contribute source code in vbforums.com(Visual Basic Forum). The community helped me way back since VB 6.0 and VBA. And in turn, it's time to give back as an experienced member. :)

Here's a an ASP.NET application I posted in ASP.NET code bank on how to update label values continuously on mouse hold. Update Label Value using jQuery/Javascript in ASP.NET

Reference: Easily do a continuous action on mouse hold using javascript

Cheers! :)

Friday, June 27, 2014

Bind XML Node Value To GridView column in ASP.NET using XPath

Given in a datasource object where in you have a column which contains an XML string and you want to bind a certain node value instead of the entire XML string to GridView column, here's a solution using XPath. ASPX:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<asp:GridView ID="gvPersons" runat="server" AutoGenerateColumns="False" BackColor="White"   
       Width="400px" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3">  
       <AlternatingRowStyle BackColor="#F7F7F7" />  
       <Columns>  
         <asp:BoundField DataField="ID" HeaderText="ID" >  
         <ItemStyle Width="50px" />  
         </asp:BoundField>  
         <asp:BoundField DataField="XMLData" HeaderText="Name" >  
         <ItemStyle Width="350px" />  
         </asp:BoundField>  
       </Columns>  
       <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />  
       <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />  
       <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />  
       <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />  
       <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />  
       <SortedAscendingCellStyle BackColor="#F4F4FD" />  
       <SortedAscendingHeaderStyle BackColor="#5A4C9D" />  
       <SortedDescendingCellStyle BackColor="#D8D8F0" />  
       <SortedDescendingHeaderStyle BackColor="#3E3277" />  
     </asp:GridView>  

C# 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
37
38
39
40
protected void BindToGridXPath()
        {
            XmlDocument xmlDoc;
            XmlNode xmlNode;
            String xpathExpr;

            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[]
                {
                    new DataColumn("ID",typeof(int)), 
                    new DataColumn("XMLData", typeof(string))
                });

            DataRow row = dt.NewRow();
            row["ID"] = 1;
            row["XMLData"] = "<Person><Name>James Minervo</Name><Age>33</Age></Person>";

            DataRow row1 = dt.NewRow();
            row1["ID"] = 2;
            row1["XMLData"] = "<Person><Name>Mike Phill</Name><Age>45</Age></Person>";

            //...codes to manipulate the datatable
            xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(row["XMLData"].ToString());
            xpathExpr = "/Person/Name";
            xmlNode = xmlDoc.SelectSingleNode(xpathExpr);
            row["XMLData"] = xmlNode.InnerText;

            xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(row1["XMLData"].ToString());
            xpathExpr = "/Person/Name";
            xmlNode = xmlDoc.SelectSingleNode(xpathExpr);
            row1["XMLData"] = xmlNode.InnerText;

            dt.Rows.Add(row);
            dt.Rows.Add(row1);

            gvPersons.DataSource = dt;
            gvPersons.DataBind();
        }

Output: