Sunday, December 30, 2012

Detect Browser Refresh to avoid events fired again in ASP.NET


If you have created an aspx page using C# and ASP.NET and have put a button on it. And in the Click event of this button if you are inserting some data in database , after click if user refresh the page than click event gets fired again resulting data insertion to database again, to stop events on the page getting fired on browser refresh we need to write bit of code to avoid it.

In this example I’ve put a Label and a Button on the page, on click the label Text becomes Hello and when I refresh the page label's text again becomes Hello

Markup




Now in the Page_Load event I m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event I am creating a Viewstate variable and assigning Session variable's value to it than in button's click event I am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed 

  
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
}
protected void imgbtn_Click(object sender, ImageClickEventArgs e)
{
//Label2.Text = imgbtn.ToolTip;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
{
Label1.Text = "Hello";
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "Page Refreshed";
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
}

Saturday, December 22, 2012

Code for update panel postback problem solving by using Jquery


 I have a grid when I postback this grid by linkbutton which is in this grid jquery function was not working in mouse over so I paste this code into update panel to avoid postback .

    script type ="text/javascript"
                var prm = Sys.WebForms.PageRequestManager.getInstance();
                prm.add_endRequest(function () {
                    grid();
                });
            script

Saturday, September 22, 2012

Refresh Page Issue in ASP.Net


Introduction

In Web Programming, the refresh click or postback is the big problem which generally developers face. So in order to avoid the refresh page issues like, if user refreshes the page after executing any button click event/method, the same method gets executed again on refresh. But this should not happen, so here is the code to avoid such issues.

Using the Code

Here the page's PreRender event and ViewState variable helps to differentate between the Button click event call or the Refresh page event call. For example, We have a web page having button to display text entered in text box to the Label.
So when page is first time loaded, then a session["update"] object is assigned by some unique value, and then thePreRender event is being called, where that session is assigned to the viewstate variable.
And on button click event, the session assigning code from page load will never called, as it is postback, so it directly calls the button click event where there is check whether the session and viewstate variables have same value. Here both values will be same. At the end of the click event method, the session variable is assigned with new unique value. Then always after click event, the PreRender event gets called where that newly assigned session value is assigned to viewstate variable.
So whenever the page is being refreshed, viewstate value will become previous value (previous value is taken from viewstate hidden control) which will never match with current session value. So whenever the control goes in button click event, the match condition never gets satisfied hence code related to button click never gets executed.

Points of Interest

Here we can understand the page events flow as well as Viewstate variable's workflow easily.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack) // If page loads for first time
    {
        // Assign the Session["update"] with unique value
        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
        //=============== Page load code =========================




        //============== End of Page load code ===================
    }
}

protected void btnDisplay_Click(object sender, EventArgs e)
{ 
    // If page not Refreshed
    if (Session["update"].ToString() == ViewState["update"].ToString())
    {
        //=============== On click event code ========================= 

        lblDisplayAddedName.Text = txtName.Text;

        //=============== End of On click event code ==================

        // After the event/ method, again update the session 

        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
    }
    else // If Page Refreshed
    {
        // Do nothing 
    }
}

protected override void OnPreRender(EventArgs e)
{
    ViewState["update"] = Session["update"];
}

Saturday, July 7, 2012

One Simple Procedure for Cursor.


Procedure That make insertion into table according weekdays which weekday data I have in my one table.

ALTER PROC [dbo].[CRS_VehicleAdultChildPrice_Flat]        
@pk_VehiclePriceID int,      
@WEEKDAYID NVARCHAR (255),
@SeasonEndDate NVARCHAR(25),
@SeasonStartDate NVARCHAR(25)    
AS      
DECLARE @fkVehiclePriceID int      
DECLARE @SessionDate  NVARCHAR(25)        
DECLARE @ChildNo int
DECLARE @ChildMinAge int
DECLARE @ChildMaxAge int    
DECLARE @AdultPrice decimal(18,2)
DECLARE @ChildPrice decimal(18,2)        
DECLARE @TourDate datetime    
DECLARE @Culture nvarchar(10)      
DECLARE @CreatedBy nvarchar(255)      
DECLARE @ModifiedBy nvarchar(255)    
DECLARE @timings nvarchar(1000)  

DECLARE @CUR CURSOR      
DECLARE @CURDATE CURSOR        

SET @CUR = CURSOR FOR SELECT        
pk_VehiclePriceID    
,AdultPrice
,VMS_TBL_VehiclePrice.Culture      
,VMS_TBL_VehiclePrice.CreatedBy      
,VMS_TBL_VehiclePrice.ModifiedBy
,VMS_TBL_VehiclePrice.timing


 FROM VMS_TBL_VehiclePrice        
INNER JOIN VMS_VehicleAdultPrice_Detail ON VMS_VehicleAdultPrice_Detail.fkVehiclePriceId=VMS_TBL_VehiclePrice.pk_VehiclePriceID      
WHERE pk_VehiclePriceID=@pk_VehiclePriceID ORDER BY pk_VehiclePriceID    
OPEN @CUR      
FETCH NEXT      
FROM @CUR INTO        
@fkVehiclePriceID,    
@AdultPrice,      
@Culture,      
@CreatedBy,      
@ModifiedBy,
@timings      
 
WHILE @@FETCH_STATUS = 0      
BEGIN      
     
   SET @CURDATE = CURSOR FOR SELECT        
   DATE_NAME FROM TBL_DATE_WEEKDAY WHERE WEEKDAYID IN (SELECT * FROM DBO.SPLIT(@WEEKDAYID,',')) AND ( CONVERT(DATETIME,DATE_NAME)>=Convert(DATETIME,@SeasonStartDate) AND CONVERT(DATETIME,DATE_NAME) <=Convert(DATETIME,@SeasonEndDate))      
   OPEN @CURDATE      
   FETCH NEXT      
   FROM @CURDATE INTO @SessionDate      
   print @@FETCH_STATUS      
   WHILE @@FETCH_STATUS = 0      
   BEGIN      
   print @SessionDate      
         
     
         INSERT INTO VMS_VehicleAdultPrice_Flat(fkVehiclePriceID, AdultPrice,TourDate, Culture, CreatedBy, CreatedOnDate, ModifiedBy, ModifiedOnDate, Row_Guid, Row_Status,timings)      
          VALUES(@fkVehiclePriceID,@AdultPrice,@SessionDate ,@Culture,@CreatedBy,GETDATE(),@ModifiedBy,GETDATE(),NEWID(),1,@timings)          
     
           
     
   FETCH NEXT      
   FROM @CURDATE INTO @SessionDate    
   END      
   CLOSE @CURDATE      
   DEALLOCATE @CURDATE      
   
FETCH NEXT      
FROM @CUR INTO @fkVehiclePriceID,  
   
@AdultPrice,  

@Culture,      
@CreatedBy,      
@ModifiedBy,
@timings      
 
 
END    
CLOSE @CUR      
DEALLOCATE @CUR



SET @CUR = CURSOR FOR SELECT        
pk_VehiclePriceID    
,ChildNo
,ChildMinAge
,ChildMaxAge
,ChildPrice

,VMS_TBL_VehiclePrice.Culture      
,VMS_TBL_VehiclePrice.CreatedBy      
,VMS_TBL_VehiclePrice.ModifiedBy

 FROM VMS_TBL_VehiclePrice        
INNER JOIN VMS_TBL_ChildPrice_Detail ON VMS_TBL_ChildPrice_Detail.fkVehiclePriceId=VMS_TBL_VehiclePrice.pk_VehiclePriceID        
WHERE pk_VehiclePriceID=@pk_VehiclePriceID ORDER BY pk_VehiclePriceID    
OPEN @CUR      
FETCH NEXT      
FROM @CUR INTO        
@fkVehiclePriceID,
@ChildNo,      
@ChildMinAge,      
@ChildMaxAge,      
@ChildPrice,      
     
@Culture,      
@CreatedBy,      
@ModifiedBy      
 
WHILE @@FETCH_STATUS = 0      
BEGIN      
     
   SET @CURDATE = CURSOR FOR SELECT        
   DATE_NAME FROM TBL_DATE_WEEKDAY WHERE WEEKDAYID IN (SELECT * FROM DBO.SPLIT(@WEEKDAYID,',')) AND ( CONVERT(DATETIME,DATE_NAME)>=Convert(DATETIME,@SeasonStartDate) AND CONVERT(DATETIME,DATE_NAME) <=Convert(DATETIME,@SeasonEndDate))      
   OPEN @CURDATE      
   FETCH NEXT      
   FROM @CURDATE INTO @SessionDate      
   print @@FETCH_STATUS      
   WHILE @@FETCH_STATUS = 0      
   BEGIN      
   print @SessionDate      
         
       
       
     
        INSERT INTO VMS_VehicleChildPrice_Flat(fkVehiclePriceID, ChildNo, ChildMinAge, ChildMaxAge, ChildPrice, TourDate, Culture, CreatedBy, CreatedOnDate, ModifiedBy, ModifiedOnDate, Row_Guid, Row_Status)      
          VALUES(@fkVehiclePriceID, @ChildNo, @ChildMinAge, @ChildMaxAge,@ChildPrice,@SessionDate ,@Culture,@CreatedBy,GETDATE(),@ModifiedBy,GETDATE(),NEWID(),1)          
     
     
     
     
   FETCH NEXT      
   FROM @CURDATE INTO @SessionDate    
   END      
   CLOSE @CURDATE      
   DEALLOCATE @CURDATE      
   
FETCH NEXT      
FROM @CUR INTO @fkVehiclePriceID,  
@ChildNo,      
@ChildMinAge,      
@ChildMaxAge,  
 
@ChildPrice,
@Culture,      
@CreatedBy,      
@ModifiedBy      
 
 
END    
CLOSE @CUR      
DEALLOCATE @CUR

Time Drop Down Filling.


 public void GetTiming()
        {
            ArrayList aTime = new ArrayList();
            int interval = Convert.ToInt32(txtTimeInterval.Text);
            DateTime EndTime = Convert.ToDateTime(txtEndTime.Text);
            DateTime StartTime = Convert.ToDateTime(txtStartTime.Text);
           
            for (int i = interval; i <= 1440+1; i++ )
            {
                if (StartTime != EndTime)
                {
                  aTime.Add(StartTime.ToString("HH:mm"));
                  StartTime = StartTime.AddMinutes(interval);
               
                }
                else if (StartTime == EndTime)
                {
                    aTime.Add(StartTime.ToString("HH:mm"));
                    break;
                }
            }
            chkTiming.DDList.DataSource = aTime;
            chkTiming.DataBind();
            chktime.Visible = true;
           
        }

Regular Expression For Specific Time Format("HH:MM")


asp:TextBox ID="txtStartTime" runat="server" Width="100" asp:TextBox
                                                                                    asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="txtStartTime"
                                                                                            Display="None" ErrorMessage="Start Time missing" SetFocusOnError="True"
                                                                                            ValidationGroup="validComboAddGrp" asp:RequiredFieldValidator
                                                                                            asp:RegularExpressionValidator ID="regextxtSessionTime" runat="server"
    ControlToValidate="txtStartTime"
    ValidationExpression="^([0-1][0-9]|[2][0-3]):([0-5][0-9])$"
    ErrorMessage="You must enter a valid time. Format: HH:MM"
    Display="none"
    SetFocusOnError="true" ValidationGroup="validComboAddGrp"
  asp:RegularExpressionValidator

Saturday, April 28, 2012

Bind Table using javascript like grid or repeater.



Bind Any Table which comes from code behind stored procedure calling....Like this simply make a method which is webmethod into code behind and call it on client side.The Total code is below I am writing here.
//--------------------Bind Elective Papers on Change Of Specialization------------------
        function ShowElectivePapers() {

            var dCID = document.getElementById('<%= ddlCourse.ClientID%>');
            var CourseID = dCID.options[dCID.selectedIndex].value;
            var dSID = document.getElementById('<%= ddlSemester.ClientID%>');
            var SemID = dSID.options[dSID.selectedIndex].value;
            var dSpec = document.getElementById('<%= ddlSpecialization.ClientID%>');
            var SpecID = dSpec.options[dSpec.selectedIndex].value;
            if (SpecID != 0) {
                BindElectivePapers(CourseID, SemID, SpecID);
            }
        }


        function BindElectivePapers(CCode, SemId, Spec) {

            $.ajax({
                type: "POST",
                url: "StudentRegistration.aspx/BindElectivePapers",
                contentType: "application/json; charset=utf-8",
                data: "{'CCode': '" + CCode + "','SemId': '" + SemId + "','Spec': '" + Spec + "'}",
                dataType: "json",
                async: false,
                success: AjaxSucceeded,
                error: AjaxFailed
            });

            function AjaxSucceeded(result) {
                DisplayChildren(result);
            }
            function AjaxFailed(result) {
                alert('no success');
            }
            function DisplayChildren(result) {
                var dtEpaper = eval(result.d);
                if (dtEpaper != null && typeof (dtEpaper) == "object") {
                    document.getElementById('<%= dvElectivePapers.ClientID%>').style.display = '';
                    var s = new Array();
                    s[s.length] = "
Elective Papers
"
                    s[s.length] = "
"
                    s[s.length] = "
"
                    s[s.length] = "
";
                    s[s.length] = "
";
                    s[s.length] = "
";
                    s[s.length] = "
";
                    s[s.length] = "
";
                    for (var i = 0; i < dtEpaper.Table.length; i++) {
                        s[s.length] = "
";
                        s[s.length] = "
";
                        s[s.length] = "
";
                        s[s.length] = "
";
                    }
                    s[s.length] = "
Paper CodePaper Name
" + dtEpaper.Table[i].Code + "" + dtEpaper.Table[i].SubName + "
";
                    s[s.length] = "
";
                    document.getElementById("<%= dvElectivePapers.ClientID%>").innerHTML = s.join("");
                }
                else {
                    document.getElementById('<%= dvElectivePapers.ClientID%>').style.display = 'none';
                }
            }
        }

        // -----------------------.cs Code with stored procedure caliing--------------

 #region "BindElectivePapers"
    [WebMethod]
    public static Dictionary BindElectivePapers(string CCode, string SemId, string Spec)
    {
        CommonManger Obj = new CommonManger();
        DataTable objEPaper = new DataTable();
        objEPaper = Obj.GetTableWithParameter("SP_GetElectivePapers_ViaSpecialization", "@CrsID", CCode, "@Sem", SemId, "@CrsSpl", Spec);
        if (objEPaper.Rows.Count > 0)
        {
            return JsonMethods.ToJson(objEPaper);
        }
        else
        {
            return null;
        }
    }
    #endregion

Wednesday, April 25, 2012

Make custom order in sql



Hi,
I can also make my query according to my customization order called Custom Order .It works as i want in which order my out will show .As simple as it is...
SELECT COUNT(*)StudentCount,SessionCode FROM dbo.tblStudentNEDESROLL GROUP BY SessionCode ORDER BY CASE
            WHEN SessionCode = '0110' THEN 1
            WHEN SessionCode = '0710' THEN 2
            WHEN SessionCode = '0111' THEN 3
            WHEN SessionCode = '0711' THEN 4
            WHEN SessionCode = '0112' THEN 5
           
         END

Friday, April 20, 2012

Set Default database in sql on New Query


This is to set any database when U want any database come to add query.In ur sql.
Exec sp_defaultdb @loginame='login', @defdb='master'

Sunday, January 22, 2012

Check checkbox only in Repeater not outside of this control


This is the code for finding particular checkbox in repeater only .it will leave the checkboxes which  outside repeater  of the page.I hope it will do what you want exactly ....enjoy coding....!!!

function checkAll(cb) {
        var TargetBaseControl = document.getElementById('pnlData');
        var TargetChildControl = "chkisPassout";

       var ctrls = document.getElementsByTagName('input');
     
        for (var i = 0; i < ctrls.length; i++)
          {
              var cbox = ctrls[i];
              if (cbox.type == "checkbox" && cbox.id.indexOf(TargetChildControl,0) >= 0)
            {
                cbox.checked = cb.checked;
            }
        }
    }