Monday, September 26, 2011

Trim Leading Or Trailing Control Characters

DECLARE @MyString VARCHAR(1000)
--Control character

DECLARE @Tab            VARCHAR(2)
DECLARE @LineFeed       VARCHAR(2)
DECLARE @CarriageReturn VARCHAR(2)
DECLARE @SearchPattern  VARCHAR(10)

SET @Tab            =              CHAR(9)
SET @LineFeed       =              CHAR(10)
SET @CarriageReturn =              CHAR(13)

--Search for any single of more chars not with specified range
SET @SearchPattern = '%[^ '   + @Tab + @LineFeed + @CarriageReturn + ']%'

SET @MyString = CHAR(10) + ' ' + CHAR(10)+ CHAR(9) + 'My name is ' + CHAR(10) 
				+ ' babu ' + CHAR(10) + ' ' + CHAR(10) + CHAR(10) + ' ' + CHAR(10)

SELECT LEN(@MyString) AS TotalLength
SELECT @MyString AS MyString

SELECT LEN( 
RTRIM( LTRIM( 
	SUBSTRING( @MyString, 
		PATINDEX(@SearchPattern, @MyString), 
		LEN(@MyString) - PATINDEX(@SearchPattern, @MyString) - PATINDEX(@SearchPattern, 
		REVERSE(@MyString)) + 2
		) 
	) ) 
) AS AfterTrimedLength

SELECT 
RTRIM( LTRIM( 
	SUBSTRING( @MyString, 
		PATINDEX(@SearchPattern, @MyString), 
		LEN(@MyString) - PATINDEX(@SearchPattern, @MyString) - PATINDEX(@SearchPattern, 
		REVERSE(@MyString)) + 2
		) 
	) ) AS AfterTrimed

Tuesday, September 13, 2011

Auto center pop up window

function PopupCenter() {
    var width = 600;
    var height = 480;
    var top = (screen.height / 2) - (height / 2);
    var left = (screen.width / 2) - (width / 2);

    var parametar = 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left;
    var url = 'Default.aspx'
    var windowName = 'Default';
    var targetWin = window.open(url, windowName, parametar);
    targetWin.focus();
    return false;
}
Page with query string
function PopupCenter(Name, Age) {
    var width = 600;
    var height = 480;
    var top = (screen.height / 2) - (height / 2);
    var left = (screen.width / 2) - (width / 2);

    var parametar = 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left;
    var url = 'Default.aspx?Name=' + Name + '&Age=' + Age;
    var windowName = 'Default';
    var targetWin = window.open(url, windowName, parametar);
    targetWin.focus();
    return false;
}
References
www.javascripter.net

msdn
htmlgoodies

Friday, August 5, 2011

Creating a Windows Service in C#.net and call a method every hour




Untitled Page





Untitled Page



In Visual Studio Select File->New->Project Select Windows and select Windows
Service


Right click on the Service1 designer and select Add Installer. This adds ProjectInstaller


Will create a file ProjectInstaller.cs





To avoid Set Service Login prompt being asked about the system username and
password you must change the Account for the serviceProcessInstaller to LocalSystem.

ServiceAccount Enumeration

ServiceAccount

stackoverflow





ServiceProcessInstaller Installs an executable containing classes that extend
ServiceBase. This class is called by installation utilities, such as InstallUtil.exe,
when installing a service application. ServiceInstaller Installs a class
that extends ServiceBase to implement a service. This class is called by the install
utility when installing a service application.



Display Name is show in name column of the service.
Set StartType as Automatic - To make the service to be started after restart/shutdown.

How to Start the service automatically after Installation?




Rename Service1 to to MyService


Create a folder and write the code to write to file


How to check whether the service called function is working or not? Right
click on the Solution(DemoService) and select Add -> New Project This console
application is used to test whether file writing works or not.


How to create Service Installer? Right click on the Solution(DemoService)
and select Add -> New Project Select Other Project Types -> Setup and Deployment
-> Setup Project


We will get the below screen.


Right click on the Setup project


Select the service project








Double click on the Application Folder


Press Ok.


Select the setup project and press F4 Manufacturer will come in path as "C:\Program
Files\ManufacturerValue" Title will come in Setup Wizard





Click on Configuration Manager


Change Debug mode to Release for the Service and Setup projects













To avoid this prompt give LocalSystem to Account property of serviceProcessInstaller.



Type control in run and select Administrative Tools -> Services







Make the service to call every 10 minutes Create a file as the below image


public class WriteToFile
    {
        public WriteToFile()
        {
            string strDateTime = DateTime.Now.ToString();
            StreamWriter sw = new StreamWriter(Path.Combine(System.IO.Path.GetTempPath(), "babu.txt"), true);
            sw.WriteLine(strDateTime);

            sw.Close();
        }
    }
Update the MyService.cs file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using DemoService.Functions;
using System.Timers;

namespace DemoService
{
    public partial class MyService : ServiceBase
    {
        //Make the service to call the for every 5 min
        System.Timers.Timer TimerObj = new System.Timers.Timer(ConvertMinutesToMilliseconds(5));

        public MyService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            TimerObj.Elapsed += new ElapsedEventHandler(OnElapsedTime);
            TimerObj.Enabled = true;
        }

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

        /// 
        /// At the end of every 5 min the event will be triggered.
        /// 
        ///         /// protected void OnElapsedTime(object source, ElapsedEventArgs e)         {             //Write the current datetime to the file                          WriteToFile objWriteToFile = new WriteToFile();         }         ///          /// Convert minutes to milliseconds                 /// ///                  /// /// ///                  public static double ConvertMinutesToMilliseconds(double minutes)          {              return TimeSpan.FromMinutes(minutes).TotalMilliseconds;          }     } } 

Friday, July 8, 2011

Switch Theme Without Postback


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ChangeTheme : System.Web.UI.Page, ICallbackEventHandler
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        //If theme is null or not changed by user use Default theme
        if (String.IsNullOrEmpty(Convert.ToString(Session["Theme"])))
            Page.Theme = "Default";
        else
            Page.Theme = Convert.ToString(Session["Theme"]);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //JavaScript Callbacks
        ClientScriptManager scriptManager = Page.ClientScript;
        String cbReference = scriptManager.GetCallbackEventReference(this, "returnValue", "ReceiveServerData", "context");
        String callbackScript = "function CallServer(returnValue, context) {" + cbReference + "; }";
        scriptManager.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);

        TextBox1.Text = DateTime.Now.ToString();
    }

    #region ICallbackEventHandler Members
    //Return value from the server to the client
    string ICallbackEventHandler.GetCallbackResult()
    {
        return Convert.ToString(Session["Theme"]);
    }

    //Get the theme name from the javascript function
    public void RaiseCallbackEvent(string eventArgument)
    {
        Session["Theme"] = eventArgument.Trim();
    }

    #endregion
}

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChangeTheme.aspx.cs" 
Inherits="ChangeTheme" %>




    Theme Switcher
    
    
    

    


    

The style set for the background body and the textbox.

You can see that, the time is not changed when we select the color.
This is done from the javascript.
To make apply the theme press the button Apply Theme.



Source Code

Saturday, March 26, 2011

GridView makeover using CSS

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

//http://atashbahar.com/post/GridView-makeover-using-CSS.aspx
public partial class StylishGridView_Demo_GridViewMakeOver : System.Web.UI.Page
{
    CustomersDataObject objData = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            objData = new CustomersDataObject();
            //DataTable dt =  objData.Select().Table ;
            gvStylish.DataSource = objData.Select();
            gvStylish.DataBind();
        }
    }

    protected void gvStylish_Sorting(object sender, GridViewSortEventArgs e)
    {
        //Change sort direction
        SortDirection = SortDirection == SortDirection.Descending ? SortDirection.Ascending : SortDirection.Descending;
        string sSortExpression = SortDirection == SortDirection.Ascending ? " Asc" : " Desc";

        //If new column, set as asc
        if (Convert.ToString(SortExpression) != e.SortExpression)
        {
            SortDirection = SortDirection.Ascending;
            sSortExpression = " Asc";
        }

        sSortExpression = e.SortExpression + sSortExpression;
        SortExpression = e.SortExpression;

        objData = new CustomersDataObject();
        gvStylish.DataSource = new DataView(objData.Select().Table, string.Empty, sSortExpression, DataViewRowState.CurrentRows);
        gvStylish.DataBind();
    }

    protected void gvStylish_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        objData = new CustomersDataObject();
        //DataTable dt =  objData.Select().Table ;
        gvStylish.PageIndex = e.NewPageIndex;
        gvStylish.DataSource = objData.Select();
        gvStylish.DataBind();
    }

    protected void gvStylish_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridView gridView = (GridView)sender;

        //You have to set the SortExpression in the aspx page.
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //To add tooltip for the header
            if (e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell cell in e.Row.Cells)
                {
                    foreach (Control ctl in cell.Controls)
                    {
                        if (ctl.GetType().ToString().Contains("DataControlLinkButton"))
                        {
                            cell.Attributes.Add("title", "Click to sort " + ((LinkButton)ctl).Text);
                        }
                    }
                }
            }

            //Set default header style for the gridview
            //Get sorted column index for the templated gridview
            SortIndex = -1;
            foreach (DataControlField field in gridView.Columns)
            {
                e.Row.Cells[gridView.Columns.IndexOf(field)].CssClass = "sortable";

                if (!string.IsNullOrEmpty(SortExpression))
                {
                    if (field.SortExpression == SortExpression)
                    {
                        SortIndex = gridView.Columns.IndexOf(field);
                    }
                }
            }

            //Set Sorted style for the gridview header
            if (SortIndex > -1)
                e.Row.Cells[SortIndex].CssClass = (SortDirection == SortDirection.Ascending
                                            ? " sortable sorted asc" : " sortable sorted desc");
        }
        else if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //To change color for the sorded gridvew entire column
            if (SortIndex > -1)
                e.Row.Cells[SortIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? " sortaltrow" : "sortrow");

            //#region Add toolTip to the asp:CommandField Starts
            //int lastCell = e.Row.Cells.Count - 1;
            //foreach (Control ctrl in e.Row.Cells[lastCell].Controls)
            //{
            //    if (ctrl.GetType().BaseType.Name == "LinkButton")
            //    {
            //        LinkButton lnkBtn = ctrl as LinkButton;

            //        switch (lnkBtn.Text.Trim())
            //        {
            //            case "Edit":
            //                lnkBtn.ToolTip = "Click to edit the record.";
            //                break;

            //            case "Delete":
            //                lnkBtn.Attributes.Add("onclick", "javascript:return confirm('Do you want to delete the selected Course?');");
            //                lnkBtn.ToolTip = "Click to delete the record.";
            //                break;
            //        }
            //    }
            //}
            //#endregion
        }
    }

    #region "Properties"
    public Int32 SortIndex
    {
        get
        {
            if (ViewState["_SortIndex_"] == null)
                ViewState["_SortIndex_"] = -1;

            return (Int32)ViewState["_SortIndex_"];
        }
        set { ViewState["_SortIndex_"] = value; }
    }

    public string SortExpression
    {
        get
        {
            if (ViewState["_SortExpression_"] == null)
                ViewState["_SortExpression_"] = string.Empty;

            return (string)ViewState["_SortExpression_"];
        }
        set { ViewState["_SortExpression_"] = value; }
    }

    public SortDirection SortDirection
    {
        get
        {
            if (ViewState["_SortDirection_"] == null)
                ViewState["_SortDirection_"] = SortDirection.Ascending;

            return (SortDirection)ViewState["_SortDirection_"];
        }
        set { ViewState["_SortDirection_"] = value; }
    }

    #endregion
}

#container /*make horizontal center of a div*/
{
 margin: 10px auto;
 width: 700px;
}
.mGrid
{
 background-color: #fff;
 border: solid 1px #525252;
 border-collapse: collapse;
 margin: 5px 0 10px 0;
 width: 100%;
 font: 11px Tahoma;
}

/*Header style starts*/
.mGrid tr th
{
 background: #424242 url(Images/grd_head.png) repeat-x top;
 border:0px;
 border-bottom: 1px solid #c1c1c1;
 border-right: 1px solid #c1c1c1;
 color: #fff;
 font-size: 0.9em;
 padding: 4px 2px;
}

/*Sorting Starts*/
.mGrid tr th.sortable
{
 padding: 0px;
}

.mGrid tr th.sortable:hover
{
 background: #b7e7fb url('Images/grid-header-sortable-back-hover.gif') top left repeat-x;
 border: 1px solid #C4C4C4;
 border-left: none;
 border-top: none;
}

.mGrid tr th.sortable a
{
 color: white;
 display: block;
 min-height: 1px;
 padding: 3px 3px 2px 2px;
 text-decoration: none;
}

.mGrid tr th.sortable a:hover
{
 text-decoration: none;
}

.mGrid tr th.sorted
{
 background: #d8ecf6 url('Images/grid-header-sorted-back.jpg') top left repeat-x;
 border: 1px solid #8B8878;
 border-left: none;
 border-top: none;
}

.mGrid tr th.asc a
{
 background: transparent url('Images/grid-header-asc-glyph.gif') center 1px no-repeat;
}

.mGrid tr th.desc a
{
 background: transparent url('Images/grid-header-desc-glyph.gif') center 1px no-repeat;
}
/*Sorting Ends*/

.mGrid tr .RowStyle
{
 border: 1px solid red;
 padding: 2px 6px 2px 4px;
}

.mGrid tr.alt
{
 background: #f2f9fc;
}

.mGrid tr.RowStyle:hover, .mGrid tr.alt:hover
{
 background: #c1c1c1 url(Images/grid-header-hover.gif) repeat-x top;
}


/*Select entire sorted column starts*/
.mGrid tr.RowStyle .sortaltrow, .mGrid tr.alt .sortaltrow 
{
    background-color: #D6D6D6;
}

.mGrid tr.RowStyle .sortrow, .mGrid tr.alt .sortrow 
{
    background-color: #EAEAEA;
}
/*Select entire sorted column ends*/

.mGrid .pgr
{
 background: #424242 url(Images/grd_pgr.png) repeat-x top;
 text-align: center; /*Make pager to be center*/
}
.mGrid .pgr table
{
 margin: 5px 0;
}
.mGrid .pgr td
{
 border-width: 0;
 color: #fff;
 font-weight: bold;
 line-height: 12px;
 padding: 0 6px;
 border-left: solid 1px #666;
}
.mGrid .pgr a
{
 color: #666;
 text-decoration: none;
}
.mGrid .pgr a:hover
{
 color: #000;
 text-decoration: none;
}



Download Images
Curtesy atashbahar

Monday, February 28, 2011

Grouping RadioButton inside gridveiw

        function uncheckOthers(id) {
            var elm = document.getElementsByTagName('input');
            for (var i = 0; i < elm.length; i++) {
                if (elm.item(i).id.substring(id.id.lastIndexOf('_')) == id.id.substring(id.id.lastIndexOf('_'))) {
                    if (elm.item(i).type == "radio" && elm.item(i) != id) elm.item(i).checked = false;
                }
            }
        }  
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //To make the RadioButton mutually exclusive
                string strScript = "uncheckOthers(" + ((RadioButton)e.Row.Cells[0].FindControl("rbSelect")).ClientID + ");";
                ((RadioButton)e.Row.Cells[0].FindControl("rbSelect")).Attributes.Add("onclick", strScript);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }