Sunday, 25 September 2016

How to create multilingual application in C# ?

Firstly defined In global.asax.cs

 protected void Application_BeginRequest()
        {
            CultureInfo info = new CultureInfo(System.Threading.Thread.CurrentThread.CurrentCulture.ToString());
            info.DateTimeFormat.ShortDatePattern = "dd.MM.yyyy";
            System.Threading.Thread.CurrentThread.CurrentCulture = info;
        }


        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies["lang"];
            if (cookie != null && cookie.Value != null)
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);
            }
            else
            {
                System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
            }
        }

In App_Global_ResourceFile folder


To create a resource file in this folder -:
default.
employee.resx (It's automatic in English language we represent string and value)

Emp  Employee

employee.bn.resx (bn means bengali language we represent string and value)

Emp Employee_bn

We represent View Pages



In LayOut Pages defined-

    <script type="text/javascript">
        function SetLanguage(obj) {
            debugger;
            $.ajax({
                cache: false,
                type: "GET",
                url: '/Home/SetCulture/?lang=' + obj,
                success: function (result) {
                    debugger;
                    window.location.reload();

                },
                error: function (result) {
                    alert("Error");
                }
            });
        }

    </script>

 public ActionResult SetCulture(string lang)
        {
            LanguageModel model = new LanguageModel();
            if (!String.IsNullOrEmpty(lang))
            {
                string culture = lang;
                CultureInfo ci = CultureInfo.GetCultureInfo(culture);
                Thread.CurrentThread.CurrentUICulture = ci;
                model.Culture = lang;
                Response.Cookies["lang"].Value = culture;
                Response.Cookies["lang"].Expires = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE).AddDays(30);
            }
            else
            {
                string culture = "en";
                CultureInfo ci = CultureInfo.GetCultureInfo(culture);
                Thread.CurrentThread.CurrentUICulture = ci;
                model.Culture = culture;
                Response.Cookies["lang"].Value = culture;
            }
            return Json(model, JsonRequestBehavior.AllowGet);

        }

<label>App_GlobalResources.employee.Emp</label>






Sunday, 10 July 2016

How to implementing jquery datepicker in bootstrap modal?

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                 <h4 class="modal-title" id="myModalLabel">Modal title</h4>

            </div>
            <div class="modal-body">
                <div class="col-md-12">
                    <div class="row">
                        <label for="idTourDateDetails">Tour Start Date:</label>
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" name="idTourDateDetails" id="idTourDateDetails" readonly="readonly" class="form-control clsDatePicker"> <span class="input-group-addon"><i id="calIconTourDateDetails" class="glyphicon glyphicon-th"></i></span>

                            </div>
                        </div>Alt Field:
                        <input type="text" name="idTourDateDetailsHidden" id="idTourDateDetailsHidden">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
            <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
    </div>
    <!-- /.modal -->

$('#idTourDateDetails').datepicker({
     dateFormat: 'dd-mm-yy',
     minDate: '+5d',
     changeMonth: true,
     changeYear: true,
     altField: "#idTourDateDetailsHidden",
     altFormat: "yy-mm-dd"
 });

// Since confModal is essentially a nested modal it's enforceFocus method
// must be no-op'd or the following error results
// "Uncaught RangeError: Maximum call stack size exceeded"
// But then when the nested modal is hidden we reset modal.enforceFocus
var enforceModalFocusFn = $.fn.modal.Constructor.prototype.enforceFocus;

$.fn.modal.Constructor.prototype.enforceFocus = function() {};

$confModal.on('hidden', function() {
    $.fn.modal.Constructor.prototype.enforceFo

Wednesday, 22 June 2016

How to multiple select list value in mvc without ctrl key?

Multiple select list value in asp.net

Multiple select list value in java script


<link href="@Url.Content("~/Content/MultiCheckbx/css/bootstrap-3.1.1.min.css")" rel="stylesheet" />
<link href="@Url.Content("~/Content/MultiCheckbx/css/bootstrap-multiselect.css")" rel="stylesheet" />
<script src="@Url.Content("~/Content/MultiCheckbx/js/bootstrap-multiselect.js")"></script>

 <script type="text/javascript">
        $(document).ready(function () {

            $('#ddlLanguage').multiselect({
                includeSelectAllOption: true,
                numberDisplayed: 1,
            });

function Validation() {
    //var language = ListboxChek();
    debugger;
    var languageids = '';
    $('#dvlanguage input[type="checkbox"]:checked').each(function (i, el) {
        languageids += el.value + ',';
        document.getElementById("hdnLanguage").value = languageids;
        var abc = document.getElementById("hdnLanguage").value;
    });
    var abcd = document.getElementById("hdnLanguage").value;
  </script>

When Insert into a table
 @Html.HiddenFor(m => m.hdnLanguage)
 <div id="dvlanguage">
 <select id="ddlLanguage" class="form-control" multiple="multiple">
  @if (Model._listLanguage.Count() > 0)
   {
        foreach (var item in Model._listLanguage)
        {
             <option value="@item.LanguageId"> @item.Name </option>
         }
   }
    </select>
 </div>

  <button type="submit" class="btn" onclick="javascript:return Validation();">Submit</button>

When Edit after that update
 @Html.HiddenFor(m => m.hdnLanguage)
<div id="dvlanguage">
 <select id="ddlLanguage" class="form-control" multiple="multiple">
    @if (Model._listLanguage.Count() > 0)
       {
           foreach (var item in Model._listLanguage)
           {
               <option value="@item.LanguageId"
                  @if (Model.hdnLanguage != null && (Model.hdnLanguage.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Any(p => (item.LanguageId.ToString().Trim().ToLower() == p.ToString().Trim().ToLower()))))
                                            { <text> selected="selected" </text>  }>
                                                                            @item.Name
                                                                        </option>
             }
        }
    </select>


 </div>
<button type="submit" class="btn" onclick="javascript:return Validation();">Submit</button>

How to multiple select list value in mvc without ctrl key?

Multiple select list value in asp.net

Multiple select list value in java script


<link href="@Url.Content("~/Content/MultiCheckbx/css/bootstrap-3.1.1.min.css")" rel="stylesheet" />
<link href="@Url.Content("~/Content/MultiCheckbx/css/bootstrap-multiselect.css")" rel="stylesheet" />
<script src="@Url.Content("~/Content/MultiCheckbx/js/bootstrap-multiselect.js")"></script>

 <script type="text/javascript">
        $(document).ready(function () {

            $('#ddlLanguage').multiselect({
                includeSelectAllOption: true,
                numberDisplayed: 1,
            });

function Validation() {
    //var language = ListboxChek();
    debugger;
    var languageids = '';
    $('#dvlanguage input[type="checkbox"]:checked').each(function (i, el) {
        languageids += el.value + ',';
        document.getElementById("hdnLanguage").value = languageids;
        var abc = document.getElementById("hdnLanguage").value;
    });
    var abcd = document.getElementById("hdnLanguage").value;
  </script>

When Insert into a table
 @Html.HiddenFor(m => m.hdnLanguage)
 <div id="dvlanguage">
 <select id="ddlLanguage" class="form-control" multiple="multiple">
  @if (Model._listLanguage.Count() > 0)
   {
        foreach (var item in Model._listLanguage)
        {
             <option value="@item.LanguageId"> @item.Name </option>
         }
   }
    </select>
 </div>

  <button type="submit" class="btn" onclick="javascript:return Validation();">Submit</button>

When Edit after that update
 @Html.HiddenFor(m => m.hdnLanguage)
<div id="dvlanguage">
 <select id="ddlLanguage" class="form-control" multiple="multiple">
    @if (Model._listLanguage.Count() > 0)
       {
           foreach (var item in Model._listLanguage)
           {
               <option value="@item.LanguageId"
                  @if (Model.hdnLanguage != null && (Model.hdnLanguage.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Any(p => (item.LanguageId.ToString().Trim().ToLower() == p.ToString().Trim().ToLower()))))
                                            { <text> selected="selected" </text>  }>
                                                                            @item.Name
                                                                        </option>
             }
        }
    </select>


 </div>
<button type="submit" class="btn" onclick="javascript:return Validation();">Submit</button>

Tuesday, 21 June 2016

How to a file and text value in javascript and sent data in mvc?

<form enctype="multipart/form-data">
    <div class="col-sm-5">
        <div class="form-group">
            <label>Weekend Date:<span id="errorWeekendDate">*</span></label>
            @Html.TextBoxFor(model => model.WeekendDate, new { @Placeholder = "Weekend Date", @required = "required", @style = "height: 35px;border: 1px solid #ccc;border-radius: 4px;" })
            <div class="clearfix"></div>
        </div>
    </div>
    <div class="col-sm-7">
        <a class="file-input-wrapper btn btn-default" style="margin-bottom: 15px;">
            <input type="file" name="file" id="fileInput" data-filename-placement="inside">
        </a>
        <input type="submit" value="Upload file" style="position: relative;top: -5px;" />
    </div>
    <br />
</form>
<div class="clearfix"></div>
<div id="dvmismatch" style="display :none;">
    @Html.Partial("_MismatchVendorList", Model)
</div>



<script type="text/javascript">
    $(function () {
        // When your form is submitted
        $("form").submit(function (e) {
            debugger;
            var errorWeekendDate = document.getElementById('errorWeekendDate');
            var WeekendDate = document.getElementById('WeekendDate');

            if (WeekendDate.value == '') {
                errorWeekendDate.style.color = "red";
                return false;
            }
            else {
                errorWeekendDate.style.color = "";
            }
            e.preventDefault();
            // Serialize your form
            var formData = new FormData($(this)[0]);
            loader();

            // Make your POST
            $.ajax({
                type: 'POST',
                url: '@Url.Action("FileCsv", "InvoiceProcessing")',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                success: function (result) {
                    debugger;
                    $("#popup_ok").click();
                    document.getElementById('dvmismatch').style.display = 'block';
                    $("#dvmismatch").html(result);
                },
                error: function (result) { alert(''); }

            });
        });
    })

function loader() {
        debugger;
        jAlert('<img src="@Url.Content("~/Content/images/ajax-loader-large.gif")" height="60" width="60" />', 'Please wait');
        $("#popup_ok").hide();
    }
</script>

        [HttpPost]
        public ActionResult FileCsv(HttpPostedFileBase file, string WeekendDate)
        {
            try
            {
                int result = 0;
                string List = string.Empty;
                DataSet ds = new DataSet();
                if (Request.Files["file"].ContentLength > 0)
                {
                    string fileExtension =
                                        System.IO.Path.GetExtension(Request.Files["file"].FileName);

                    string ImportCSVFile = Request.Files["file"].FileName;
                    string FileName = Request.Files["file"].FileName;
                    string[] strFileName = FileName.Split('.');
                    FileName = strFileName[0];

                    string fileLocation = Server.MapPath("~/Content/CSVFile/") + Request.Files["file"].FileName;
                    if (System.IO.File.Exists(fileLocation))
                    {
                        System.IO.File.Delete(fileLocation);
                    }
                    Request.Files["file"].SaveAs(fileLocation);

                    DataTable dt = new DataTable();

                    string fileName1 = Request.Files["file"].FileName;
                    string path = Path.Combine(Server.MapPath("~/Content/CSVFile/"), fileLocation);

 

                return PartialView("_MismatchVendorList", model);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


Sunday, 19 June 2016

How to bind a partial view in a div?

 <div id="dvMappingList" style="display:none;"> </div>

        public ActionResult ServicetoServiceMapping()
        {
            AModel model = new AModel();
            try
            {
             

                return PartialView("_ServiceMapping", model);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

function bindServicetoService(serviceId, IsServiceId) {
        debugger;
        $('#dvMappingList').html('');
        loader();
        $.ajax({
            cache: false,
            type: "GET",
            url: '@Url.Action("ServicetoServiceMapping", "Component")',
            data: { serviceId: serviceId, IsServiceId: IsServiceId },
            success: function (result) {
                debugger;
                $("#dvMappingList").html(result);
                $('.tabclass li').removeClass("active");
                $('#litab3').addClass("active");
                $('.tab-content div').removeClass("in active");
                $('#tab3').addClass("in active");
                //document.getElementById("litab3").style.display = "block";
                document.getElementById("dvMappingList").style.display = "block";
                $("#popup_ok").click();
            },
        }
    )
    };

And after that top to message display and reload the page-:

In Partial view page-

 <div id="prefix_108058000000" class="Metronic-alerts alert alert-success fade in" style="display: none;">
            <a type="button" class="close" data-dismiss="alert" aria-hidden="true"></a>
            <span id="spnmessage1"></span>
        </div>
        <div id="prefix_Error" class="Metronic-alerts alert alert-danger fade in" style="display: none;">
            <a type="button" class="close" data-dismiss="alert" aria-hidden="true"></a>
            <span id="spnmessage2"></span>
        </div>


In Main Page

<div class="page-content" id="dvSubComponat">

In a div tab and partial pages...........

<ul class="nav nav-tabs tabclass">
        <li class="active" id="litab1"><a data-toggle="tab" href="#tab1">A Mapping</a></li>
        <li id="litab2" style="display:none;"><a data-toggle="tab" href="#tab2">Add Edit Employee</a></li>
        <li id="litab3" style="display:none;"><a data-toggle="tab" href="#tab3">DepartmentMapping Mapping</a></li>
        <li id="litab4" style="display:none;"><a data-toggle="tab" href="#tab4">Add Edit Deaprtment Mapping</a></li>
    </ul>

<div class="form-body">
 <div id="tab1" class="tab-pane fade in active">
                                                <div id="dvEmployee">
                                                    @Html.HiddenFor(a => a.EmpID)
                                                    <div class="form-group" style="margin-left:-217px;">
                                                        <label class="control-label col-md-3">
                                                            Search EmployeeID :
                                                        </label>
                                                        <div class="col-md-4">
                                                            @Html.TextBoxFor(m => m.SerTextID, new { @class = "form-control", @onkeypress = "return PopulateEmployeeID();" })
                                                        </div>
                                                    </div>
                                                    <div id="dvserAllList">
                                                        @Html.Partial("_EmployeeAllListPartial", Model)
                                                    </div>
                                                </div>

                                                <div id="dvmaplist" style="display:none;">
                                                    @Html.Partial("_ComponentMappingPartial", Model)
                                                </div>

                                                <div id="dvunmaplist" style="display:none;">
                                                    @Html.Partial("_ComponentUnMappingPartial", Model)
                                                </div>

                                            </div>
</div>

<div id="tab2" class="tab-pane fade">
            @Html.Action("AddEditEmployee", "Component", new { ID = 0 })
        </div>
</div>

 function SuccessSubComponent(data) {
        $("#popup_ok").click();
        if (data != null) {
            debugger;
            if (data.indexOf("exist") != -1) {
                $('#prefix_Error').show();
                $('#prefix_Error').removeClass("fade");
                $("#spnmessage2").html(data);
                $("#spnmessage2").focus();
                $('html,body').animate({
                    scrollTop: $("#dvSubComponat").offset().top
                },
       'slow');
                setTimeout("loadSubComponentReload()", 1000);
            }
            else {
                debugger;
                $('#prefix_108058000000').show();
                $('#prefix_108058000000').removeClass("fade");
                $("#spnmessage1").html(data);
                $("#spnmessage1").focus();
                $('html,body').animate({
                    scrollTop: $("#dvSubComponat").offset().top
                },
       'slow');
                setTimeout("loadComponentMapReload()", 1000);
            }
        }
    }

    function loadComponentMapReload() {
        window.location.href = "@Url.Action("ComponentMapping", "Component")";
    }


Wednesday, 15 June 2016

How to display some character in mvc?

@(model.ShortDescription.Length > 130 ? model.ShortDescription.Substring(0, 131)+"..." : model.ShortDescription)

Wednesday, 1 June 2016

How to multiple parameter pass in window.location in mvc?

window.location.href = "/Controller/Action?id=" + historyId + "&check=" + itemfilter;

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:


 

Monday, 22 February 2016

How to search data character by character in SQL server?

Table - t_Event

CREATE TABLE [dbo].[t_Event](
[EventID] [int] IDENTITY(1,1) NOT NULL,
[OrganizationName] [nvarchar](250) NULL,
[OrganizationID] [int] NULL,
[Title] [nvarchar](500) NULL,
[DescriptionShort] [nvarchar](500) NULL,
[DescriptionLong] [nvarchar](4000) NULL,
[Location] [nvarchar](500) NULL,
[EventDate] [smalldatetime] NULL,
[ExpirationDate] [smalldatetime] NULL,
[URL] [nvarchar](250) NULL,
[FileName] [nvarchar](250) NULL,
[Active] [bit] NULL,
[EventTime] [nvarchar](250) NULL,
 CONSTRAINT [PK_t_Event] PRIMARY KEY CLUSTERED
(
[EventID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


ALTER PROC [dbo].[Sp_Fetch_AllEventByString](@SearchName VARCHAR(200))
AS
BEGIN
IF ISNULL(@SearchName,'') = ''
    BEGIN
        SELECT EventID, OrganizationName, OrganizationID, Title, DescriptionShort, DescriptionLong,
SUBSTRING(FileName, CHARINDEX('.', FileName) + 1, LEN(FileName)) as extension ,
Location, EventDate, ExpirationDate, URL, FileName, Active,EventTime from dbo.t_Event
    END
    ELSE
    BEGIN
        DECLARE @Count INT;
        DECLARE @i  INT = 0

        WHILE (@i) < LEN(@SearchName)
        BEGIN    
            SELECT @Count = COUNT(*) FROM t_Event
            WHERE (OrganizationName LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName) - @i)  + '%')
            OR (Title LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName) - @i)  + '%')
            OR (DescriptionShort LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName)- @i)  + '%')
            OR (DescriptionLong LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName) - @i)  + '%')
           
            IF @Count > 0
            BEGIN
                 SELECT EventID, OrganizationName, OrganizationID, Title, DescriptionShort, DescriptionLong,
SUBSTRING(FileName, CHARINDEX('.', FileName) + 1, LEN(FileName)) as extension ,
Location, EventDate, ExpirationDate, URL, FileName, Active,EventTime from dbo.t_Event
                WHERE (OrganizationName LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName) - @i)  + '%')
                OR (Title LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName) - @i)  + '%')
                OR (DescriptionShort LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName) - @i)  + '%')
                OR (DescriptionLong LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName) - @i)  + '%')
                order by Title
             
            END
            SET @i = @i + 1
   
        END
    END
END

How to search data in SQL server?

Table- Blog

CREATE TABLE [dbo].[Blog](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[Title] [nvarchar](max) NULL,
[ShortDescription] [nvarchar](max) NULL,
[Description] [nvarchar](max) NULL,
[ImageUrl] [nvarchar](255) NULL,
[CategoryId] [int] NULL,
[TagKeyWord] [nvarchar](255) NULL,
[SeoTitle] [nvarchar](255) NULL,
[SeoKeyword] [nvarchar](255) NULL,
[SeoDescription] [nvarchar](max) NULL,
[Status] [bit] NULL CONSTRAINT [DF_Blog_Status]  DEFAULT ((0)),
[UserType] [nvarchar](255) NULL,
[UserId] [bigint] NULL,
[CreatedDate] [datetime] NULL CONSTRAINT [DF_Blog_CreatedDate]  DEFAULT (getdate()),
 CONSTRAINT [PK_Blog] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Table - BlogCategory
CREATE TABLE [dbo].[BlogCategory](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ParentID] [int] NOT NULL,
[Name] [varchar](max) NULL,
[Active] [bit] NOT NULL CONSTRAINT [DF_BlogCategory_Active]  DEFAULT ((1)),
[seo_keywords] [varchar](255) NULL,
[seo_description] [varchar](255) NULL,
 CONSTRAINT [PK_BlogCategory] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO




Create PROC [dbo].[usp_Blog_Search](@SearchName VARCHAR(200))
AS
BEGIN
IF ISNULL(@SearchName,'') = ''
    BEGIN
SELECT b.ID, b.Title, b.ShortDescription, b.Description, b.ImageUrl, b.CategoryId, b.TagKeyWord, b.SeoTitle, b.SeoKeyword, b.SeoDescription,
 b.Status, b.UserType, b.UserId, b.CreatedDate, c.Name,
(case UserType when 'U1' then (select FullName from dbo.UserDetail u where u.ID = b.UserId) 
when 'A1' then (select FirstName + ' ' + LastName from dbo.AdminUser a where a.Id = b.UserId) end) as UserName,
(select COUNT(bv.BlogID) from BlogVisits bv where bv.BlogId=b.ID)  as ViewCount, 
(select COUNT(br.ID) from BlogReply br where br.BlogId=b.ID and br.Status=1) as CommentCount,(select COUNT(br.ID) from BlogReply br where br.BlogId=b.ID) as CommentCountWithoutStatus,
(case when [Status]=1 then 'Active' when [Status]=0 then 'InActive' end) as StatusActiveDeActive
from Blog b
inner join dbo.BlogCategory c on c.ID= b.CategoryId
where b.[Status]=1  order by b.ID desc
    END
    ELSE
    BEGIN            
SELECT b.ID, b.Title, b.ShortDescription, b.Description, b.ImageUrl, b.CategoryId, b.TagKeyWord, b.SeoTitle, b.SeoKeyword, b.SeoDescription,
 b.Status, b.UserType, b.UserId, b.CreatedDate, c.Name,
(case UserType when 'U1' then (select FullName from dbo.UserDetail u where u.ID = b.UserId) 
when 'A1' then (select FirstName + ' ' + LastName from dbo.AdminUser a where a.Id = b.UserId) end) as UserName,
(select COUNT(bv.BlogID) from BlogVisits bv where bv.BlogId=b.ID)  as ViewCount, 
(select COUNT(br.ID) from BlogReply br where br.BlogId=b.ID and br.Status=1) as CommentCount,(select COUNT(br.ID) from BlogReply br where br.BlogId=b.ID) as CommentCountWithoutStatus,
(case when [Status]=1 then 'Active' when [Status]=0 then 'InActive' end) as StatusActiveDeActive
from Blog b
inner join dbo.BlogCategory c on c.ID= b.CategoryId
WHERE ((Title LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName))  + '%')
or(TagKeyWord LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName))  + '%')
or(Name LIKE '%' + SUBSTRING(@SearchName,1,LEN(@SearchName))  + '%'))
and [Status]=1 order by ID desc
    END
END




Friday, 19 February 2016

How to use bootstrap editor in MVC?

<link href="~/Content/Editor/css/bootstrap.css" rel="stylesheet" />
<link href="~/Content/Editor/css/font-awesome.css" rel="stylesheet" />
<script src="~/Content/Editor/Scripts/jquery-1.10.2.js"></script>
<script src="~/Content/Editor/Scripts/bootstrap.js"></script>
<link href="~/Content/Editor/summernote/summernote.css" rel="stylesheet" />
<script src="~/Content/Editor/summernote/summernote.js"></script>
<script src="~/Content/Editor/Scripts/home-index.js"></script>

In above css and jquery are important for Editor

 @Html.TextAreaFor(model => model.Content, new { @class = "form-control", @row = 10 })

http://www.c-sharpcorner.com/uploadfile/3d39b4/bootstrap-wysiwyg-editor-in-asp-net-mvc/