Thursday, January 19, 2012

Keep Session Alive


<script language="javascript" type="text/javascript">
    var sessionTimeoutWarning = '<%= System.Configuration.ConfigurationSettings.AppSettings["SessionWarning"].ToString()%>'; //get Value from Webcofig
    var sessionTimeout = "<%= Session.Timeout %>"; //Get Sesstion TimeOut
    var timeOnPageLoad = new Date();
    var sessionWarningTimer = null;
    var redirectToWelcomePageTimer = null;
    //For warning
    var sessionWarningTimer;
    //To redirect to the welcome page
    var redirectToWelcomePageTimer;

    function CheckBrowserSession() {
        //For warning
        sessionWarningTimer = setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000);

        //To redirect to the welcome page
        redirectToWelcomePageTimer = setTimeout('RedirectToWelcomePage()', parseInt(sessionTimeout) * 60 * 1000);

    }
    //Session Warning
    function SessionWarning() {
        //minutes left for expiry
        var minutesForExpiry = (parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning));
        var message = 'Your session will expire in another ' + minutesForExpiry + 'mins. Do you want to extend the session?';
        //Confirm the user if he wants to extend the session
        if (Confirm(message)) {
            if (redirectToWelcomePageTimer != null) {
                clearTimeout(redirectToWelcomePageTimer);
            }
            //reset the time on page load
            timeOnPageLoad = new Date();

            sessionWarningTimer = setTimeout('SessionWarning()', parseInt(sessionTimeoutWarning) * 60 * 1000);

            //To redirect to the welcome page
            redirectToWelcomePageTimer = setTimeout('RedirectToWelcomePage()', parseInt(sessionTimeout) * 60 * 1000);

        }
        //*************************
        //Even after clicking ok(extending session) or cancel button,
        //if the session time is over. Then exit the session.
        var currentTime = new Date();
        //time for expiry
        var timeForExpiry = timeOnPageLoad.setMinutes(timeOnPageLoad.getMinutes() + parseInt(sessionTimeout));

        //Current time is greater than the expiry time
        if (Date.parse(currentTime) > timeForExpiry) {
            alert("Session expired. You will be redirected to welcome page");
            window.location = "Login/index";
        }
        //**************************
    }

    //Session timeout
    function RedirectToWelcomePage() {
        alert("Session expired. You will be redirected to welcome page");
        window.location = "Login/index";
    }


  $(document).ready(function () {
            CheckBrowserSession()
   
            });

</script>

Tuesday, January 10, 2012

Validate File upload Control


function ValidateFileUpload(ControlID, filename) {

            var isValid = false;
            var Extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
            var extArray = new Array("gif", "jpg", "tif", "jpeg", "tiff", "pdf", "txt", "doc", "docx", "rtf");

            for (var i = 0; i < extArray.length; i++) {
                if (extArray[i] == Extension) {
                    isValid = true;
                    break;
                }
            }
            if (isValid == false) {
                document.getElementById(ControlID).value = "";
                alert(' <%=ViewRes.Common.Invalidfileformat%>');
            }

        }


<input class="txtfld FileUpload" onchange="ValidateFileUpload(this.id,this.value)"
                            type="file" id="file1" name="AttributeImages1" />

Tuesday, December 20, 2011

Trim() function for IE


  String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, "");
        };


  var SelectedClient = $("#SelectedClient").val();
    var Data= SelectedClient.trim()

Wednesday, August 31, 2011

Asp.Net MVC and Report Viewer Control



public ActionResult GetActiveRecordReports()
        {
            List<PE_getActiveCaseListResult> myResult = new List<PE_getActiveCaseListResult>();
            try
            {
                // myResult = (List<PE_getActiveCaseListResult>)Session["GETACTIVEREPORTDATA"];
                myResult = (List<PE_getActiveCaseListResult>)WebserviceHelper.GetReportData("GETACTIVEREPORTDATA"); //List
                CasesModel model = new CasesModel();
                LocalReport localReport = new LocalReport();
                localReport.ReportPath = Server.MapPath("~/Reports/ActiveCaseReport.rdlc"); //Report Path
                String[] dateFrom = Request.QueryString[1].ToString().Split('K'); //Date
                String[] dateTo = Request.QueryString[2].ToString().Split('K');
                DateTime DateBegin = new DateTime(Convert.ToInt32(dateFrom[2]), Convert.ToInt32(dateFrom[0]), Convert.ToInt32(dateFrom[1]));
                DateTime DateEnd = new DateTime(Convert.ToInt32(dateTo[2]), Convert.ToInt32(dateTo[0]), Convert.ToInt32(dateTo[1]));
                string FileType = Request.QueryString[3].ToString();// File Type "PDF,Excel,TIF

                ReportDataSource reportDataSource = new ReportDataSource("AciveDataSet", myResult); //Dateset
                ReportParameter pFrom = new ReportParameter("DateFrom", DateBegin.ToString("MM/dd/yyyy")); //Parameter
                ReportParameter pTo = new ReportParameter("DateTo", DateEnd.ToString("MM/dd/yyyy"));
                localReport.SetParameters(new ReportParameter[] { pFrom, pTo });


                localReport.DataSources.Add(reportDataSource);
                string reportType = FileType;
                string mimeType;
                string encoding;
                string fileNameExtension;
                string deviceInfo = string.Empty;
                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes;
                //The DeviceInfo settings should be changed based on the reportType
                //http://msdn2.microsoft.com/en-us/library/ms155397.aspx

                //Render the report
                renderedBytes = localReport.Render(
                    reportType,
                    null,
                    out mimeType,
                    out encoding,
                    out fileNameExtension,
                    out streams,
                    out warnings);

                Response.AddHeader("content-disposition", "attachment; filename=ActiveCaseReport." + fileNameExtension);
                return File(renderedBytes, mimeType);

            }

            catch (Exception ex)
            {
                employment.CommonClasses.PeErrorLog.InsertErrorLog("User Name:-" + employment.CommonClasses.ControlHelper.GetPeSessionUserName(),
                                                                "GetActiveRecordReports():- " + ex.Message.ToString(), " Address:-" + Request.Path);
            }

            return null;
        }

Thursday, July 21, 2011

Select Dropdownlist Selected text through Value in JQuery



function ddlSelectedValue(obj,value) {
            $(obj).each(function () {
                $('option', this).each(function () {
                    if ($(this).val() == value) {
                        $(this).attr('selected', 'selected')
                    };
                });
            });

Wednesday, July 13, 2011

Add and Remove Style Sheet at Runtime in Javascript


function AddstyleSheets () {

 var cssNode = document.createElement('link');
            cssNode.type = 'text/css';
            cssNode.rel = 'stylesheet';
            cssNode.href = '<%: Url.Content("~/Content/css/index.css")%>';
            cssNode.media = 'screen';
            cssNode.title = 'dynamicLoadedSheet';
            document.getElementsByTagName("head")[0].appendChild(cssNode);

}

function RemovestyleSheets () {
            var styleSheets = document.styleSheets;
            var href = '<%: Url.Content("~/Content/css/index.css")%>';
          
            for (var i = 0; i < styleSheets.length; i++) {
               if (styleSheets[i].href == href) {
                  styleSheets[i].disabled = true;
                    break;
                }
            }

        }