Wednesday, 1 June 2016

How to split the string in asp.net?

   if (!string.IsNullOrWhiteSpace(tempitemnoList))
                    {
                        string[] tempNumber = tempitemnoList.Split(new string[] { "/" }, StringSplitOptions.None);
                        if (tempNumber.Count() > 0)
                        {
                            for (int i = 0; i < tempNumber.Count(); i++)
                            {
                                if (tempNumber[i] != "")
                                {
                                    string[] temp = tempNumber[i].Split(new string[] { "," }, StringSplitOptions.None);
                                    if (temp.Count() > 0)
                                    {
                                        if (temp[0] != "")
                                        {
                                            string VendorItemNo = temp[0];
                                            VendorItem item = new VendorItem();
                                            var data = objdb.GetInvoiceImportPriceById(Convert.ToInt32(temp[0])).FirstOrDefault();
                                            if (data != null)
                                            {
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return Json(new { success = true }, JsonRequestBehavior.AllowGet);

Monday, 23 May 2016

How to more than one list value to add another list value in MVC?

 *************Employee Model*******************
 public classEmployeeModel
    {
        public EmployeeModel()
        {
            EmployeeList = new List<EmployeeModel>();
            StudentList = new List<EmployeeModel>();

            ServiceList = new List<SelectListItem>();
            ParentList = new List<SelectListItem>();
            GenderList= new List<SelectListItem>
            {
               new SelectListItem() {Text = "--Select--", Value ="0" },
               new SelectListItem() {Text = "Male", Value ="1" },
               new SelectListItem() {Text = "Female", Value ="2"},
             };
        }
        public int ID { get; set; }
        public string Name{ get; set; }
        public string Address{ get; set; }
        public int Age{ get; set; }
        public string Mobile{ get; set; }
     
        public List<EmployeeModel> EmployeeList { get; set; }
        public List<EmployeeModel> StudentList { get; set; }
        public IEnumerable<Employee> SerList { get; set; }

        public decimal? ServiceUsage { get; set; }
        public decimal? ServiceCost_Per_Annum { get; set; }
        public decimal? ServiceCost_for_Service { get; set; }

        public List<SelectListItem> GenderList{ get; set; }

    }

************************End Employee Model**************************
var empList = _apiService.GetAllEmployee().ToList();
                    model.EmployeeList = stcList.Select(x =>
                    {
                        return new EmployeeModel()
                        {
                            ID = x.ID == null ? 0 : x.ID.Value,
                            Name = string.IsNullOrEmpty(x.Name) ? "" : x.Name,
                            Address= string.IsNullOrEmpty(x.Address) ? "" : x.Address,
                            Mobile= string.IsNullOrEmpty(x.Mobile) ? "" : x.Mobile,
                            Age= x.Age == null ? Convert.ToInt32(0) : x.Age,
                        };
                    }).ToList();

                    var stuList = _apiService.GetAllStudent().ToList();
                    model.StudentList = stuList .Select(x =>
                        {
                            return new ComponentModel()
                            {
                               ID = x.ID == null ? 0 : x.ID.Value,
                            Name = string.IsNullOrEmpty(x.Name) ? "" : x.Name,
                            Address= string.IsNullOrEmpty(x.Address) ? "" : x.Address,
                            Mobile= string.IsNullOrEmpty(x.Mobile) ? "" : x.Mobile,
                            Age= x.Age == null ? Convert.ToInt32(0) : x.Age,
                            };
                        }).ToList();


var AddExData = new List<EmployeeModel>();

AddExData.AddRange(model.EmployeeList);
AddExData.AddRange(model.StudentList);

Sunday, 1 May 2016

How to windows authentication in mvc?

Firstly, in web.config to configure-:

<system.web>  
    <authentication mode="Windows"></authentication>
    <authorization>
      <deny users="?" />
    </authorization>
 </system.web>

After that Project property (F4 Click)
Windows Authentication Diable and Autonymous Authentication Enabled.

After that it works.
  string domainUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            string IsAuthentication = System.Web.HttpContext.Current.Request.IsAuthenticated.ToString();
            string[] paramsLogin = domainUser.Split('\\');
            string UserName = paramsLogin[1].ToString();

How to log out windows authentication in mvc?

public ActionResult LogOut()
{
    HttpCookie cookie = Request.Cookies["TSWA-Last-User"];

    if(User.Identity.IsAuthenticated == false || cookie == null || StringComparer.OrdinalIgnoreCase.Equals(User.Identity.Name, cookie.Value))
    {
        string name = string.Empty;

        if(Request.IsAuthenticated)
        {
            name = User.Identity.Name;
        }

        cookie = new HttpCookie("TSWA-Last-User", name);
        Response.Cookies.Set(cookie);

        Response.AppendHeader("Connection", "close");
        Response.StatusCode = 401; // Unauthorized;
        Response.Clear();
        //should probably do a redirect here to the unauthorized/failed login page
        //if you know how to do this, please tap it on the comments below
        Response.Write("Unauthorized. Reload the page to try again...");
        Response.End();

        return RedirectToAction("Index");
    }

    cookie = new HttpCookie("TSWA-Last-User", string.Empty)
    {
        Expires = DateTime.Now.AddYears(-5)
    };

    Response.Cookies.Set(cookie);

    return RedirectToAction("Index");

}

Wednesday, 30 March 2016

How to drag and drop(dynamic control) bind and save the data in asp.net?



<div dir="ltr" style="text-align: left;" trbidi="on">
<html lang="en">
<head>
   
    <title>Add Dynamic Label</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet"></link>
    <link href="Content/StyleSheet.css" rel="stylesheet"></link>
    <link href="Content/Print.css" media="print" rel="stylesheet"></link>
    <script src="Scripts/jquery-1.11.1.min.js"></script>
    <script src="Scripts/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/floatthead/1.3.2/jquery.floatThead.js"></script>
    <script src="/Scripts/jquery.visible.min.js"></script>
    <style>
        #div1 {
            width: 500px;
            height: 300px;
            padding: 10px;
            border: 1px solid #aaaaaa;
        }
    </style>

    <script type="text/javascript">
        function insertWebForm() {
            debugger;
            if (document.getElementById('<%=txtPage.ClientID%>').value == '') {
                document.getElementById('<%=txtPage.ClientID%>').focus();
                return false;
            }
            var pageName = document.getElementById('<%=txtPage.ClientID%>').value;
            var isCheck = document.getElementById('<%=chkstatus.ClientID%>').checked;
            document.getElementById('<%=hdlField.ClientID%>').value = "";
            var label = document.getElementById('<%=hdlField.ClientID%>').value;

            var fname = document.getElementById("FName");
            var title = document.getElementById("Title");
            var lname = document.getElementById("LName");
            var company = document.getElementById("Company");
            var phone = document.getElementById("Phone");

         
            if (fname) {
                document.getElementById('<%=hdlField.ClientID%>').value = document.getElementById('<%=hdlField.ClientID%>').value + "/" + fname.id;
            }
            if (title) {
                document.getElementById('<%=hdlField.ClientID%>').value = document.getElementById('<%=hdlField.ClientID%>').value + "/" + title.id;
            }
            if (lname) {
                document.getElementById('<%=hdlField.ClientID%>').value = document.getElementById('<%=hdlField.ClientID%>').value + "/" + lname.id;
            }

            if (company) {
                document.getElementById('<%=hdlField.ClientID%>').value = document.getElementById('<%=hdlField.ClientID%>').value + "/" + company.id;
            }
            if (phone) {
                document.getElementById('<%=hdlField.ClientID%>').value = document.getElementById('<%=hdlField.ClientID%>').value + "/" + phone.id;
            }

            if (mobile) {
                document.getElementById('<%=hdlField.ClientID%>').value = document.getElementById('<%=hdlField.ClientID%>').value + "/" + mobile.id;
            }
       
            $.ajax({
                type: "POST",
                url: "DragAndDrop.aspx/insertPageNamewithLabel",
                data: '{pageName: "' + pageName + '", isCheck: "' + isCheck + '",  label: "' + document.getElementById('<%=hdlField.ClientID%>').value + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                }
            });

        }

        function OnSuccess(response) {
            debugger;
            if (response.d == "true") {
                document.getElementById('<%=hdlField.ClientID%>').value = "";
                var abc = document.getElementById('<%=hdlField.ClientID%>').value;
                window.location = '/DynamicLabelList.aspx';
            }
            else {
                document.getElementById('<%=hdlField.ClientID%>').value = "";
                var abc = document.getElementById('<%=hdlField.ClientID%>').value;
                alert("Page Name already inserted");
            }
        }

        function RemoveLabelControl(div) {
            document.getElementById("labelContainer").removeChild(div.parentNode);
        }
    </script>


    <script type="text/javascript">
        function drag(ev) {
            document.getElementById('<%=hdnLabel.ClientID%>').value = ev.target.innerHTML;
        }

        function allowDrop(ev) {
            debugger;
            var counter = 0;
            var label = document.getElementById('<%=hdnLabel.ClientID%>').value;
            if (label) {
                var div = document.createElement('DIV');

                var fname = document.getElementById(label);
                if (fname) {
                }
                else {
                    debugger;
                    div.innerHTML = '<label class="col-xs-4" style="margin-left: 17px;">' + label + '</label>&nbsp;' +
                           '<input name = "DynamicTextBox" type="text" id = "' + label + '" />&nbsp;' +
                           '<input id="Button' + counter + '" type="button" ' +
                           'value="Remove" onclick = "RemoveLabelControl(this)" />' +
               '<br/><br/>';
                }
                document.getElementById("div1").appendChild(div);
                counter++;
            }
        }

        function RemoveLabelControl(div) {
            document.getElementById("div1").removeChild(div.parentNode);
        }
    </script>

</head>
<body>

    <form id="form1" runat="server">
        <div class="container">
            <div class="col-md-4">
                <br />
                <br />
                <asp:label id="lblMsg" runat="server" style="color: green; margin-left: 500px;">
                <asp:hiddenfield id="hdnLabel" runat="server">
                <asp:hiddenfield id="hdlField" runat="server">
                <asp:hiddenfield id="hdnTextValue" runat="server">
                <br />
                <span style="font-family: Arial;">Click to Lead Field</span>&nbsp;&nbsp;
                <br />
                <label draggable="true" for="FName" ondragstart="drag(event)">FName</label>
                <br />
                <label draggable="true" for="LName" ondragstart="drag(event)">LName</label>
                <br />
                <label draggable="true" for="Title" ondragstart="drag(event)">Title</label>
                <br />
                <label draggable="true" for="Company" ondragstart="drag(event)">Company</label>
                <br />
                <label draggable="true" for="Phone" ondragstart="drag(event)">Phone</label>

                <br />

                <br />
                <br />
            </asp:hiddenfield></asp:hiddenfield></asp:hiddenfield></asp:label></div>
<div class="col-md-8">
                <h1>
Web Form</h1>
<br />
                <div class="col-xs-12">
                    <label class="col-sm-4 control-label" for="Scheduler Name">*Page Name</label>
                    <div class="col-sm-8">
                        <asp:textbox id="txtPage" runat="server"></asp:textbox>
                    </div>
</div>
<br />
                <br />
                <div class="col-xs-12">
                    <label class="col-sm-4 control-label" for="Custom View" style="padding-bottom: 28PX;">Status</label>
                    <div class="col-sm-8">
                        <asp:checkbox id="chkstatus" runat="server">
                    </asp:checkbox></div>
</div>
<div class="col-xs-6">
                </div>
<br />
                <br />
                <br />
                <br />

                Drag the DynamicLabels into the Rectangle:<br />


                <div id="div1" ondragover="allowDrop(event)" style="overflow: auto;">
</div>
<br />

                <br />

            </div>
<asp:button class="btn btn-default" id="btnSave" onclientclick="insertWebForm()" runat="server" style="margin-left: 210px;" text="Save">
            &nbsp;
              <asp:button class="btn btn-default" id="btnBack" onclick="btnBack_Click" runat="server" text="Back">
        </asp:button></asp:button></div>
</form>
</body>
</html></div>


In Code Behind-:

 public static string insertPageNamewithLabel(string pageName, string isCheck, string label)
    {
        string result = "true";

        DataTable dt = new DataTable();
        SqlDataAdapter da;
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source="";Initial Catalog="";Persist Security Info=True;User ID="";Password=""";

        SqlCommand cmd = new SqlCommand("select * from page  where Name='" + pageName + "'", con);
        da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        con.Open();
        cmd.ExecuteNonQuery();
        if (dt.Rows.Count > 0)
        {
            result = "false";
            //lblMsg.Text = "Page Name already inserted";
            //lblMsg.ForeColor = System.Drawing.Color.Green;
        }
        else
        {
            SqlConnection coninsert = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString);
            coninsert.Open();
            string strquery = "INSERT INTO [dbo].[Page]([Name],[Status]) VALUES (@name,@status);SELECT CAST(scope_identity() AS int)";
            SqlCommand cmdinsert = new SqlCommand(strquery, coninsert);
            cmdinsert.Parameters.AddWithValue("@name", pageName);
            if (isCheck == "false")
            {
                cmdinsert.Parameters.AddWithValue("@status", false);
            }
            else
            {
                cmdinsert.Parameters.AddWithValue("@status", true);
            }
            int pageId = (int)cmdinsert.ExecuteScalar();
            if (pageId > 0)
            {
                if (label.Length > 0)
                {
                    string[] splitId = label.Split(new string[] { "/" }, StringSplitOptions.None);
                    if (splitId.Count() > 0)
                    {
                        for (int i = 0; i < splitId.Count(); i++)
                        {
                            if (splitId[i] != "")
                            {

                                SqlConnection mycon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString);
                                mycon.Open();
                                string strquery1 = "insert into PageField (PageID, ControlToDisplay, FieldLabel, RequiredValidation, OrderBy, OptionalValue)values(@pageid,@Control,@fieldlabel,@required,@orderby,@optionalvalue);SELECT CAST(scope_identity() AS int)";

                                SqlCommand cmdPageLabel = new SqlCommand(strquery1, mycon);

                                cmdPageLabel.Parameters.AddWithValue("@pageid", pageId);
                                cmdPageLabel.Parameters.AddWithValue("@Control", "Single Line Text");
                                cmdPageLabel.Parameters.AddWithValue("@fieldlabel", splitId[i].ToString());
                                cmdPageLabel.Parameters.AddWithValue("@required", false);
                                cmdPageLabel.Parameters.AddWithValue("@orderby", 1);
                                cmdPageLabel.Parameters.AddWithValue("@optionalvalue", "");

                                int pagefieldId = (int)cmdPageLabel.ExecuteScalar();
                                if (pagefieldId > 0)
                                {

                                }
                            }
                        }
                    }
                }
                result = "true";
            }
        }

        return result;
    }

Add Dynamic Label



Click to Lead Field  







Web Form








Drag the DynamicLabels into the Rectangle: