Thursday 11 December 2014

Windows Task Scheduler for automatic run a program in dot new

How to create Windows Task Scheduler 
Right click on the mycomputer

Then click on the create task
Click on the trigger then click on the new then set settings
Click on the action after that click on the new then click on the browse file select ur exe file. Then click ok



Wednesday 10 December 2014

save date format in c#

 oBLDataHelper.AddParameter("@PlnTo", DateTime.ParseExact(other.PlnTo, "dd-MM-yyyy", null));

Tuesday 9 December 2014

date validation in jquery

 $('body').on('change', '#RaTo', function () {
        if ($.datepicker.parseDate('dd-mm-yy', $('#RaFrom').val()) > $.datepicker.parseDate('dd-mm-yy', $('#RaTo').val())) {
            window.parent.window.parent.showMessage('Rent agreement fromdate should not greater than todate', 'error');
            return false;
        }

Monday 8 December 2014

file upload and download in mvc

 public ActionResult Other(string id)
        {
            Other other = new Other();
            BOOfficeMaster bOOfficeMaster = bLOfficeMaster.GetOfficeMasterById(Convert.ToInt32(id));
            other.PSASOfficeCode = bOOfficeMaster.PSASOfficeCode;
            other.ProfitCenterCode = bOOfficeMaster.ProfitCenterCode;
            other.PFsubCode = bOOfficeMaster.PFsubCode;
            other.ESICSubcode = bOOfficeMaster.ESICSubcode;
            other.PasaraLicenceNumber = bOOfficeMaster.PasaraLicenceNumber;
            other.PlnFrom = Convert.ToDateTime(bOOfficeMaster.PlnFrom).ToShortDateString();
            other.PlnTo = Convert.ToDateTime(bOOfficeMaster.PlnTo).ToShortDateString();
            other.ShopEstablishmentLicenceNumber = bOOfficeMaster.ShopEstablishmentLicenceNumber;
            other.SelnFrom = Convert.ToDateTime(bOOfficeMaster.SelnFrom).ToShortDateString();
            other.SelnTo = Convert.ToDateTime(bOOfficeMaster.SelnTo).ToShortDateString();
            other.RentAgreement = bOOfficeMaster.RentAgreement;
            other.RaFrom = Convert.ToDateTime(bOOfficeMaster.RaFrom).ToShortDateString();
            other.RaTo = Convert.ToDateTime(bOOfficeMaster.RaTo).ToShortDateString();
            other.TrainingCertificateLicenceNumber = bOOfficeMaster.TrainingCertificateLicenceNumber;
            other.TclnFrom = Convert.ToDateTime(bOOfficeMaster.TclnFrom).ToShortDateString();
            other.TclnTo = Convert.ToDateTime(bOOfficeMaster.TclnTo).ToShortDateString();
            other.PasaraLicences = bOOfficeMaster.PasaraLicences;
            other.ShopEstablishmentLicences = bOOfficeMaster.ShopEstablishmentLicences;
            other.RentAgreements = bOOfficeMaster.RentAgreements;
            other.TrainingCertificates = bOOfficeMaster.TrainingCertificates;
            PSAS.Models.CustomerMaster.BusinessLayer.BLCustomerMaster oBLCustomerMaster = new Models.CustomerMaster.BusinessLayer.BLCustomerMaster();
            PSAS.Models.CustomerMaster.BusinessObject.BODocumentPathConfig oBODocumentPathConfig = null;
            oBODocumentPathConfig = oBLCustomerMaster.getDocumentPathConfig(91);
            //oBODocumentPathConfig = oBLCustomerMaster.getDocumentPathConfig(102);
            Folder oBODocumentUploaded = new Folder();
            DataTable DTfilePath = new DataTable();
            DTfilePath = oBODocumentUploaded.GetFileinfo();
            DataRow dtr = DTfilePath.NewRow();
            string FilePath = "";
            if (Directory.Exists(oBODocumentPathConfig.DestinationPath.Trim()))
            {
                if (Directory.Exists(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), id.ToString())))
                {
                    foreach (var folderName in new DirectoryInfo(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), id.ToString())).GetDirectories())
                    {
                        int i = folderName.GetFiles("*.*").Length;
                        if (i > 0)
                        {
                            foreach (var file in folderName.GetFiles())
                            {
                                FilePath = FilePath + "<a target='_parent' href='DownloadFiles?FilePath=" + Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), id.ToString()) + "\\" + folderName + "\\" + file + "&FileName=" + file + "&filetype=" + file.Extension + "' >Download</a>,";
                            }
                            FilePath = FilePath.Substring(0, FilePath.Length - 1);
                            dtr[folderName.ToString()] = FilePath;
                            FilePath = "";
                        }



                    }
                }
                DTfilePath.Rows.Add(dtr);
                ViewBag.datatable = DTfilePath;
            }
            return PartialView("Other", other);
        }
        public FileResult DownloadFiles(string FilePath, string FileName, string filetype)
        {

            String headerKey = "Content-Disposition";
            String headerValue = "attachment; filename=" + "" + FileName + "";
            Response.AppendHeader(headerKey, headerValue);
            Response.TransmitFile(FilePath);
            Response.End();
            return File(FilePath, filetype, FileName);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UpdateOther(Other other)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    bLOfficeMaster.UpdateOther(other);
                    string officeCode = other.PSASOfficeCode.ToString();
                    PSAS.Models.CustomerMaster.BusinessLayer.BLCustomerMaster oBLCustomerMaster = new Models.CustomerMaster.BusinessLayer.BLCustomerMaster();
                    PSAS.Models.CustomerMaster.BusinessObject.BODocumentPathConfig oBODocumentPathConfig = null;
                    //oBODocumentPathConfig = oBLCustomerMaster.getDocumentPathConfig(102);
                    oBODocumentPathConfig = oBLCustomerMaster.getDocumentPathConfig(91);
                    createfolder("PASARALICENCE", officeCode, oBODocumentPathConfig.DestinationPath);
                    createfolder("SHOPANDESTABLISHMENTLICENCE", officeCode, oBODocumentPathConfig.DestinationPath);
                    createfolder("RENTAGREEMENT", officeCode, oBODocumentPathConfig.DestinationPath);
                    createfolder("TRAININGCERTIFICATE", officeCode, oBODocumentPathConfig.DestinationPath);
                    if (other.PasaraLicencefu.ContentLength > 0)
                        other.PasaraLicencefu.SaveAs(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), officeCode, "PASARALICENCE", other.PasaraLicencefu.FileName));
                    if (other.ShopEstablishmentLicencefu.ContentLength > 0)
                        other.ShopEstablishmentLicencefu.SaveAs(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), officeCode, "SHOPANDESTABLISHMENTLICENCE", other.ShopEstablishmentLicencefu.FileName));
                    if (other.RentAgreementfu.ContentLength > 0)
                        other.RentAgreementfu.SaveAs(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), officeCode, "RENTAGREEMENT", other.RentAgreementfu.FileName));
                    if (other.TrainingCertificatefu.ContentLength > 0)
                        other.TrainingCertificatefu.SaveAs(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), officeCode, "TRAININGCERTIFICATE", other.TrainingCertificatefu.FileName));
                    TempData["success"] = "Data Updated Successfully.";
                 
                }
             
            }
            catch (Exception ex)
            {
                TempData["error"] = ex.Message.ToString();
            }
            return RedirectToAction("Details");
        }

//DestinationPath=C:\PSASMVC\AppDocument\PSASOFFICEDOCUMENT\(example)
   public void createfolder(string subFolderName, string officeCode, string DestinationPath)
        {
            if (!Directory.Exists(DestinationPath.Trim()))
            {
                DirectoryInfo di = Directory.CreateDirectory(DestinationPath.Trim());
            }
            if (!Directory.Exists(Path.Combine(DestinationPath.Trim(), officeCode)))
            {
                DirectoryInfo di = Directory.CreateDirectory(Path.Combine(DestinationPath.Trim(), officeCode));
            }
            if (!Directory.Exists(Path.Combine(DestinationPath.Trim(), officeCode, subFolderName)))
            {
                DirectoryInfo di = Directory.CreateDirectory(Path.Combine(DestinationPath.Trim(), officeCode, subFolderName));
            }
        }

DOM
 public class Folder
    {
        public DataTable GetFileinfo()
        {
            DataTable DTFileName = new DataTable();
            DTFileName.Columns.Add("PASARALICENCE", typeof(string));
            DTFileName.Columns.Add("SHOPANDESTABLISHMENTLICENCE", typeof(string));
            DTFileName.Columns.Add("RENTAGREEMENT", typeof(string));
            DTFileName.Columns.Add("TRAININGCERTIFICATE", typeof(string));
            return DTFileName;
        }
    }
    

Saturday 6 December 2014

File upload using MVC 4 with Ajax

<html>
    <head>
    <title>Upload Example</title>
        <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#Upload").click(function () {
                var formData = new FormData();
                var totalFiles = document.getElementById("FileUpload").files.length;
                for (var i = 0; i < totalFiles; i++) {
                    var file = document.getElementById("FileUpload").files[i];

                    formData.append("FileUpload", file);
                }
                $.ajax({
                    type: "POST",
                    url: '/Home/Upload',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        alert('succes!!');
                    },
                    error: function (error) {
                        alert("errror");
                    }
                });
            });
        });

</script>
</head>
<body>
    <input type="file" id="FileUpload" multiple />
    <input type="button" id="Upload" value="Upload" />
</body>
</html>
MVC CODE

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication12.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public void Upload()
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                var fileName = Path.GetFileName(file.FileName);

                var path = Path.Combine(Server.MapPath("~/Junk/"), fileName);
                file.SaveAs(path);
            }

        }
}
}

Friday 5 December 2014

date validation in jquery

function validatedate(inputText) {
    var dateformat = /^(0?[1-9]|[12][0-9]|3[01])[-](0?[1-9]|1[012])[-]\d{4}$/;

    // Match the date format through regular expression
    if (dateformat.test(inputText)) {

        var pdate = inputText.split('-');

        var dd = parseInt(pdate[0]);
        var mm = parseInt(pdate[1]);
        var yy = parseInt(pdate[2]);

        // Create list of days of a month [assume there is no leap year by default]
        var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        if (mm == 1 || mm > 2) {
            if (dd > ListofDays[mm - 1]) {
                return false;
            }
        }
        if (mm == 2) {
            var lyear = false;
            if ((!(yy % 4) && yy % 100) || !(yy % 400)) {
                lyear = true;
            }

            if ((lyear == false) && (dd >= 29)) {
                return false;
            }

            if ((lyear == true) && (dd > 29)) {
                return false;
            }
        }
    }
    else {
        return false;
    }
    return true;
}

Tuesday 2 December 2014

jquery selectable

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication10.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">

  <style>
  #feedback { font-size: 1.4em; }
  #selectable .ui-selecting { background:#bdbcbc; }    
  #selectable .ui-selected { background: #bdbcbc; color: white; }
  #selectable { list-style-type: none; margin: 0; padding: 0; width: 20%; }
  #selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
  </style>
  <script>
      $(function () {
          $("#selectable").selectable({
              stop: function () {
                  var result = $("#select-result").empty();
                  $(".ui-selected", this).each(function () {
                      var index = $("#selectable li").index(this);
                      result.append(" #" + (index + 1));
                  });
              }
          });
      });
  </script>
</head>
   
<body>

<p id="feedback">
<span>You've selected:</span> <span id="select-result">none</span>.
</p>

<ol id="selectable">
  <li class="ui-widget-content">General Data</li>
  <li class="ui-widget-content">Communication Data</li>
  <li class="ui-widget-content">Other Data</li>
</ol>
</body>
</html>

Monday 1 December 2014

how to create folder and save file in mvc

 public void createfolder(string subFolderName, string officeCode, string DestinationPath)
        {
            if (!Directory.Exists(DestinationPath.Trim()))
            {
                DirectoryInfo di = Directory.CreateDirectory(DestinationPath.Trim());
            }
            if (!Directory.Exists(Path.Combine(DestinationPath.Trim(), officeCode)))
            {
                DirectoryInfo di = Directory.CreateDirectory(Path.Combine(DestinationPath.Trim(), officeCode));
            }
            if (!Directory.Exists(Path.Combine(DestinationPath.Trim(), officeCode, subFolderName)))
            {
                DirectoryInfo di = Directory.CreateDirectory(Path.Combine(DestinationPath.Trim(), officeCode, subFolderName));
            }
        }

[HttpPost]
        public ActionResult Save(BOOfficeMaster bOOfficeMaster)
        {
            if (ModelState.IsValid)
            {
                bLOfficeMaster.Save(bOOfficeMaster);
                var m = bLOfficeMaster.GetOfficeMaster().OrderByDescending(n => n.PSASOfficeCode).First();
                PSAS.Models.CustomerMaster.BusinessLayer.BLCustomerMaster oBLCustomerMaster = new Models.CustomerMaster.BusinessLayer.BLCustomerMaster();
                string officeCode = m.PSASOfficeCode.ToString();
                PSAS.Models.CustomerMaster.BusinessObject.BODocumentPathConfig oBODocumentPathConfig = null;
                oBODocumentPathConfig = oBLCustomerMaster.getDocumentPathConfig(91);

                createfolder("PASARALICENCE", officeCode, oBODocumentPathConfig.DestinationPath);
DestinationPath="C:\PSASMVC\AppDocument\PSASOFFICEDOCUMENT\";
                createfolder("SHOPANDESTABLISHMENTLICENCE", officeCode, oBODocumentPathConfig.DestinationPath);
                createfolder("RENTAGREEMENT", officeCode, oBODocumentPathConfig.DestinationPath);
                createfolder("TRAININGCERTIFICATE", officeCode, oBODocumentPathConfig.DestinationPath);
                if (bOOfficeMaster.PasaraLicencefu.ContentLength > 0)
                    bOOfficeMaster.PasaraLicencefu.SaveAs(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), officeCode, "PASARALICENCE", bOOfficeMaster.PasaraLicencefu.FileName));
                if (bOOfficeMaster.ShopEstablishmentLicencefu.ContentLength > 0)
                    bOOfficeMaster.ShopEstablishmentLicencefu.SaveAs(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), officeCode, "SHOPANDESTABLISHMENTLICENCE", bOOfficeMaster.ShopEstablishmentLicencefu.FileName));
                if (bOOfficeMaster.RentAgreementfu.ContentLength > 0)
                    bOOfficeMaster.RentAgreementfu.SaveAs(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), officeCode, "RENTAGREEMENT", bOOfficeMaster.RentAgreementfu.FileName));
                if (bOOfficeMaster.TrainingCertificatefu.ContentLength > 0)
                    bOOfficeMaster.TrainingCertificatefu.SaveAs(Path.Combine(oBODocumentPathConfig.DestinationPath.Trim(), officeCode, "TRAININGCERTIFICATE", bOOfficeMaster.TrainingCertificatefu.FileName));
                TempData["success"] = "Data Saved Successfully.";
            }
            return RedirectToAction("Index");
        }

Friday 28 November 2014

CRUD Operations using jTable jQuery Plug-in and ASP.NET Web API 2 OData Service

This article will demonstrate how to perform CRUD (Create, Read, Update, Delete) operations using jTable jQuery plug-in and ASP.NET Web API 2 OData service.
Used Environment: VS 2013 Update 1, Entity Framework 6, ASP.NET Web API 2, jTable 2.4.0

Create OData Service:

I am going to use same OData service which I created in my previous tutorial (Steps 1-7). Here is quick view to create OData Service.
Create “Empty” ASP.NET project with “Web API” folders and core references and add a model “Person.cs
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
[Table("Person")]
public class Person
{
 
    public int ID { get; set; }
 
    [Required]
    [MaxLength(50)]
    public string Name { get; set; }
      
    [Required]
    [MaxLength(20)]
    public string Phone { get; set; }
      
    [Required]
    [MaxLength(50)]
    public string Email { get; set; }
 
}
Add a controller with “Web API 2 OData Controller with actions, using Entity Framework“, select Person class as Model and create new context.
Replace the code of WebApiConfig.cs with following to add the EDM and route.
?
01
02
03
04
05
06
07
08
09
10
public static class WebApiConfig
   {    
  
       public static void Register(HttpConfiguration config)
       {
           ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
           builder.EntitySet<Person>("Persons");
           config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
       }
   }
When you run it first time, the database is created. Add some data in database for testing and check service by opening following URL:
http://hostname/odata/Persons

Add A View as OData Client:

We will add a view to consume OData service in same app.
Solution Explorer > Right click on Controller folder > Add > Controller > Select “MVC 5 Controller -Empty” > add > name “HomeController” > Add
Open HomeController > Right click on Index method > Add View > Remove “Use a layout page” selection > Add

Add jTable:

To install jTable, run the following command in the Package Manager Console
Install-Package jTable
It will add jtable folder in Scripts folder.
Open View and Add following CSS references:
?
1
2
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Scripts/jtable/themes/metro/blue/jtable.css" rel="stylesheet" /> 
Add following javascript references:
?
1
2
3
<script src="~/Scripts/jquery-1.10.2.js"></script>
   <script src="~/Scripts/jquery-ui-1.9.2.min.js"></script>
   <script src="~/Scripts/jtable/jquery.jtable.js"></script>
In a better way, you can create bundle for css and js files and use it with @Styles.Render(“~/Content/cssbundlename”) @Scripts.Render(“~/bundles/jsbundlename”). I kept in traditional way for quick understanding.
In html body tag:
?
1
2
3
<div style="max-width:600px;margin-top:15px">
        <div id="PersonContainer"></div>
</div>
To define action and fields of jTable:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
$(function () {
 
       $('#PersonContainer').jtable({
           title: 'Person Information',
           paging: true,
           pageSize: 10,
           sorting: true,
           multiSorting: true,
           defaultSorting: 'Name asc',
           actions: {
               listAction: getListData,
               deleteAction: deleteItem,
               createAction: createItem,
               updateAction: updateItem
           },
           fields: {
               ID: {
                   key: true,
                   create: false,
                   edit: false,
                   list: false
               },
               Name: {
                   title: 'Name',
                   width: '30%'
               },
               Email: {
                   title: 'Email address',
                   width: '30%'
               },
               Phone: {
                   title: 'Phone',
                   width: '30%'
               }
           }
       });
       $('#PersonContainer').jtable('load');
   });
I have not not covered validation to keep the app simple.

Read Operation:

To get data:
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function getListData(postData, jtParams) {
     
    var ret;
    var query = "/odata/Persons" //root uri
    + "?$select=ID,Name,Email,Phone" //reduce the payload to what we need
    + "&$inlinecount=allpages"
    + "&$orderby=" + jtParams.jtSorting.replace(' DESC', ' desc').replace(' ASC', ' asc')
    + "&$skip=" + jtParams.jtStartIndex
    + "&$top=" + jtParams.jtPageSize
    //+ "&$format=json" //give me json... will be used in newer OData
    //+ "&$callback=callback"; //this is my callback for future
    return $.Deferred(function ($dfd) {
        $.ajax({
            url: query,
            type: 'GET',
            dataType: 'json',
            data: postData,
            success: function (data) {
                ret = {
                    'Result': "OK",
                    'Records': data.value,
                    'TotalRecordCount': data['odata.count']
                };
                $dfd.resolve(ret);
            },
            error: function () {
                $dfd.reject();
            }
        });
    });
 
}
Here OData service response data is converted into jTable plugin required format.

Create Operation:

To insert data, POST HTTP verb is used.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
function createItem(postData) {
            var ret;
            return $.Deferred(function ($dfd) {
                $.ajax({
                    url: '/odata/Persons',
                    type: 'POST',
                    dataType: 'json',
                    data: postData,
                    success: function (data) {
                        ret = {
                            'Result': "OK",
                            'Record': data
                        };
                        $dfd.resolve(ret);
                    },
                    error: function () {
                        $dfd.reject();
                    }
                });
            });
        }

Update Operation:

To update data, PUT HTTP verb is used.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function updateItem(item) {
            var ret;
            return $.Deferred(function ($dfd) {
                $.ajax({
                    url: '/odata/Persons(' + getParameterByName(item, 'ID') + ')',
                    type: 'PUT',
                    dataType: 'json',
                    data: item,
                    success: function (data) {
                        ret = {
                            'Result': "OK",
                            'Record': data
                        };
                        $dfd.resolve(ret);
                    },
                    error: function () {
                        $dfd.reject();
                    }
                });
            });
        }
         
          function getParameterByName(str, name) {
            var sURLVariables = str.split('&');
            for (var i = 0; i < sURLVariables.length; i++) {
                var sParameterName = sURLVariables[i].split('=');
                if (sParameterName[0] == name) {
                    return sParameterName[1];
                }
            }
        }
For update operation, We need url in ‘/odata/Persons(1)’ format. To get id from item, getParameterByName method is used.

Delete Operation:

To delete data, Delete HTTP verb is used.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
function deleteItem(item) {
            return $.Deferred(function ($dfd) {
                $.ajax({
                    url: '/odata/Persons(' + item.ID + ')',
                    type: 'DELETE',
                    dataType: 'json',
                    data: item,
                    success: function (data) {
                        $dfd.resolve({ 'Result': "OK" });
                    },
                    error: function () {
                        $dfd.reject();
                    }
                });
            });
        }

CRUD jtable jquery odata CRUD Operations using jTable jQuery Plug in and ASP.NET Web API 2 OData Service