Tuesday, December 9, 2014

How to disable all controls on the Page

How to disable all controls on a page.

You can add all different controls in the code below to disable and enable them. This fill find all controls on the page and will disable or enable it based on value being passed to it.
public void DisablePageControls(bool status)
        {

            foreach (Control c in Page.Controls)
            {
                foreach (Control ctrl in c.Controls)
                {

                    if (ctrl is TextBox)
                        ((TextBox)ctrl).Enabled = status;
                    else if (ctrl is Button)
                        ((Button)ctrl).Enabled = status;
                    else if (ctrl is RadioButton)
                        ((RadioButton)ctrl).Enabled = status;
                    else if (ctrl is RadioButtonList)
                        ((RadioButtonList)ctrl).Enabled = status;
                    else if (ctrl is ImageButton)
                        ((ImageButton)ctrl).Enabled = status;
                    else if (ctrl is CheckBox)
                        ((CheckBox)ctrl).Enabled = status;
                    else if (ctrl is CheckBoxList)
                        ((CheckBoxList)ctrl).Enabled = status;
                    else if (ctrl is DropDownList)
                        ((DropDownList)ctrl).Enabled = status;
                    else if (ctrl is HyperLink)
                        ((HyperLink)ctrl).Enabled = status;
                }
            }

        }

DisablePageControls(false); // To enable
DisablePageControls(true); // To disable


Message Box using Telerik Rad Window Manager

Message Box using Telerik Rad Window Manager
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" EnablePageHeadUpdate="False" EnableAJAX="true">
        </telerik:RadAjaxManager>
<telerik:RadWindowManager ID="RadWindowManager1" runat="server" EnableShadow="false"  DestroyOnClose="true">
</telerik:RadWindowManager>
public void ShowMessage(string message, int x = 350, int y = 150)
{
  RadWindowManager window = null;
  window = (RadWindowManager)this.Page.FindControl("RadWindowManager1");
  window.DestroyOnClose = true;
  window.EnableShadow = false;
  window.RadAlert(message, x, y, "Information", "");
 }


//To call

ShowMessage(“Message that needs to be displayed”);


Message Box or Alert using JavaScript



Progress bar for long running task in Parallel.ForEach

Progress bar for long running task in Parallel.ForEach

Please note to update the progress bar and update the counter in thread safe manner, the code is written into lock block.
Lock keyword is used to handle the threads to enter into critical section.

int counter, totalFiles;
private void StartJob_Click(object sender, EventArgs e)
{
 progressBar1.Maximum = 100;
 progressBar1.Step = 1;
 progressBar1.Value = 0;
 backgroundWorker1.RunWorkerAsync();           
 }

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
 List files = GetFiles();
 totalFiles = files.Count;
 // Let say Reading Files and Stroing them into Database
 Object countLock = new Object();
 Parallel.ForEach(Files, file =>
 {
  ProcessFiles(file);
  lock (countLock)
  {
   counter++;
   i++;
   backgroundWorker1.ReportProgress((i * 100) / totalFiles);
  }
 });

}

private void ReportProgress(int value)
{
  progressBar1.Value = value;
 label1.Text = string.Format("{0} Files Processed from the total of {1}: Completed: {2}%", counter, totalFiles, value.ToString());
}

Monday, December 8, 2014

Windows Service to run a function at specified time

Running a windows service on specific time and a given interval.

The below service is scheduled to run between – 4.50 PM – 5.00 PM every day. The service will run for the interval of 15 minutes.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EAdvicesServices
{
    partial class Service1 : ServiceBase
    {
        System.Timers.Timer timer1 = null;
        public Service1()
        {
            InitializeComponent();
            this.CanHandlePowerEvent = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanStop = true;
           
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            //For each process timer should be mentioned here.
            double elapseTime = Convert.ToDouble("900000");
            timer1 = new System.Timers.Timer(elapseTime);
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timer1.Start();

           

        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            timer1.Stop();
            timer1.Enabled = false;
        }

        protected void timer1_Elapsed(object source, System.Timers.ElapsedEventArgs aa)
        {
           
            TimeSpan currentDate = DateTime.Now.TimeOfDay;
            TimeSpan scheduleStartDate = DateTime.Parse("1/1/2013 04:50:00 PM").TimeOfDay;
            TimeSpan scheduleEndDate = DateTime.Parse("1/1/2013 05:00:00 PM").TimeOfDay;

            if ((TimeSpan.Compare(currentDate, scheduleStartDate) > 0) && (TimeSpan.Compare(currentDate, scheduleEndDate) < 0))
            {
                RunServiceProgram();
            }
        }

        private void RunServiceProgram()
        {
            //Write here you code to execute the program
        }
    }
}



Auto redirect to login page when Session is expired

Auto redirect to login page on session timeout. Just added the below method in you page.

Note: This code is reference from other site.
private void CheckSessionTimeout()
        {
            string msgSession = "Warning: Within next 3 minutes, if you do not do anything, our system will redirect to the login page. Please save changed data.";
            //time to remind, 3 minutes before session ends
            int int_MilliSecondsTimeReminder = (this.Session.Timeout * 60000) - 3 * 60000;
            //time to redirect, 5 milliseconds before session ends
            int int_MilliSecondsTimeOut = (this.Session.Timeout * 60000) - 5;

            string str_Script = @"
                    var myTimeReminder, myTimeOut;
                    clearTimeout(myTimeReminder);
                    clearTimeout(myTimeOut); " +
                    "var sessionTimeReminder = " +
                      int_MilliSecondsTimeReminder.ToString() + "; " +
                    "var sessionTimeout = " + int_MilliSecondsTimeOut.ToString() + ";" +
                    "function doReminder(){ alert('" + msgSession + "'); }" +
                    "function doRedirect(){ window.location.href='login.aspx'; }" + @"
                    myTimeReminder=setTimeout('doReminder()', sessionTimeReminder);
                    myTimeOut=setTimeout('doRedirect()', sessionTimeout); ";

             ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(),
                   "CheckSessionOut", str_Script, true);
        }


protected void Page_Load(object sender, EventArgs e)
{
 this.CheckSessionTimeout();
}



How to refresh parent page on closing of Pop Up Window, RadGrid

In this, I will show you how to can refresh a RadGrid control on the parent page, from a pop up window when it is closed.

Main Page.aspx
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server" nablePageHeadUpdate="False" EnableAJAX="true">
</telerik:RadAjaxManager>

function ShowInsertForm()
{
var manager = window.radopen("PopUp.aspx", "PopUp");
manager.setSize(650, 325);
manager.set_visibleStatusbar(false);
manager.center();
manager.SetActive();
return false;
}

function RefreshGrid(arg)
{
 if (!arg)
 {
  var AjaxManager = $find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>");
  if (AjaxManager != null)
  AjaxManager.ajaxRequest("Rebind");
 }
else
 {
  var AjaxManager = $find("<%= RadAjaxManager.GetCurrent(Page).ClientID %>");
  if (AjaxManager != null)
  AjaxManager.ajaxRequest("RebindAndNavigate");
 }
}

<telerik:RadWindowManager ID="RadWindowManager2" runat="server" EnableShadow="false" OnClientPageLoad="OnClientPageLoad" VisibleStatusbar="false">
        <Windows>
            <telerik:RadWindow ID="PopUp" runat="server" Title="Popup window" ReloadOnShow="true" Behaviors="Maximize,Close,Minimize,Move,Pin" ShowContentDuringLoad="false" Modal="true">
            </telerik:RadWindow>
        </Windows>

    </telerik:RadWindowManager>
MainPage.aspx.cs

  //Register the AjaxManager here
protected void Page_Load(object sender, EventArgs e)
{
  RadAjaxManager manager = RadAjaxManager.GetCurrent(Page);
  manager.AjaxRequest += new     RadAjaxControl.AjaxRequestDelegate(RadAjaxManager1_AjaxRequest);
}

protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
 if (e.Argument == " CloseAndRebind ")
 {
  // Refresh /Reload the grid control here
 }
}
Popup.aspx
<telerik:RadScriptManager ID="RadScriptManagerPopUp" runat="server" ></telerik:RadScriptManager>
      <script type="text/javascript">
          function CloseAndRebind(args) {
              GetRadWindow().BrowserWindow.refreshGrid(args);
              GetRadWindow().close();
          }
          function GetRadWindow() {
              var oWindow = null;
              if (window.radWindow)
                  oWindow = window.radWindow;
                  //Will work in Moz in all cases, including clasic dialog               
              else if (window.frameElement.radWindow)
                  oWindow = window.frameElement.radWindow;
              //IE (and Moz as well)               
              return oWindow;
          }
          function CancelEdit() {
              GetRadWindow().close();
          }

    </script>
Popup.aspx.cs

private void Close()
{
 ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind();", true);
}