Friday, November 16, 2012

Return Some/Specific Column from a table or Joined Table using LINQ

How to fetch some column from table in linq


[HttpGet]
        public JsonResult ShowAllMstStocklistScheme()
        {

            var v = PR.ShowAllMstStocklistScheme().Select(p => new { p.ID, p.Scheme });
            return Json(v, JsonRequestBehavior.AllowGet);
        }

in code "new { p.ID, p.Scheme }" is declare column name or table property name which you want to access through this query.

Some problem arise when we going to bind dropdown in kendo from a table which has a foreign key realtion. That time we need to access specific column from table.

we can use this way of return from LINQ data.  

Transaction Commit And Rollback in LINQ


How to Use transaction.
When we want to save data to multiple table or in multiple time in a table use transaction.
follow code snip below. 


Class Abc {

//Object Declaration
ProjectRepository pr = new ProjectRepository();
DBDataContext DBObject = new DBDataContext();

//Action
public ActionResult FormEntry(FormCollection fc)
{
  System.Data.Common.DbTransaction Tran=null;
  DBObject.Connection.Open();
  Tran = DBObject.Connection.BeginTransaction();
  DBObject.Transaction = Tran;
           
 try
 {

       //---Code of insert or Update---
               DataTable dtc = (DataTable)SessionBag.Current.ChequeDetailsXV;
               if (dtc.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dtc.Rows)
                        {
                            CapitalDetail Pc = new CapitalDetail();
                            Pc.PrGroup_ID = Convert.ToInt32(dr["PrGroup_ID"]);
                            Pc.Capi_Amount = Convert.ToInt32(dr["Amount"]);
                            Pc.Capi_Bank = Convert.ToString(dr["ChqBankBranch"]);
                            Pc.Capi_Bank_Branch = Convert.ToString(dr["ChqBankBranch"]);
                            //Pc.Capi_OutStation = Convert.ToString(dr["DrawNo"]);
                            Pc.Capi_ChequeNo = Convert.ToInt32(dr["ChqNo"]);
                            Pc.Capi_Date = Convert.ToDateTime(dr["ChqDate"]);
                            Pc.Capi_EntryDate = Convert.ToDateTime(DateTime.Now);
                            Pc.Capi_Type = Convert.ToString("Cheque");
                           
                            pr.Add(Pc);

                        }
                    }

        pr.Save();
        Tran.Commit();
 }
catch (Exception ex)
 {
        Tran.Rollback();

 }

finally
{
if (DBObject.Connection != null && DBObject.Connection.State ==                                                                                                                      System.Data.ConnectionState.Open)
       {
           DBObject.Connection.Close();
                       
       }
     
}
}

Friday, November 9, 2012

Kendo UI Validation for Dublicate Value Checking


I am faced a problem with validation for duplicate value checking from server using json. My code is runing fine in each click but error message show in second click(One click in side text box put value then click out side the text box - that time code execute but error message show . again i click in that text box and again click out side text box ,again my code run and this time error message show) . Please find my mistake and help me to show validation message in single escape or single click of text box.
Now I solve by adding ajax async clode in the to  of the javascript. We get success if you use this.

script language="javascript" type="text/javascript"

//KendoUi Validation
    var validatable = $("#ApplicationNo").kendoValidator({
        onfocusout: true,
        onkeyup: true,
        rules: {
            ApplicationNo: function (input) {
                $.post("/Home/CheckAppNo", 
               { ApplicationNo: $("#ApplicationNo").val() }, 
               function (data) { b1 = data; })
                return b1;
              }

        },

        messages: {
            ApplicationNo: "Already Exist"
        }
    }).data("kendoValidator");

   var validatable = 
       $(".k-content").kendoValidator().data("kendoValidator");
 


script language="javascript" type="text/javascript"

//KendoUi Validation

        $.ajaxSetup({ async: false }); 
 
    var validatable = $("#ApplicationNo").kendoValidator({
        onfocusout: true,
        onkeyup: true,
        rules: {
            ApplicationNo: function (input) {
                $.post("/Home/CheckAppNo", 
              { ApplicationNo: $("#ApplicationNo").val() }, 
                function (data) { b1 = data; })
                return b1;
            }

        },

        messages: {
            ApplicationNo: "Already Exist"
        }
    }).data("kendoValidator");

   var validatable = 
       $(".k-content").kendoValidator().data("kendoValidator");

C # Code

    public JsonResult CheckAppNo(string ApplicationNo)
    {
        bool IsOk = projectRepository.CheckAppNumber(ApplicationNo);
        return Json(IsOk, JsonRequestBehavior.AllowGet);
        //return new JsonResult { Data = IsOk };
    }
 
 

Html

< input type="text" id="ReferredBy" name="ReferredBy" class="k-textbox" required />
 
 

How Upload Using KendoUI Uploader



Kendo UI  Uploader :
Create a kendo ui uploader control in MVC View
@(Html.Kendo().Upload()
                .Name("fileUploader")
                .Async(a => a
                            .Save("Save", "Test")
                            .Remove("Remove", "Test")
                    //.SaveUrl("")
                    .AutoUpload(false)
        )
                        .Events(events => events
                            .Cancel("onCancel")
                            .Complete("onComplete")
                            .Error("onError")
                            //.Progress("onProgress")
                            .Remove("onRemove")
                            .Select("onSelect")
                            .Success("onSuccess")
                            .Upload("onUpload")
                        )
    )
</div>

JavaScript

<script>
    function onSelect(e) {
        $("#details").text("Select :: " + getFileInfo(e));
    }

    function onUpload(e) {
        $("#details").text("Upload :: " + getFileInfo(e));
    }

    function onSuccess(e) {
        $("#details").text("Success (" + e.operation + ") :: " + getFileInfo(e));
    }

    function onError(e) {
       // $("#details").text("Error (" + e.operation + ") :: " + getFileInfo(e));
    }

    function onComplete(e) {
       // $("#details").text("Complete");
    }

    function onCancel(e) {
        $("#details").text("Cancel :: " + getFileInfo(e));
    }

    function onRemove(e) {
        $("#details").text("Remove :: " + getFileInfo(e));
    }

    function onProgress(e) {

        $("#details").text("Upload progress :: " + e.percentComplete + "% :: " + getFileInfo(e));
    }

    function getFileInfo(e) {
        return $.map(e.files, function (file) {
            var info = file.name;

            // File size is not available in all browsers
            if (file.size > 0) {
                info += " (" + Math.ceil(file.size / 1024) + " KB)";
            }
            return info;
        }).join(", ");
    }
</script>
<div id="details" />



Add Controller  -  Action to Save and Remove File.
public ActionResult Save(IEnumerable<HttpPostedFileBase> fileUploader)//fileUploader name must be the name of uploader Control.
        {
            // The Name of the Upload component is "fileUploader"
            foreach (var file in fileUploader)
            {
                // Some browsers send file names with full path. We only care about the file name.
                var fileName = Path.GetFileName(file.FileName);
                var destinationPath = Path.Combine(Server.MapPath("~/download/"), fileName);


                file.SaveAs(destinationPath);
            }


            // Return an empty string to signify success
            return Content("");



        }




        public ActionResult Remove(string[] fileNames)
        {
            foreach (var fullName in fileNames)
            {
                var fileName = Path.GetFileName(fullName);
                var physicalPath = Path.Combine(Server.MapPath("~/download/"), fileName);


                // TODO: Verify user permissions


                if (System.IO.File.Exists(physicalPath))
                {
                    System.IO.File.Delete(physicalPath);
                }
            }


            // Return an empty string to signify success
            return Content("");



        }


SQL Optimization

  SQL Optimization  1. Add where on your query  2. If you remove some data after the data return then remove the remove condition in the sel...