Recent Posts

Tags

Community

Email Notifications

All Links

Blogs I Read

My Articles

JavaScript & CSS

Date & Time

SQL Server 2000/2005

Articles I Read

ASP.NET Free Controls

MVFP (Most Valuable Forum Posts)

Archives

July 2005 - Posts

Recursion is the Key

I have been stuck with an asp.net 2.0 Web application trying to schedule and organize elements in a ListBox, in such a way to add items to prevent overlapping, inclusions, and exclusions.

Finally, the problem was solved using Recursion.

Make sure always to keep in mind that concept.

Recursion is the Key

 

Regards

 

Dynamic Sorting in SQL Stored Procedure

Have you ever faced this error message from SQL Query Analyzer?

Server: Msg 245, Level 16, State 1, Procedure Paged_SelectAllProducts, Line 38
Syntax error converting the nvarchar value 'Chai' to a column of data type int.

That was generated when I was trying to ORDER BY a SELECT statement dynamically.

Check this example:

SELECT 
         ProductID,
         ProductName,
         UnitsInStock
FROM 
         Products
ORDER BY 
        -- This is called Dynamic Order BY
        CASE    WHEN @SortExpression = 1 THEN ProductID
        WHEN @SortExpression = 2 THEN ProductName
        END


I have the SortExpression as an input parameter to know by which column I should order the results.

Now, if the SortExpression is 1, the result will be ordered by ProductID.

What happens if the SortExpression is 2? You will get the above error, why?

What happens is that, the CASE statement converts implicitly all the parameters to teh First Data Type in the List of Cases. In this case, the query expects that all the Order By parameters should be of type Int, why? Because, the first Case is ProductID of type Int, so when it tries to Order By any of the subsequent parameters it will convert them into Int which is the data type of the first parameter in the list.

A work around would be using Multiple CASE Statments as follows:

SELECT 
        ProductID,
        ProductName,
        UnitsInStock
FROM 
        Products
ORDER BY 
        -- This is called Dynamic Order BY
        CASE    WHEN @SortExpression = 1 THEN ProductID END,
        CASE    WHEN @SortExpression = 2 THEN ProductName END

Hope that helps a bit,

Regards


 

First Community Night

Yesterday, the LebDev .NET UserGroup in Lebanon, presented the first night in a series of Community Nights sponsored by Microsoft Lebanon Office.

The Community Nights is an event whose goal is to share knowledge between developers about the latest .NET technologies.

Frias Hamdan President of the LebDev and Samer Chidiac PR, both are Microsoft MVPs, presented yesterday an overview of ASP.NET 2.0 and Visual Studio.NET 2005 Beta2. The first night was great guys, congratulations.

Next Monday, Wessam Zeidan, a Microsoft MVP and I will present a new session about Web Parts in ASP.NET 2.0.

If you are interested in joining us, please visit the http://www.lebdev.net

Regards,

 

UDF To Split a String and Return Specific Field

I saw a question today on the asp.net forums today on how to split a string and get each field inside the splitted string.

Mrs. Terri Morton, proposed a good solution, and it happened that I had used before a method similar to a one proposed by Terri, so here it is, look at the title and look at the code below:

The original method to split a string I used from the following article: http://www.4guysfromrolla.com/webtech/031004-1.shtml

However, I add the return value at a specific location functionality, which is usefull sometimes.

CREATE FUNCTION [dbo].SplitAt
(
    -- Returns NULL if index > maximum index in the input list
    @List NVARCHAR(2000),
    @SplitOn NVARCHAR(5),
    @Position INT
)
  
RETURNS VARCHAR(100)
     
AS  
    BEGIN
        DECLARE @IPosition INT
        DECLARE @RtnValue VARCHAR(100)
        SET @IPosition  = 1 

        -- While a delimiter is found in the original list
        WHILE ( CHARINDEX(@SplitOn,@List) > 0 )
        BEGIN

            -- If the position of the required item equals to the counter of the current item
            IF ( @IPosition = @Position )            
            BEGIN
                -- Get that data
                SELECT  @RtnValue =  ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))
            END

            -- Incrememt the cursor
            SELECT @IPosition = @IPosition + 1

            -- Remove from the original list the already checked item
            SELECT @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
        END

        -- We might be asking the last item in the original string
        IF ( @IPosition = @Position )
        BEGIN
            SELECT @RtnValue = @List
        END
        ELSE
        BEGIN
            SELECT @RtnValue = NULL
        END

        RETURN (@RtnValue)
    
    END

How to use the above method?

DECLARE @ID INT
DECLARE @Fname VARCHAR(20)

SELECT @ID = CAST( fn_SplitAt('1-Bilal', '-', 1) AS INT ),
            @Fname = CAST ( fn_SplitAt('1-Bilal', '-', 2) AS VARCHAR )

Hope that helps,


Regards

Nullable In C# 2.0

There is something nice in C# 2.0, the Nullable Types, where a variable defined with a nullable type can represent any data of its nullable type plus a null value. When assigning a nullable variable to another variable, you need to check if the former is null or not and accordingly assign values:

int? intVar1 = 20;
int intVar2;

if ( intVar1 == null )
     intVar2 = 12;
else
     intVar2 = intVar1.Value;

You can write the above as follows:

intVar2 = intVar1 ?? 12;

If intVar1 is null, then intVar2 will be assigned 12, else it will be assigned to intVar1.Value which is 20.

Hope that helps,

 

Enterprise Library - Data Access Application Block

I would like to announce my second article on http://www.aspalliance.com:

Get Started with the Enterprise Library Data Access Application Block

Hope you will benefit from it to the max.

Regards

 


Pre Select an Item in CheckBoxList and ListBox

In a previous post, I told you how to pre select an item in the DropDownList, now we will see how to pre select an item in the CheckBoxList and ListBox:

ListItem listitem = ((CheckBoxList)Page.FindControl(chboxDays)).Items.FindByValue("Monday");
listitem.Selected = true;

 

Hope that help too.

Regards

 

Auto Populating ListBox, CheckBoxList, DropDownList

Hello:

Make sure always to bind the ListBox, CheckBoxList, DropDownList ONLY ON !Page.IsPostBack.

There are two benefits to do so:

1- No need to have a second access to the database upon postback.

2- Selection of items will be preserved.

if (!Page.IsPostBack)
{
    this.ListBox1.DataSource = ...;
    this.ListBox1.DataBind();
}

Hope that helps, 

Getting Selected Items in ListBox, CheckBoxList, DropDownList

I was working today in a personal project and I had to get the selected items in a CheckBoxList, I thought of putting the code here so that you can have a look at it, its a bit tricky.

foreach (ListItem item in ((CheckBoxList)Page.FindControl("chkDays")).Items)
{
    if (item.Selected)
    {
        aDays.Add(item.Value);
    }
}

Hope that helps,

 

Some Nice Features about VS.NET 2005

There is a feature which surprised me today while working with VS.NET 2005 Beta version.

When you type : if, directly after typing if, press Tab, VS.NET will create for you the Condition & { }

The same thing applies to else, type else followed by Tab.

That is really great.

Regards

 

Posted: Jul 21 2005, 03:16 PM by simple | with no comments
Filed under:
Validate DropDownList

Here is an example of how to do so:

<form id="Form1" method="post" runat="server">
   <asp:DropDownList id="DropDownList1" runat="server">
       <asp:ListItem Value="-1">--> Choose  <--asp:ListItem>
       <asp:ListItem Value="1">Lebanonasp:ListItem>
       <asp:ListItem Value="2">Kuwaitasp:ListItem>
   </asp:DropDownList>
   <asp:RequiredFieldValidator id="RequiredFieldValidator1" 
runat="server" ErrorMessage="You must select a valid option" ControlToValidate="DropDownList1" InitialValue="-1"
Display="Dynamic" /
>
<P> <asp:Button id="Button1" runat="server" Text="Post Back" />
<P> <form>


Hope that helps,

Regards.

Define an Event Handler for a HyperLink Server Control

Hello, a common question on the ASP.NET Forum is:

How to define an Event Handler for a HyperLink?

The solution as follows:

protected System.Web.UI.WebControls.HyperLink HyperLink1;
    
private void Page_Load(object sender, System.EventArgs e)
{
    HyperLink1.Attributes.Add("onClick",
Page.GetPostBackEventReference(this.HyperLink1,"HyperLinkPostBack$"+this.HyperLink1.ID)); if ( (IsPostBack) && (Request.Form["__EVENTTARGET"] != null) && (Request.Form["__EVENTARGUMENT"].ToString().StartsWith("HyperLinkPostBack")) ) { string[] args = Request.Form["__EVENTARGUMENT"].ToString().Split('$'); if ( (string.Compare(args[0], "HyperLinkPostBack", false, System.Globalization.CultureInfo.InvariantCulture) == 0)
&& (args.Length > 1) ) { HyperLinkHandler(args[1].ToString()); } } } public void HyperLinkHandler(string ID) { Response.Write("You clicked HyperLink with ID : "+ ID); }
 
 
 Or You could use this way, using IPostBackEventHandler:
private void Page_Load(object sender, System.EventArgs e)
{
    HyperLink1.Attributes.Add("onClick", Page.GetPostBackEventReference(this, "HyperLinkPostBack" + "$" + this.HyperLink1.ID));
}

public void RaisePostBackEvent(string eventArgument)
{
    if (!string.IsNullOrEmpty(eventArgument))
        {
            string[] args = eventArgument.Split('$');
                if ((string.Compare(args[0], "HyperLinkPostBack", false, System.Globalization.CultureInfo.InvariantCulture) == 0) 
&& (args.Length > 1)) { HyperLinkHandler(args[1].ToString()); } } } public void HyperLinkHandler(string ID) { Response.Write("You clicked HyperLink with ID : " + ID); }
 

Hope that helps,

Regards

 


Add JavaScript Functionality to GridView

If you want to change the Cursor when the mouse is over the GridView, follow the simple steps below:

protected void RowCreated (object sender, GridViewRowEventArgs e)
{
    e.Row.Attributes.Add("onMouseOver", "this.style.cursor='n-resize'");
}


Hope that helps,

Regards

 

Posted: Jul 14 2005, 09:58 AM by simple | with no comments
Filed under:
Extend GridView

I want ot point you to two important links on Extending GridView, by Frerik Normen:

1- http://fredrik.nsquared2.com/print.aspx?PostID=186

2- http://fredrik.nsquared2.com/print.aspx?PostID=177

Hope that helps,

Regards

 

 

 

Posted: Jul 14 2005, 09:43 AM by simple | with no comments
Filed under:
DropDownList Pre Select

Sometimes you need to load a Web Form from Database. You might have a DropDownList inside the Web Form that you want to select a specific item in it, to do so you can try any of the two listed methods:

1- Set Selection by Text:
string strText;
DropDownList1.Items.FindByText(strText.ToLower().Trim()).Selected = true;

2- Set Selection by Value
string strValue;
DropDownList1.Items.FindByValue(strValue.ToLower().Trim()).Selected = true;

Regards,

TemplateField in GridView

You can call a custom method inside the TemplateField of the GridView as follows:

<TemplateField>
  <ItemTemplate>
      <%# GetSum((int)Eval(“Number1“), (int)Eval(“Number2“)) %>
  </ItemTemplate>
</TemplateField>

public string GetSum(int num1, int num2)
{
     return (num1+num2).ToString();
}

Hope that helps,

Regards

Posted: Jul 13 2005, 01:43 PM by simple | with 1 comment(s)
Filed under:
DateTime Methods

I had today to work with some DateTime calculations.

I need two methods:

1- Get time difference between two dates, in such a way to have the following formats in the returned value:

- Hours
- Minutes (01 -> 1 minute, 10 -> 10 minutes,...)
- Seconds
- Hours.Minutes
- Hours:Minutes:Seconds

2- Add a double value for a DateTime

- double value (7.02 -> 7 hours and 2 minutes, 7.10/7.1 -> 7 hours and 10 minutes)
- DateTime value

Check the methods below:

// partType :

//    0 - Hours,

//    1 - Minutes,

//    2 - Seconds,

//    3 - Hours.Minutes (HH.MM)

//    4 - All (HH:MM:SS)

private string GetTimeBetweenDates(DateTime firstDate,
DateTime secondDate,
int partType)

{

    string returnDate = null;

    if ( firstDate < secondDate )

    {

        TimeSpan spanDiff = secondDate.Subtract(firstDate);  

        int Hours   = spanDiff.Hours;

        int Minutes = spanDiff.Minutes;

        string strMinutes = string.Empty;

       int Seconds = spanDiff.Seconds;

 
       // Fix minutes

        switch (Minutes)

        {

          case 1: case 2: case 3: case 4: case 5: case 6:

                strMinutes = "0" + Minutes;

                break;

          default:

                strMinutes = Minutes.ToString();

                break;

        }

                                   

        //return value

        switch (partType)

        {

           case 0:

                 returnDate = Hours.ToString();

                 break;

           case 1:

                 returnDate = strMinutes;

                 break;

           case 2:

                 returnDate = Seconds.ToString();

                 break;

           case 3:

                 returnDate = Hours + "." + strMinutes;

                 break;

           case 4:

                 returnDate = Hours + ":" + strMinutes + ":" + Seconds;

                 break;

         }

    }

    // return date               

    return (returnDate);

}

 

private void AddTimeToDate(double dbTime, ref DateTime OriginalDate)

{

   string[] SplitTimeToAdd = dbTime.ToString().Split('.');

  double Hours = Convert.ToDouble(SplitTimeToAdd[0].ToString());

              

   // Add the hours

   OriginalDate = OriginalDate.AddHours(Hours);

                

   // Do some conversion on minutes

  // .0x -> Reads 5 minutes,

   // .x0  -> Reads 50 minutes

   // .xx -> Reads 33 minutes

   // .00 -> Reads 0 minutes

   double Minutes = 0.0;

                 

   // Convert the minutes section to an array of chars

   if ( SplitTimeToAdd.Length > 1 )

   {

     if ( SplitTimeToAdd[1].Length >= 1 )

     {          

       // .x case

       if ( (SplitTimeToAdd[1].Length == 1) )

          Minutes = (Convert.ToDouble(SplitTimeToAdd[1].ToString()) * 10 );

       else

          Minutes = Convert.ToDouble(SplitTimeToAdd[1].ToString());

                             

       // Add the calculated minutes

       OriginalDate = OriginalDate.AddMinutes(Minutes);

     }

   }

   else

     // Add the calculated minutes

     OriginalDate = OriginalDate.AddMinutes(Minutes);

}

Facts about GridView

Hi: I would like to share with you some facts about the Events fired in the GridView:

 ----------------------------------------------------------
RowCommand
       Is Fired BEFORE 
                  SelectedIndexChanging
                             Is Fired BEFORE
                                          SelectedIndexChanged
-----------------------------------------------------------

----------------------------------------------------------
RowDeleting
       Is Fired BEFORE
                   ObjectDataSource Delete Method
                             Is Fired BEFORE 
                                          RowDeleted
-----------------------------------------------------------

-----------------------------------------------------------
The CommandName in:
    1- ButtonField
    2- CommandField
    3- TemplateField containing a Button, LinkButton, ImageButton

If set to:
    1- Delete
    2- Select
    3- Insert
    4- Edit
    5- etc...

The first method to fire is RowCommand before any other method.
For example, if you have set OnRowDeleted, OnRowDeleting, OnRowCommand in the GridView on your page, the events are as follows:

1- RowCommand
2- OnRowDeleting
3- OnRowDeleted

Hope the information above helps you out.

Regards




 

Posted: Jul 12 2005, 04:32 PM by simple | with no comments
Filed under:
ASP.NET 2.0 Security Cont'd

A good solution to my problem could be:

Integrate SqlMembershipProvider + Profile object to be able to customize the membership API to my needs.

Now you can inherit from SqlMembershipProvider, customize the methods you want, if additional data is needed, use the Profile object to hold that additional data.

Hope that helps.

Regards

 

Posted: Jul 07 2005, 01:40 PM by simple | with no comments
Filed under:
Some Happy News About ASP.NET 2.0 Security

Hello:

I have been trying hard to customize the ASP.NET 2.0 Membership API to my own needs. However, all what I can do as it seems is just to customize the Data Store by overriding the MembershipProvider and interacting with a database other than SQL Server 2000 or SQL Server Express 2005.

What I wanted to do is still use the ASP.NET 2.0 Membership API but customize certain methods like the CreateUser, GetUser and other methods to reflect the users of my own application I am working on.

Still I couldn't succeed.

BUT, the good news are: LoginView, LoginName, LoginStatus are work regardless of the ASP.NET 2.0 Membership API. This means that if you are using FormsAuthentication without even using any of the Membership API, then you can stil use those valuable controls :D

Hope that helps a bit,

Regards

 

Posted: Jul 06 2005, 11:07 AM by simple | with no comments
Filed under:
More Posts Next page »