Monday, September 9, 2013

Calculate days month and year in sql server

DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int
SELECT @date = '10/19/77'

SELECT @tmpdate = @date

SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(m, @months, @tmpdate)
SELECT @days = DATEDIFF(d, @tmpdate, GETDATE())

SELECT @years as year, @months as month, @days as days

Friday, May 24, 2013

merge two datatable and sum the data and bind into gridview

  MergeDT.Merge(ds.Tables[1]);
MergeDT.Merge(ds.Tables[2]);

 protected void CreateTotalTarget(DataTable MergeDT)
    {
        if (MergeDT != null)
        {
            if (MergeDT.Rows.Count > 0)
            {
                DataTable PrincipalDT = new DataTable();
                DataView dv = new DataView(MergeDT);
                DataTable FinalDT = MergeDT.Clone();
                PrincipalDT = dv.ToTable(true, "PrincipalName");
                for (int i = 0; i < PrincipalDT.Rows.Count; i++)
                {
                    object ISGQ1TgT;
                    ISGQ1TgT = MergeDT.Compute("SUM([ISG Q1 Trgt])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");
                    object ISGQ1Ach;
                    ISGQ1Ach = MergeDT.Compute("SUM([ISG Q1 Ach])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");

                    object ISGQ2TgT;
                    ISGQ2TgT = MergeDT.Compute("SUM([ISG Q2 Trgt])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");
                    object ISGQ2Ach;
                    ISGQ2Ach = MergeDT.Compute("SUM([ISG Q2 Ach])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");

                    object ISGQ3TgT;
                    ISGQ3TgT = MergeDT.Compute("SUM([ISG Q3 Trgt])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");
                    object ISGQ3Ach;
                    ISGQ3Ach = MergeDT.Compute("SUM([ISG Q3 Ach])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");

                    object ISGQ4TgT;
                    ISGQ4TgT = MergeDT.Compute("SUM([ISG Q4 Trgt])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");
                    object ISGQ4Ach;
                    ISGQ4Ach = MergeDT.Compute("SUM([ISG Q4 Ach])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");

                    object Annual_Trgt;
                    Annual_Trgt = MergeDT.Compute("SUM([Annual_Trgt])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");
                    object Annual_Ach;
                    Annual_Ach = MergeDT.Compute("SUM([Annual_Ach])", "PrincipalName='" + PrincipalDT.Rows[i]["PrincipalName"].ToString() + "'");

                    DataRow drow = null;
                    drow = FinalDT.NewRow();
                    drow["PrincipalName"] = PrincipalDT.Rows[i]["PrincipalName"].ToString();
                    drow["ISG Q1 Trgt"] = ISGQ1TgT;
                    drow["ISG Q1 Ach"] = ISGQ1Ach;
                    drow["ISG Q2 Trgt"] = ISGQ2TgT;
                    drow["ISG Q2 Ach"] = ISGQ2Ach;
                    drow["ISG Q3 Trgt"] = ISGQ3TgT;
                    drow["ISG Q3 Ach"] = ISGQ3Ach;
                    drow["ISG Q4 Trgt"] = ISGQ4TgT;
                    drow["ISG Q4 Ach"] = ISGQ4Ach;
                    drow["Annual_Trgt"] = Annual_Trgt;
                    drow["Annual_Ach"] = Annual_Ach;

                    FinalDT.Rows.InsertAt(drow, 1);
                  
                }
                DataView _dv = new DataView(FinalDT);
                _dv.Sort = "PrincipalName ASC";
                gvTotalTarget.DataSource = _dv;
                gvTotalTarget.DataBind();
            }
        }
   
    }

Monday, April 8, 2013

Disable right click control and many keys

function DisableRightClick(event)
       {
               if (event.button==2)
               {
               alert("Right Clicking not allowed!");
               }
       }


 function DisableCtrlKey(e)
           {
               var code = (document.all) ? event.keyCode:e.which;
               var message = "Ctrl key functionality is disabled!";
               if (parseInt(code)==17)
                       {
                       alert(message);
                       window.event.returnValue = false;
                       }
               if (parseInt(code)==18)
                       {
                       alert("Alt key functionality is disabled!");
                       window.event.returnValue = false;
                       }
               if (parseInt(code)==32)
                       {
                       alert("Space key is disabled");
                       window.event.returnValue = false;
                       }
               if (parseInt(code)==45)
                       {
                       alert("Insert key is disabled!");
                       window.event.returnValue = false;
                       }
           }

oncopy="return false;" onpaste="return false;" oncut="return false;" ondragstart="return false" onselectstart="return false"

Wednesday, April 3, 2013

trim in javascript

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function isBlank(s)
{
     if(s==null)
     return true;
     if(s.match(/^\s*$/))
     {
         return true
     }
     return false;
}

    if(isBlank(trim(objTourName.value,' ')) || trim(objTourName.value,' ').length ==0)
    {
        alert("Tour Name can not be left blank.");
        objTourName.focus();
        return false;
    }

Only numbers decimal not allowed

<script type="text/javascript">
        function checkIt(evt) {
            evt = (evt) ? evt : window.event
            var charCode = (evt.which) ? evt.which : evt.keyCode
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                alert("Only Numbers allowed");
                return false
            }
            
            document.getElementById("errorMessage").innerHTML = ""
            return true
        }
        function Changed( textControl )
        {
           if(textControl.value.indexOf(".") !== -1)
           {
               alert("decimal values not allowed");textControl.value='';return false;
           }
           return true;
        }

</script>
<asp:TextBox ID="TextBox1" runat="server" onKeyPress="return checkIt(event)" onchange="javascript: Changed(this);" ></asp:TextBox>

Tuesday, February 26, 2013

If you want to check null value in aspx value while binding data


<%#Eval("BranchFax") != DBNull.Value ? "Fax:" : ""%>
<%#Eval("BranchFax") != DBNull.Value ? Eval("BranchFax") + ",&nbsp;" : ""%>

<asp:TextBox ID="TextBox1" Height="19" Width="30" runat="server" Text = '<%#Eval("CName") != null ? Eval("CName") : "Not available" %>'></asp:TextBox>

bind date in aspx file

<%# DataBinder.Eval(Container.DataItem,"MarDate","{0:dd-MMM-yyyy}")%>

Update progress bar


 <asp:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="pnlPopup" BehaviorID="mdlPopup"
        PopupControlID="pnlPopup" BackgroundCssClass="modalBackground" />
    <asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none;
        border: none; background: none" Height="100px" Width="200px  ">
        <div align="center" style="margin-top: 13px;">
            <img src="../App_Themes/Theme1/Images/progressbar_1.gif" />
        </div>
    </asp:Panel>


<script type="text/javascript">
<!--
//-->

         //  register for our events
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);  
           
            function beginRequest(sender, args){
                // show the popup
                $find('mdlPopup').show();      
            }

            function endRequest(sender, args) {
                //  hide the popup
                $find('mdlPopup').hide();
            }


    </script>


<style >
        .modalBackground
        {
            background-color: gray;
            filter: alpha(opacity=60);
            opacity: 0.6;
        }
        .modalPopup
        {
            background-color: White;
            border-width: 1px;
            border-style: solid;
            border-color: Gray;
            padding: 0px;
        }
    </style>


Thursday, February 14, 2013

What are your current roles and responsibilities in the current organisation



  1. I take part in database designing
  2. Requirement analysis
  3. Development according the design 
  4. Unit testing

Why do you want to leave your current job/organization/company?

 I am looking for a position which would have excellent match for my skills and experience. In my present job there is very limited scope of growth. I am interested in a new challenge and an opportunity to use my technical skills and experience in a different capacity.

Fill cascading dropdown of ajaxtoolkit

Write below code in webservice file:

[WebMethod]
    public CascadingDropDownNameValue[] fillProducts(string knownCategoryValues, string category)
    {
        int PrincipalId;
        System.Collections.Specialized.StringDictionary PrincipalList = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        PrincipalId = Convert.ToInt32(PrincipalList["ddlPrincipal"]);

        objQuotation = new clsQuotation();
        objQuotationBO = new clsQuotationBO();
        objQuotationBO.I32PrincipalId = Convert.ToInt32(PrincipalId);
        objQuotationBO.I32ProductStatus = 1;
        DataTable dt = objQuotation.ProductListing(objQuotationBO);

        List<CascadingDropDownNameValue> ProductList = new List<CascadingDropDownNameValue>();
        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    ProductList.Add(new CascadingDropDownNameValue(dt.Rows[i]["ProductName"].ToString(), dt.Rows[i]["ProductId"].ToString() + "~" + dt.Rows[i]["Price"].ToString() + "~" + dt.Rows[i]["ProductDescription"].ToString()));
                }

            }
        }
        return ProductList.ToArray();
    }

    [WebMethod]
    public CascadingDropDownNameValue[] fillPrincipals()
    {
        objQuotation = new clsQuotation();
        DataTable dt = objQuotation.PrincipalListing();       
        List<CascadingDropDownNameValue> PrincipalList = new List<CascadingDropDownNameValue>();
        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                DataView v = dt.DefaultView;
                v.RowFilter = "IsDeleted=0";
                dt = v.ToTable();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    PrincipalList.Add(new CascadingDropDownNameValue(dt.Rows[i]["PrincipalName"].ToString(), dt.Rows[i]["PrincipalId"].ToString()));
                }

            }
        }
        return PrincipalList.ToArray(); ;
    }
////////////////////////// aspx file code

<td style="vertical-align: top">
                        <asp:DropDownList ID="ddlPrincipal" runat="server" CssClass="drop-down" Style="width: 185px">
                        </asp:DropDownList>
                        <asp:CascadingDropDown ID="cddlPrincipal" runat="server" TargetControlID="ddlPrincipal"
                            Category="ddlPrincipal" PromptText="- Please Select -" ServicePath="~/GetMasterData.asmx"
                            ServiceMethod="fillPrincipals"  LoadingText="Please wait">
                        </asp:CascadingDropDown><%--SelectedValue='<%# Eval("PrincipalId") %>'--%>
                    </td>
                    <td style="vertical-align: top" >
                        <asp:DropDownList ID="ddlProducts" runat="server" CssClass="drop-down" Style="width: 165px">
                        </asp:DropDownList>
                        <asp:CascadingDropDown ID="cddlProducts" runat="server" TargetControlID="ddlProducts" ParentControlID="ddlPrincipal"
                         Category="ddlProducts" PromptText="- Please Select -" ServicePath="~/GetMasterData.asmx"
                         ServiceMethod="fillProducts" UseContextKey="true" ></asp:CascadingDropDown>
                    </td>

Report in MBS with dynamic pivoting


/****** Object:  StoredProcedure [dbo].[Proc_GetMealReport]    Script Date: 02/14/2013 15:31:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec Proc_GetMealReport 10,2012
ALTER PROCEDURE [dbo].[Proc_GetMealReport](
@MonthId INT,
@pYear INT)
AS
BEGIN
DECLARE @days INT, @daylist VARCHAR(MAX),@MealPrice INT, @daycollist varchar(max), @daysumlist varchar(max),@SubsidyPrice INT
/*set @MonthId = 9
set @pYear = 2012*/

SELECT @days = DAY(DATEADD(D,-1, DATEADD(m,1, CAST(cast(@pYear*100+@MonthId as varchar)+'01'  as date))))

;with ctedays as (
select 1 as dd
union all
select dd+1 from ctedays where dd<@days
)

 select * into #days from ctedays
select @daylist = stuff((select ',[' + cast(dd as varchar) + ']' from #days for xml path('')),1,1,'')
select @daycollist = stuff((select ',ISNULL([' + cast(dd as varchar) + '],0) AS ['+ cast(dd as varchar)+ ']'
from #days for xml path('')),1,1,'')
select @daysumlist = stuff((select '+ISNULL([' + cast(dd as varchar) + '],0)' from #days for xml path('')),1,1,'')
Select @MealPrice =(SELECT PRICE FROM PriceMaster WHERE Active=1)
Select @SubsidyPrice =(SELECT Subsidy FROM PriceMaster WHERE Active=1)

DECLARE @QUERY NVARCHAR(MAX)
SET @QUERY = 'select ROW_NUMBER() OVER (ORDER BY username) As [S.No.], UserID ,
UserName AS [User Name],'  + @daycollist + ',' + @daysumlist+ 'AS [Total Meal],(' + @daysumlist + ')*'
+Convert(VARCHAR(10),@MealPrice-@SubsidyPrice)+' AS [Total Price]
from (
select dd, u.UserId,(u.FirstName+'' ''+u.LastName) AS UserName,isnull((self+Client),0) AS tot,0 as [Total Meal],0 AS [Total Price]
from #days
left join BookingDetails bd on dd = DAY(mealdate)
and YEAR(mealdate)= ' + CAST(@pYear as varchar) + ' and MONTH(mealdate) =  '
+  cast(@MonthId as varchar) + '
JOIN Users u
ON
u.UserID=bd.UserID
) src pivot(Min(tot) for dd in(' + @daylist + '))  pvt ORDER BY [User Name]'


print @QUERY
EXEC (@QUERY)

drop table #days

END

Security Checks


for //CSRF on aspx page:
in ispagepostback


 utility obj = new utility();
CSRF_Token.Value = obj.Initialize_CSRF_Token();

out of the ispagepostback


                utility obj2 = new utility();
                if (!obj2.Validate_CSRF_Token(CSRF_Token.Value))
                {
                    obj2.CSRF_Attack_Found();
                }



public string Initialize_CSRF_Token()
        {
            if (HttpContext.Current.Session["CSRF_Token"] != null)
            {
                return HttpContext.Current.Session["CSRF_Token"].ToString();
            }
            else
                return "0";
        }

        public bool Validate_CSRF_Token(string CSRF_Token)
        {
            if (HttpContext.Current.Session["CSRF_Token"] != null)
            {
                if (CSRF_Token == HttpContext.Current.Session["CSRF_Token"].ToString())
                {
                    return true;
                }
                //else
                //{
                //    return false;
                //}

            }
            return false;
        }

        public void CSRF_Attack_Found()
        {
            HttpContext.Current.Session.Clear();
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Response.Redirect("~/ErrorPages/GeneralError.aspx");
        }

        public static void CheckReffererURL()
        {
            string SiteUrl = string.Empty;
            SiteUrl = ConfigurationManager.AppSettings["SiteUrl"].ToString();
            if (HttpContext.Current.Request.UrlReferrer == null)
            {
                HttpContext.Current.Response.Redirect("~/ErrorPages/PageNotFound.aspx");
            }
            if (!HttpContext.Current.Request.UrlReferrer.ToString().Contains(SiteUrl))
            {
                HttpContext.Current.Response.Redirect("~/ErrorPages/PageNotFound.aspx");

            }
        }

        public static bool CheckSqlInjection(string strQuery)
        {
            //return true;
            strQuery = strQuery.ToLower();
            if ((strQuery.IndexOf("or 1=1") != -1) || (strQuery.IndexOf("drop") != -1) || (strQuery.IndexOf("truncate") != -1) || (strQuery.IndexOf("xtype") != -1) || (strQuery.IndexOf("Union all") != -1)
    || (strQuery.IndexOf("--") != -1) || (strQuery.IndexOf(";") != -1) || (strQuery.IndexOf(";") != -1) || (strQuery.IndexOf("/*") != -1) || (strQuery.IndexOf("*/") != -1) || (strQuery.IndexOf("@@") != -1) || (strQuery.IndexOf("@") != -1)
    || (strQuery.IndexOf("cast") != -1) || (strQuery.IndexOf("cursor") != -1) || (strQuery.IndexOf("declare") != -1) || (strQuery.IndexOf("exec") != -1) || (strQuery.IndexOf("execute") != -1) || (strQuery.IndexOf("fetch") != -1)
    || (strQuery.IndexOf("alter") != -1))
                return false;
            else
                return true;

        }

        public bool validateNumeric(string number)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(number, @"^[0-9]{1,10}$"))       //0-9, accept max 10 digits
                return false;
            else
                return true;
        }

        public static void CheckSSL()
        {
            string LocalURL = "http://localhost";
            if (!HttpContext.Current.Request.Url.ToString().Contains(LocalURL))
            {
                if (!HttpContext.Current.Request.IsSecureConnection)
                {
                    string redirectUrl = HttpContext.Current.Request.Url.ToString().Replace("http:", "https:");
                    HttpContext.Current.Response.Redirect(redirectUrl);

                }
            }

        }

Pie Chart in ASP.NET with C#


   private void showPieChart()
        {
            try
            {
                DataSet ds = new DataSet();
                ds = (DataSet)(Session["ds"]);
                DataSet dset = new DataSet();
                dset = (DataSet)(Session["dset"]);
                if (dset != null && dset.Tables[0].Rows.Count > 0)
                {
                    string[] x1 = new string[rdOptions.Items.Count];
                    int[] y1 = new int[rdOptions.Items.Count];
                    int cntDs = 0;

                    int sum = 0;
                    for (int i = 0; i < dset.Tables[1].Rows.Count; i++)
                    {
                        sum += Convert.ToInt16(dset.Tables[1].Rows[i]["Record"]);
                    }
                    for (int i = 0; i < rdOptions.Items.Count; i++)
                    {
                        if (!string.IsNullOrEmpty(ds.Tables[0].Rows[Convert.ToInt32(hdnCnt.Value)]["offline_answers" + (i + 1)].ToString()))
                            sum += Convert.ToInt16(ds.Tables[0].Rows[Convert.ToInt32(hdnCnt.Value)]["offline_answers" + (i + 1)]);
                    }
                    DataSet dset1 = new DataSet();
                    for (int i = 0; i < rdOptions.Items.Count; i++)
                    {
                        int onlineAnswer = 0;
                        using (DataBaseAccess db1 = new DataBaseAccess(true))
                        {
                            db1.AddParameter("@Qid", id);
                            db1.AddParameter("@SelOption", rdOptions.Items[i].Text);
                            dset1 = db1.ExecuteDataSet("proc_ReturnResponse");
                            if (dset1 != null)
                            {
                                if (dset1.Tables.Count > 0 && dset1.Tables[0].Rows.Count > 0)
                                {

                                    for (int cnt = 0; cnt < dset1.Tables[0].Rows.Count; cnt++)
                                    {
                                        onlineAnswer += Convert.ToInt16(dset1.Tables[0].Rows[cnt]["Record"]);
                                    }
                                }

                            }
                        }
                        Int32 offline_answered = 0;
                        if (!string.IsNullOrEmpty(ds.Tables[0].Rows[Convert.ToInt32(hdnCnt.Value)]["offline_answers" + (i + 1)].ToString()))
                            offline_answered = Convert.ToInt16(ds.Tables[0].Rows[Convert.ToInt32(hdnCnt.Value)]["offline_answers" + (i + 1)]);

                        Int32 calcPer = Convert.ToInt32(((offline_answered + onlineAnswer) * 100) / sum);

                        x1[i] = rdOptions.Items[i].Value.ToString();


                        y1[i] = calcPer;   //have only offline record //Convert.ToInt16(dset.Tables[0].Rows[i]["Record"])
                        cntDs++;
                    }



                    //remoove empty elements
                    List<string> y = x1.ToList<string>();
                    // y.RemoveAll(p => string.IsNullOrEmpty(p));
                    x1 = y.ToArray();


                    List<int> z = y1.ToList<int>();
                    //   z.RemoveAll(p => p == 0);
                    y1 = z.ToArray();

                    Chart1.Series[0].Points.DataBindXY(x1, y1);

                    //Chart1.Series[0].Label = "#VALX (#PERCENT{P2})";


                    Chart1.Series[0].ChartType = SeriesChartType.Pie;
                    //Chart1.Series[0].ChartArea = SeriesChartType.StackedArea.ToString();
                    //Chart1.Series[0].ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), RadioButtonList1.SelectedItem.Text, true);

                    ///////////////////
                    this.Chart1.Series[0]["PieLabelStyle"] = "Outside";
                    this.Chart1.Series[0]["3DLabelLineSize"] = "30";
                    //this.Chart1.Series[0]["LabelsRadialLineSize"] = "0.15";
                    //this.Chart1.Series[0]["LabelsHorizontalLineSize"] = "0.15";
                  
                        this.Chart1.Series[0].Label = "#PERCENT{P0}";
                        // Add a legend to the chart and dock it to the bottom-center
                        this.Chart1.Legends.Add("Legend1");
                        this.Chart1.Legends[0].Enabled = true;
                        this.Chart1.Legends[0].Docking = Docking.Bottom;
                        this.Chart1.Legends[0].Alignment = System.Drawing.StringAlignment.Near;
                  
                    // Show labels in the legend in the format "Name (### %)"
                    this.Chart1.Series[0].LegendText = "#VALX";
                    Chart1.Legends[0].LegendStyle = LegendStyle.Column;
                    //Chart2.Legends[0].MaximumAutoSize = 50;
                    Chart1.Legends[0].TextWrapThreshold = 450;
                    // By sorting the data points, they show up in proper ascending order in the legend
                    // this.Chart1.DataManipulator.Sort(PointSortOrder.Descending, Chart1.Series[0]);
                    ////////////////////
                    foreach (var itemName in Chart1.Series[0].Points)
                    {

                        string Lablename = ((System.Web.UI.DataVisualization.Charting.DataPointCustomProperties)(itemName)).AxisLabel.ToLower().Trim();
                        if (hdnSelectedbarText.Value.ToLower().Trim() == Lablename)
                        {
                            Chart1.Series[0]["BarLabelStyle"] = "Center";

                            ((System.Web.UI.DataVisualization.Charting.DataPointCustomProperties)(itemName)).Label = "#PERCENT{P0}  " + System.Environment.NewLine + "(You are here)";
                            ((System.Web.UI.DataVisualization.Charting.DataPointCustomProperties)(itemName)).IsValueShownAsLabel = true;
                            ((System.Web.UI.DataVisualization.Charting.DataPointCustomProperties)(itemName)).Font = new System.Drawing.Font("Arial, Helvetica, sans-serif", 9, System.Drawing.FontStyle.Bold);
                        }
                        Lablename = string.Empty;
                        if (((DataPoint)(itemName)).YValues[0] == 0)
                        {
                            ((DataPoint)(itemName)).Label = string.Empty;
                            ((DataPoint)(itemName)).AxisLabel = string.Empty;
                            ((DataPoint)(itemName)).IsVisibleInLegend = false;
                         
                        }
                    }
                    Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;

                    SetColor();
                    Chart1.SaveImage(HttpContext.Current.Request.PhysicalApplicationPath + "Chart1.jpg");
                    //  lblNo.Text = sum.ToString();
                }
            }
            catch (Exception ex)
            {
                //Response.Write("No Response Available");
            }
        }

Bar Chart in ASP.NET with C#


 private void ShowBarChart1()
        {
            DataSet ds = new DataSet();
            ds = (DataSet)(Session["ds"]);

            DataSet dset = new DataSet();

            string SelOptValue = hdnSelValue.Value;
            hdnSelectedbarText.Value = hdnSelValue.Value;

            using (DataBaseAccess db = new DataBaseAccess(true))
            {
                db.AddParameter("@Qid", id);
                db.AddParameter("@SelOption", SelOptValue);
                dset = db.ExecuteDataSet("proc_ReturnResponse");
                Session["dset"] = dset;
            }


            try
            {
                if (dset != null && dset.Tables[0].Rows.Count > 0)
                {
                    DataTable DT = new DataTable();
                    DT = dset.Tables[1];
                    DT.DefaultView.Sort = "Record";
                    DT = DT.DefaultView.ToTable();
                    string[] x1 = new string[rdOptions.Items.Count];
                    int[] y1 = new int[rdOptions.Items.Count];
                    int cntDs = 0;
                    int others = 0;

                    //get sum
                    int sum = 0;

                    for (int i = 0; i < DT.Rows.Count; i++)
                    {
                        sum += Convert.ToInt16(DT.Rows[i]["Record"]);
                        // onlineAnswer += Convert.ToInt16(dset.Tables[0].Rows[i]["Record"]);
                    }
                    for (int i = 0; i < rdOptions.Items.Count; i++)
                    {
                        if (!string.IsNullOrEmpty(ds.Tables[0].Rows[Convert.ToInt32(hdnCnt.Value)]["offline_answers" + (i + 1)].ToString()))
                            sum += Convert.ToInt16(ds.Tables[0].Rows[Convert.ToInt32(hdnCnt.Value)]["offline_answers" + (i + 1)]);
                    }
                    //  ResponseCount = sum;
                    DataSet dset1 = new DataSet();
                    for (int i = 0; i < rdOptions.Items.Count; i++)
                    {
                        int onlineAnswer = 0;
                        using (DataBaseAccess db1 = new DataBaseAccess(true))
                        {
                            db1.AddParameter("@Qid", id);
                            db1.AddParameter("@SelOption", rdOptions.Items[i].Text);
                            dset1 = db1.ExecuteDataSet("proc_ReturnResponse");
                            if (dset1 != null)
                            {
                                DataTable DT1 = new DataTable();
                                DT1 = dset1.Tables[1];
                                DT1.DefaultView.Sort = "Record";
                                DT1 = DT.DefaultView.ToTable();
                                if (dset1.Tables.Count > 0 && dset1.Tables[0].Rows.Count > 0)
                                {

                                    for (int cnt = 0; cnt < dset1.Tables[0].Rows.Count; cnt++)
                                    {
                                        onlineAnswer += Convert.ToInt16(dset1.Tables[0].Rows[cnt]["Record"]);
                                    }
                                }

                            }
                        }

                        Int32 offline_answered = 0;
                        if (!string.IsNullOrEmpty(ds.Tables[0].Rows[Convert.ToInt32(hdnCnt.Value)]["offline_answers" + (i + 1)].ToString()))
                            offline_answered = Convert.ToInt16(ds.Tables[0].Rows[Convert.ToInt32(hdnCnt.Value)]["offline_answers" + (i + 1)]);
                        Int32 calcPer = Convert.ToInt32(((offline_answered + onlineAnswer) * 100) / sum);

                        x1[i] = rdOptions.Items[i].Value.ToString();

                        y1[i] = calcPer;

                    }

                    //remoove empty elements
                    List<string> y = x1.ToList<string>();
                    // y.RemoveAll(p => string.IsNullOrEmpty(p));
                    x1 = y.ToArray();


                    List<int> z = y1.ToList<int>();
                    //  z.RemoveAll(p => p == 0);
                    y1 = z.ToArray();



                    Chart2.Series[0].Points.DataBindXY(x1, y1);
                    Chart2.Series[0].ChartType = SeriesChartType.Bar;

                    Random random = new Random();

                    foreach (var item in Chart2.Series[0].Points)
                    {
                        Color c = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
                    }

                    ///////////////////

                    //  this.Chart1.Series[0]["PieLabelStyle"] = "Outside";
                    this.Chart2.Series[0].Label = "#PERCENT{P0}";
                    // Add a legend to the chart and dock it to the bottom-center
                    this.Chart2.Legends.Add("Legend1");
                    this.Chart2.Legends[0].Enabled = true;
                    this.Chart2.Legends[0].Docking = Docking.Bottom;
                    this.Chart2.Legends[0].Alignment = System.Drawing.StringAlignment.Near;

                    Chart2.ChartAreas["ChartArea2"].AxisX.MajorGrid.Enabled = false;
                    Chart2.ChartAreas["ChartArea2"].AxisY.MajorGrid.Enabled = false;
                    Chart2.ChartAreas[0].AxisY.Enabled = AxisEnabled.False;
                    Chart2.ChartAreas[0].AxisX.Enabled = AxisEnabled.False;
                    Chart2.Width = 600;
                    Chart2.Series[0].IsValueShownAsLabel = true;
                    Chart2.Series[0].IsVisibleInLegend = false;

                    ///Code for showing legengs in in one line.
                    Chart2.Legends[0].LegendStyle = LegendStyle.Column;
                    Chart2.Legends[0].TextWrapThreshold = 450;
                    ///
                    foreach (var itemName in Chart2.Series[0].Points)
                    {
                        string Lablename = ((System.Web.UI.DataVisualization.Charting.DataPointCustomProperties)(itemName)).AxisLabel.ToLower().Trim();
                        if (hdnSelectedbarText.Value.ToLower().Trim() == Lablename)
                        {
                            Chart2.Series[0]["BarLabelStyle"] = "Left";
                            ((System.Web.UI.DataVisualization.Charting.DataPointCustomProperties)(itemName)).Label = "#PERCENT{P0}  " + "(You are here)";
                            ((System.Web.UI.DataVisualization.Charting.DataPointCustomProperties)(itemName)).Font = new System.Drawing.Font("Arial, Helvetica, sans-serif", 9, System.Drawing.FontStyle.Bold);
                        }
                        Lablename = string.Empty;
                    }

                    SetBarChartColor();
                    Chart2.SaveImage(HttpContext.Current.Request.PhysicalApplicationPath + "Chart2.jpg");
                }
            }
            catch (Exception ex)
            {
                //Response.Write("No Response Available");
            }
        }
     

Thursday, January 31, 2013

Validations in ASP.NET C#

static bool IsNumeric(string sExpression)
{
Regex objRegx = new Regex(@"[^0-9-\.]");
return !objRegx.IsMatch(sExpression);
}


 public bool OnlyAlphabets(string objValue, int minLen, int maxLen)
        {
            Regex re = new Regex("^[a-z,A-Z\\s]{" + minLen + "," + maxLen + "}$");
            if (!re.IsMatch(objValue))
            {
                return false;
            }
            else
            {
                return true;
            }

        }


 public bool OnlyNumbers(string objValue, int minLen, int maxLen)
        {
            Regex re = new Regex("^[0-9]{" + minLen + "," + maxLen + "}$");
            if (!re.IsMatch(objValue))
            {
                return false;
            }
            else
            {
                if ((objValue.Length < minLen) || (objValue.Length > maxLen))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }          
        }


public bool ValidateEmail(string objValue)
        {
            Regex re = new Regex("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
            if (!re.IsMatch(objValue))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
 public bool ValidateMobile(string objValue,int minLen, int maxLen)
        {
            Regex re = new Regex("^[0-9]{10}");
            if (!re.IsMatch(objValue))
            {
                return false;
            }
            else
            {
                return true;
            }
        }