Friday, 3 October 2014

working with knockout js

for this you need to download knockout js

Example 1

My MVC Application

[ Log On ]

First Name:

Hello,First: mukesh

Last Name:

Hello,Last: trivedi

Hello,fullName: mukesh trivedi

 


<script src="../../Scripts/knockout.js" type="text/javascript"></script>
<h2>First Name:<input data-bind='value: firstName'> </input></h2> 
<h2>Hello,First: <span data-bind='text: firstName'> </span></h2> 

<h2>Last Name:<input data-bind='value: lastName'> </input></h2> 
<h2>Hello,Last: <span data-bind='text: lastName'> </span></h2>

<h2>Hello,fullName: <span data-bind='text: fullName'> </span></h2>

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

    var obj = [ 
    firstName = ko.observable("my first name"),
    lastName = ko.observable("my last name")];

    this.fullName = ko.pureComputed(function () {
      
        return this.firstName() + " " + this.lastName();
    }, this);



    ko.applyBindings(obj);
   


</script>

  =============================================

 Example 2

Graduation PostGraduation
Male FeMale

controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Knockout2.Models;

namespace KnockoutMvc.Controllers
{
    public class EmployeeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View("EmployeeInfo");
        }

        [HttpPost]
        public ActionResult SaveEmployee(Employee emp)
        {
            //EmployeeMode save code here
            return View("EmployeeInfo");
        }

        [HttpGet]
        public  ActionResult PhoneList()
        {
            return View("EmployeePhone");
        }

    }
}
 ========================================

core.js


function Employee()
 {
    var that = this;
    that.FirstName = ko.observable("");
    that.LastName = ko.observable("");
    that.FullName = ko.computed(function () {
        return that.FirstName() + " " + that.LastName();
    });
    that.DateOfBirth = ko.observable("");
    that.EducationList = ko.observableArray();
    that.Gender = ko.observable("0");
    that.DepartmentList = ko.observableArray([{ Id: '0', Name: "CSE" }, { Id: '1', Name: "MBA" }]);
    that.DepartmentId = ko.observable("1");
}
function EmployeeVM() {
    var that = this;
    that.Employee = new Employee();
    that.reset = function () {
        that.Employee.FirstName("");
        that.Employee.LastName("");
        that.Employee.DateOfBirth("");
        that.DateOfBirth = ko.observable("");
        that.EducationList = ko.observableArray();
        that.Gender = ko.observable("0");
        that.DepartmentList = ko.observableArray([{ Id: '0', Name: "CSE" }, { Id: '1', Name: "MBA"}]);
    };
    that.submit = function () {
        var json1 = ko.toJSON(that.Employee);
        $.ajax({
            url: '/Employee/SaveEmployee',
            type: 'POST',
            dataType: 'json',
            data: json1,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                var message = data.Message;
            }
        });
    };
};
var _vm = new EmployeeVM();
$(function () {
    ko.applyBindings(_vm);
});

view

@model Knockout2.Models.Employee
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>EmployeeInfo</title>
    <script src="../../Scripts/core.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script src="../../Scripts/knockout-3.0.0.js" type="text/javascript"></script>  
   </script>
   
</head>
<body>
    <form id="employeeForm" name="employeeForm" method="POST">
        <div id="form-root">
            <div>
                <label class="form-label">First Name:</label>
                <input type="text" id="txtFirstName" name="txtFirstName" data-bind="value:Employee.FirstName" />
            </div>
             <div>
                <label class="form-label">Last Name:</label>
                <input type="text" id="txtLastName" name="txtLastName" data-bind="value:Employee.LastName"  />
            </div>
            <div>
                <label class="form-label">Full Name:</label>
                <input type="text" id="txtFullName" name="txtFullName" data-bind="value:Employee.FullName" readonly="readonly"  />
            </div>
            <div>
                <label class="form-label">Date Of Birth:</label>
                <input type="text" id="txtDateOfBirth" name="dateOfBirth" data-bind="value:Employee.DateOfBirth"  />
            </div>
            <div>
                <label>Education:</label>
                <input type="checkbox" value="graduation" id="chkGraduation" name="chkGraduation" data-bind="checked:Employee.EducationList" />Graduation
                <input type="checkbox" value="postGraduation" id="chkPostGraduation" name="chkPostGraduation" data-bind="checked:Employee.EducationList" />PostGraduation
            </div>
            <div>
                <label>Gender:</label>
                <input type="radio" id="rdoMale" name="gender" value="0"  data-bind="checked:Employee.Gender" />Male
                <input type="radio" id="rdoFeMale" name="gender" value="1" data-bind="checked:Employee.Gender"  />FeMale
            </div>
            <div>
                <label class="form-label">Department:</label>
                <select id="ddlDepartment" name="ddlDepartment" data-bind="options:$root.Employee.DepartmentList, optionsValue:'Id', optionsText:'Name', value:Employee.DepartmentId">
                </select>
            </div>
            <div>
                <input type="button" id="btnSubmit" value="Submit" data-bind = "click: submit" />
                 <input type="button" id="btnReset" value="Reset" data-bind = "click: reset" />
            </div>
        </div>
    </form>
</body>
</html>
 

==============================================

 

 

Saturday, 27 September 2014

ajax call

 if (document.forms[0].checkValidity()) {
 
                e.preventDefault();
 
                $.ajax({
                    type: "POST",
                    url: Person.SaveUrl,
                    data: ko.toJSON(Person.ViewModel),
                    contentType: 'application/json',
                    async: true,
                    beforeSend: function () {
                        // Display loading image
                    },
                    success: function (result) {
                        // Handle the response here.
                    },
                    complete: function () {
                        // Hide loading image.
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        // Handle error.
                    }
                });
 
            }
 

Friday, 12 September 2014

Multilevel Menu in mvc 3.0

table structure

MenuId    MenuName    MenuOrder    MainMenuId    ControllerName    ActionName    LinkName
1               Home                   1               NULL                   Controller1          Index               Home
2             Microsoft              2               NULL                   Controller2           Index           Microsoft
3             Windows               1                 2                          Controller1           Index            Windows
4             WindowsXP           1                3                           Controller1          Index          Windows XP
5               Windows7            2                3                            Controller2          Index         Windows 7
6            Windows8              3                3                            Controller1           Index         Windows 8
7              MS Office            2                2                             Controller1          Index          MS Office
8               Apple                 3                NULL                     Controller1          Index            Apple
9            IPhone                  1                   8                            Controller1          Index             IPhone
10          IPad                      2                8                             Controller1          Index             IPad
11          MacAir                 3                8                              Controller1         Index           Mac AirNot

=========================================================================
controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MultilevelMenu.Models;

namespace MultilevelMenu.Controllers
{
    public class MenuController : Controller
    {
        MenuEntities MEnt = new MenuEntities();

        [ChildActionOnly]
        public ActionResult Menus()
        {
            var mMenu = MEnt.Menu.ToList();
            return PartialView(mMenu);
        }

    }
}
============================================================
model

using System.Data.Entity;
using System.Data.Mapping;

namespace MultilevelMenu.Models
{
    public class MenuEntities : DbContext
    {
        public DbSet<Menus> Menu { get; set; }
    }
}
==============================================================
Menus.cshtml

@model IEnumerable<MultilevelMenu.Models.Menus>
<div>
    @Html.Raw(@Html.ParentMenus(Model))
</div>
=============================================================
.cs file

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

namespace MultilevelMenu.Models
{
    [Table("Menus")]
    public class Menus
    {
        [Key]
        public int MenuId { get; set; }
        public string MenuName { get; set; }
        public int MenuOrder { get; set; }
        public int? MainMenuId { get; set; }
        public string LinkName { get; set; }
        public string ActionName { get; set; }
        public string ControllerName { get; set; }
    }

}
================================================================
htmlhelper class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using MultilevelMenu.Models;

namespace MultilevelMenu.HtmlHelpers
{
    public static class HtmlHelperExtensions
    {
        public static string ParentMenus(this HtmlHelper html, IEnumerable<Menus> menu)
        {
            string htmlOutput = string.Empty;

            if (menu.Count() > 0)
            {
                htmlOutput += "<ul class='sf-menu'>";
                var MainMenu = from mainMenu in menu where mainMenu.MainMenuId == null orderby mainMenu.MenuOrder select mainMenu;
                foreach (Menus m in MainMenu)
                {
                    htmlOutput += "<li>";
                    htmlOutput += LinkExtensions.ActionLink(html, m.LinkName, m.ActionName, m.ControllerName);
                    htmlOutput += SubMenus(html, menu, m.MenuId);
                    htmlOutput += "</li>";
                }
                htmlOutput += "</ul>";
            }
            return htmlOutput;
        }

        private static string SubMenus(this HtmlHelper html, IEnumerable<Menus> SubMenu, int MenuId)
        {
            string htmlOutput = string.Empty;
            var subMenu = from sm in SubMenu where sm.MainMenuId == MenuId orderby sm.MenuOrder select sm;
            if (subMenu.Count() > 0)
            {
                htmlOutput += "<ul>";
                foreach (Menus m in subMenu)
                {
                    htmlOutput += "<li>";
                    htmlOutput += LinkExtensions.ActionLink(html, m.LinkName, m.ActionName, m.ControllerName);
                    htmlOutput += SubMenus(html, SubMenu, m.MenuId);
                    htmlOutput += "</li>";
                }
                htmlOutput += "</ul>";
            }
            return htmlOutput;
        }

        //private static string SubMenus(IEnumerable<Menus> iEnumerable)
        //{
        //    throw new NotImplementedException();
        //}
    }
}
=================================================================
Output like this:

Multilevel Menu


Saturday, 6 September 2014

working with google chart in mvc

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

namespace Mvcchart.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public JsonResult GetData()
        {
            return Json(CreateCompaniesList(), JsonRequestBehavior.AllowGet);
        }

        private IEnumerable<Company> CreateCompaniesList()
        {
            List<Company> companies = new List<Company>();

            Company company = new Company() { Expense = 1200, Salary = 2000, Year = new DateTime(2012, 1, 1).ToString("yyyy/MM") };
            Company company1 = new Company() { Expense = 1300, Salary = 2100, Year = new DateTime(2012, 2, 1).ToString("yyyy/MM") };
            Company company2 = new Company() { Expense = 1240, Salary = 2000, Year = new DateTime(2012, 3, 1).ToString("yyyy/MM") };
            Company company3 = new Company() { Expense = 1100, Salary = 3300, Year = new DateTime(2012, 4, 1).ToString("yyyy/MM") };
            Company company4 = new Company() { Expense = 140, Salary = 1100, Year = new DateTime(2012, 5, 1).ToString("yyyy/MM") };
            Company company5 = new Company() { Expense = 1500, Salary = 1900, Year = new DateTime(2012, 6, 1).ToString("yyyy/MM") };

            companies.Add(company);
            companies.Add(company1);
            companies.Add(company2);
            companies.Add(company3);
            companies.Add(company4);
            companies.Add(company5);

            return companies;
        }

     
    }
}
=================================================================
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        google.load("visualization", "1", { packages: ["corechart"] });
        google.setOnLoadCallback(drawChart);
        function drawChart() {
            $.get('/Home/GetData', {},
    function (data) {
        var tdata = new google.visualization.DataTable();

        tdata.addColumn('string', 'Year');
        tdata.addColumn('number', 'Salary M');
        tdata.addColumn('number', 'Expense');

        for (var i = 0; i < data.length; i++) {
            tdata.addRow([data[i].Year, data[i].Salary, data[i].Expense]);
        }

        var options = {
            title: "mukesh Salary For the current year"
        };

        var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
        chart.draw(tdata, options);
    });
        }
    </script>
</head>
<body>
    <div>
        <div id="chart_div" style="width: 900px; height: 500px;">
        </div>
    </div>
</body>
</html>
======================================================================
class



public class Company
    {
       public int  Expense {get;set;}
        public int  Salary {get;set;}
        public string Year { get; set; }       
    }
======================================================
Result


mukesh Salary For the current yearSalary MExpense2012/012012/022012/032012/042012/052012/0601,0002,0003,0004,000

Monday, 1 September 2014

Using Group by in Entity Framework

we have emp table  and department table

EmpID    EmpName    salary
1    Mukesh                 3000.00
2    Rakesh                  3000.00
3    Raghav                  3000.00
4    Sunil                     3000.00
5    radhika                 3000.00
6    gajraj singh          3000.00
7    akshay                  3000.00
8    anuradha             3000.00
9    hari                     3000.00
10    dee                    3000.00
11    dee                    3000.00
12    dee                   3000.00
13    ajay ml            3000.00
14    sudama           3000.00
15    raju                3000.00
16    iti                  3000.00
17    ravi               3000.00 
==========================================================
department


Depid    Depname    Address1    City    EmpID
1    IT    B/1 new delhi    delhi    4
2    Software    Mamura    Noida    2
3    Software    sector 15    Noida    3
4    Software    shuklaganj    Kanpur    1
5    Medical    Babina    jhansi    7
6    Railway    Babina    Jhansi    8
7    Railway    Babina    Jhansi    9
8    Railway    Babina    Jhansi    10
9    Railway    Babina    Jhansi    11
10    Railway    Babina    Jhansi    12
11    Railway    Babina    Jhansi    13
12    Railway    Babina    Jhansi    14
13    Railway    Babina    Jhansi    15
14    Railway    Babina    Jhansi    16
15    Railway    Babina    Jhansi    17


==================================================================

CountryEntities obj = new CountryEntities();
            var datalist = (from s in obj.Employees
                            join sl in obj.Departments on s.EmpID equals sl.EmpID
                            group s by new { s.EmpName, sl.Depname } into g

                            select new { department = g.Key.Depname, empName = g.Key.EmpName, totalsalary = g.Sum(P => P.salary) });

            GridView1.DataSource = datalist;
            GridView1.DataBind();
=================================================================
output
here output will come on department and name basis


departmentempNametotalsalary
ITSunil3000.00
Medicalakshay3000.00
Railwayajay ml3000.00
Railwayanuradha3000.00
Railwaydee9000.00
Railwayhari3000.00
Railwayiti3000.00
Railwayraju3000.00
Railwayravi3000.00
Railwaysudama3000.00
SoftwareMukesh3000.00
SoftwareRaghav3000.00
SoftwareRakesh3000.00




using object Parameter in Entity Framework

     [HttpPost]
        public ActionResult About(Employee1 onjemp)
        {
            int k=0;
            if (ModelState.IsValid)
            {
                System.Data.Objects.ObjectParameter output = new System.Data.Objects.ObjectParameter("CustomerCount", typeof(int));
               
               
                Employee emp = new Employee();
               // emp.EmpName = onjemp.EmpName;
               // objenties.Employees.AddObject(emp);

                k = objenties.insert(onjemp.EmpName, "Railway", "Babina", "Jhansi", output);
               // k = objenties.SaveChanges();
                int j =Convert.ToInt32(output.Value);
                if (j> 0)
               {
                   ViewBag.sucess = "Inserted Successfull";
                   Employee1 onjemp1 = new Employee1();
                   return View("~/Views/Home/Index.cshtml", onjemp1);
               }
               else
               {

                   ViewBag.sucess = "Some Problem";
                  
                   return View(onjemp);

               }

               
            }
            else
            {
                return View("~/Views/Home/Index.cshtml", onjemp);
            }
        }

Tuesday, 26 August 2014

Closest Tr Example








    $(document).ready(function () {

        $("#tbl .cntname").click(function () {
            var row = $(this).closest('tr');
            // var id = $(".cntcode", row).text().trim();
            var id = $(".cnt", row).text().trim();
            alert(id);

        });



    });
<table id="tbl">
    <tr>
    <td class="cntcode">
      @item.countrycode
    </td>
 <td class="cntname">@item.Name</td>
 <td class="cnt">401</td>
  </tr>
</table>   

Saturday, 19 July 2014

Sql Important Task

Sql  Task 1  Database backup

DECLARE @name VARCHAR(50) -- database name 
DECLARE @path VARCHAR(256) -- path for backup files 
DECLARE @fileName VARCHAR(256) -- filename for backup 
DECLARE @fileDate VARCHAR(20) -- used for file name

SET @path = 'D:\BACK\' 

SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

DECLARE db_cursor CURSOR FOR 
SELECT name
FROM MASTER.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb') 

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @name  

WHILE @@FETCH_STATUS = 0  
BEGIN  
       SET @fileName = @path + @name + '_' + @fileDate + '.BAK' 
       BACKUP DATABASE @name TO DISK = @fileName 

       FETCH NEXT FROM db_cursor INTO @name  
END  

CLOSE db_cursor  
DEALLOCATE db_cursor

Task  2  Bulk insert
 file1.txt

"Kelly","Reynold","kelly@reynold.com"
"Kelly","Reynold","kelly@reynold.com" "John","Smith","bill@smith.com" "Sara","Parker","sara@parker.com" - See more at: http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file#sthash.K2zFx1ZA.dpuf
"Kelly","Reynold","kelly@reynold.com" "John","Smith","bill@smith.com" "Sara","Parker","sara@parker.com" - See more at: http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file#sthash.K2zFx1ZA.dpuf
 "aa","bb","cc"
"Kelly","Reynold","kelly@reynold.com"
 BULK INSERT temp1 FROM 'D:\aa.txt' WITH (FIELDTERMINATOR = '","')

file2.txt
aa,bb,cc
 BULK INSERT temp1 FROM 'D:\aa.txt' WITH (FIELDTERMINATOR =',')
FileType=1 (TxtFile1.txt)
"Kelly","Reynold","kelly@reynold.com"
"John","Smith","bill@smith.com"
"Sara","Parker","sara@parker.com"
FileType=2 (TxtFile2.txt)
Kelly,Reynold,kelly@reynold.com
John,Smith,bill@smith.com
Sara,Parker,sara@parker.com
- See more at: http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file#sthash.K2zFx1ZA.dpuf
FileType=1 (TxtFile1.txt)
"Kelly","Reynold","kelly@reynold.com"
"John","Smith","bill@smith.com"
"Sara","Parker","sara@parker.com"
FileType=2 (TxtFile2.txt)
Kelly,Reynold,kelly@reynold.com
John,Smith,bill@smith.com
Sara,Parker,sara@parker.com
- See more at: http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file#sthash.K2zFx1ZA.dpuf
FileType=1 (TxtFile1.txt)
"Kelly","Reynold","kelly@reynold.com"
"John","Smith","bill@smith.com"
"Sara","Parker","sara@parker.com"
FileType=2 (TxtFile2.txt)
Kelly,Reynold,kelly@reynold.com
John,Smith,bill@smith.com
Sara,Parker,sara@parker.com
- See more at: http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file#sthash.K2zFx1ZA.dpuf

BULK INSERT tmpStList FROM 'c:\TxtFile2.txt' WITH (FIELDTERMINATOR = ',') - See more at: http://www.sqlteam.com/article/using-bulk-insert-to-load-a-text-file#sthash.K2zFx1ZA.dpuf

 

Wednesday, 9 July 2014

image priview and crop image in asp.net

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Crop Image using crop plugin</title>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script src="jquery.Jcrop.js" type="text/javascript"></script>
    <link href="jquery.Jcrop.css" rel="stylesheet" type="text/css" />
     <script type="text/javascript">
       
         function getcroparea(c) {
             $('#hdnx').val(c.x);
             $('#hdny').val(c.y);
             $('#hdnw').val(c.w);
             $('#hdnh').val(c.h);
         };
</script>
    
<script type="text/javascript">
    function showimagepreview(input) {
        $("#imgprvw").show();
        if (input.files && input.files[0]) {
          
            var filerdr = new FileReader();
            filerdr.onload = function (e) {

                $('#imgprvw').attr('src', e.target.result);
                $('#imgprvw').Jcrop({
                    onSelect: getcroparea
                });

            }
            filerdr.readAsDataURL(input.files[0]);
            $("#imgprvw").hide();
          

        }
    }
</script>
   
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:FileUpload runat="server" ID="filUpload1" onchange="showimagepreview(this)" />
    <asp:Image ID="imgprvw" runat="server" src="" />
   
    </div>

    <div>
<input type="hidden" id="hdnx" runat="server" />
<input type="hidden" id="hdny" runat="server"/>
<input type="hidden" id="hdnw" runat="server"/>
<input type="hidden" id="hdnh" runat="server" />
<asp:Button ID="btncrop" runat="server" OnClick="btncrop_Click" Text="Crop Images" />
<img id="imgcropped" runat="server" visible="false" />
</div>
    </form>
</body>
</html>
==================================================================
using System;
using System.Drawing;
using System.IO;
using Image = System.Drawing.Image;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btncrop_Click(object sender, EventArgs e)
    {
        try
        {
            string filename = Path.GetFileName(filUpload1.PostedFile.FileName);
            string fname = filename;
            string fpath = Path.Combine(Server.MapPath("~/images"), fname);
            filUpload1.SaveAs(Server.MapPath("images/" + filename));
               Image oimg = Image.FromFile(fpath);
               
                Rectangle cropcords = new Rectangle(
                Convert.ToInt32(hdnx.Value),
                Convert.ToInt32(hdny.Value),
                Convert.ToInt32(hdnw.Value),
                Convert.ToInt32(hdnh.Value));
                string cfname, cfpath;
                Bitmap bitMap = new Bitmap(cropcords.Width, cropcords.Height, oimg.PixelFormat);
                Graphics grph = Graphics.FromImage(bitMap);
                grph.DrawImage(oimg, new Rectangle(0, 0, bitMap.Width, bitMap.Height), cropcords, GraphicsUnit.Pixel);
                cfname = "crop_" + fname;
                cfpath = Path.Combine(Server.MapPath("~/cropimages"), cfname);
                bitMap.Save(cfpath);
                imgcropped.Visible = true;
                imgcropped.Src = "~/cropimages/" + cfname;
            
            }
            catch (Exception ex)
            {
                throw ex;
            }
    }
}
================================================
you need to download  jscrop js
thanks



using + operator in c# & javasript for concatenation example


            string strOut;
            strOut = "<table width='300' border='1' cellspacing='0' cellpadding='3'>";

            strOut = strOut + "<tr>";

            strOut = strOut + "<th colspan='2'>The + operator in JavaScript</th>";
            strOut = strOut + "</tr>";

            strOut = strOut + "<tr>";
            strOut = strOut + "<th>When used in</th>";
            strOut = strOut + "<th>Performs</th>";
            strOut = strOut + "</tr>";
            strOut = strOut + "<tr>";
            strOut = strOut + "<td>"+101+"</td>";
            strOut = strOut + "<td>"+301+"</td>";
            strOut = strOut + "</tr>";
            strOut = strOut + "<tr>";
            strOut = strOut + "<td>" + 401 + "</td>";
            strOut = strOut + "<td>" + 501 + "</td>";
            strOut = strOut + "</tr>";
            strOut = strOut + "</table>";
  Response.write(strout); in c#
Document.write(strout); in javascript

Sunday, 6 July 2014

auto complte in mvc

 Home Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Autocomplete.Models;
using newauto.Models;
using newauto.Controllers;

namespace Autocomplete.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        CountryEntities _entites = new CountryEntities();
        public ActionResult Index()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult Autocomplete(string term)
        {
            var data = (from x in _entites.countries
                        where x.CountryName.Contains(term)
                        select new City
                        {
                            Key = x.pkCountryId,
                            Value = x.CountryName
                        }).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GetDetail(int id)
        {
            DemoModel model = new DemoModel();
           // select data by id here display static data;
            if (id == 0)
            {
                model.id = 1;
                model.name = "Yogesh Tyagi";
                model.mobile = "9460516787";

            }
            else {
                model.id = 2;
                model.name = "Pratham Tyagi";
                model.mobile = "9460516787";
          
            }

            return Json(model);
          
        }

    }
}

=================================================================
view

@{
    ViewBag.Title = "Index";
}



<script src="../../Scripts/jquery-ui-1.8.20.js" type="text/javascript"></script>

<h2>Index</h2>
  @Html.Label("Enter Your name")
                @Html.TextBox("PassId")
<div id="VisitorDetail">
                    <label>Id</label><div id="Id"></div>
                    <label>Name</label><div id="Name"></div>
                    <label>Mobile</label><div id="Mobile"></div>
  </div>
<script type="text/javascript">
    $(document).ready(function () {
        $('#VisitorDetail').hide();
    });
    $("#PassId").autocomplete({
        source: function (request, response) {
            var customer = new Array();
            $.ajax({
                async: false,
                cache: false,
                type: "POST",
                url: "@(Url.Action("Autocomplete", "Home"))",
                data: { "term": request.term },
                success: function (data)
                {
                if(data.length==0)
                {
                    $('#VisitorDetail').hide();
                alert('No Records Found');
                }
                else
                {
                 $('#VisitorDetail').show();
                alert('No Records Found'+'1');
                    for (var i = 0; i < data.length ; i++)
                     {
                
                        customer[i] = { label: data[i].Value, Id: data[i].Key };
                      }
                    }
                }
            });
            response(customer);
        },
         select: function (event, ui) {
             //fill selected customer details on form
             $.ajax({
                 cache: false,
                 async: false,
                 type: "POST",
                 url: "@(Url.Action("GetDetail", "Home"))",
                data: { "id": ui.item.Id },

                success: function (data) {
                    $('#VisitorDetail').show();
                    $("#Id").html(data.id)
                    $("#Name").html(data.name)
                    $("#Mobile").html(data.mobile)
                    action = data.Action;
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve states.');
                }
            });
        }
     });

</script>=================================================================




Friday, 27 June 2014

converting html to pdf with image using itextsharp

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
     <form id="form1" runat="server">
<%--<asp:Panel ID="pnlPerson" runat="server">--%>
<div ID="pnlPerson" runat="server">

    <table border="1" style="font-family: Arial; font-size: 10pt; width: 200px">
    <tr><td>
   
<div><img src="http://localhost:60736/img/mukesh1.jpg" /></div>
</td>
        <tr>
            <td colspan="2" style="background-color: #18B5F0; height: 18px; color: White; border: 1px solid white">
                <b>Personal Details</b>
            </td>
        </tr>
        <tr>
            <td><b>Name:</b></td>
            <td><asp:Label ID="lblName" runat="server"></asp:Label></td>
        </tr>
        <tr>
            <td><b>Age:</b></td>
            <td><asp:Label ID="lblAge" runat="server"></asp:Label></td>
        </tr>
        <tr>
            <td><b>City:</b></td>
            <td><asp:Label ID="lblCity" runat="server"></asp:Label></td>
        </tr>
        <tr>
            <td><b>Country:</b></td>
            <td><asp:Label ID="lblCountry" runat="server"></asp:Label></td>
        </tr>
    </table>
</div>
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" />
    </form>
</body>
</html>
===========================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Data;

namespace Webpdfgenerate
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Populate DataTable
                DataTable dt = new DataTable();
                dt.Columns.Add("Name");
                dt.Columns.Add("Age");
                dt.Columns.Add("City");
                dt.Columns.Add("Country");
                dt.Rows.Add();
                dt.Rows[0]["Name"] = "Mudassar Khan";
                dt.Rows[0]["Age"] = "27";
                dt.Rows[0]["City"] = "Mumbai";
                dt.Rows[0]["Country"] = "India";

                //Bind Datatable to Labels
                lblName.Text = dt.Rows[0]["Name"].ToString();
                lblAge.Text = dt.Rows[0]["Age"].ToString();
                lblCity.Text = dt.Rows[0]["City"].ToString();
                lblCountry.Text = dt.Rows[0]["Country"].ToString();
            }
        }
        protected void btnExport_Click(object sender, EventArgs e)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            pnlPerson.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();

        }
    }
}

Saturday, 31 May 2014

Binding dropdown list in gridview:


       Binding dropdown list in gridview:




name
age
id
mukesh
12
     
mukesh1
13
     
mukesh2
14
     

using like Operator in Procedure sql server

CREATE PROCEDURE Proc_customersearch    
@code nvarchar(10)=null,   
@name nvarchar(20)=null   
AS   
begin   
DECLARE @SQL nvarchar(500)   
if((@code is not null) and (@name is null))   
     begin   
       SET @SQL = 'SELECT CustACNumber ,Cust_Name,Contactperson,Addressline1,Addressline2,postalcode,Telephoneno, Faxnumber,EmailID,Country,IATAAreacode,ControllinglocationCode,Cust_IataCode FROM M_customercodes WHERE CustAcNumber LIKE '''  + @code + '%''
 
'   
       EXEC (@SQL)   
     end   
else if((@code is null) and (@name is  not null))   
      begin   
       SET @SQL = 'SELECT CustACNumber ,Cust_Name,Contactperson,Addressline1,Addressline2,postalcode,Telephoneno, Faxnumber,EmailID,Country,IATAAreacode,ControllinglocationCode,Cust_IataCode FROM M_customercodes WHERE Cust_Name LIKE '''  + @name + '%''' 
 
       EXEC (@SQL)   
     end   
  else if((@code is not null) and (@name is  not null))      
       begin   
          SET @SQL = 'SELECT CustACNumber ,Cust_Name,Contactperson,Addressline1,Addressline2,postalcode,Telephoneno ,Faxnumber,EmailID,Country,IATAAreacode,ControllinglocationCode,Cust_IataCode FROM M_customercodes WHERE Cust_Name LIKE '''  + @name + '%''
 
 and CustAcNumber LIKE '''  + @code + '%'' '   
          EXEC (@SQL)   
       end   
        
  end   
   

tree view control

First Create Class Of PageModules

using
System;
using System.Data;using System.Configuration;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq; 
 
public class PageModules{public PageModules(){
//// TODO: Add constructor logic here//}#region /// <summary>/// Field to store ID/// </summary>private int _id;/// <summary>/// Field to store Menu Name/// </summary>private string _menuName;/// <summary>/// Field to store Page Url/// </summary>private string _pageUrl;/// <summary>/// Field to store Parent ID/// </summary>private int _parentId;/// <summary>/// Field to store Is Active/// </summary>private bool _isActive;/// <summary>/// Field to store Display Order/// </summary>private int _displayOrder;/// <summary>/// Field to store Create By/// </summary>private string _createBy;/// <summary>/// Field to store Create Date/// </summary>private DateTime _createDate;/// <summary>/// Field to store Update By/// </summary>private string _updateBy;/// <summary>/// Field to store Update Date/// </summary>private DateTime _updateDate;/// <summary>/// Field to store selected flag/// </summary>private bool _isSelected;#endregion#region /// <summary>/// Gets or Sets ID/// </summary>public int ID{
get { return _id; }set { _id = value; }}
/// <summary>/// Gets or Sets MenuName/// </summary>public string MenuName{
get { return _menuName; }set { _menuName = value; }}
/// <summary>/// Gets or Sets PageURL/// </summary>public string PageURL{
get { return _pageUrl; }set { _pageUrl = value; }}
/// <summary>/// Gets or Sets ParentID/// </summary>public int ParentID{
get { return _parentId; }set { _parentId = value; }}
/// <summary>/// Gets or Sets IsActive/// </summary>public bool IsActive{
get { return _isActive; }set { _isActive = value; }}
/// <summary>/// Gets or Sets DisplayOrder/// </summary>public int DisplayOrder{
get { return _displayOrder; }set { _displayOrder = value; }}
/// <summary>/// Gets or Sets CreateBy/// </summary>public string CreateBy{
get { return _createBy; }set { _createBy = value; }}
/// <summary>/// Gets or Sets CreateDate/// </summary>public DateTime CreateDate{
get { return _createDate; }set { _createDate = value; }}
/// <summary>/// Gets or Sets UpdateBy/// </summary>public string UpdateBy{
get { return _updateBy; }set { _updateBy = value; }}
/// <summary>/// Gets or Sets UpdateDate/// </summary>public DateTime UpdateDate{

get { return _updateDate; }set { _updateDate = value; }}
/// <summary>/// Gets or Sets IsSelected/// </summary>public bool IsSelected{
get { return _isSelected; }set { _isSelected = value; }}
#endregion 
}
 
then design like this

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="one.aspx.cs" Inherits="one" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><
head runat="server"><title></title></
head><
body><form id="form1" runat="server"><asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager><div>
</div><asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate>
<asp:TreeView ID="TreeView1" runat="server" ></asp:TreeView></ContentTemplate></asp:UpdatePanel></form></
body></
html>-- 


----------------------------------.aspx code------------------------------------------
using System;
using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Data.SqlClient;using System.Configuration;public partial class one : System.Web.UI.Page{
SqlConnection con = new SqlConnection("database=master;data source=YOGENDRA;integrated security=true");
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e){

try{
if (!IsPostBack){
LoadMenu();
}
 
 
}

catch (Exception ex){
 
 
}
}

private void LoadMenu(){

List<PageModules> oListPageModules = null;
try{
oListPageModules = GetPageModule();
FillMenu(oListPageModules);
}
catch (Exception ex){

throw ex;}
}

public List<PageModules> GetPageModule(){

 


PageModules oPageModule = null;
List<PageModules> oPageModuleList = null;
// DataSet oDs = null;try{
//oDs = SqlHelper.ExecuteDataset(con, CommandType.Text, "select * from r_PageModule");con.Open();
cmd =
new SqlCommand("select* from tbl", con);cmd.CommandType =
CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
// dr = SqlHelper.ExecuteReader(con, CommandType.Text, "select * from menu22");if (dr != null){
oPageModuleList =
new List<PageModules>();
while (dr.Read()){
oPageModule =
new PageModules();
if (dr["id"] != null && dr["id"] != DBNull.Value){
oPageModule.ID =
int.Parse(dr["id"].ToString());}

if (dr["name"] != null && dr["name"] != DBNull.Value){
oPageModule.MenuName = dr[
"name"].ToString().Trim();}

if (dr["url"] != null && dr["url"] != DBNull.Value){
oPageModule.PageURL = dr[
"url"].ToString().Trim();}

if (dr["parentid"] != null && dr["parentid"] != DBNull.Value){
oPageModule.ParentID =
int.Parse(dr["parentid"].ToString());}

if (dr["displayorder"] != null && dr["displayorder"] != DBNull.Value){
oPageModule.DisplayOrder =
int.Parse(dr["displayorder"].ToString());}
oPageModuleList.Add(oPageModule);
}
dr.Close();
}
}

catch (Exception ex){

throw ex;}

finally{
con.Close();
}
return oPageModuleList;}

private void FillMenu(List<PageModules> oPageModulesList){

List<PageModules> oParentModules = null;
try{
// If Page modules is not nullif (oPageModulesList != null && oPageModulesList.Count > 0){

foreach (PageModules oPages in oPageModulesList){

if (oPages.ParentID == 0){

if (oParentModules == null)oParentModules =
new List<PageModules>();oParentModules.Add(oPages);
}
}

// If parent modules is not nullif (oParentModules != null){

// Sort parent modulesoParentModules.Sort(delegate(PageModules pm1, PageModules pm2){

return pm1.DisplayOrder.CompareTo(pm2.DisplayOrder);});
LoadPageModules(oParentModules, oPageModulesList);
}
}
}

catch (Exception ex){

throw ex;}
}

private void LoadPageModules(List<PageModules> oParentModules, List<PageModules> oPageModulesList){

TreeNode childMenuItem = null;
TreeNode parentMenuItem = null;
List<PageModules> oChildModules = null;
try{
// Iterate each parent moduleoParentModules.ForEach(delegate(PageModules oParentModule){
parentMenuItem =
new TreeNode();parentMenuItem.Text = oParentModule.MenuName;
parentMenuItem.Value = oParentModule.ID.ToString();

if (!string.IsNullOrEmpty(oParentModule.PageURL)){
parentMenuItem.NavigateUrl = ResolveUrl(oParentModule.PageURL);
}

else{
parentMenuItem.Selected =
false;}
 
 

foreach (PageModules oChildPages in oPageModulesList){

if (oChildPages.ParentID == oParentModule.ID){

if (oChildModules == null)oChildModules =
new List<PageModules>();oChildModules.Add(oChildPages);
}
}

if (oChildModules != null){

// Get child menu itemschildMenuItem = AddChildNode(oChildModules, ref parentMenuItem);oChildModules =
new List<PageModules>();}
TreeView1.Nodes.Add(parentMenuItem);
});
}

catch (Exception ex){

throw ex;}
}

private TreeNode AddChildNode(List<PageModules> oChildModules, ref TreeNode parentMenuItem){

TreeNode childMenuItem = null;
List<PageModules> oSubChildModules = null;
try{
// If child modules are foundif (oChildModules != null && oChildModules.Count > 0){

// Sort child modulesoChildModules.Sort(delegate(PageModules pm1, PageModules pm2){

return pm1.DisplayOrder.CompareTo(pm2.DisplayOrder);});

// Iterate each child moduleforeach (PageModules oChildModule in oChildModules){

// Create child menu itemchildMenuItem = new TreeNode();childMenuItem.Text = oChildModule.MenuName;
childMenuItem.Value = oChildModule.ID.ToString();

if (!string.IsNullOrEmpty(oChildModule.PageURL)){
childMenuItem.NavigateUrl = ResolveUrl(oChildModule.PageURL);
}

else{
childMenuItem.Selected =
false;}
oSubChildModules = GetPageModule();

// Find child page modulesoSubChildModules = oSubChildModules.FindAll(delegate(PageModules oPageModule){

return ((oPageModule.ParentID == oChildModule.ID) ? true : false);});

if (oSubChildModules != null){

// Populate child sub menuAddChildNode(oSubChildModules, ref childMenuItem);}
parentMenuItem.ChildNodes.Add(childMenuItem);
}
}
}

catch (Exception ex){

throw ex;}

return childMenuItem;}
}