Translate

Thursday 3 December 2015

MVC equerry mail

http://www.mikesdotnetting.com/article/268/how-to-send-email-in-asp-net-mvc

Angular JS

http://www.codeproject.com/Articles/869433/AngularJS-MVC-Repository-Dispose

Thursday 26 November 2015

c# add stylesheet with .less file in your website

Install 

Tools –> Library Package Manager –> Package Manager Console
PM> Install-Package dotLess



<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/less")
        @Scripts.Render("~/bundles/modernizr")
    </head>


And add your bundle to the appropriate location within BundleConfig.cs

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        // NOTE: existing bundles are here 

        // add this line
      bundles.Add(new LessBundle("~/Content/less").Include("~/Content/*.less"));
    }
}


dotLess will apply transforms to your web.config when you install it 
through NuGet to provide handlers which can process a specific LESS 
file:
---------------------

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler, dotless.Core" />
  </configSections>
  <!-- these probably do something useful -->
  <dotless minifyCss="false" cache="true" web="false" />
  <system.webServer>
    <handlers>
      <!-- for IIS7+ -->
      <add name="dotless" path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler,dotless.Core" resourceType="File" preCondition="" />
    </handlers>
  </system.webServer>
  <system.web>
    <httpHandlers>
      <!-- for IIS6 -->
      <add path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler, dotless.Core" />
    </httpHandlers>
  </system.web>
</configuration>



-----------------------
Or Follow this Link
http://www.brendanforster.com/blog/yet-another-implement-less-in-aspnetmvc-post.html

Monday 2 November 2015

Saturday 26 September 2015

For Details on Layer and Tire

https://msdn.microsoft.com/en-gb/library/ee658109.aspx

http://stackoverflow.com/questions/120438/whats-the-difference-between-layers-and-tiers

Friday 18 September 2015

Get USD to INR exchange rate dynamically in C# by Pabitra

using System.IO;
using System.Net;
using System.Xml;
----------------------

 private void button2_Click(object sender, EventArgs e)
        {
            WebRequest webrequest = WebRequest.Create("http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=INR");
            HttpWebResponse response = (HttpWebResponse)webrequest.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(responseFromServer);
            string value = doc.InnerText;

            MessageBox.Show(value);
            reader.Close();
            dataStream.Close();
            response.Close();


        }

Saturday 12 September 2015

Date Time Picker in Jquery

  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#<%=txtFromdate.ClientID%>').datepicker({ dateFormat: "dd/mm/yy" }).val()
            $('#<%=txtTodate.ClientID%>').datepicker({ dateFormat: "dd/mm/yy" }).val()
        });
      
   </script>


<div>

<asp:TextBox ID="txtFromdate" Width="35%" runat="server" placeholder="Select Date" ToolTip="From Date" AutoCompleteType="Disabled" TabIndex="1"></asp:TextBox>

<br/>
<asp:TextBox ID="txtTodate" Width="35%" runat="server" placeholder="Select Date" ToolTip="From Date" AutoCompleteType="Disabled" TabIndex="1"></asp:TextBox>



</div>

Friday 31 July 2015

Concate Sql Query in c#

  The  Below query is concate in c#
When a long query we write we impliments this
Solution
-----------
 protected void Button1_Click(object sender, EventArgs e)
    {

        string Name = "Pabitra";
        // string Query = "insert into tblEmployee ( id, name ) values( " + 4 + ",'" + Name + "' )";
        string Query = "insert into tblEmployee " +
            " (        " +
            " id,      " +
            " name     " +
            " )        " +

            " values(  " +
            "" + 4 + "," +
            "'" + Name + "' " +
            " )";
        Response.Write(Query);
    }

Sunday 19 July 2015

Wednesday 8 July 2015

Key Down Events and Key press Events

Key Down Events
-----------------


<script type="text/javascript">
        $(document).ready(function () {
            $("#<%= txtcontactno.ClientID%>").keydown(function (e) {
                if (e.shiftKey)
                    e.preventDefault();
                else {
                    var nKeyCode = e.keyCode;
                    //Ignore Backspace and Tab keys      
                    if (nKeyCode == 8 || nKeyCode == 9)
                        return;
                    if (nKeyCode < 95) {
                        if (nKeyCode < 48 || nKeyCode > 57)
                            e.preventDefault();
                    }
                    else {
                        if (nKeyCode < 96 || nKeyCode > 105)
                            e.preventDefault();
                    }
                }
            });
        });
    </script>



Key press Events
-----------------
 <script type="text/javascript">

        $(document).ready(function () {
            //called when key is pressed in textbox
            $('#<%=txtcontactno.ClientID%>').keypress(function (e) {
                alert('hello');
                //if the letter is not digit then display error and don't type anything
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    //display error message
                    //  alert('Please Enter ');
                    //  $("#errmsg").html("Digits Only").show().fadeOut("slow");
                    return false;
                }
            });
        });

    </script>
------------

Monday 6 July 2015

sql alter drop rename column in the table

To add a column in a table, use the following syntax:
------------------------------
ALTER TABLE table_name
ADD column_name datatype

-----------------------------
To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):
--------------------------------------
ALTER TABLE table_name
DROP COLUMN column_name
-----------------------------


To change the data type of a column in a table, use the following syntax:
--------------------------------------------
ALTER TABLE table_name
ALTER COLUMN column_name datatype


----------------------------------
To rename Column Name
-------------------------
EXEC sp_RENAME 'table_name.old_name', 'new_name', 'COLUMN'

Thursday 18 June 2015

get ip address in c#

 //using System.Net;
        string hostName = Dns.GetHostName(); // Retrive the Name of HOST  
        string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
        Response.Write("My IP Address is :" + myIP);



or
-------
string ip_address = Convert.ToString(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
   Response.Write("My IP Address is :" + ip_address);  

C#- different type of alert message in code behind

 string Message = "Pabitra you as Microsoft Employee !";
         ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Pabitra you as Microsoft Employee !');", true);
         ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + Message + "');", true);

         ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('Pabitra you as Microsoft Employee !');", true);
         ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + Message + "');", true);

         Response.Write(@"<script language='javascript'>alert('Pabitra you as Microsoft Employee ! ')</script>");
         Response.Write(@"<script language='javascript'>alert('"+Message+"')</script>");

         Page.ClientScript.RegisterStartupScript(Page.GetType(), "MessageBox", "<script language='javascript'>alert('Pabitra you as Microsoft Employee !');</script>");
         Page.ClientScript.RegisterStartupScript(Page.GetType(),"MessageBox","<script language='javascript'>alert('" + Message + "');</script>");

         ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", "alert('Pabitra you as Microsoft Employee !')", true);
         ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", "alert('" + Message + "')", true);
        ////////////////
ClientScript.RegisterStartupScript(this.GetType(), "Email", "<script>GetEmail();</script>");
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Please Enter Data')", true);

         ClientScript.RegisterClientScriptBlock(GetType(), "Email", "GetEmail();", true);
        //In Html Page
        <head>
        <script type="text/javascript" language="javascript">
         function GetEmail() {
             alert('hi');
         }
        </script>
    </head>
    ///////////////////////////

Wednesday 17 June 2015

custom message in asp.nt

<%@ 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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnClick" runat="server" Text="Click Me" OnClick="btnClick_Click" />
    </div>
    </form>
</body>
</html>
---------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }
    protected void btnClick_Click(object sender, EventArgs e)
    {
        CustomPopup.Show(this.Page, "Hello Pabitra Microsoft");
    }
   
 
}
public static class CustomPopup
{
    public static void Show(this Page Page, String Message)
    {
        Page.ClientScript.RegisterStartupScript(Page.GetType(),"MessageBox","<script language='javascript'>alert('" + Message + "');</script>");
    }
}

c# Page.ClientScript.RegisterStartupScript

 Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('Hello Mr Pabitra Now your eligible for join in microsoft');window.location.href=('Thanku.aspx');</script>");

Friday 29 May 2015

Friday 22 May 2015

Create Log file on the Same Directory

protected void btnClick_Click(object sender, EventArgs e)
        {
            int x = 10;
            TextBox1.Text = "";
            TextBox1.Text = "wwww";
            TextBox1.Text = "111111111111111111111111";        
             try
            {
                x = x + Convert.ToInt32(TextBox1.Text);
            }
            catch (Exception ex)
            {            
                System.IO.File.WriteAllText(Server.MapPath("Error/Date_"+DateTime.Now.ToString("dd-MM-yyyy")+"-ErrorLog-Time-HHmmss-" + DateTime.Now.ToString("HH-mm-ss") + ".txt"), ex.ToString());
             

            }
        }

Sql Trigger Insert,Update,Delete

create table tblMain
  (
   Id int not null Primary Key identity(1,1) ,
   Name varchar(100),
   dflag int,
   userId varchar(20)
    )


create table tblMain_Image
  (
  AutoId bigint not null Primary key identity(1,1),
    Id int  not null,
    Name varchar(100),
    userId varchar(20),
    dflag int,
Sys_Date datetime default getdate(),
sys_Time  varchar(20) default RIGHT(CONVERT(CHAR(20), GETDATE(), 22), 11)--For AM and PM
    )
----------------------------------INSERT----------------------------  
create trigger [dbo].[Triger_Insert_tblMain] ON  [dbo].[tblMain] FOR INSERT
AS
BEGIN
     set nocount on
    insert into [dbo].[tblMain_Image]
           (Id,Name,userId,dflag)
    SELECT Id,Name,userId,0
    FROM inserted;
 
END
----------------------------------INSERT-----------------------------------


----------------------------------UPDATE---------------------------------
create trigger [dbo].[Triger_Update_tblMain] ON  [dbo].[tblMain] FOR UPDATE
AS
BEGIN
    set nocount on
    insert into [dbo].[tblMain_Image]
           (Id,Name,userId,dflag)
    SELECT Id,Name,userId,1
    FROM inserted;
 
END
---------------------------------UPDATE---------------------------------


---------------------------DELETE------------------------------------
create  trigger Triger_Delete_tblMain on  [dbo].[tblMain]
FOR DELETE
AS
begin
 set nocount on
     insert into [dbo].[tblMain_Image]
           (Id,Name,userId,dflag)
    SELECT Id,Name,userId,2
    FROM deleted;
end
---------------------------DELETE------------------------------------

Thursday 21 May 2015

SQL Setting Default value of Date and time in Table

create table Mst_Category
(
Cat_Auto bigint not null primary key identity(1,1),
Cat_Id varchar(20) not null,
Cat_Name varchar(100),
userId varchar(20),
dflag int,
Sys_Date datetime default getdate(),
sys_Time  time default CONVERT(time, GETDATE())
)


create table Mst_Category
(
Cat_Auto bigint not null primary key identity(1,1),
Cat_Id varchar(20) not null,
Cat_Name varchar(100),
userId varchar(20),
dflag int,
Sys_Date datetime default getdate(),
sys_Time  varchar(20) default RIGHT(CONVERT(CHAR(20), GETDATE(), 22), 11)--For AM and PM
)

Tuesday 19 May 2015

Data Annotations in entity framework

sql server Differnce between varchar and nvarchar

varchar DataType
-----------------------
Varchar means variable characters and it is used to store non-unicode characters. It will allocate the memory based on number characters inserted. Suppose if we declared varchar(50) it will allocates memory of 0 characters at the time of declaration. Once we declare varchar(50) and insert only 10 characters of word it will allocate memory for only 10 characters.

nvarchar DataType
----------------------
 nvarchar datatype same as varchar datatype but only difference nvarchar is used to store Unicode characters and it allows you to store multiple languages in database. nvarchar datatype will take twice as much space to store extended set of characters as required by other languages.

So if we are not using other languages then it’s better to use varchar datatype instead of nvarchar 

Wednesday 13 May 2015

Separate quey and parameters in sql sp_executesql


DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @IntVariable INT
DECLARE @Lastlname varchar(30)
SET @SQLString = N'SELECT @LastlnameOUT = max(lname)
                   FROM pubs.dbo.employee WHERE job_lvl = @level'
SET @ParmDefinition = N'@level tinyint,
                        @LastlnameOUT varchar(30) OUTPUT'
SET @IntVariable = 35
EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@level = @IntVariable,
@LastlnameOUT=@Lastlname OUTPUT
SELECT @Lastlname

sp_executesql having multiple parameters


create table   Students
 (
 StudentId int primary key not null
 ,StudentName varchar(200) not null  
  )
insert into Students(StudentId,StudentName)values(1,'Pabitra Behera')
insert into Students(StudentId,StudentName)values(2,'Pabitra')
insert into Students(StudentId,StudentName)values(3,'d')
insert into Students(StudentId,StudentName)values(1,'Pabitra')

DECLARE @ExecStr NVARCHAR(4000),@studentId int,@Name varchar(50) ;
set @studentId=1
set @Name='Pabitra Behera'
SELECT @ExecStr = 'SELECT * FROM dbo.Students where StudentId=1 and StudentId=@studentId and StudentName=@Name';
EXEC sp_executesql @ExecStr,N'@studentId int,@Name varchar(50)',@studentId,@Name

--------------------------------------------------------------------------------------

DECLARE @ExecStr NVARCHAR(4000),@studentId int,@Name varchar(50) ;
set @studentId=1
set @Name='Pabitra Behera'
SELECT @ExecStr = 'SELECT * FROM dbo.Students where StudentId=@studentId and StudentName=@Name';
EXEC sp_executesql @ExecStr,N'@studentId int,@Name varchar(50)',@studentId,@Name
--------------------------------------------------------------------------------------

sp_executesql in procedure with separate query,parameter

CREATE PROCEDURE Myproc-- 'pabitra','@parm1OUT',''
    @parm varchar(10),
    @parm1OUT varchar(30) OUTPUT,
    @parm2OUT varchar(30) OUTPUT
    AS
      SELECT @parm1OUT='parm 1' + @parm
     SELECT @parm2OUT='parm 2' + @parm
GO
DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @parmIN VARCHAR(10)
DECLARE @parmRET1 VARCHAR(30)
DECLARE @parmRET2 VARCHAR(30)
SET @parmIN=' returned'
SET @SQLString=N'EXEC Myproc @parm,
                             @parm1OUT OUTPUT, @parm2OUT OUTPUT'
SET @ParmDefinition=N'@parm varchar(10),
                      @parm1OUT varchar(30) OUTPUT,
                      @parm2OUT varchar(30) OUTPUT'

EXECUTE sp_executesql
    @SQLString,
    @ParmDefinition,
    @parm=@parmIN,
    @parm1OUT=@parmRET1 OUTPUT,@parm2OUT=@parmRET2 OUTPUT

SELECT @parmRET1 AS "parameter 1", @parmRET2 AS "parameter 2"
go
drop procedure Myproc

Alternative way for execute query like storeprocedure

 create table   Students
 (
 StudentId int primary key not null
 ,StudentName varchar(200) not null    
  )
insert into Students(StudentId,StudentName)values(1,'d')
               insert into Students(StudentId,StudentName)values(4,'Pabitra')
select * from Students

One parameter 

DECLARE @ExecStr NVARCHAR(4000);
SELECT @ExecStr = 'SELECT * FROM dbo.Students WHERE StudentName LIKE @StudentName';
EXEC sp_executesql @ExecStr, N'@StudentName varchar(15)', 'd';



More than one parameter 
DECLARE @ExecStr NVARCHAR(4000);
SELECT @ExecStr = 'SELECT * FROM dbo.Students WHERE StudentName LIKE @StudentName and StudentId LIKE @StudentId';
EXEC sp_executesql @ExecStr, N'@StudentName varchar(15),@StudentId int', 'd', 1;

Friday 8 May 2015

like operator in sql server 2008

 I want to search with Example : Pabitra Behera
-----------------------------------------------
Case 1: Search From Start
select * from Mst_Emp where Cat_Name like  'pabitra'+'%'--Result: Pabitra Behera
select * from Mst_Emp where Cat_Name like  'Behera'+'%'---Result: No Result
create Procedure Ret_EmployeeData
as begin
select * from Mst_Emp where Cat_Name like  'pabitra'+'%'
end
-----------------------

Case 1: Search From Any Position
select * from Mst_Emp where Cat_Name like  '%'+'pabitra'+'%'--Result :Pabitra Behera
select * from Mst_Emp where Cat_Name like  'Behera'+'%'--Result :Pabitra Behera
create Procedure Ret_EmployeeData
as begin
select * from Mst_Emp where Cat_Name like  '%'+'pabitra'+'%'--Result :Pabitra Behera
end

Thursday 30 April 2015

sql query export data from local database to online database

       IF NOT EXISTS(SELECT * FROM master.dbo.sysservers
        WHERE srvname='OnlineSqlServerName')
         BEGIN
            EXEC sp_addlinkedserver 'OnlineSqlServerName',N'Sql server'
         END
   EXEC sp_addlinkedsrvlogin 'OnlineSqlServerName','false','sa','OnlineSqlUser','onlineSqlPwd'
INSERT INTO [OnlineSqlServerName].OnlineDatabase.dbo.OnlineTable(column1,column2,column3,column4,column5,column6)
 SELECT column1,column2,column3,column4,column5,column6
 from [dbo].[LocalTable]

 Example:
 ---------------------
        IF NOT EXISTS(SELECT * FROM master.dbo.sysservers
        WHERE srvname='898.9.999.996')
         BEGIN
            EXEC sp_addlinkedserver '898.9.999.996',N'Sql server'
         END
   EXEC sp_addlinkedsrvlogin '898.9.999.996','false','sa','Retailuser','ms12345'


INSERT INTO [898.9.999.996].dbRetail.dbo.Mst_EmployeeMast(EmpName,Addresss,city,mob,dob,statuss)
 SELECT EmpName,Addresss,city,mob,dob,statuss
 from [dbo].[EMP] 

Saturday 25 April 2015

C# Random number

 protected void btnRandom_Click(object sender, EventArgs e)
    {
        Random Rnumber = new Random();
       // int x = Rnumber.Next(maxValue);
        int RandommaxValue = Rnumber.Next(99999999);
        //int RandomMaxMinValue = Rnumber.Next(MinVal, MaxVal);
        int RandomMaxMinValue = Rnumber.Next(0,99999999);
        Response.Write(RandommaxValue);
    }

c# Join and Split String

 string[] Arr = { "Microsoft", "IBM", "Oracle" };    
        // ... Join strings into a single string.
        string joinedString = string.Join("|", Arr);
        Response.Write("joined :"+"<br>");
        Response.Write(joinedString + "<br>");// Result Microsoft|IBM|Oracle
        Response.Write("Splits :" + "<br>");
        string[] SplitArr = joinedString.Split('|');
        Response.Write(SplitArr[0]);// Result Microsoft

c# Array last item,first Item index of

 string[] myarray = { "Pabi", "Pabitra", "Gitu", "Ram" };

               //Find First Element of an array
               //---------------------------------    
               Response.Write(myarray[0].ToString());
               // Last Element
               //-----------------
               int totalLength = myarray.Length;
               int LastItemIndex = totalLength - 1;
               Response.Write(myarray[LastItemIndex].ToString());

                 ////Index of an Array
                //-----------------
                //     Tips:
               //IndexOf methods return -1 when no element is found. This value often must be checked in an if-statement.
               int PositionOfIndex = Array.IndexOf(myarray, "Pabi");
               Response.Write(myarray[PositionOfIndex]);

Friday 24 April 2015

c# Array looping and array length

protected void btnArrayForloop_Click(object sender, EventArgs e)
    {
        string[] array = new string[3];
        array[0] = "Thanks";
        array[1] = "Pabitra";
        array[2] = "Behera";
        for (int i = 0; i < array.Length; i++)
        {
            // Get element by index.
            string element = array[i];
            Response.Write(element);
        }
        Console.WriteLine(); // Write blank line.
        foreach (string element in array)
        {
            // Cannot assign element in this loop.
            Response.Write(element);
        }

//Array Length
Response.Write(array [array .Length - 1]);
    }


Array Declaration in c#

///Array Declaration
        string[] array = new string[3];
        string[] array1 = new string[]{};
        string[] array13 = {};
        string[] arr = new string[]
   {
   "cat",
   "dog",
   "panther",
   "tiger"
};

Join in array element

   protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(string.Join(" ", Method()));
    }


static string[] Method()
    {
        string[] array = new string[3];
        array[0] = "THANK";
        array[1] = "YOU";
        array[2] = "Pabitra";
       // string[] array = {"THANK","YOU","Pabitra"};
       
        return array;
    }
  

What is var in c#

Var:The var type is an implicitly-typed local variable. It is the same to the compiler as an explicit string array.

Thursday 23 April 2015

execute dynamic sql command in sql server 2008

DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75),@G_Id int
DECLARE @city varchar(75)
SET @columnList = 'a.Id,a.Name,a.City,a.G_Id'
SET @city = '''bbsr'''
set @G_Id=1
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM mytable a
 WHERE a.City='+@city+'and a.G_Id='+convert(varchar,@G_Id)
 --print @sqlCommand
EXEC (@sqlCommand)

execute dynamic sql command in sql server 2008

DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75),@G_Id int
DECLARE @city varchar(75)
SET @columnList = 'a.Id,a.Name,a.City,a.G_Id'
SET @city = '''bbsr'''
set @G_Id=1
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM mytable a
 WHERE a.City='+@city+'and a.G_Id='+convert(varchar,@G_Id)
 --print @sqlCommand
EXEC (@sqlCommand)

Friday 17 April 2015

sql server procedure list on created date

SELECT name,create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,create_date, GETDATE()) < 500
order by create_date asc
-----------------------------------------------------



SELECT
    name,
    create_date,
    modify_date
FROM sys.procedures
order by create_date desc
or
SELECT
    name,
    create_date,
    modify_date
FROM sys.procedures
order by create_date asc









---------------------------
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,create_date, GETDATE()) < 30
---------------------
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < 7

--------------------------------------
SELECT name,create_date, modify_date
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,create_date, GETDATE()) < 30

Tuesday 14 April 2015

numeric validation in jquery textbox

Only number or validate text box which receive only number in javascript function


 <script type="text/javascript">
function isNumber(evt) {
            evt = (evt) ? evt : window.event;
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                return false;
            }
            return true;
        }
    </script>



For html input Control
-------------------------
<input type="text" id="txtEidNo" onkeypress="isNumber(event)" />



For ASPX TextBox Control
-------------------------
<asp:TextBox ID="txtEidNo" runat="server" onkeypress="return isNumber(event)"></asp:TextBox> 




In jquery 
----------------
For html input Control
------------------------------
<input type="text" id="txtEidNo" />

<script type="text/javascript">
        $(document).ready(function () {
            $("#txtEidNo").keydown(function (e) {
                if (e.shiftKey)
                    e.preventDefault();
                else {
                    var nKeyCode = e.keyCode;
                    //Ignore Backspace and Tab keys    
                    if (nKeyCode == 8 || nKeyCode == 9)
                        return;
                    if (nKeyCode < 95) {
                        if (nKeyCode < 48 || nKeyCode > 57)
                            e.preventDefault();
                    }
                    else {
                        if (nKeyCode < 96 || nKeyCode > 105)
                            e.preventDefault();
                    }
                }
            });
        });
    </script>




For ASPX TextBox Control
-------------------------
<asp:TextBox ID="txtEidNo" runat="server" ></asp:TextBox> 

<script type="text/javascript">
        $(document).ready(function () {
            $("#<%= txtEidNo.ClientID%>").keydown(function (e) {
                if (e.shiftKey)
                    e.preventDefault();
                else {
                    var nKeyCode = e.keyCode;
                    //Ignore Backspace and Tab keys      
                    if (nKeyCode == 8 || nKeyCode == 9)
                        return;
                    if (nKeyCode < 95) {
                        if (nKeyCode < 48 || nKeyCode > 57)
                            e.preventDefault();
                    }
                    else {
                        if (nKeyCode < 96 || nKeyCode > 105)
                            e.preventDefault();
                    }
                }
            });
        });
    </script>

Friday 20 March 2015

ScriptManager dynamically alert message

string msg="Hello Pabitra";
 string message = "alert('"+msg+"');";
                    ScriptManager.RegisterStartupScript(this, this.GetType(),"alert" + UniqueID, message, true);

Wednesday 18 March 2015

sorting in datatable

DataTable dtddlHotel=GetDataFromData();
 DataTable distinctTable = dtddlHotel.DefaultView.ToTable( /*distinct*/ true);

--------------------------------------
Or
------------
Example
----------
Table Emp Has One column Year and having Data
------------------
Year
------
2014
2015
2016



----------------------
DataTable dt = new DataTable();
       dt=getData("Select Year From emp");
        DataView dtview = new DataView(dt);
        dtview.Sort = "Year DESC";    
        dt = dtview.ToTable();
------------------------------------
Now In dt
contain
Result
---------------------
Year
--------
2016
2015
2014    
----------------------------------------
For Asending
-------------------
DataTable dt = new DataTable();
       dt=getData("Select Year From emp");
        DataView dtview = new DataView(dt);
        dtview.Sort = "Year ASC";    
        dt = dtview.ToTable();   

Tuesday 17 March 2015

Date Format in c#

public  DateTime GetBDFormatedDate(string _date)
        {
            CultureInfo provider = CultureInfo.InvariantCulture;
            string dateTime = _date;
            string[] formats = { "dd/MM/yyyy", "dd-MM-yyyy", "d/M/yyyy", "d.M.yyyy", "d-M-yyyy", "d M yyyy", "d/M/yy", "d.M.yy", "d-M-yy", "d M yy", "MM/dd/yyyy", "MM-dd-yyyy", "M/d/yyyy", "M.d.yyyy", "M-d-yyyy", "M-d-yyyy", "M/d/yy", "M.d.yy", "M-d-yy", "M d yy" };
            DateTime dtdateTime = DateTime.Now;
            try
            {
                dtdateTime = DateTime.ParseExact(dateTime, formats, provider, DateTimeStyles.AdjustToUniversal);
            }
            catch { }
            return dtdateTime;
        }

Monday 16 March 2015

foreach loop in Repeater control in asp.net

<asp:Repeater ID="rptr" runat="server">
                                                <ItemTemplate>
                                                    <div class="divclass" >
                                                      <a href="<%#Eval("link") %>" ><img src='<%#Eval("imgurl") %>'  /> </a>
                                                    </div>
                                               
                                                </ItemTemplate>
                                            </asp:Repeater>    



   foreach (RepeaterItem ri in rpt.Items)
        {
            LinkButton lnk = ri.FindControl("LinkButton1") as LinkButton;
            lnk.Text="Pabitra";
            lnk.ToolTip = "Pabitra";
        }

Saturday 14 February 2015

sql Procedure with ROLLBACK TRAN

Simply Copy and past it in ur Sql server and webform it will work
------------------------------------------------------------------

Write this code in Sql
--------------------------

CREATE TABLE tblEmp
(
em_Id int NOT NULL primary key,
em_Name varchar(200) NULL
)


---------------------------------------

CREATE PROCEDURE tblEmpInsert --1001,'pabitramicrosoftreasearch.blogspot.com'
    -- Add the parameters for the stored procedure here
@em_Id        int,
@em_Name      varchar(200)=NULL,
@msg      varchar(200)=NULL  output
AS
BEGIN --Starts begin
Declare  @errorDueto INT ---Declare For Error Checking
   
SET NOCOUNT ON;---Declare For not Count the rows affected
BEGIN TRAN Mytransatation --Mytransatation = Is likea Alias

    SET @errorDueto = 0 
    Insert into tblEmp(em_Id,em_Name) values(@em_Id,@em_Name)
   
   
     IF (@@ERROR <> 0)
     SET @errorDueto = 100
   
     IF (@@ERROR = 0)        
     SET @msg='Emplyee Save Successfully'
     ELSE  
     SET @msg=' faild due to '+@errorDueto



    IF(@errorDueto <> 0)
    BEGIN
    ROLLBACK TRAN Mytransatation
    RETURN @errorDueto
    END
    ELSE
    COMMIT TRAN Mytransatation
end ------end of begin
-----------------------------------------------

MyEmployee Design Page
---------------------------------------


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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.7.1.min.js"></script>
     <script type="text/javascript">
         function Validate() {
             if (!CheckValidate("<%=txtEmpID.ClientID %>", "Employee ID")) {
                document.getElementById("<%=txtEmpID.ClientID %>").style.backgroundColor = "red";
                return false;
            }
             if (!CheckValidate("<%=txtEmpName.ClientID %>", "Employee Name")) {
                document.getElementById("<%=txtEmpName.ClientID %>").style.backgroundColor = "red";
                return false;
            }

        }
    </script>
   <script type="text/javascript">
    function CheckValidate(ControlID, msg)
           {
               var  VarControlID = document.getElementById(ControlID);
               if (VarControlID.value == "")
                    {
                      alert(msg + ' cannot be  Blank!');
                      VarControlID.focus();
                      return false;
                    }
          return true;
        }
   </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        Employee ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; :&nbsp;
        <asp:TextBox ID="txtEmpID" runat="server"></asp:TextBox>
        <br />
        Employee Name&nbsp;&nbsp; :&nbsp;
        <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
        <br />
&nbsp;&nbsp;&nbsp;
        <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="btnSave" OnClientClick="return Validate();" runat="server" Text="Save" OnClick="btnSave_Click" />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
   
    </div>
    </form>
</body>
</html>
------------------------------------------------------------------------------------------
My Class file
-------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class EmployeeDtl : System.Web.UI.Page
{
    string SqlCon = "server=.;uid=sa;pwd=pabitramicrosoft;database=master";
     //or
   // string Sqlconn=System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString();
    SqlConnection con;
    SqlCommand cmd;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {

        try
        {
            string Message = "";
            con = new SqlConnection(SqlCon);
            cmd = new SqlCommand("tblEmpInsert", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@em_Id", Convert.ToInt32(txtEmpID.Text));
           // cmd.Parameters.AddWithValue("@em_Id", "qq");
            //cmd.Parameters.AddWithValue("@em_Id", "133.345");
            cmd.Parameters.AddWithValue("@em_Name", txtEmpName.Text);
            SqlParameter p = new SqlParameter("@msg", SqlDbType.VarChar, 8000);
            p.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(p);
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd.ExecuteNonQuery();
            Message = (string)cmd.Parameters["@msg"].Value;
            con.Close();
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + Message + "');", true);
        }
        catch (SqlException ex)
        {
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('"+ex.Message+"');", true);
        }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + ex.Message+ "');", true);
        }
    }
}
-------------------------------------------------------------------------------------------------------------------

Thursday 5 February 2015

split string assign in gridview

 protected void btnShow_Click(object sender, EventArgs e)
    {
        string value = "Pabitra,Pabitra2,Pabitra3,Pabitra4,Pabitra5";
       // using System.Text.RegularExpressions;
       // string[] lines = Regex.Split(value, ",");
        string[] lines = value.Split(',');
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        foreach (string line in lines)
        {
            DataRow dr = dt.NewRow();
            dr["Name"] = line;
            dt.Rows.Add(dr);
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

Monday 2 February 2015

how to find control in gridview rowcommand in asp.net c# ?

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Find"))
        {
           One Way(1)
          ----------
                     // int indexno = int.Parse(e.CommandArgument.ToString());
                     // GridViewRow row = GridView1.Rows[indexno ];
          One Way(2)
          ----------
            GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);                 Label SubCatID = (Label)row.FindControl("lblSubCatID");
            string Sub = SubCatID.Text;      
       
        }
    }    

Procedure Error Handleing

create proc MyProcedure
(
@Emp_Id int,
@Name nvarchar(50),
@Action varchar(3),
@message nvarchar(100) output
)
as
begin
 if(@Action='U')
 begin
  update tblEMP set E_name=@Name where Emp_Id=@Emp_Id  
 end    
 if(@@ERROR=0)
  set @message='Save successfully.'
 else
  set @message='Error in deletion.'
end  

Dialog box in C$ web app

using System.Windows.Forms;
--------------------------------------------
 int x=Insert(txtId.Text,txtName.Text);

if (MessageBox.Show(msg+"  Do you want Add another In The same species .. ?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                   
                }else

{

}

Saturday 31 January 2015

Alert Msg In C#

  string msg = InsertEmployee(1,txtName.Text);

 ScriptManager.RegisterStartupScript(this,this.GetType(),"", "alert('" + msg + "');window.location.href=('Default.aspx');", true);




ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Please Enter Data')", true);



----------------------
 Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Insufficient Access Previlage');window.location.href=('LogiPage.aspx');", true);

ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + msg + "');window.location.href='InsertPage.aspx';", true);
------------------------

 ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + msg + "');", true);     
                 //ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + msg + "');window.location.href=('Default.aspx');", true);     
                ScriptManager.RegisterStartupScript(this,this.GetType(),"","alert('ddddddddd');", true);  

Saturday 24 January 2015

Google Map Current Loacatation

Copy the Code And Past in Aspx Page and Run You Find the Current Locatation
------------------------------------------------------------------


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

<!DOCTYPE html>
<html>
    <head>
        <script src="http://maps.google.com/maps/api/js?sensor=false">
        </script>
        <script>
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showCurrentLocation);
            }
            else {
                alert("Geolocation API not supported.");
            }

            function showCurrentLocation(position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                var coords = new google.maps.LatLng(latitude, longitude);

                var mapOptions = {
                    zoom: 15,
                    center: coords,
                    mapTypeControl: true,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                //create the map, and place it in the HTML map div
                map = new google.maps.Map(
                document.getElementById("mapPlaceholder"), mapOptions
                );

                //place the initial marker
                var marker = new google.maps.Marker({
                    position: coords,
                    map: map,
                    title: "Current location!"
                });
            }
        </script>
    </head>
    <style>
    #mapPlaceholder {
        height: 400px;
        width: 700px;
    </style>
    <body>
        <div>
        <h2>HTML5 Show Location on GoogleMap Sample</h2>
        <div id="mapPlaceholder"></div>
        </div>
    </body>
</html>

Wednesday 21 January 2015

Split Sting

  string SplitString = "Hello Pabitra !123456! City IS :bhubaneswar";
        string Name = SplitString.Split('!')[1];
        string City = SplitString.Split(':')[1];
         Response.Write(Name);
         Response.Write(City);

Saturday 10 January 2015

Send Mail in c# through gmail

using System.Configuration;
using System.Net;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
----------------
 protected void btnSendMail1_Click(object sender, EventArgs e)
      {
          string ToWhomYouMail = "pabitrakiims@gmail.com";//Send to mail
          string Subject = "Test Mail";
          string mailbody = "<html><body><div>Dear Sir ,Good Morning</div></body></html>";
          bool m = send_mail(ToWhomYouMail, Subject, mailbody);
          if (m)
          {
              ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Mail Send Sucessfully !');", true);
          }
          else
          {
              ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('An Error Occurs !');", true);
          }
      }



 public bool send_mail(string ToMail,string subject,string body)
       {
           bool k = false;
           try
           {
               MailMessage msg = new MailMessage("pabitra.best28@gmail.com", ToMail);
               msg.To.Add(ToMail);
            msg.Subject = subject;
            msg.Body = body;
            msg.IsBodyHtml = true;
            AlternateView view;
            SmtpClient client;
            msg.IsBodyHtml = true;
            client = new SmtpClient();
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.Credentials = new System.Net.NetworkCredential("pabitra.best28@gmail.com", "password@123");
            client.EnableSsl = true; //Gmail works on Server Secured Layer
            client.Send(msg);
            k = true;
            //return k;
        }catch(Exception ex)
        {
            k = false;
        }
        return k;
     
    }

Friday 9 January 2015

Tuesday 6 January 2015

stored procedures in entity framework c#


CREATE TABLE [dbo].[Employees](
    [ID] [int] NULL,
    [Name] [varchar](100) NULL,
    [Gender] [varchar](20) NULL,
    [Salary] [int] NULL
)
insert into Employees(ID,Name,Gender,Salary)values(1,'Pabitra','Male',10000)
insert into Employees(ID,Name,Gender,Salary)values(2,'Geetanjali','Female',20000)
insert into Employees(ID,Name,Gender,Salary)values(3,'Manoranjan','Male',30000)
insert into Employees(ID,Name,Gender,Salary)values(4,'Prativa','Female',40000)
insert into Employees(ID,Name,Gender,Salary)values(5,'Aloka','Male',50000)
insert into Employees(ID,Name,Gender,Salary)values(6,'Ashrita','Female',60000)
insert into Employees(ID,Name,Gender,Salary)values(7,'Chintamani','Male',70000)
insert into Employees(ID,Name,Gender,Salary)values(8,'Nishi','Female',80000)
insert into Employees(ID,Name,Gender,Salary)values(9,'Nihar','Male',90000)
insert into Employees(ID,Name,Gender,Salary)values(10,'Pabitra','Male',100000)
insert into Employees(ID,Name,Gender,Salary)values(11,'Sankar','Male',110000)
insert into Employees(ID,Name,Gender,Salary)values(12,'Himashu','Male',110000)

Repeater Control In Asp.net

USE [DBPABITRA]
GO

/****** Object:  Table [dbo].[tbexecutive]    Script Date: 01/06/2015 17:47:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[tbexecutive](
[id] [varchar](10) NULL,
[workername] [varchar](50) NULL,
[currentadd] [varchar](50) NULL
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO


-------------------------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.Configuration;
using System.Data.SqlClient;
public partial class RepeatearControl : System.Web.UI.Page
{  
    SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=mypass;database=MyDB");
    protected void Page_Load(object sender, EventArgs e)
    {

        if (con.State == ConnectionState.Closed)
        {

            con.Open();

        }

        if (Page.IsPostBack == false)
        {

            Show_Data();

        }

    }

    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {

        if (e.CommandName == "edit")
        {

            ((Label)e.Item.FindControl("Label1")).Visible = false;

            ((Label)e.Item.FindControl("Label2")).Visible = false;

            ((TextBox)e.Item.FindControl("Textbox1")).Visible = true;

            ((TextBox)e.Item.FindControl("Textbox2")).Visible = true;

            ((LinkButton)e.Item.FindControl("LinkEdit")).Visible = false;

            ((LinkButton)e.Item.FindControl("LinkDelete")).Visible = false;

            ((LinkButton)e.Item.FindControl("LinkUpdate")).Visible = true;

            ((LinkButton)e.Item.FindControl("Linkcancel")).Visible = true;

        } if (e.CommandName == "delete")
        {

            SqlCommand cmd = new SqlCommand("delete from tbexecutive where id=@id", con);

            cmd.Parameters.AddWithValue("@id", e.CommandArgument);

            cmd.ExecuteNonQuery();

            cmd.Dispose();

            Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "");

            Show_Data();

        }

        if (e.CommandName == "update")
        {

            string str1 = ((TextBox)e.Item.FindControl("TextBox1")).Text;

            string str2 = ((TextBox)e.Item.FindControl("TextBox2")).Text;

            SqlDataAdapter adp = new SqlDataAdapter("update tbexecutive set workername=@workername, currentadd=@add where id=@id", con);

            adp.SelectCommand.Parameters.AddWithValue("@workername", str1);

            adp.SelectCommand.Parameters.AddWithValue("@add", str2);

            adp.SelectCommand.Parameters.AddWithValue("@id", e.CommandArgument);

            DataSet ds = new DataSet();

            adp.Fill(ds);

            Show_Data();

            Page.ClientScript.RegisterStartupScript(this.GetType(), "ch", "");

        } if (e.CommandName == "cancel")
        {

            ((Label)e.Item.FindControl("Label1")).Visible = true;

            ((Label)e.Item.FindControl("Label2")).Visible = true;

            ((TextBox)e.Item.FindControl("TextBox1")).Visible = false;

            ((TextBox)e.Item.FindControl("TextBox2")).Visible = false;

            ((LinkButton)e.Item.FindControl("LinkEdit")).Visible = true;

            ((LinkButton)e.Item.FindControl("LinkDelete")).Visible = true;

            ((LinkButton)e.Item.FindControl("LinkUpdate")).Visible = false;

            ((LinkButton)e.Item.FindControl("Linkcancel")).Visible = false;

        }



    }

    public void Show_Data()
    {

        SqlDataAdapter adp = new SqlDataAdapter("select * from tbexecutive ORDER BY workername ASC", con);

        DataSet ds = new DataSet();

        adp.Fill(ds);

        Repeater1.DataSource = ds;

        Repeater1.DataBind();

    }

}

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


<!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 id = "Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form2" runat="server">
    <div>
   
        <asp:Repeater ID="Repeater1" runat="server"
            onitemcommand="Repeater1_ItemCommand">
            <HeaderTemplate>
           

          <table width="350"><tr
bgcolor="#FF6600"><td>Name</td><td>Address</td><td>Action</td></tr></HeaderTemplate>

           <ItemTemplate><tr><td> <asp:Label
ID="Label1" runat="server" Text='<%#Eval("workername")
%>'></asp:Label>

      <asp:TextBox ID="TextBox1" runat="server"
Text='<%#Eval("workername") %>'
Visible="false"></asp:TextBox>
        </td>
        <td>
        <asp:Label ID="Label2" runat="server" Text='<%#Eval("currentadd") %>'></asp:Label>

      <asp:TextBox ID="TextBox2" runat="server"
Text='<%#Eval("currentadd") %>'
Visible="false"></asp:TextBox>
        </td>
         <td>

      <asp:LinkButton ID="LinkEdit" runat="server"
CommandArgument='<%#Eval("id") %>'
CommandName="edit">Edit</asp:LinkButton>

          <asp:LinkButton ID="LinkDelete" runat="server"
CommandArgument='<%#Eval("id") %>'
CommandName="delete">Delete</asp:LinkButton>

          <asp:LinkButton ID="LinkUpdate" runat="server"
CommandArgument='<%#Eval("id") %>' CommandName="update"
Visible="false">Update</asp:LinkButton>

          <asp:LinkButton ID="Linkcancel" runat="server"
CommandArgument='<%#Eval("id") %>' CommandName="cancel"
Visible="false">Cancel</asp:LinkButton>
            </td>
        </tr>
           
     
       
        </ItemTemplate>
        </asp:Repeater>
   
    </div>
    </form>
</body>
</html>
---------------------------

Monday 5 January 2015

Random Number in Sql Server

Random Number in Sql Server
--------------------------

declare  @RandomNumber bigint
SELECT  @RandomNumber= CAST(RAND() *

100000000 AS bigint)
print @RandomNumber

IUD IN EntityFramework

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;
using System.Data.SqlClient;
namespace DemoEntityFrameWork
{
    public partial class Default2 : System.Web.UI.Page
    {
        DBPABITRAEntities dbcontext = new DBPABITRAEntities();
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
        TBL_EMP_ENTITY ob = new TBL_EMP_ENTITY();

        try
        {
            ob.EM_ID = int.Parse(TextBox1.Text);
            ob.EM_NAME = TextBox2.Text;
            ob.EM_STATUS = "1";
            dbcontext.TBL_EMP_ENTITY.Add(ob);
            dbcontext.SaveChanges();
            TextBox1.Text = "";
            TextBox2.Text = "";
            Response.Write("<script>alert('Save Sucessfully !');</script>");
        }catch(SqlException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
     
   

           
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            DBPABITRAEntities db = new DBPABITRAEntities();
            int ID=Convert.ToInt32(TextBox1.Text);
            var empQuery = from emp in db.TBL_EMP_ENTITY
                           where emp.EM_ID == ID
                           select emp;
            TBL_EMP_ENTITY ob = empQuery.Single();
            ob.EM_ID = int.Parse(TextBox1.Text);
            ob.EM_NAME = TextBox2.Text;
            ob.EM_STATUS = "1";          
          int x=  db.SaveChanges();
          Response.Write(x.ToString()+"Record Will be Updated......");
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DBPABITRAEntities db = new DBPABITRAEntities();
            int ID = Convert.ToInt32(TextBox1.Text);
            //create a new object using the value of EmpId
            TBL_EMP_ENTITY objEmp = new TBL_EMP_ENTITY() { EM_ID = ID };

            //attach and delete object
            db.TBL_EMP_ENTITY.Attach(objEmp);
           
            //db.TBL_EMP_ENTITYS.DeleteObject(objEmp);

            //save changes
            db.SaveChanges();
        }
    }
}

Encryption of procedure in sql server

create PROCEDURE MyProcedure WITH ENCRYPTION AS
BEGIN
 PRINT 'This text is going to be decrypted'
END