Blog of a Filipino Developer about C#, VB.NET, ASP.NET, Java, PHP, SQL Server, MySql and Oracle RSS 2.0
# Thursday, September 11, 2008

Speaking of free books... Below are the list of free ebooks that I recommend reading/downloading for this month. I personally love Karl Seguin's book and giving it 5 out 5 stars is actually an understatement if you ask me. :)

Karl Seguin's Foundation Of Programming: Building Better Software rocks so much I recommended it to everyone I know. This 79 page book is pack with a hearty bowl of software development knowledge that would teach you about the principles of development that you should have known way before you started coding that nightmarish system.

Red Gate's Dissecting SQL Server Execution Plan is a must read for anyone who deals with data on a daily basis. It talks about how to optimize your querries and understand whats causing your querries to sleep on you while being executed.

InfoQ's Domain Driven Design Quickly is a quickly-readable summary and introduction to the fundamentals of DDD that tries to summarizes Eric Evans' book as well as Jimmy Nilsson's Applying Domain Driven Design and various other sources. The book gives you hints and tips about DDD as well as ideas on how to start DDD in your own projects.

Minh T. Nguyen's Visual Studio.NET Tips & Tricks is a must read for all developers who use Visual Studio. Enuff said!

So what are you waiting for? Download and read 'em now!

Thursday, September 11, 2008 11:48:37 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | All about Keith | ASP.NET | Tech News and Issues | Your Career
Thursday, September 11, 2008 11:40:03 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
Tech News and Issues
# Friday, September 05, 2008

Ever heard of ColorTranslator? It's a really cool class that you can use to convert colors in .NET. One of the things that it can do is that enables you to convert HTML colors to Windows colors and vice versa. One particular scenario wherein you might want to use this class is when you want to use HTML colors on your WinForm.

Below are examples on how to use this calls:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ColorTranslatorTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //convert a system.drawing.color to html
            Color c1 = Color.AntiqueWhite;
            button1.BackColor = c1;
            button1.Text = ColorTranslator.ToHtml(c1);

            //convert an html color to a gdi+ color
            string htmlColor = "#FFAD55";
            Color c2 = ColorTranslator.FromHtml(htmlColor);
            button2.BackColor = c2;
            button2.Text = ColorTranslator.ToHtml(c2);

            //convert a win32 color to gdi+ color
            int colorHexadecimalValue = 0xA267;
            Color c3 = ColorTranslator.FromWin32(colorHexadecimalValue);
            button3.BackColor = c3;
            button3.Text = ColorTranslator.ToWin32(c3).ToString("X");
        }
    }
}

HTH

Friday, September 05, 2008 5:59:10 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | Tutorial
# Tuesday, August 19, 2008

One of the common problems that you would encounter when you are building applications that utilize views is that sometimes there are cases wherein a view gets out of date. This happens when you add a new column to a table a view is refrencing.

To fix this some people would delete the view and recreate it but there is better solution called sp_refreshview. sp_refreshview updates the metadata for the specified non-schema-bound view. Persistent metadata for a view can become outdated because of changes to the underlying objects upon which the view depends[description from msdn].

Here's a remark from MSDN regarding sp_refreshview:

"If a view is not created with schemabinding, sp_refreshview should be run when changes are made to the objects underlying the view that affect the definition of the view. Otherwise, the view might produce unexpected results when it is queried."

The syntax is pretty straight-forward

   EXECUTE sp_refreshview '<view name>'

Once executed the views definition would be updated.

What if I want to execute sp_refreshview on all the views in my database? The answer is to create a cursor that would execute sp_refreshview on each of your view. Below is a script that does exacrly what you need:

--Refresh the underlying metadata of all views
DECLARE @viewName AS VARCHAR(255)

DECLARE listOfViews CURSOR FOR
SELECT [name] 
FROM sysobjects 
WHERE xtype = 'V'


OPEN listOfViews

    FETCH NEXT FROM listOfViews into @viewName

    WHILE (@@FETCH_STATUS <> -1)
    BEGIN

        FETCH NEXT FROM listOfViews INTO @viewName
        EXEC sp_refreshview @viewName

    END

CLOSE listOfViews

DEALLOCATE listOfViews

HTH

Tuesday, August 19, 2008 7:49:57 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
SQL

I've been doing a  lot of code deployments lately and I've come across several occasions wherein my stored procedures wouldn't run as fast as expected compared to it's previously known execution time. The problem lies on the statistics not getting updated after change has been made against an index or other object that may affect efficiency. Since stored procedures are compiled, recompiling them would update these statistics.

Here's a remark about sp_recompile taken from the MSDN website

"The queries used by stored procedures and triggers are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures and triggers may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries."

The syntax is pretty straight-forward:

EXEC sp_recompile '<name of your sp>'

Once executed the stored procedure would then be marked for recompilation and would then be recompiled on the next execution. Niffty huh?!

But what if I want to recompile all my stored procedures? Well, fear not! You can use a cursor that would iterate on all the stored procedure in your current database and execute an sp_recompile against all of them. Below is the script to accomplish this task:

--Recompile all stored procedures on the current database
DECLARE @StoredProcedureName AS VARCHAR(255)

DECLARE listOfStoredProcedure CURSOR FOR
SELECT [Name] FROM sysobjects 
WHERE XTtype = 'P'


OPEN listOfStoredProcedure

    FETCH NEXT FROM listOfStoredProcedure into @StoredProcedureName

    WHILE (@@FETCH_STATUS <> -1)
    BEGIN

        FETCH NEXT FROM listOfStoredProcedure INTO @StoredProcedureName
        EXEC sp_recompile @StoredProcedureName

    END

CLOSE listOfStoredProcedure

DEALLOCATE listOfStoredProcedure

GO

HTH

*Note: sp_recompile can also recompile triggers

Tuesday, August 19, 2008 7:31:14 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
SQL

Ever thought of how to capitalize the first letter of every word in a string? Here's how:

[C#]

using System;
using System.Globalization;

namespace KeithRull.CapitalizingLetters
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string textToTransform = "keith, you need to post more blogs!";

            Console.WriteLine("Original text: " + textToTransform);

            //capitalizing the first letter of our text using the current culture
            Console.WriteLine("Capitalize using the current culture: "
                + CultureInfo.CurrentCulture.TextInfo.ToTitleCase(textToTransform));

            //capitalizing the first letter of our text using a defined culture
            CultureInfo newCultureInfo = new CultureInfo("zh-Hans", false);
            TextInfo textInfo = newCultureInfo.TextInfo;
            Console.WriteLine("Capitalize using a specified culture: " + textInfo.ToTitleCase(textToTransform));

            Console.Read();
        }
    }
}

[VB.NET]

Imports System
Imports System.Globalization
 
Namespace KeithRull.CapitalizingLetters
    Friend Class Program
        Shared  Sub Main(ByVal args() As String)
            Dim textToTransform As String =  "keith, you need to post more blogs!" 
 
            Console.WriteLine("Original text: " + textToTransform)
 
            'capitalizing the first letter of our text using the current culture
            Console.WriteLine("Capitalize using the current culture: "
                Dim CultureInfo.CurrentCulture.TextInfo.ToTitleCase(textToTransform)) As +
 
            'capitalizing the first letter of our text using a defined culture
            Dim NewCultureInfo As CultureInfo =  New CultureInfo("zh-Hans",False) 
            Dim textInfo As TextInfo =  NewCultureInfo.TextInfo 
            Console.WriteLine("Capitalize using a specified culture: " + textInfo.ToTitleCase(textToTransform))
 
            Console.Read()
        End Sub
    End Class
End Namespace

HTH

Tuesday, August 19, 2008 6:54:48 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | Tutorial
# Monday, August 11, 2008

Wooohooo!! Get 'em here!

Combined Visual Studio 2008 Service Pack 1 and .NET Framework 3.5 Service Pack 1

The update for Visual Studio 2008 SP1 and .NET Framework 3.5 Service Pack 1 in a single install.

.NET Framework 3.5 Service Pack 1

The update for just the .NET 3.5 Service Pack 1, it does not include updates for Visual Studio 2008.

Monday, August 11, 2008 6:37:23 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | Tech News and Issues
# Saturday, July 26, 2008

Sorry for not being able to post anything interesting the past few months. Anyway, I saw this old thread at DevPinoy.org the other day and I realized that nobody has posted a complete sample solution that would solve and show how to accomplish dynamic input rows in a GridView. I was thinking of replying to it a few months back but i guess work caught up at me and I wasn't able to do so. I found some free time last week and decided to build an app to demonstrate how to solve this question.

Ok, lets start by analyzing the question:

Hi guys,

I have a problem here. How can i create a dynamic row in gridview the row will defend from the user input. For example the user enter a 4 then the gridview will generate 4 rows. Please site me an example.

Thanks,
D_Conqueror

From what I understood the user wants to be able to create dynamically rows of data in the GridView depending on the number he enters on a Textbox. We can accomplish this by creating a datasource with the same number of rows as the user specified and binding it to our GridView.

To demonstrate how to solve this problem i decided to create this sample.

To start off with our tiny project we need to create a page that would ask the user for the number of rows he wan'ts to display on the GridView. The page will contain a TextBox for input and a LinkButton that we will use for submitting the value to a seperate page. Below is the HTML code for our first page (Default.aspx):

dynamiggridview01.jpg

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dynamic GridView Input Rows</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="width:330px;">
        Number of rows to create:&nbsp; 
        <asp:TextBox ID="numberOfRowsTextBox" runat="server"></asp:TextBox>
        <div style="text-align:right;">
            <asp:LinkButton ID="submitLinkButton" runat="server" 
                onclick="submitLinkButton_Click">Submit</asp:LinkButton>
        </div>
    </div>
    </form>
</body>
</html>

and below is the code listing for Default.aspx

using System;

public partial class _Default : System.Web.UI.Page 
{
    protected void submitLinkButton_Click(object sender, EventArgs e)
    {
        Response.Redirect(String.Format(
                            "DynamicGridViewPage.aspx?rows={0}"
                            , numberOfRowsTextBox.Text));
    }
}

As you can see, all we are doing is passing the value of our TextBox as a query string parameter to our second page. The true juice of our solution is on the next page. But before we go into detail to that we need to setup first what type of values needs to be shown on the page. For this example i've decided to display a simple Person class that has for fields. An ID, a Firstname, a Lastname, and a boolean field called IsChristian. Below is the code for our Person class:

using System;

/// <summary>
/// Summary description for Person
/// </summary>
public class Person : IPerson
{
    private int _ID;
    private string _firstname;
    private string _lastname;
    private bool _isChristian;

    public int ID
    {
        get { return _ID; }
        set { _ID = value; }
    }

    public string Firstname 
    {
        get { return _firstname; }
        set { _firstname = value; }
    }

    public string Lastname
    {
        get { return _lastname; }
        set { _lastname = value; }
    }

    public bool IsChristian
    {
        get { return _isChristian; }
        set { _isChristian = value; }
    }

    public Person()    {}

    public override string ToString()
    {
        string returnValue = @"ID: " + this.ID.ToString() + "<br />"
                            + "Firstname: " + this.Firstname + "<br />"
                            + "Lastname: " + this.Lastname + "<br />"
                            + "Is Christian: " + this.IsChristian.ToString();
        
        return returnValue;
    }
}

I also created a class Persons that is a generic list of type Person. In that class I created a contructor that accepts a integer value that we will use to create the dummy list of person. The code for our Persons class is listed below:

using System;
using System.Collections.Generic;

/// <summary>
/// Summary description for Persons
/// </summary>
public class Persons: List<Person>
{
    public Persons() {}

    public Persons(int rowCount) {
        this.Clear();
        for (int i = 1; i <= rowCount; i++)
        {
            Person p = new Person();
            p.ID = i;
            this.Add(p);
        }
    }
}

Now on our second page, DynamicGridViewPage.aspx, I decided to place 4 controls. A GridView that would contain our input boxes, a label to display messages, a button to submit the fields and another GridView to show the submit values. I've added these few quirks on the page to demonstrate how you can retrieve entered values in a GridView. Below is the HTML listing for the DynamicGridViewPage.aspx.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="dynamicGridView" runat="server" AutoGenerateColumns="False" 
            DataKeyNames="ID">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="idLabel" 
                            runat="server" 
                            Text='<%# Bind("ID") %>'>
                        </asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Firstname">
                    <ItemTemplate>
                        <asp:TextBox ID="firstnameTextBox" 
                            runat="server">
                        </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Lastname">
                    <ItemTemplate>
                        <asp:TextBox ID="lastnameTextBox" 
                            runat="server">
                        </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Christian">
                    <ItemTemplate>
                        <asp:CheckBox ID="isChristianCheckBox" 
                            runat="server" 
                            Enabled="true" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:LinkButton ID="submitLinkButton" runat="server" 
            onclick="submitLinkButton_Click">Submit</asp:LinkButton>
        <br />
        <br />
        <asp:Label ID="messageLabel" runat="server"></asp:Label>
        <asp:GridView ID="submitedRecordsGridView"
            runat="server">
            <EmptyDataTemplate>
                <b>No record submitted!</b>
            </EmptyDataTemplate>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

One of the things that you would quickly realize on our page is that the only thing I'm binding to our GridView is the ID property. The reason is because we don't really need to bind all the fields to our GridView because we are just creating rows. Next, lets look at the code behind for our page.

using System;
using System.Web.UI.WebControls;
using System.Text;

public partial class DynamicGridViewPage : System.Web.UI.Page
{
    public int RowCount
    {
        get
        {
            int returnValue = 0;

            if (Request.QueryString["rows"] != null)
            {
                try
                {
                    int.TryParse(Request.QueryString["rows"].ToString()
                                , out returnValue);
                }
                catch{
                    messageLabel.Text = @"Invalid row count! 
                                        Go back to the <a href=""Default.aspx"">home page</a> 
                                        to enter a value!";
                }
            }

            return returnValue;
        }
    }
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Persons listOfPersons = new Persons(RowCount);

            dynamicGridView.DataSource = listOfPersons;
            dynamicGridView.DataBind();
        }
    }
    protected void submitLinkButton_Click(object sender, EventArgs e)
    {
        Persons listOfPerson = new Persons();
        StringBuilder messageBuilder = new StringBuilder();

        foreach (GridViewRow gr in dynamicGridView.Rows)
        {
            if (gr.RowType == DataControlRowType.DataRow)
            {
                Person p = new Person();

                if (gr.FindControl("idLabel") != null)
                {
                    p.ID = int.Parse((gr.FindControl("idLabel") as Label).Text);
                }

                if (gr.FindControl("firstnameTextBox") != null)
                {
                    p.Firstname = (gr.FindControl("firstnameTextBox") as TextBox).Text;
                }

                if (gr.FindControl("lastnameTextBox") != null)
                {
                    p.Lastname = (gr.FindControl("lastnameTextBox") as TextBox).Text;
                }

                if (gr.FindControl("isChristianCheckBox") != null)
                {
                    p.IsChristian = (gr.FindControl("isChristianCheckBox") as CheckBox).Checked;
                }

                if (!p.Firstname.Equals(String.Empty) 
                    && !p.Lastname.Equals(String.Empty))
                {
                    listOfPerson.Add(p);
                }
                else
                {
                    messageBuilder.Append(String.Format(
                                            @"Record on line number {0} 
                                              was not submitted because 
                                              it doesn''t have a 
                                              Firstname or Lastname!<br />"
                                            , p.ID));
                }
            }
        }

        if (messageBuilder.Length > 0)
        {
            messageLabel.Text = messageBuilder.ToString();
        }
        else
        {
            messageLabel.Text = String.Empty;
        }

        submitedRecordsGridView.DataSource = listOfPerson;
        submitedRecordsGridView.DataBind();
    }
}

What happens on the code-behind is pretty simple. When the page loads it checks to see if it is not a PostBack, if it's not then it tries to retrieve the rows to create using the RowCount property. Once retrieved, that value is then passed to the contructor of the Persons class to create a dummy list of items that would then be assigned to the DataSource property of our GridView.

dynamiggridview02.jpg

dynamiggridview03.jpg

I've added code to the submit button to simulate submissions to show how you can retrieve the values entered on our GridView.

dynamiggridview04.jpg

And that's it. Thats how you create a dynamic rows in a GridView and access the values. I hope i was to shed light on this issue. Thanks!

Want the source code? Download it here: KeithRull.DynamicGridViewRows.v2.zip (6.37 KB)

Saturday, July 26, 2008 10:21:24 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | ASP.NET
Archive
<September 2008>
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Keith Rull
Sign In
Statistics
Total Posts: 271
This Year: 0
This Month: 0
This Week: 0
Comments: 182
Themes
Pick a theme:
All Content © 2010, Keith Rull
DasBlog theme 'Business' created by Christoph De Baene (delarou)