Monday, 16 December 2013

Repository Details for employees

Account Repository

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

namespace MVCDemo.Repository
{
    public class AccountRepository
    {
        public bool AuthenticateUser(string UserName, string Password)
        {
            try
            {
                if (UserName == "Admin@gmail.com" && Password == "admin")
                    return true;
                else
                    return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}

Employee Repository :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using MVCDemo.Models;

namespace MVCDemo.Repository
{
    public class EmployeeRepository
    {
        TestEntities _db = new TestEntities();

        public IEnumerable<EmployeeMaster> GetAllEmployee()
        {
            return (from e in _db.EmployeeMasters select e);
        }

        public bool SaveEmployee(EmployeeMaster emp)
        {
            try
            {
                if (emp.EmployeeId > 0)
                    _db.Entry(emp).State = EntityState.Modified;
                else
                    _db.EmployeeMasters.Add(emp);
                _db.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
           
        }

        public EmployeeMaster GetEmpByID(int Id = 0)
        {
            return (from e in _db.EmployeeMasters where e.EmployeeId == Id select e).FirstOrDefault();
        }

        public bool DeleteEmp(int Id = 0)
        {
            var emp = GetEmpByID(Id);
            _db.EmployeeMasters.Remove(emp);
            _db.SaveChanges();
            return true;
        }
    }
}

Invoice Repository :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MVCDemo.Models;
using System.Data;

namespace MVCDemo.Repository
{
    public class InvoiceRepository
    {
        TestEntities _db = new TestEntities();

        public IEnumerable<InvoiceMaster> GetAllInvoice()
        {
            return (from e in _db.InvoiceMasters select e);
        }

        public bool SaveInvoice(InvoiceMaster Inv)
        {
            try
            {
                if (Inv.InvoiceID > 0)
                    _db.Entry(Inv).State = EntityState.Modified;
                else
                    _db.InvoiceMasters.Add(Inv);
                _db.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }

        }

        public InvoiceMaster GetInvByID(int Id = 0)
        {
            return (from e in _db.InvoiceMasters where e.InvoiceID == Id select e).FirstOrDefault();
        }

        public bool DeleteInv(int Id = 0)
        {
            var Inv = GetInvByID(Id);
            _db.InvoiceMasters.Remove(Inv);
            _db.SaveChanges();
            return true;
        }
    }
}

Friday, 13 December 2013

Find chare occurence in string

 protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnget_Click(object sender, EventArgs e)
    {
        CountAllCharacters(txtinput.Text,'a');
    }

    protected void CountAllCharacters(string text,char pattern)
    {
        text = text.ToUpper();
        for (int i = 0; i < text.Length; i++)
        {
            //don't count same char a second time
            if (text[i] != ' ' && (i == 0 || !text.Substring(0, i - 1).Contains(text[i])))
            {
                int count = CountCharacters(pattern, text);
                lblresult.Text = pattern.ToString() + " Occures " + count + " Times";
                //lblresult.Text = string.Format("{0} occurs {1} {2}", pattern.ToString().ToLower(), count.ToString(), count > 1 ? "times" : "time");
            }
        }
    }
    protected int CountCharacters(char target, string text)
    {
        int returnVal = 0;
        for (int i = 0; i < text.Length; i++)
        {
            if (text[i].ToString().ToUpper() == target.ToString().ToUpper())
                returnVal++;
        }
        return returnVal;
    }

Insert more than 1000 records at a time into sql database

               StringBuilder sbSql = new StringBuilder();

                int Count = 0;

                int bunch = 999;

                int Total;
            
                Total = ContactList.Count;
             

                int Mod = Total % bunch;
                for (int l = 0; Mod == 0 ? l < Total / bunch : l <= Total / bunch; l++)
                {
                    sbSql.Append(@"INSERT INTO              ContactDetail(UserId,ContactName,ContactNo,EmailID,RecordID,IsFriend,Status,CreatedOn) VALUES");
                   // Response.Write("Outer Looop" + i.ToString() + "<br/><br/>");
                    for (int i = Count; i <= bunch * (l + 1); i++)
                    {
                      //  Response.Write("Inner Looop" + j.ToString() + "<br/>");
                        string values = string.Format("({0},{1},{2},{3},{4},{5},{6},{7}),",
                           new string[] { Convert.ToString(UserId), "'" + ContactList[i].name + "'", "'" + ContactList[i].contactNo + "'", "'" + ContactList[i].Emails + "'", ContactList[i].RecordID, "0", "0", "'" + CreatedOn + "'" });
                        sbSql.Append(values);
                        Count++;
                        if (Total == Count)
                            break;
                    }
                    string sql = sbSql.ToString();
                    sql = sql.TrimEnd(',');
                    SqlConnection con = new SqlConnection();
                    con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
                    con.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandText = sql;
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.ExecuteNonQuery();
                    sbSql.Clear();

Reverse string logic without using reverse function

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnget_Click(object sender, EventArgs e)
    {
        lblreverse.Text = Reverse(txtInput.Text);
    }
    public static string Reverse(string inputString)
    {
        var chars = inputString.ToCharArray();
        for (int i = 0; i < (chars.Length / 2); i++)
        {
            var temp = chars[i];
            chars[i] = chars[chars.Length - 1 - i];
            chars[chars.Length - 1 - i] = temp;
        }
        return new string(chars);
    }

    public static string Reverse3(string inputString)
    {
        var result = new StringBuilder();
        for (int i = inputString.Length - 1; i >= 0; i--)
        {
            result.Append(inputString[i]);
        }
        return result.ToString();
    }

    public static string Reverse2(string inputString)
    {
        var result = new StringBuilder();
        foreach (char ch in inputString)
        {
            result.Insert(0, ch);
        }
        return result.ToString();
    }
}

Tuesday, 5 November 2013

Bundle Config to delare new bundle for example datepicker

    bundles.Add(new ScriptBundle("~/bundles/Datepicker").Include(
                       "~/Scripts/Datepicker/jquery-1.9.1.js",
                       "~/Scripts/Datepicker/jquery-ui.js"));

Thursday, 31 October 2013

How to Generate Models using entity frmework

Entity framwork

RightClick on Models Folder 
-> Add new item 
-> Data 
->ADO.NET Entity Data Model
-> name the model 
-> Generate From db 
-> edmx file will be generated 
-> rightclick on open area of .edmx file 
-> Add Code Generation Item 
-> Select Online template and serach for ADO.NET DBContext 
-> using that Entity object generator create the model 
-> it will create model class for each and every table
   of your database.

Edit View

@model MVCDemo.Models.EmployeeMaster
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
    Edit</h2>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.20.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<link href="../../Scripts/Datepicker/jquery-ui.css" rel="stylesheet" type="text/css" />
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/Datepicker")
<script language="javascript" type="text/javascript">
    var createuser = jQuery.noConflict();
    createuser(function () {
        createuser("#CountryId").change(function () {
            var selectedItem = createuser(this).val();
            var ddlCities = createuser("#CityId");
            if (selectedItem.toString().length > 0 && parseInt(selectedItem) > 0) {
                createuser.ajax({
                    cache: false,
                    type: "GET",
                    url: '@Url.Action("GetCity", "Employee")',
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: { "CountryId": selectedItem },
                    success: function (data) {
                        ddlCities.html('');
                        createuser.each(data, function (id, option) {
                            ddlCities.append(createuser('<option></option>').val(option.Value).html(option.Text));
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert('Failed to retrieve City.');
                    }
                });
            }
            else {
                ddlCities.html('');
                ddlCities.append(createuser('<option></option>').val('').html('--Select City--'));
            }
        });
    });

    var createuser = jQuery.noConflict();
    createuser(document).ready(function () {
        var selectedItem = createuser("#CountryId").val();
        var ddlCities = createuser("#CityId");
        if (selectedItem.toString().length > 0 && parseInt(selectedItem) > 0) {
            createuser.ajax({
                cache: false,
                type: "GET",
                url: '@Url.Action("GetCity", "Employee")',
                async: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: { "CountryId": selectedItem },
                success: function (data) {
                    ddlCities.html('');
                    createuser.each(data, function (id, option) {
                        ddlCities.append(createuser('<option></option>').val(option.Value).html(option.Text));
                    });
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve City.');
                }
            });
            createuser("#CityId").val('@ViewBag.CityId');
            createuser("#Occupation").val('@ViewBag.Occu');
        }
        else {
            ddlCities.html('');
            ddlCities.append(createuser('<option></option>').val('').html('--Select City--'));
        }
    });

    var jqdatepicker = jQuery.noConflict();

    jqdatepicker(function () {
        jqdatepicker("#DOB").datepicker
            ({
                changeMonth: true,
                changeYear: true,
                dateFormat: 'mm/dd/yy'
            });

    });

    var createuser1 = jQuery.noConflict();
    createuser1(function () {
        $('#DOB').blur(function () {
            var birthday = createuser1(this).val();
            if (birthday.value != '') {
                var birthdayDate = new Date(birthday);
                dateNow = new Date();

                var years = dateNow.getFullYear() - birthdayDate.getFullYear();
                var months = dateNow.getMonth() - birthdayDate.getMonth();
                var days = dateNow.getDate() - birthdayDate.getDate();
                alert(days);
                if (isNaN(years)) {

                    document.getElementById('Age').value = '';
                    document.getElementById('lblError').innerHTML = 'Input date is incorrect!';
                    return false;

                }
                else {
                    document.getElementById('lblError').innerHTML = '';

                    if (months < 0 || (months == 0 && days < 0)) {

                        //alert(document.getElementById('Age'));
                        years = parseInt(years) - 1;
                        document.getElementById('Age').value = years + ' Years ' + months + ' Month ' + days + ' days'
                    }
                    else {
                        //alert(document.getElementById('Age').value);
                        document.getElementById('Age').value = years + ' Years ' + months + ' Month ' + days + ' days'
                    }
                }
            }
        });
    });

    var createuser = jQuery.noConflict();
    createuser(function () {
        createuser("#Occupation").change(function () {
            var selectedItem = createuser(this).val();
            var div1 = document.getElementById('GrossSalary');
            if (selectedItem.toString() == "Job" || selectedItem.toString() == "Bussiness") {
                div1.style.display = "block";
            }
            else {
                div1.style.display = "none";
            }
        });
    });

    var createuser = jQuery.noConflict();
    createuser(document).ready(function () {
        var selectedItem = createuser("#Occupation").val();
        var div1 = document.getElementById('GrossSalary');
        if (selectedItem.toString() == "Job" || selectedItem.toString() == "Bussiness") {
            div1.style.display = "block";
        }
        else {
            div1.style.display = "none";
        }
    });

</script>
@using (Html.BeginForm("Edit", "Employee", FormMethod.Post, new { id = "EditEmp" }))
{
    @Html.HiddenFor(model => model.EmployeeId)
    <div>
        <div>
            <div>
                Employee Code:
            </div>
            <div>
                @Html.TextBoxFor(ModelItem => Model.EmpCode)
            </div>
            <div>
                Emp Name:
            </div>
            <div>
                @Html.TextBoxFor(ModelItem => Model.EmpName)
            </div>
            <div>
                Gender:
            </div>
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@Html.RadioButtonFor(model => model.Gender, "Male", new { id = "male", @style = "width:0px;" })Male
                @*@Html.Label("male", "Male")*@
            </div>
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@Html.RadioButtonFor(model => model.Gender, "Female", new { id = "female", @style = "width:0px;" })Female
                @* @Html.Label("female", "Female")*@
            </div>
            <div>
                Country:
            </div>
            <div>
                @Html.DropDownList("CountryId", ViewBag.Country as SelectList, "--Select City--")
            </div>
            <div>
                City:
            </div>
            <div>
                @* @Html.DropDownListFor(ModelItem => Model.CityMaster.CityId, new SelectList(ViewBag.City, "CityId", "CityName", ViewBag.SelCity), new { style = "width:310px" })
                @Html.ValidationMessageFor(ModelItem => Model.CityMaster.CityId)*@
                <select id="CityId" name="CityId" style="max-width: 250px;">
                    <option value="">--Select City--</option>
                </select>
                @*<select id="CityId">
                    <option>--Select City--</option>
                </select>*@
            </div>
            <div>
                DOB
            </div>
            <div>
                @Html.EditorFor(ModelItem => Model.DOB)
                @* <input type="text" id="DOB" name="DOB" value='@ViewBag.DOB' onblur="getAge(this)" />*@
                <div id="lblError">
                </div>
            </div>
            <div>
                Age
            </div>
            <div>
                @*<div id="Age"></div>*@
                @Html.TextBoxFor(ModelItem => Model.Age, new { id = "Age" })
                @*<input type="text" id="Age" name="AgeMonth" />*@
            </div>
            <div>
                Occupation
            </div>
            <div>
                @*@Html.DropDownList("CountryId", ViewBag.Country as SelectList, "--Select City--")*@
                @Html.DropDownList("Occupation", ViewBag.Occupation as SelectList)
            </div>
            <div id="GrossSalary">
                <div>
                    GrossSalary
                </div>
                <div>
                    @Html.TextBoxFor(ModelItem => Model.GrossSalary)
                </div>
            </div>
            <div>
                <input type="submit" value="submit" />
                <a href="/Employee/ListEmployees" style = "text-decoration:none;">
                    <input type="button" value="Cancel" >
                </a>
                @*<input type="button" onclick="document.location.href('Employee/ListEmployees')" value="Cancel" />*@
            </div>
        </div>
    </div>
}