Thursday, August 30, 2012

Ajax Calls in asp.net

asp:   
function CheckGroupName() {
            var name = $('#<%= txtGroupName.ClientID %>').val();
            $.ajax({
                url: "CreateGroups.aspx/CheckGroupName",   // Current Page, Method 
                data: JSON.stringify({ name: name }), // parameter map as JSON 
                type: "POST", // data has to be POSTed 
                contentType: "application/json", // posting JSON content     
                dataType: "JSON",  // type of data is JSON (must be upper case!) 
                timeout: 10000,    // AJAX timeout 
                success: function (result) {
                    if (result == '{"d":"Yes"}') {
                      
                        alert('Entered Group Name alredy Exists for the account.Please Use a Differenet name to register.');
                        return false;
                    }
                },
                error: function (xhr, status) {
                    alert(status + " - " + xhr.responseText);
                }
            });

        }

aspx.cs:
  [WebMethod]
        public static string CheckGroupName(string name)
        {
            if (Activayt.Business.Group.IsExists(AccountID, name, _parent))
            {
              
                return "Yes";
            }
            else
            {
                return "";
            }
        }

Wednesday, August 29, 2012

Webservices in asp.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace Activayt.UI
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
     [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
       [System.Web.Services.WebMethod(EnableSession=true)]
       [System.Web.Script.Services.ScriptMethod]
        public  string[] GetGroupName(string prefixText)
        {
            string s = Session["UserName"].ToString();
            SqlConnection cn = new SqlConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            String strCn = ConfigurationManager.ConnectionStrings["SQLConString"].ToString();
            cn.ConnectionString = strCn;
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = cn;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select Distinct Name from tbl_Groups G left outer join  tbl_GroupXUsers GU on G.GroupID=GU.GroupID where G.Status=1 and ((GU.UserID=(select UserID from tbl_Users where Email='" + Session["UserName"].ToString() + "') and MasterAccountID=(select AccountID from tbl_Accounts  where Name='" + Session["AccountName"].ToString() + "')) or CreatedBy='" + Session["UserName"].ToString() + "') and Name like @myParameter";
            cmd.Parameters.AddWithValue("@myParameter", "%" + prefixText + "%");

            try
            {
                cn.Open();
                cmd.ExecuteNonQuery();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
            }
            catch
            {
            }
            finally
            {
                cn.Close();
            }
            dt = ds.Tables[0];

            List<string> txtGroupNames = new List<string>();
            String dbValues;

            foreach (DataRow row in dt.Rows)
            {

                dbValues = row["Name"].ToString();
                dbValues = dbValues.ToLower();
                txtGroupNames.Add(dbValues);
            }

            return txtGroupNames.ToArray();
        }
       [System.Web.Services.WebMethod(EnableSession = true)]
       [System.Web.Script.Services.ScriptMethod]
       public string[] GetManagers(string prefixText)
       {
           string s = Session["UserName"].ToString();
           SqlConnection cn = new SqlConnection();
           DataSet ds = new DataSet();
           DataTable dt = new DataTable();
           String strCn = ConfigurationManager.ConnectionStrings["SQLConString"].ToString();
           cn.ConnectionString = strCn;
           SqlCommand cmd = new SqlCommand();
           cmd.Connection = cn;
           cmd.CommandType = CommandType.Text;
           cmd.CommandText = "select distinct Email from tbl_GroupXUsers GU inner join tbl_Groups G on G.GroupID=GU.GroupID inner join tbl_Users U on U.UserID=GU.UserID where GU.UserID=(select UserID from tbl_Users where Email='" + Session["UserName"].ToString() + "' and Status=1) and Role='manager' and G.Status=1 and MasterAccountID=(select AccountID from tbl_Accounts where Name='" + Session["AccountName"].ToString() + "') and Email like @myParameter";
           cmd.Parameters.AddWithValue("@myParameter", "%" + prefixText + "%");
           try
           {
               cn.Open();
               cmd.ExecuteNonQuery();
               SqlDataAdapter da = new SqlDataAdapter(cmd);
               da.Fill(ds);
           }
           catch
           {
           }
           finally
           {
               cn.Close();
           }
           dt = ds.Tables[0];

           List<string> txtManagers = new List<string>();
           String dbValues;

           foreach (DataRow row in dt.Rows)
           {

               dbValues = row["Email"].ToString();
               dbValues = dbValues.ToLower();
               txtManagers.Add(dbValues);
           }

           return txtManagers.ToArray();
       }
       [System.Web.Services.WebMethod(EnableSession = true)]
       [System.Web.Script.Services.ScriptMethod]
       public string[] GetAnalyst(string prefixText)
       {
           string s = Session["UserName"].ToString();
           SqlConnection cn = new SqlConnection();
           DataSet ds = new DataSet();
           DataTable dt = new DataTable();
           String strCn = ConfigurationManager.ConnectionStrings["SQLConString"].ToString();
           cn.ConnectionString = strCn;
           SqlCommand cmd = new SqlCommand();
           cmd.Connection = cn;
           cmd.CommandType = CommandType.Text;
           cmd.CommandText = "select distinct Email from tbl_GroupXUsers GU inner join tbl_Groups G on G.GroupID=GU.GroupID inner join tbl_Users U on U.UserID=GU.UserID where GU.UserID=(select UserID from tbl_Users where Email='" + Session["UserName"].ToString() + "' and Status=1) and Role='analyst' and G.Status=1  and MasterAccountID=(select AccountID from tbl_Accounts where Name='" + Session["AccountName"].ToString() + "') and  Email like @myParameter";
           cmd.Parameters.AddWithValue("@myParameter", "%" + prefixText + "%");

           try
           {
               cn.Open();
               cmd.ExecuteNonQuery();
               SqlDataAdapter da = new SqlDataAdapter(cmd);
               da.Fill(ds);
           }
           catch
           {
           }
           finally
           {
               cn.Close();
           }
           dt = ds.Tables[0];

           List<string> txtManagers = new List<string>();
           String dbValues;

           foreach (DataRow row in dt.Rows)
           {

               dbValues = row["Email"].ToString();
               dbValues = dbValues.ToLower();
               txtManagers.Add(dbValues);
           }

           return txtManagers.ToArray();
       }
       [System.Web.Services.WebMethod(EnableSession = true)]
       [System.Web.Script.Services.ScriptMethod]
       public string[] GetAdministrator(string prefixText)
       {
           string s = Session["UserName"].ToString();
           SqlConnection cn = new SqlConnection();
           DataSet ds = new DataSet();
           DataTable dt = new DataTable();
           String strCn = ConfigurationManager.ConnectionStrings["SQLConString"].ToString();
           cn.ConnectionString = strCn;
           SqlCommand cmd = new SqlCommand();
           cmd.Connection = cn;
           cmd.CommandType = CommandType.Text;
           cmd.CommandText = "select distinct Email from tbl_GroupXUsers GU inner join tbl_Groups G on G.GroupID=GU.GroupID inner join tbl_Users U on U.UserID=GU.UserID where GU.UserID=(select UserID from tbl_Users where Email='" + Session["UserName"].ToString() + "' and Status=1) and Role='administrator' and G.Status=1 and MasterAccountID=(select AccountID from tbl_Accounts where Name='" + Session["AccountName"].ToString() + "') and Email like @myParameter";
           cmd.Parameters.AddWithValue("@myParameter", "%" + prefixText + "%");

           try
           {
               cn.Open();
               cmd.ExecuteNonQuery();
               SqlDataAdapter da = new SqlDataAdapter(cmd);
               da.Fill(ds);
           }
           catch
           {
           }
           finally
           {
               cn.Close();
           }
           dt = ds.Tables[0];

           List<string> txtManagers = new List<string>();
           String dbValues;

           foreach (DataRow row in dt.Rows)
           {

               dbValues = row["Email"].ToString();
               dbValues = dbValues.ToLower();
               txtManagers.Add(dbValues);
           }

           return txtManagers.ToArray();
       }
       [System.Web.Services.WebMethod(EnableSession = true)]
       [System.Web.Script.Services.ScriptMethod]
       public string[] GetMembers(string prefixText)
       {
           SqlConnection cn = new SqlConnection();
           DataSet ds = new DataSet();
           DataTable dt = new DataTable();
           String strCn = ConfigurationManager.ConnectionStrings["SQLConString"].ToString();
           cn.ConnectionString = strCn;
           SqlCommand cmd = new SqlCommand();
           cmd.Connection = cn;
           cmd.CommandType = CommandType.Text;
           cmd.CommandText = "select distinct Email from tbl_Roles R inner join tbl_RoleXUsers RU on RU.RoleID=R.RoleID inner join tbl_Users U on U.UserID=RU.UserID where RU.UserID="+Convert.ToInt64(Session["UserID"])+" and R.MasterAccountID="+Convert.ToInt64(Session["AccountID"])+" and Email like @myParameter";
           cmd.Parameters.AddWithValue("@myParameter", "%" + prefixText + "%");

           try
           {
               cn.Open();
               cmd.ExecuteNonQuery();
               SqlDataAdapter da = new SqlDataAdapter(cmd);
               da.Fill(ds);
           }
           catch
           {
           }
           finally
           {
               cn.Close();
           }
           dt = ds.Tables[0];
           List<string> txtMembers = new List<string>();
           String dbValues;
           foreach (DataRow row in dt.Rows)
           {
               dbValues = row["Email"].ToString();
               dbValues = dbValues.ToLower();
               txtMembers.Add(dbValues);
           }
           return txtMembers.ToArray();
       }
    }
}

Captcha in asp.net using c#.net

mscaptcha.xml:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>MSCaptcha</name>
    </assembly>
    <members>
        <member name="M:MSCaptcha.CaptchaControl.ValidateCaptcha(System.String)">
            <summary>
            Validate the user's text against the CAPTCHA text
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaControl.HtmlColor(System.Drawing.Color)">
            <summary>
            returns HTML-ized color strings
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaControl.CssStyle">
            <summary>
            returns css "style=" tag for this control
            based on standard control visual properties
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaControl.Render(System.Web.UI.HtmlTextWriter)">
            <summary>
            render raw control HTML to the page
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaControl.GenerateNewCaptcha">
            <summary>
            generate a new captcha and store it in the ASP.NET Cache by unique GUID
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaControl.System#Web#UI#IPostBackDataHandler#LoadPostData(System.String,System.Collections.Specialized.NameValueCollection)">
            <summary>
            Retrieve the user's CAPTCHA input from the posted data
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaControl.BackColor">
            <summary>
            Background color for the captcha image
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaControl.FontColor">
            <summary>
            Color of captcha text
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaControl.NoiseColor">
            <summary>
            Color for dots in the background noise
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaControl.LineColor">
            <summary>
            Color for the background lines of the captcha image
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaControl.IsDesignMode">
            <summary>
            are we in design mode?
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.RenderImage">
            <summary>
            Forces a new Captcha image to be generated using current property value settings.
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.RandomFontFamily">
            <summary>
            Returns a random font family from the font whitelist
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.GenerateRandomText">
            <summary>
            generate random text for the CAPTCHA
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.RandomPoint(System.Int32,System.Int32,System.Int32,System.Int32)">
            <summary>
            Returns a random point within the specified x and y ranges
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.RandomPoint(System.Drawing.Rectangle)">
            <summary>
            Returns a random point within the specified rectangle
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.TextPath(System.String,System.Drawing.Font,System.Drawing.Rectangle)">
            <summary>
            Returns a GraphicsPath containing the specified string and font
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.GetFont">
            <summary>
            Returns the CAPTCHA font in an appropriate size
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.GenerateImagePrivate">
            <summary>
            Renders the CAPTCHA image
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.WarpText(System.Drawing.Drawing2D.GraphicsPath,System.Drawing.Rectangle)">
            <summary>
            Warp the provided text GraphicsPath by a variable amount
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.AddNoise(System.Drawing.Graphics,System.Drawing.Rectangle)">
            <summary>
            Add a variable level of graphic noise to the image
            </summary>
        </member>
        <member name="M:MSCaptcha.CaptchaImage.AddLine(System.Drawing.Graphics,System.Drawing.Rectangle)">
            <summary>
            Add variable level of curved lines to the image
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.UniqueId">
            <summary>
            Returns a GUID that uniquely identifies this Captcha
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.RenderedAt">
            <summary>
            Returns the date and time this image was last rendered
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.Font">
            <summary>
            Font family to use when drawing the Captcha text. If no font is provided, a random font will be chosen from the font whitelist for each character.
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.FontWarp">
            <summary>
            Amount of random warping to apply to the Captcha text.
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.BackgroundNoise">
            <summary>
            Amount of background noise to apply to the Captcha image.
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.TextChars">
            <summary>
            A string of valid characters to use in the Captcha text.
            A random character will be selected from this string for each character.
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.TextLength">
            <summary>
            Number of characters to use in the Captcha text.
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.Text">
            <summary>
            Returns the randomly generated Captcha text.
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.Width">
            <summary>
            Width of Captcha image to generate, in pixels
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.Height">
            <summary>
            Height of Captcha image to generate, in pixels
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.FontWhitelist">
            <summary>
            A semicolon-delimited list of valid fonts to use when no font is provided.
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.BackColor">
            <summary>
            Background color for the captcha image
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.FontColor">
            <summary>
            Color of captcha text
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.NoiseColor">
            <summary>
            Color for dots in the background noise
            </summary>
        </member>
        <member name="P:MSCaptcha.CaptchaImage.LineColor">
            <summary>
            Color for the background lines of the captcha image
            </summary>
        </member>
        <member name="T:MSCaptcha.CaptchaImage.FontWarpFactor">
            <summary>
            Amount of random font warping to apply to rendered text
            </summary>
        </member>
        <member name="T:MSCaptcha.CaptchaImage.BackgroundNoiseLevel">
            <summary>
            Amount of background noise to add to rendered image
            </summary>
        </member>
        <member name="T:MSCaptcha.CaptchaImage.LineNoiseLevel">
            <summary>
            Amount of curved line noise to add to rendered image
            </summary>
        </member>
    </members>
</doc>

web.config:

<system.web>
   <httpHandlers>
      <add verb="GET" path="CaptchaImage.axd" type="MSCaptcha.CaptchaImageHandler, MSCaptcha"/>
    </httpHandlers>
</system.web>


Adding Captcha dll :


  <cc1:CaptchaControl ID="Captcha1" runat="server" CaptchaBackgroundNoise="Low" CaptchaLength="5"
                                                        CaptchaHeight="60" CaptchaWidth="160" CaptchaLineNoise="None" CaptchaMinTimeout="5"
                                                        CaptchaMaxTimeout="240" FontColor="#529E00" BackColor="Silver" />

dynamically create levels in component art grid

 
.aspx:
 <ComponentArt:DataGrid runat="server" ID="grdGroups" Width="785" ShowFooter="true"
            RunningMode="Server" ClientIDMode="AutoID" AutoTheming="true" PagerStyle="Numbered">
        </ComponentArt:DataGrid>
   
.aspx.cs:




 if (!Page.IsPostBack)
            {
buildTopLevel();
                    grdGroups.DataBind();
}
private void buildTopLevel()
        {
            if (Session["UserName"] != null)
            {
                grdGroups.ID = "Grid1";
                grdGroups.Width = 750;
                grdGroups.ShowFooter = true;
                grdGroups.AutoTheming = true;
                // grid.ClientIDMode = ClientIDMode.AutoID;
                grdGroups.PagerStyle = ComponentArt.Web.UI.GridPagerStyle.Numbered;
                DataSet ds = new DataSet();
                List<GroupDO> objListGroupDO = new List<GroupDO>();
                ObjGroupDO.AccountID = Convert.ToInt64(Session["AccountID"]);
                ObjGroupDO.UEmail = Session["UserName"].ToString();
                objListGroupDO = Group.SelectAll(ObjGroupDO.AccountID, ObjGroupDO.UEmail);
                ds = ConvertListToDataSet(objListGroupDO);
                ViewState["Data"] = ds;
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int levels = Convert.ToInt32(ds.Tables[0].Compute("max(Level)", string.Empty));
                    objListGroupDO.Clear();
                    objListGroupDO = Activayt.Business.Group.SelectGroups(ObjGroupDO.AccountID, ObjGroupDO.UEmail);
                    ds = null;
                    ds = ConvertListToDataSet(objListGroupDO);
                    grdGroups.Levels.Clear();
                    for (int i = 0; i < levels; i++)
                    {
                        GridLevel gridLevel = new GridLevel();
                        grdGroups.Levels.Add(gridLevel);
                        grdGroups.Levels[i].DataKeyField = "GroupID";
                        GridColumn column1 = new GridColumn();
                        column1.DataField = "GroupName";
                        GridColumn column2 = new GridColumn();
                        column2.DataField = "Administrator";
                        GridColumn column3 = new GridColumn();
                        column3.DataField = "Manager";
                        GridColumn column4 = new GridColumn();
                        column4.DataField = "Analyst";
                        GridColumn column5 = new GridColumn();
                        column5.DataField = "GroupID";
                        gridLevel.Columns.Add(column1);
                        gridLevel.Columns.Add(column2);
                        gridLevel.Columns.Add(column3);
                        gridLevel.Columns.Add(column4);
                        gridLevel.Columns.Add(column5);
                        grdGroups.Levels[i].Columns[4].Visible = false;
                    }
                    grdGroups.DataSource = ds.Tables[0];
                    int i1 = grdGroups.Levels.Count;
                }
            }
        }
        public void OnNeedRebind(object sender, EventArgs oArgs)
        {
            grdGroups.DataBind();
        }
        public void OnNeedDataSource(object sender, EventArgs oArgs)
        {
            buildTopLevel();
        }
        public void OnNeedChildData(object sender, ComponentArt.Web.UI.GridNeedChildDataSourceEventArgs args)
        {
            DataSet ds=(DataSet)ViewState["Data"];
            int Level = Convert.ToInt32(ds.Tables[0].Compute("max(Level)", string.Empty));
            for (int i = 0; i < Level; i++)
            {
                if (args.Item.Level == i)
                {
                    DataView dv = ds.Tables[0].DefaultView;
                    dv.RowFilter = "ParentGroupID=" + args.Item["GroupID"];
                    args.DataSource = dv.ToTable();
                }

            }

        }
        public void OnPageChanged(object sender, ComponentArt.Web.UI.GridPageIndexChangedEventArgs oArgs)
        {
            grdGroups.CurrentPageIndex = oArgs.NewIndex;
        }
        public void OnSort(object sender, ComponentArt.Web.UI.GridSortCommandEventArgs oArgs)
        {
            grdGroups.Sort = oArgs.SortExpression;
        }
        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
            grdGroups.NeedRebind += new ComponentArt.Web.UI.Grid.NeedRebindEventHandler(OnNeedRebind);
            grdGroups.NeedDataSource += new ComponentArt.Web.UI.Grid.NeedDataSourceEventHandler(OnNeedDataSource);
            grdGroups.NeedChildDataSource += new ComponentArt.Web.UI.Grid.NeedChildDataSourceEventHandler(OnNeedChildData);
            grdGroups.PageIndexChanged += new ComponentArt.Web.UI.Grid.PageIndexChangedEventHandler(OnPageChanged);
            grdGroups.SortCommand += new ComponentArt.Web.UI.Grid.SortCommandEventHandler(OnSort);
        }
        #endregion
  private void buildTopLevel()
        {
            if (Session["UserName"] != null)
            {
                grdGroups.ID = "Grid1";
                grdGroups.Width = 750;
                grdGroups.ShowFooter = true;
                grdGroups.AutoTheming = true;
                // grid.ClientIDMode = ClientIDMode.AutoID;
                grdGroups.PagerStyle = ComponentArt.Web.UI.GridPagerStyle.Numbered;
                DataSet ds = new DataSet();
                List<GroupDO> objListGroupDO = new List<GroupDO>();
                ObjGroupDO.AccountID = Convert.ToInt64(Session["AccountID"]);
                ObjGroupDO.UEmail = Session["UserName"].ToString();
                objListGroupDO = Group.SelectAll(ObjGroupDO.AccountID, ObjGroupDO.UEmail);
                ds = ConvertListToDataSet(objListGroupDO);
                ViewState["Data"] = ds;
                if (ds.Tables[0].Rows.Count > 0)
                {
                    int levels = Convert.ToInt32(ds.Tables[0].Compute("max(Level)", string.Empty));
                    objListGroupDO.Clear();
                    objListGroupDO = Activayt.Business.Group.SelectGroups(ObjGroupDO.AccountID, ObjGroupDO.UEmail);
                    ds = null;
                    ds = ConvertListToDataSet(objListGroupDO);
                    grdGroups.Levels.Clear();
                    for (int i = 0; i < levels; i++)
                    {
                        GridLevel gridLevel = new GridLevel();
                        grdGroups.Levels.Add(gridLevel);
                        grdGroups.Levels[i].DataKeyField = "GroupID";
                        GridColumn column1 = new GridColumn();
                        column1.DataField = "GroupName";
                        GridColumn column2 = new GridColumn();
                        column2.DataField = "Administrator";
                        GridColumn column3 = new GridColumn();
                        column3.DataField = "Manager";
                        GridColumn column4 = new GridColumn();
                        column4.DataField = "Analyst";
                        GridColumn column5 = new GridColumn();
                        column5.DataField = "GroupID";
                        gridLevel.Columns.Add(column1);
                        gridLevel.Columns.Add(column2);
                        gridLevel.Columns.Add(column3);
                        gridLevel.Columns.Add(column4);
                        gridLevel.Columns.Add(column5);
                        grdGroups.Levels[i].Columns[4].Visible = false;
                    }
                    grdGroups.DataSource = ds.Tables[0];
                    int i1 = grdGroups.Levels.Count;
                }
            }
        }
        public void OnNeedRebind(object sender, EventArgs oArgs)
        {
            grdGroups.DataBind();
        }
        public void OnNeedDataSource(object sender, EventArgs oArgs)
        {
            buildTopLevel();
        }
        public void OnNeedChildData(object sender, ComponentArt.Web.UI.GridNeedChildDataSourceEventArgs args)
        {
            DataSet ds=(DataSet)ViewState["Data"];
            int Level = Convert.ToInt32(ds.Tables[0].Compute("max(Level)", string.Empty));
            for (int i = 0; i < Level; i++)
            {
                if (args.Item.Level == i)
                {
                    DataView dv = ds.Tables[0].DefaultView;
                    dv.RowFilter = "ParentGroupID=" + args.Item["GroupID"];
                    args.DataSource = dv.ToTable();
                }

            }

        }
        public void OnPageChanged(object sender, ComponentArt.Web.UI.GridPageIndexChangedEventArgs oArgs)
        {
            grdGroups.CurrentPageIndex = oArgs.NewIndex;
        }
        public void OnSort(object sender, ComponentArt.Web.UI.GridSortCommandEventArgs oArgs)
        {
            grdGroups.Sort = oArgs.SortExpression;
        }
        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
            grdGroups.NeedRebind += new ComponentArt.Web.UI.Grid.NeedRebindEventHandler(OnNeedRebind);
            grdGroups.NeedDataSource += new ComponentArt.Web.UI.Grid.NeedDataSourceEventHandler(OnNeedDataSource);
            grdGroups.NeedChildDataSource += new ComponentArt.Web.UI.Grid.NeedChildDataSourceEventHandler(OnNeedChildData);
            grdGroups.PageIndexChanged += new ComponentArt.Web.UI.Grid.PageIndexChangedEventHandler(OnPageChanged);
            grdGroups.SortCommand += new ComponentArt.Web.UI.Grid.SortCommandEventHandler(OnSort);
        }
        #endregion

levels in component art grid in asp.net using c#.net

 if (!Page.IsPostBack)
            {
  buildTopLevel();
                        grdGroups.DataBind();
}   
 private void buildTopLevel()
        {
            if (Session["UserName"] != null)
            {
                DataSet ds = new DataSet();
                List<GroupDO> objListGroupDO = new List<GroupDO>();
                ObjGroupDO.AccountID = Convert.ToInt64(Session["AccountID"]);
                ObjGroupDO.UEmail = Session["UserName"].ToString();
                objListGroupDO = Activayt.Business.Group.SelectGroups(ObjGroupDO.AccountID, ObjGroupDO.UEmail);
                ds = ConvertListToDataSet(objListGroupDO);
                grdGroups.DataSource = ds;
            }
       
        }
 public void OnNeedRebind(object sender, EventArgs oArgs)
        {
            grdGroups.DataBind();
        }
        public void OnNeedDataSource(object sender, EventArgs oArgs)
        {
            buildTopLevel();
        }
        public void OnNeedChildData(object sender, ComponentArt.Web.UI.GridNeedChildDataSourceEventArgs args)
        {
            ObjGroupDO.UEmail = Session["UserName"].ToString();
            ObjGroupDO.AccountID =Convert.ToInt64(Session["AccountID"]);
            List<GroupDO> objListGroups=Group.SelectAll(ObjGroupDO.AccountID,ObjGroupDO.UEmail);
            DataSet ds = ConvertListToDataSet(objListGroups);
            if (args.Item.Level == 0)
            {
                DataView dv = ds.Tables[0].DefaultView;
                dv.RowFilter = "ParentGroupID=" + args.Item["GroupID"];
                args.DataSource = dv.ToTable();
            }
            else if (args.Item.Level == 1)
            {
                DataView dv = ds.Tables[0].DefaultView;
                dv.RowFilter = "ParentGroupID=" + args.Item["GroupID"];
                args.DataSource = dv.ToTable();
            }
        }
        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
            grdGroups.NeedRebind += new ComponentArt.Web.UI.Grid.NeedRebindEventHandler(OnNeedRebind);
            grdGroups.NeedDataSource += new ComponentArt.Web.UI.Grid.NeedDataSourceEventHandler(OnNeedDataSource);
            grdGroups.NeedChildDataSource += new ComponentArt.Web.UI.Grid.NeedChildDataSourceEventHandler(OnNeedChildData);

        }
        #endregion

Mail Sending in asp.net

 <system.net>
    <mailSettings>
      <smtp>
        <network host="smtp.gmail.com" port="25" userName="emai address" password="emaipassword"/>
      </smtp>
    </mailSettings>
  </system.net>
<appsettings>
<add  key="Mail From" value=" From Email Address"/>
<add  key="Mail From Name" value=" From Name"/>
</appsettings>
 private void SendConfirmMail(string GroupName,string AccountName,string Email,string RoleName)
        {
                System.Net.Mail.MailMessage iMailMessage = new System.Net.Mail.MailMessage();
                SmtpClient smtp = new SmtpClient();
                if (ConfigurationManager.AppSettings["MailFrom"] != null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<div style=\"display: block; background: #FFFFFF; width: 650px; float: left; border: 10px solid #ccc;\">");
                    sb.Append("<table style=\"font-family:Arial; font-size:12px;\"><tr><td>");
                    sb.Append("<img alt=\"Activayt\" src=\"http://202.53.10.34:591/images/logo-new.png\" width=\"250px\" height=\"64px\" border=\"none\"/></td></tr><tr><td><br />");
                    sb.Append("<div style=\"width: auto; line-height: 23px; min-width: 104px; height: 24px; background: #3DADE1; ");
                    sb.Append("font-family: Arial; font-size: 13px; font-weight: bold; text-align: left; color: #FFFFFF; ");
                    sb.Append("vertical-align: middle; float: left; padding: 0px 15px 0px 15px;line-height:13.25px;\">Added to <strong>" + GroupName + "</strong> as    " + RoleName + "</div></td></tr><tr>");
                    sb.Append("<td>&nbsp;&nbsp;&nbsp;Dear <strong> &nbsp;"+ Email +"&nbsp; </strong> ,</td></tr><tr><td>");
                    sb.Append("The &nbsp;&nbsp;<strong>Account Manager</strong>&nbsp;&nbsp;of &nbsp;&nbsp;&nbsp;<strong>" + AccountName + "</strong>&nbsp;&nbsp;&nbsp; has been added you on Activayt.com as Group" + RoleName + ".</td></tr></table>");
                    sb.Append("<table width=\"650px\" style=\"font-family:Arial; font-size:12px;\"><tr><td><strong></strong></td>");
                    sb.Append("<td></td><td></td></tr><tr><td><strong></strong></td><td></td>");
                    sb.Append("<td></td></tr><tr><td><strong></strong></td><td></td><td></td></tr></table>");
                    sb.Append("<table width=\"650px\" style=\"font-family:Arial; font-size:12px;\"><tr><td>");
                    sb.Append("&nbsp;&nbsp;&nbsp;Please <a href=\"http://202.53.10.34:591/UseCaseHelp.aspx?RN=" + Crypto.ActionEncrypt(RoleName) + "\" style=\"color: #0000cc;\" target=\"_blank\">Click Here</a> to Start exploring your new role on Activayt.com</td></tr><tr><td><br />");
                    sb.Append("&nbsp;Thanks &amp; Regards</td></tr><tr><td>&nbsp;Activayt  Team</td></tr></table></div>");
                    iMailMessage.From = new MailAddress(ConfigurationManager.AppSettings["MailFrom"].ToString(), ConfigurationManager.AppSettings["MailFromName"].ToString());
                    iMailMessage.To.Add(new MailAddress(Email));
                    iMailMessage.IsBodyHtml = true;
                    iMailMessage.Body = sb.ToString();
                    iMailMessage.Subject = "You are added as a Group  " + ObjGroupDO.Role;
                    smtp.Send(iMailMessage);
                }
                else
                {

                }
        }

Treeview dynamically adding parent and Child Nodes in asp.net

       private void PopulateTreeview()
        {
            ObjGroupDO.AccountID =Convert.ToInt64(Session["AccountID"]);
            ObjGroupDO.UEmail = Session["UserName"].ToString();
            this.tvHierarchyView.Nodes.Clear();
            List<GroupDO> objGroupList = Group.SelectAll(ObjGroupDO.AccountID,ObjGroupDO.UEmail);
            foreach (GroupDO hTree in objGroupList)
            {
                GroupDO parentNode = objGroupList.Find(delegate(GroupDO emp) { return emp.GroupID == hTree.ParentGroupID; });
                if (parentNode != null)
                {
                    foreach (TreeNode tn in tvHierarchyView.Nodes)
                    {
                        if (tn.Value == parentNode.GroupID.ToString())
                        {
                            tn.ChildNodes.Add(new TreeNode(hTree.GroupName.ToString(), hTree.GroupID.ToString()));
                        }
                        if (tn.ChildNodes.Count > 0)
                        {
                            foreach (TreeNode ctn in tn.ChildNodes)
                            {
                                RecursiveChild(ctn, parentNode.GroupID.ToString(), hTree);
                            }
                        }
                    }
                }
                else
                {
                    tvHierarchyView.Nodes.Add(new TreeNode(hTree.GroupName, hTree.GroupID.ToString()));
                }
            }

        }
        public void RecursiveChild(TreeNode tn, string searchValue, GroupDO hTree)
        {
            if (tn.Value == searchValue)
            {
                tn.ChildNodes.Add(new TreeNode(hTree.GroupName.ToString(), hTree.GroupID.ToString()));
            }
            if (tn.ChildNodes.Count > 0)
            {
                foreach (TreeNode ctn in tn.ChildNodes)
                {
                    RecursiveChild(ctn, searchValue, hTree);
                }
            }
        }

Friday, August 24, 2012

Delete All Tables ,Store Procedures,Views and Functions in SQL

Delete All Tables

--Delete All Keys

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO

Delete All Stored Procedures

declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'p'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
            if @procName <> 'DeleteAllProcedures'
                  exec('drop procedure ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur

Delete All Views


declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'v'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
                  exec('drop view ' + @procName)
                  fetch next from cur into @procName
      end
close cur
deallocate cur

Delete All Functions


declare @procName varchar(500)
declare cur cursor
    for select [name] from sys.objects where type = 'fn'
open cur

fetch next from cur into @procName
      while @@fetch_status = 0
      begin
                  exec('drop function ' + @procName)
                  fetch next from cur into @procName
      end

close cur
deallocate cur

Send Mails In SQl Jobs

Today in this article I would discuss about the Database Mail which is used to send the Email using SQL Server.  Previously I had discussed about SQL SERVER – Difference Between Database Mail and SQLMail. Database mail is the replacement of the SQLMail with many enhancements. So one should stop using the SQL Mail and upgrade to the Database Mail. Special thanks to Software Developer Monica, who helped with all the images and extensive testing of subject matter of this article.
In order to send mail using Database Mail in SQL Server, there are 3 basic steps that need to be carried out. 1) Create Profile and Account 2) Configure Email 3) Send Email.
Step 1) Create Profile and Account:
You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings which are shown below:
Step 2) Configure Email:
After the Account and the Profile are created successfully, we need to configure the Database Mail. To configure it, we need to enable the Database Mail XPs parameter through the sp_configure stored procedure, as shown here:
sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO
Step 3) Send Email:
After all configurations are done, we are now ready to send an email. To send mail, we need to execute a stored procedure sp_send_dbmail and provide the required parameters as shown below:
USE msdb
GO
EXEC sp_send_dbmail @profile_name='PinalProfile',
@recipients='test@Example.com',
@subject='Test message',
@body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'
After all validations of the parameters entered are done, certain stored procedures are executed and the mail is queued by Service Broker, read more at SQL SERVER – Introduction to Service Broker.
Database Mail keeps copies of outgoing e-mail messages and displays them in the sysmail_allitems, sysmail_sentitems, sysmail_unsentitems, sysmail_faileditems . The status of the mail sent can be seen in sysmail_mailitems table, when the mail is sent successfully the sent_status field of the sysmail_mailitems table is set to 1 which can again be seen in sysmail_sentitems table. The mails that are failed will have the sent_status field  value to 2 and those are unsent will have value 3.
The log can be checked in sysmail_log table as shown below:
SELECT *
FROM sysmail_mailitems
GO
SELECT *
FROM sysmail_log
GO
Status can be verified using sysmail_sentitems table.
After sending mail you can check the mail received in your inbox, just as I received as shown below.