Thursday, May 19, 2011

Custom Rating Control, create your own simple rating control


I have implemented rating control in one of my application by using two images (blue star and white star), and written c# code for displaying the rating selected by the user, you can store the selected rating in the database also and display accordingly.

You might be wondering if rating controls are already available then why build from scratch, your thinking is absolutely right; however I wanted a simple light weight control for my application so that I can change anything I want.
First what is does it display 5 rating white stars and when user click on any star let’s say click on 3rd  then you have to replace the image URL of previous 2 images and the clicked one to blue (whatever color you like), so it will become 3 blue star.
Lets have a look at the sample code. You just need to pass the rating value to the setFeebackScore method; it will set the images and display the score description accordingly. You can create this control as a component and use it wherever you want in your application.

  private const string IMAGE_FEEDBACK_BLUE      = "/_layouts/images/neon_FeedbackBlue.JPG";
  private const string IMAGE_FEEDBACK_WHITE   = "/_layouts/images/neon_FeedbackWhite.JPG";

  private void setFeedbackScore(float rating)
        {
            if (rating == float.Parse("1"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = "(Poor)";
            }
            else if (rating == float.Parse("2"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = "(Fair)";
            }
            else if (rating == float.Parse("3"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = "(Good)";
            }
            else if (rating == float.Parse("4"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = "(Very Good)";
            }
            else if (rating == float.Parse("5"))
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_BLUE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_BLUE;

                lblScoreDescription.Text = "(Excellent)";
            }
            else
            {
                imgPoor.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgFair.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgVeryGood.ImageUrl = IMAGE_FEEDBACK_WHITE;
                imgExcellent.ImageUrl = IMAGE_FEEDBACK_WHITE;

                lblScoreDescription.Text = string.Empty;
            }

Friday, March 25, 2011

JavaScript to auto increase height of multiline text box


Here is the Java script code for auto resizing multiline text box. What it does is when user keeps typing in the text box and reach to the end line then text box height automatically increases.
<script type="text/javascript">
// this function takes text box as input parma which need to grow in height upon typing
    function AutoResizeMultilineTextBox(txtBox) {

        nCols = txtBox.cols; // find total columns set to the text box
        sVal = txtBox.value; // total characters
        nVal = sVal.length; // total lenth of the character
        nRowCnt = 1; // new row count variable reset to 1

        // this loop is written to find out total new row count to be added depending upon the character lenght
        //and new line found in the character
        for (i = 0; i < nVal; i++) {
            if (sVal.charAt(i).charCodeAt(0) == 13) {
                nRowCnt += 1;
                }
            }

        // check if new row count is less than the rown count covered by the character
        if (nRowCnt < (nVal / nCols)) { nRowCnt = 1 + (nVal / nCols); }
            txtBox.rows = nRowCnt+2;      

    }
</script>


Example text box

<asp:TextBox ID="txtMsg" runat="server"  TextMode="MultiLine"  onkeyup="AutoResizeMultilineTextBox(this)" Rows="3" Columns="50" />

Above code will cover all scenarios
-          User Continuous typing
-          User keep hitting new line (Enter Button)
-          User hit back button

Event Validation Error when switching between aspx pages


 In .Net web applications when you switch between pages very frequently sometimes you might observe exceptions (page breaks).

Exception:
Invalid postback or callback argument. Event validation is enabled using <pages enableeventvalidation="true" /> in configuration or <%@ page enableeventvalidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.”

Solution:
This problem occurs when post back happen before completely loading the previous page, to avoid this problem you need add following code under page element in web.config file
<pages  ValidateRequest="false"  EnableEventValidation="true" >
This will solve your problem; you don’t need to add these setting codes in all your aspx pages, if you have added it under page element in web.config then it will work for all the pages throughout the application.

Tuesday, August 3, 2010

How to keep session alive in asp.net application


Friends, many times we get requirements to increase the session timeout expiry time on the application server, so what we do basically we go in web.config file and set session time out to some time period, by default its 20 mins, but remember sometime you increase time period in web.config file and it doesn't work why?? The reason is you also have to check your application pool recycling time period it should be more than the session expiry period which you are doing in web.config file.

 Yo! But anyways you did not avoid session expiration in your application, session will still expire in your application let's say if user filling a long form in your application or kept a page open and gone out for coffee. So now what will happen? Session will expire right? By the time use will be back and resume with the work.

Some people do session resetting in code behind by checking if session is null then read User ID () from cookies and reset it. Or if it is intranet application and AD authentication then you get the current logged in user in system and set it in session.Now if you don't wanna do all above crap In your application, what all you wanna do is don't let session to get expire unless user close the browser. To implement this behavior in your applications simply follow below steps.
  1. First of all let me give you some brief about working session state in asp.net. By default it is set to 20 min, so if user sends a request to the server (in simple language browse a page) then server stores the time when request came and extend the session time out to 20 min, so if after 10 min user send again a request so it keeps extended to 20 min, if user don't send any request to server till 20 min then session get expires. This is basic working of session state.

  2. From first step you know that, server need to get any request from client to keep session alive, so now we can think of some methodology to keep pinging the server, below is the script which will keep sending request to the server and will keep session alive.

    Create a SessionCheck.aspx page in your application; you can keep this page blank. So that if it gets called from the browser then it should not be over loaded.

    Using Java Scrip:
    Image will be used to keep session alive by changing image src, assigning this property to some 
    <img id="imgSessionCheck" width="1" height="1" />

    <script type="text/javascript" >
    //Variable used to prevent caching on some browsers and knowing the count how many times user sends request to server.
        var counter;
        counter = 0;

        function KeepSession() {
    // Increase counter value
        counter++;

        // Gets reference of image
        var img = document.getElementById("imgSessionCheck");

        // Set new src value, which will send a request to the server
    img.src = "http://servername:port/appName/SessionCheck.aspx?count=" + counter;

        // now schedule this process to happen in some time interval, in this example its 1 min
        setTimeout(KeepSession, 60000);
    }

        // Call this function for a first time
        KeepSession();
        </script>

    Using JQuery:
    <script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script language="javascript" type="text/javascript">

        function KeepSession() {
        // A request to server
        $.post("http://servername:port/appName/SessionCheck.aspx");

        //now schedule this process to happen in some time interval, in this example its 1 min
        setInterval(KeepSession, 60000);
    }

        // First time call of function
        KeepSession();
     </script>

    So it's simple just you need to put this script in your page.

    Thanks for ready this post.

    Happy Coding!!!

Wednesday, May 26, 2010

Controlling SQL Server 2005 behavior by setting database options regarding NULL values


To access SQL Server there are many Tools and interfaces available, these interfaces can have some default settings to control the database behavior from front end. Right now I am going to talk about most familiar database front end interface SQL Server Management Studio.

To open database Options,

Right Click your database >> Properties >> Options, you will get below screen shot.






ANSI NULL Default:

The default option ANSI NULL DEFAULT corresponds to two session settings ANSI_NULL_DFLT_ON and ANSI_NULL_DFLT_OFF. When ANSI null default database option is false, then the new columns created with the ALTER TABLE and CREATE TABLE statements are by default NOT NULL if Nullability for the column is not explicitly defined.

When this option is set to ON, columns comply with the ANSI SQL-92 rules for column nullability. That is if you don't specifically indicate whether a column in a table allows NULL values, NULLs are allowed. When this option is set to OFF, newly created columns do not allow NULLs if no nullability constrains is specified.

ANSI_NULLS:

Database option ANSI Nulls corresponds to the session settings SET ANSI_NULLS. When this option is set to true, all comparison to a null value evaluate to false. When it is set to false, comparison of non-Unicode values to a null evaluate to true if both values are NULL.

In addition if this option is set to true then your code must use the function IS NULL to determine whether a column has a NULL value. When this option is set to false, SQL Server allows=NULL as a synonym for IS NULL and <> NULL as a synonym for IS NOT NULL.

Below is the code snippet to demonstrate this behavior.

I have a user table in which Email column is having NULL values,

-- This query returns all the rows where email = null, so column to null comparison works

set
ANSI_NULLS
OFF

GO

select
*
from Users where email =
NULL


 

-- This query doesnt return any row, colum to NULL comparison doesnt work

set
ANSI_NULLS
ON

GO

select
*
from Users where email =
NULL


 

ANSI_PADDING:

When this option is set to ON, string being compared with each other are set to the same length before the comparison take place. When this option is OFF, no padding takes place.

ANSI_WARNING:

When this option is set to ON, errors or warnings are issued when conditions such as division by zero or arithmetic overflow occurs.

CONCAT_NULL_YEILDS_NULL:

When this option is set to ON, concatenating two strings results in a NULL string if either of the string is NULL. When this option is set to OFF, a NULL string treated as an empty (zero-length) string for the purpose of concatenation.

Monday, May 17, 2010

Saving changes is not permitted. How to save the changes in table design, column ordering in SQL Server 2005 / 2008


Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that requires the table to be re-created.

Screen shot:





While designing database or during initial development mode I keep changing the database schema (sometimes adding more fields or re-arranging the column positions) I got this popup many times and that makes me to go and write alter script to do the changes in table schema but through alter script I dont know how to change the column position so at last I have to fix this popup and do my changes easily through table designer.

Below are few steps to fix this popup and it will never appear

Step1: in SSMS, go to Tools>>Options…






Step 2: Drill down to Designers >> Table and Database Designers

Step 3: You will see bunch of check boxes there is one which is highlighted in above screen shot "Prevent saving changes that requires table re-creation" uncheck this check box,

Hit OK, that's all you are done, now go to your table designer and add columns, rearrange column position now it will not prompt any popup.

Cheers!!!!

Thursday, May 13, 2010

Table Variable Vs Temp table in SQL Server


In many scenarios we need some temporary table for the processing of data. Now you have two option 1) Table Variable, 2) temp Table. Which one do you choose? Let's talk about differences between these two and make sure our decision to use one of them is best for our requirement.

Table VariableTemp Table
Performance differences
Table variables don't participate in transactions, logging or locking. This means they're faster as they don't require the overhead, but conversely you don't get those features.Temporary Tables are real tables so you can do things like CREATE Indexes, etc. If you have large amounts of data for which accessing by index will be faster than temporary tables are a good option
You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (e.g. make a function to split a string into a table of values on some arbitrary delimiter).You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing data types over time, since you don't need to define your temp table structure upfront.
A table variable can only have a primary index, A temp table can have indexes
If speed is an issue Table variables can be fasterBut if there are a lot of records, or the need to search the temp table of a clustered index, then a Temp Table would be better.
A table variables don't have column statistics, This means that the query optimizer doesn't know how many rows are in the table variable (it guesses 1), which can lead to highly non-optimal plans been generated if the table variable actually has a large number of rowsWhereas temp tables do have column statistics so the query optimizer can choose different plans for data involving temp tables
You cannot alter a Table variable with DDL statement (so you cannot create a non clustered index on a table variable). That makes every table variable a heap, or at best a table with a single, clustered index, and every table variable access a table scan (or clustered index scan)Temp tables can be altered with DDL statements
User table variable if there less records for processingUse temp table if you have huge record for processing
Syntactical difference
-To create table variable
declare @T table  
(firstColumn varchar(100))


-insert operation
insert into @T select 'some value'

-select statement
select * from @T
-You can create temp table
create table #T 
 (firstColumn varchar(100))

-Insert Operation
insert into #T select 'some value'



-Select statement
select * from #T

 

So now I think you can make wise decision which one to use when. Have fun -J


 

Happy Coding!!!