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.
:)