Wednesday, 21 December 2011

How to execute DDL command through ADO.Net ?

SqlConnection mySqlConnection = new SqlConnection("Data Source = LocalServer;Initial Catalog=dbAccount;Integrated Security=True;");

SqlCommand mySqlCommand = mySqlConnection.CreateCommand();

mySqlCommand.CommandText = "CREATE TABLE MyEmployee (ID int CONSTRAINT PK_Persons PRIMARY KEY, FirstName nvarchar(15) NOT NULL, LastName nvarchar(15) NOT NULL, DateOfBirth datetime )";

mySqlConnection.Open();

int result = mySqlCommand.ExecuteNonQuery();
        
mySqlConnection.Close();

How do I split a string by a multi-character delimiter in C# ?

string myString = "This is a new sentence.";
string[] _res = myString
.Split(new string[]{ "is" }, StringSplitOptions.None);
for(int i=0; i<_res.length; i++)
    Console.Write(_res[i]);

Tuesday, 20 December 2011

Difference between Repeater, Datalist, GridView

Repeater:
It contains Header Template, Item template , alternate
Item template and footer template. it can't support
Selection, editing, sorting and paging. this is read only
and fast.

Datalist:
It contains Header Template, Item template , alternate
Item template , Edit item template and footer template. it
can't support sorting and paging but support selection and
editing

GridView:
It contains Header Template, Item template , alternate Item
template , Edit item template and footer template. it can
support selection, editing , sorting and paging. Mostly
every developer caught used this control.

                          Repeater  DataList  GridView  ListView
Flow layout         Yes            Yes            No           Yes
Table layout        No             No            Yes           No
Style propertie    No            Yes            Yes           Yes
Column layout     No            Yes            No           No
Paging                  No             No            Yes          Yes
Sorting                 No            No            Yes           Yes
Edit/Delete          No            No            Yes           Yes
Insert                   No            No            No           Yes
Grouping             No           Yes             No            Yes

Friday, 16 December 2011

Why JSON ?

(1) Because JSON is easy to write. It is just like creating and accessing class in javascript in object notation
(2) If you like Generic Class, you will fall in love with JSON.
(3) JSON is just key : value pairs assigned within an object.
(4) JSON is very fast.
(5) It is easy to understand and can be integrated in any web application very easily.
(6) Better organized data if prepared in well mannered way.
(7) On the server-side you can easily serialize/deserialize your objects to/from JSON.
(8) Almost every browser is giving support for JSON.

What is JSON ?

JSON stands for JavaScript Object Notation that is a language independent text format which is fast and easy to understand.On the server-side you can easily serialize/deserialize your objects to/from JSON.JSON (Java Script Object Notation) provides a simple data format for the exchange of information between the browser and server. In other words JSON is light weight data-interchange format.
An object described in JSON consists of a set of curly braces {} enclosing a set of attribute-value pairs.
For example:
{"movielist": ["Friday the 13th", "Friday the 13th Part 2", "Friday the 13th Part III", "Friday the 13th: The Final Chapter", "Friday the 13th: A New Beginning"]}

Thursday, 15 December 2011

Bulk insert excel to sql ?

sp_configure 'show advanced options' , 1
RECONFIGURE;
Go
sp_configure 'Ad Hoc Distributed Queries' , 1
RECONFIGURE;
GO

SELECT * INTO ItemTemp FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=D:\StudentDetails.xls', [Sheet1$])

Monday, 12 December 2011

How to access ServerSide method from GridView's ItemTemplate

While working with GridView, there may be a case where 
we actually need to do some operations in serverside for 
which we may be in a need to call a server side
method from ItemTemplate of a GridView.

Say for example, 
I had a situation where i need to call a server side 
method (which return a string value) from ItemTemplate.
So i used a label in the ItemTemplate like 


<asp:TemplateField HeaderText="Testing">
<ItemTemplate>
<asp:Label ID="lblCustomerAge" Text='<%# GetCategory() %>' runat="server">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>

Here GetCategory is the server side method.Code-behind is given below

  protected string GetCategory()
    {
       // Do whatever you want here
        return "TestCategory"; // For eg. passing a string
    }

How to open a pop up window with specified location through Javascript

Below is the javascript method that opens a popup with specific height,width,location etc

function openQuadPopup(val) {           
            var width = screen.width - 100;
            var height = screen.height - 100;
            var leftPos = (screen.width - width - 30) / 2;
            var topPos = (screen.height - height - 30) / 2;
            myWindow = window.open('TestPage.aspx?QueryStringValue=' + val, 'NameForPopup', 'menubar=0,resizable=0,width=' + width + ',height=' + height + "'");

            myWindow.moveTo(leftPos, topPos);          
        }

Sunday, 20 November 2011

Difference between Session object and Application object in asp.Net

Session variables are used to store user specific information where as in application variables we can't store user specific information.

Default lifetime of the session variable is 20 mins and based on the requirement we can change it.Application variables are accessible till the application ends.

sessions allows information to be stored in one page and accessed in another,and it supports any type of object, including your own custom data types. Application state allows you to store global objects that can be accessed by any client.

The common thing between session and application is both support the same type of objects,retain information on the server, and uses the same dictionary -based syntax.

Tuesday, 15 November 2011

What methods are fired during the page load?

Init() - when the page is instantiated
Load() - when the page is loaded into server memory
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.

difference between Inline and Codebehind code in asp.net ?

Inline Code is mixing client and serverside code on the same page like HTML and JavaScript. So precompilation is no need.
CodeBehind .aspx separately only for serverside code. So it provides good performance than inline code. Why because CodeBehind needs to be compile in advance.

Wednesday, 9 November 2011

Google API to get distance between two cities.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Maps JavaScript API Example: Extraction of Geocoding Data</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
<!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html -->
    <script type="text/javascript">

    var geocoder, location1, location2;
    function initialize() {
        geocoder = new GClientGeocoder();
    }

    function showLocation() {
        geocoder.getLocations(document.forms[0].address1.value, function (response) {
            if (!response || response.Status.code != 200)
            {
                alert("Sorry, we were unable to geocode the first address");
            }
            else
            {
                location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                geocoder.getLocations(document.forms[0].address2.value, function (response) {
                    if (!response || response.Status.code != 200)
                    {
                        alert("Sorry, we were unable to geocode the second address");
                    }
                    else
                    {
                        location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                        calculateDistance();
                    }
                });
            }
        });
    }

    function calculateDistance()
    {
        try
        {
            var glatlng1 = new GLatLng(location1.lat, location1.lon);
            var glatlng2 = new GLatLng(location2.lat, location2.lon);
            var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
            var kmdistance = (miledistance * 1.609344).toFixed(1);

            document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + '<br /><strong>Address 2: </strong>' + location2.address + '<br /><strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
            //document.getElementById('results').innerHTML = '<strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
        }
        catch (error)
        {
            alert(error);
        }
    }

    </script>
  </head>

  <body onload="initialize()">

    <form action="#" onsubmit="showLocation(); return false;">
      <p>
        <input type="text" name="address1" value="Address 1" class="address_input" size="40" />
        <input type="text" name="address2" value="Address 2" class="address_input" size="40" />
        <input type="submit" name="find" value="Search" />
      </p>
    </form>
    <p id="results"></p>

  </body>
</html>

Saturday, 5 November 2011

How to zoom In and zoom Out image in asp.net through javascript

ASPX Code : 
 <div>
    <img border="0" src="img1.jpg" width="100"height="100"
    onmouseover="zoom('247px','268px','296px','336px',this);"
    onmouseout="zoom('47px','68px','47px','68px',this);" />
    </div>
JavaScript Java :
   <script language="javascript" type="text/javascript" >
    var nW,nH,oH,oW;
    function zoom(iWideSmall,iHighSmall,iWideLarge,iHighLarge,whichImage)
    {   
        oW=whichImage.style.width;
        oH=whichImage.style.height;   
        if((oW==iWideLarge)||(oH==iHighLarge))   
        {
            nW=iWideSmall;
            nH=iHighSmall;
        }
        else
        {
            nW=iWideLarge;
            nH=iHighLarge;
        }
        whichImage.style.width=nW;
        whichImage.style.height=nH;
    }
  </script>

Tuesday, 4 October 2011

What is the difference between select count(*) and select count(any_column)?

  • COUNT(*) will include NULLS
  • COUNT(column_name) will not include NULLS.
Example :
create table myTable (id int,name nvarchar(100))
insert into myTable values(1,null)
insert into myTable values(null,'Hello')
insert into myTable values(null,null)

select COUNT(*) from myTable
Result : 3
select COUNT(name) from myTable
Result : 1

Sunday, 2 October 2011

Rename the Table/View/SP in SQL Server

sp_rename is used to rename the sql objects.
Syntax :
sp_rename 'Old Object Name','New Object Name'

sp_rename automatically renames the associated index whenever a PRIMARY KEY or UNIQUE constraint is renamed. If a renamed index is tied to a PRIMARY KEY constraint, the primary key is also automatically renamed by sp_rename.

Renaming a stored procedure, view or trigger will not change the name of the corresponding object name in the syscomments table. This may result in problems generating a script for the object as the old name will be inserted from the syscomments table into the CREATE statement. For best results, do not rename these object types. Instead, drop and re-create the object by its new name.
Note : sp_rename is not check  the object dependency.

Friday, 30 September 2011

Maximum Capacity Specifications for SQL Server

                        SQL Server (32/64-bit)
Nested stored procedure levels 32
Nested subqueries 32
Nested trigger levels 32
Nonclustered indexes per table 999
Parameters per stored procedure 2100
Parameters per user-defined function 2100
REFERENCES per table 253
User connections 32767
XML indexes 249
Rows per table Limited by available storage
Column in table 1024

How many ways are there to implement locking in ADO.NET?

Following are the ways to implement locking using ADO.NET:-
  • When we call “Update” method of Data Adapter it handles locking internally. If the Dataset values are not matching with current data in Database, it raises concurrency exception error. We can easily trap this error using Try. Catch block and raise appropriate error message to the user.
  • Define a Date time stamp field in the table. When actually you are firing the UPDATE SQL statements, compare the current timestamp with one existing in the database.
  • Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old data is same as the current data.

Wednesday, 14 September 2011

How to Programmatically add JavaScript File to Asp.Net page?

If you do not want to add your JavaScript files declaratively via HTML to your ASP.Net page, you can do it in code, and here is how:
Just add this code to the Page_Init event handler on your page:

    protected void Page_Init(object sender, EventArgs e)
    {
        HtmlGenericControl js = new HtmlGenericControl("script");
        js.Attributes["type"] = "text/javascript";
        js.Attributes["src"] = "jscript/formfunctions.js";
        Page.Header.Controls.Add(js);
    }

How do I dynamically add CSS file for ASP.NET ASPX page?

To add CSS Stylesheeet file programatically to ASPX page we can use .NET HtmlLink class in the Page_Init event handler:

protected void Page_Init(object sender, EventArgs e)
  {
    // Define an HtmlLink control.
    HtmlLink myHtmlLink = new HtmlLink();
    myHtmlLink.Href = "~/StyleSheet.css";
    myHtmlLink.Attributes.Add("rel", "stylesheet");
    myHtmlLink.Attributes.Add("type", "text/css");

    // Add the HtmlLink to the Head section of the page.
    Page.Header.Controls.Add(myHtmlLink);
  }

How to maintain ScrollBar position on postbacks in ASP.NET Page?

If your pages are high/long and controls that cause postback are placed on the bottom it can be really annoying for users to manually scroll down after every postback.
<%@ Page Language="C#" AutoEventWireup="true" MaintainScrollPositionOnPostback="true" %>
// or (on page load)
 Page.MaintainScrollPositionOnPostBack = true;
After the postback and reload of the page, the previous scroll position will be restored.

How to get the selected item from UL using jQuery?

<script src="jquery-1.6.2.js" type="text/javascript"></script>
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $('#myUl li').click(function () {
                $('#myUl li').removeClass('selected');
                $(this).addClass('selected');
            });
        });
    </script>
    <style type="text/css">
        .selected
        {
            color: red;
            background-color:Yellow;
            width:100px;
        }
    </style>
 <div>
    <h1>College Courses</h1>
        <ul id="myUl">
            <li>BASIC</li>
            <li>PGDCA</li>
            <li>MBA</li>
            <li>MCA</li>
            <li>B-TECH</li>
            <li>M-TECH</li>
        </ul>
    </div>

Why using "Document Ready Function" with jQuery functions ?

$(document).ready(function(){
   // jQuery functions go here...
});
This is to prevent any jQuery code when form/document is not completed loading.

jQuery Syntax

Basic syntax is: $(selector).action()
   * A dollar sign to define jQuery
   * A (selector) to find HTML elements
   * A jQuery action() to be performed on the element(s)

Tuesday, 13 September 2011

How to call Webmethod using Javascript and JQuery in asp.net ?


//-- .Aspx Code
 <script src="jquery-1.6.2.js" type="text/javascript"></script>
 //---- Using Javascript -----
    <script type="text/javascript">
        function myServiceFun() {
            PageMethods.myWebMethods(webMethodSuccess, webMethodFail);
        }
        function webMethodSuccess(name) {
            alert(name);
        }
        function webMethodFail(myError) {
            alert(myError);
        }
    </script>
 //---- Using JQuery ----
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnJQuery").click(function () {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/myWebMethods",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        AjaxSucceeded(msg);
                    },
                    error: AjaxFailed
                });
            });
        });

        function AjaxSucceeded(result) {
            if (result.d == true)
                alert(result.d);
            else
                alert(result.d);
        }

        function AjaxFailed(result) {
            alert(result.status + ' ' + result.statusText);
        }   
    </script>

   <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <input id="btnJS" type="button" value="JS-WebMethod" onclick="myServiceFun();" />
    <input id="btnJQuery" type="button" value="JQuery-WebMethod" />

//--- .cs code

 [WebMethod]
    public static string myWebMethods()
    {
        string str = "";
        SqlConnection con = new SqlConnection("Data Source=MyserverName;Initial Catalog=DBName;User  ID=Rajesh;Password=Rolen");
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter adp = new SqlDataAdapter();
        con.Open();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        DataTable dt = new DataTable();
        cmd.CommandText = "select * from student order by NewId()";
        adp.SelectCommand = cmd;
        adp.Fill(dt);
        cmd.ExecuteNonQuery();
        str = dt.Rows[1]["stuname"].ToString();
        con.Close();
        return str;
    }

Note : If have any problem then set blow tag in web.config

<httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </httpModules>

Friday, 2 September 2011

Distinct with Row_number() in sql

create table StudentAttendance(AttendId int,AttendDate datetime,BatchName nvarchar(50),FacultyName nvarchar(50))
insert into StudentAttendance values(1,'08/03/2011','DotNet Batch','Rajesh Rolen')
insert into StudentAttendance values(2,'09/03/2011','DotNet Batch','Rajesh Rolen')
insert into StudentAttendance values(3,'10/03/2011','DotNet Batch','Rajesh Rolen')

create table StudentAttendanceTrans(AttTransId int,AttendId int,StudentId int)
insert into  StudentAttendanceTrans values (1,1,1001)
insert into  StudentAttendanceTrans values (2,1,1002)
insert into  StudentAttendanceTrans values (3,1,1003)
insert into  StudentAttendanceTrans values (4,2,1001)
insert into  StudentAttendanceTrans values (5,2,1002)
insert into  StudentAttendanceTrans values (6,2,1003)
insert into  StudentAttendanceTrans values (7,3,1001)
insert into  StudentAttendanceTrans values (8,3,1002)
insert into  StudentAttendanceTrans values (9,3,1003)

select distinct row_number() over(order by P.AttendDate )as Sno,
    P.AttendId,P.AttendDate,P.BatchName,P.FacultyName from StudentAttendance P
    inner join StudentAttendanceTrans T on T.AttendId = P.AttendId
SNo Id   Date              BatchName      Faculty Name
1      1    2011-08-03    DotNet Batch    Rajesh Rolen
2      1    2011-08-03    DotNet Batch    Rajesh Rolen
3      1    2011-08-03    DotNet Batch    Rajesh Rolen
4      2    2011-09-03    DotNet Batch    Rajesh Rolen
5      2    2011-09-03    DotNet Batch    Rajesh Rolen
6      2    2011-09-03    DotNet Batch    Rajesh Rolen
7      3    2011-10-03    DotNet Batch    Rajesh Rolen
8      3    2011-10-03    DotNet Batch    Rajesh Rolen
9      3    2011-10-03    DotNet Batch    Rajesh Rolen
Note : here distinct is not working fine.

select distinct row_number() over(order by P.AttendDate )as Sno,
    P.AttendId,P.AttendDate,P.BatchName,P.FacultyName from StudentAttendance P
    inner join StudentAttendanceTrans T on T.AttendId = P.AttendId
    group by P.AttendId,P.AttendDate,P.BatchName,P.FacultyName
SNo Id   Date              BatchName      Faculty Name

1      1    2011-08-03    DotNet Batch    Rajesh Rolen
2      2    2011-09-03    DotNet Batch    Rajesh Rolen
3      3    2011-10-03    DotNet Batch    Rajesh Rolen
Note : here distinct is working fine.

Get record in random order ?

You can get table records randomly with the help of NEWID() function.
NEWID() is a built-in function which returns unique identifier.
Syntax:
select * from TblStudent Order by NEWID()

Bulk insert in sql using C#.Net ?

// Create table in sql
            CREATE TABLE Student(
          StuId int,
          StuName nvarchar(50),
          StuEmail nvarchar(100),
          StuAdd nvarchar(100),
          StuMobile nvarchar(50))
// Implement in C#.Net
using System.IO;
using System.Data.SqlClient;
using System.Configuration;

 private void bulkInser_InSql()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("Name");
            dt.Columns.Add("Email");
            dt.Columns.Add("Add");
            dt.Columns.Add("Mobile");

            dt.Rows.Add(1, "Amit", "Amit@yahoo.com", "Jodhpur", "98979843534");
            dt.Rows.Add(2, "Ashok", "Ashok@yahoo.com", "Jaipur", "097895674745");
            dt.Rows.Add(3, "Vijay", "Vijay@yahoo.com", "Udaipur", "96784565654");
            dt.Rows.Add(4, "Dinesh", "Dinesh@yahoo.com", "Raj", "978657657");
            dt.Rows.Add(5, "Hunny", "Hunny@yahoo.com", "Jodhana", "84556756456");

            using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString()))
            {
                cn.Open();
                using (SqlBulkCopy copy = new SqlBulkCopy(cn))
                {
                    copy.ColumnMappings.Add(0, 0);
                    copy.ColumnMappings.Add(1, 1);
                    copy.ColumnMappings.Add(2, 2);
                    copy.ColumnMappings.Add(3, 3);
                    copy.ColumnMappings.Add(4, 4);

                    copy.DestinationTableName = "Student";
                    copy.WriteToServer(dt);
                }
            }
        }

SqlBulkCopy uses ADO.NET to connect to a database to bulk load the data. I have created an SqlConnection object, and that object reference is used to create the SqlBulkCopy object. The DestinationTableName property references a table in the database where the data is to be loaded. A handy feature of SqlBulkCopy is the SqlBulkCopyColumnMappingCollection. Column mappings define the relationships between columns in the data source and columns in the destination. This is handy if the data source file has columns that don’t need to be inserted into the database. Column mappings can be set by an index, such as the example above, or they can be set by the name of the column. Using the index is handy when you’re working with files that contain no column names. Finally the data is sent to the database by running the WriteToServer method.

Prevent the Back option after Log Out:

Step 1 In the Page_Load event of your master page: 
protected void Page_Load(object sender, EventArgs e)
 {
   if(!IsPostBack)
   {
    if (Session["LoginId"] == null)
      Response.Redirect("frmLogin.aspx");
    else
    {
      Response.ClearHeaders();
      Response.AddHeader("Cache-Control", "no-cache, no-store,
      max-age=0, must-revalidate");
      Response.AddHeader("Pragma", "no-cache");
    }
  }
}
 
Step 2 Do clear the session on the Logout button as:
Session.Abandon();
 Session.Clear(); 
 
Step 3 
<script language="text/javascript">
function back()
{
 windows.history.forward(1);
}
</script>
<body onload="back()">
 

how to add videos in your application using HTML5 ?

<body>
<video controls="controls" >
  <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"
  type="video/mp4" /><!-- Safari / iOS, IE9 -->
  <source src="http://clips.vorwaerts-gmbh.de/VfE.webm"
  type="video/webm" /><!-- Chrome10+, Ffx4+, Opera10.6+ -->
  <source src="http://clips.vorwaerts-gmbh.de/VfE.ogv"
  type="video/ogg"  /><!-- Firefox3.6+ / Opera 10.5+ -->
</video>
</body>

Scrollbar in gridview ?

<div style="OVERFLOW: auto; WIDTH: 800px; HEIGHT: 240px">
       Gidview
</div>

Found interesting? Add this to

Tuesday, 30 August 2011

How to find second maximum value from a table?

1. select * from myTable WHERE myId = (SELECT  MAX(myId-1) FROM myTable)
2. select  MAX(myId-1) from myTable
3. select * from myTable where myId=(select max(myId) from myTable where myId<(select max(myId)
    from myTable))

Tuesday, 23 August 2011

The jQuery html() method works for both HTML and XML documents?

No ! It only works for HTML.

What are jQuery Selectors?

Selectors are used in jQuery to find out DOM elements. Selectors can find the elements via ID, CSS, Element name and hierarchical position of the element.

Why jQuery?

There are many following functionality.
       1. Cross-browser support (IE, Safari, Opera,Chrome,Firefox)
       2. AJAX functions
       3. CSS functions
       4. DOM manipulation
       5. DOM transversal
       6. Attribute manipulation
       7. Event detection and handling
       8. JavaScript animation
       9. Hundreds of plug-ins for pre-built user interfaces, advanced animations, form validation etc.
       10. Expandable functionality using custom plug-ins

What is jQuery?

JQuery is Lightweight and CrossBrowser JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. The biggest advantage over Javascript is that it reduces lines of code as huge code written in JavaScript, can be done easily acheived with jQuery in few lines.

Saturday, 20 August 2011

How to create csv file in dot Net ?

 string filename = "";
            //----------------- File Name ----------
            string Day = DateTime.Now.Day.ToString();
            string Month = DateTime.Now.ToString("MMM");
            string Year = DateTime.Now.Year.ToString();
            string Hour = DateTime.Now.Hour.ToString();
            string Minute = DateTime.Now.Minute.ToString();
            string Second = DateTime.Now.Second.ToString();
            string strName = Day + "_" + Month + "_" + Year + "__" + Hour + "_" + Minute + "_" + Second + ".xls";
            filename = Server.MapPath("~/XLSFiles/" + strName);
            Session["AttachedFileName"] = filename;
            //--------------------------------------
            try
            {
                string sTableStart = @"<HTML><BODY><TABLE Border=1>";
                string sTableEnd = @"</TABLE></BODY></HTML>";
                StringBuilder sTableData = new StringBuilder();
                //----XLS Column Headings---------
                string sTHead = "<TR>";
                sTHead += @"<TH>S.No</TH>";
                sTHead += @"<TH>Name</TH>";
                sTHead += @"<TH>DOB</TH>";
                sTHead += @"<TH>App.Date</TH>";
                sTHead += @"<TH>Type</TH>";
                sTHead += @"<TH>Status</TH>";
                sTHead += @"</TR>";
                //------------- XLS Row asign ---------
                int SNOCounter = 1;
                string[] outerArray = hiddenIGAppointmentValuePair.Value.Split(':');
                for (int j = 0; j < gridAppointments.Rows.Count; j++)
                {
                    string[] innerArray = outerArray[j].Split(';');
                    if (innerArray[1].ToString() == "1")
                    {
                        sTableData.Append(@"<TR>");
                        sTableData.Append(@"<TD>" + SNOCounter.ToString() + @"</TD>"); // SNo
                        sTableData.Append(@"<TD>" + gridAppointments.Rows[j].Items[3].Text + @"</TD>"); // Name
                        sTableData.Append(@"<TD>" + gridAppointments.Rows[j].Items[4].Text + @"</TD>"); // DOB
                        sTableData.Append(@"<TD>" + gridAppointments.Rows[j].Items[5].Text + @"</TD>"); // AppDate
                        sTableData.Append(@"<TD>" + gridAppointments.Rows[j].Items[6].Text + @"</TD>"); // Type
                        sTableData.Append(@"<TD>" + gridAppointments.Rows[j].Items[7].Text + @"</TD>"); // Status
                        sTableData.Append(@"</TR>");
                        SNOCounter += 1;
                    }
                }
                //-------------------------------------
                string sTable = sTableStart + sTHead + sTableData.ToString() + sTableEnd;
                System.IO.StreamWriter oExcelWriter = System.IO.File.CreateText(filename);
                oExcelWriter.WriteLine(sTable);
                oExcelWriter.Close();
            }
            catch
            {
            }

Friday, 19 August 2011

How to disable/enable all constraints and triggers for database?

To disable all constraints and triggers:
sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
sp_msforeachtable 'ALTER TABLE ? DISABLE TRIGGER  all'
To enable all constraints and triggers:
exec sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'
sp_msforeachtable
'ALTER TABLE ? ENABLE TRIGGER  all'


Wednesday, 27 July 2011

Monday, 25 July 2011

Threads

Thread th = new Thread(Fill_IgGrid);
th.Priority = ThreadPriority.Normal;
th.IsBackground = true;

th.Start(_List); //object of the parameter (_Generic List)
or
th.Start(); // non of parameter

private void Fill_IgGrid()
{
 //------- Grid bind code
}

Saturday, 23 July 2011

What is the purpose of XML Namespaces?

An XML Namespace is collection of element types and attribute names. It consists of two parts :

1) The first part is the URI used to identify the namespace
2) The second part is the element type or attribute name itself.


The various purpose of XML Namespace are
1. Combine fragments from different documents without any naming conflicts.
2. Write reusable code modules that can be invoked for specific elements and attributes. Universally unique names guarantee that
such modules are invoked only for the correct elements and attributes.
3. Define elements and attributes that can be reused in other schemas or instance documents without fear of name collisions.
 

Friday, 22 July 2011

Can you encrypt view state data of an aspx page?

Yes, you encrypt view state data of an aspx page by setting the page's ViewStateEncryptionMode property to true.

What is the advantage of storing an XML file in the applications App_Data folder?

The contents of the App_Data folder will not be returned in response to direct HTTP requests.

What are the best practices to follow to secure connection strings in an ASP.NET web application?

1. Always store connection strings in the site's Web.config file. Web.config is very secure. Users will not be able to access web.config from the browser.
2. Do not store connection strings as plain text. To help keep the connection to your database server secure, it is recommended that you encrypt connection string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource control or other data source controls.
Why is "Connecting to SQL Server using Integrated Security" considered a best practice?Connecting to SQL Server using integrated security instead of using an explicit user name and password, helps avoid the possibility of the connection string being compromised and your user ID and password being exposed.

StreamReader and StreamWriter classes in .Net

Hi friends,in this post i would like to explain StreamReader & StreamWriter classes in C#.Net.

* StreamReader is used to read data from the file.
* StreamWriter is used to write data into the file.
* Directly we are not write data into the file. First we should write into RAM & then through flush() it will be   written into the file.

StreamReader methods:

1)Read() : Reads single character.
2)ReadLine() : Reads single line.
3)ReadToEnd() : Reads full file.

For Example:

StreamReader str=new StreamReader(file1);
txtBox1.Text=str.ReadToEnd();
str.Close();

StreamWriter methods:

1)Write()
2)WriteLine()

For Example:

StreamWriter stw=new StreamWriter(file1);
stw.Write(txtBox1.Text);
stw.Flush();
stw.Close();

Thursday, 21 July 2011

Type Casting In .Net

* Type casting is the concept of converting one datatype to another datatype.

* C#.Net supports 2 types of type casting:
1)Implicit type casting.
2)Explicit type casting.

* Implicit type casting is under control or CLR.
* Explicit type casting is under control of programmer.

* Converting from Lower data types into Higher data types is called as Implicit type casting.
For Example:
Byte---->Long(Implicit)

* Converting from Higher data types into Lower data types is called as Explicit type casting.
For Example:
long---->int(Explicit)

Thursday, 7 July 2011

Magic table in sql

The tables "INSERTED" and "DELETED" are called magic tables of the SQL Server. 
We can not see these tables in the data base.But we can access these tables from the "TRIGGER".
When we insert the record into the table, the magic table"INSERTED" will be created 
In that table the current inserted row will be available. We can access this record in the 
"TRIGGER".
When we delete the record from the table, the magic table "DELETED" will be created
In that table the current deleted row will be available. We can access this record in the
"TRIGGER".
When we update the record from the table, the both magic table will be created. old values insert in "DELETED" table and new values insert in "INSERTED" table. We can access both record through the "TRIGGER".
Example :
Create the tables :
create table LOGTABLE (UserId nvarchar(100),Message nvarchar(100),Mode nvarchar(50))
create table tblAccountDetail(Acc_id int,Acc_Code nvarchar(100),Acc_Name nvarchar(100))
Create insert trigger
create TRIGGER LogMessage_Insert
ON tblAccountDetail
FOR INSERT
AS
   DECLARE @Code varchar(50)
   DECLARE @NAME varchar(50)
   SELECT @Code= Acc_code,@NAME =Acc_Name  FROM INSERTED
   INSERT INTO LOGTABLE(UserId,Message,Mode) values (@Code,@NAME,'Insert')
GO
create update trigger
create trigger logMessage_Update
on tblAccountDetail
for update
as 
   DECLARE @Code varchar(50)
   DECLARE @NAME varchar(50)
   SELECT @Code= Acc_code,@NAME =Acc_Name  FROM INSERTED
   INSERT INTO LOGTABLE(UserId,Message,Mode) values (@Code,@NAME,'Update New')   
   
   DECLARE @Code1 varchar(50)
   DECLARE @NAME1 varchar(50)
   SELECT @Code1= Acc_code,@NAME1 =Acc_Name  FROM DELETED
   INSERT INTO LOGTABLE(UserId,Message,Mode) values (@Code1,@NAME1,'Update Old')
GO
create delete trigger
CREATE TRIGGER LogMessage_Delete
ON tblAccountDetail
FOR DELETE
AS
   DECLARE @Code varchar(50)
   DECLARE @NAME varchar(50)
   SELECT @Code= Acc_code,@NAME =Acc_Name  FROM DELETED
   INSERT INTO LOGTABLE(UserId,Message,Mode) values (@Code,@NAME,'Delete')
GO
///////////////
insert into tblAccountDetail values(1,'Code-1','Name-1')
in this case trigger will auto fired and insert new row in LOGTABLE table 
select from the magic tables "INSERTED"

Saturday, 2 July 2011

About Yourself

Now I am looking for a challenging internship position in an established company. Basically,
I am an experienced and flexible person can be successful at any kind of works.
"Hardworking", "Task-oriented", "Solution-oriented", "Dependable", "Motivated",
"Independent", "Team player" are all examples of good terms you can use.
There are many more.
I am a self-starter dedicated, hard-working person who works well with other, punctual, detail oriented a team player, great organizational and interpersonal skills.

What is foreign key ?

 A foreign key points to the primary key of another table or A foreign key represent the value of a primary key in a related table. While primary keys must contain unique values, foreign keys may have duplicates.
For instance, if we use student ID as the primary key in a Students table (each student has a unique ID), we could use student ID as a foreign key in a Courses table: as each student may do more than one course, the student ID field in the Courses table (often shortened to Courses.student ID) will hold duplicate values

The purpose of the foreign key is to maintain referential integrity of the data.

What is Primary key?

Primary key is used to uniquely identify a row in a table. A table can have only one primary key. Primary keys don’t allow null values. Primary key will create clustered index by default. It can be defined at the column level or at the table level.
Primary Key can be defined while creating a table with Create Table command or it can be added with the Alter table command.

Primary key defined at the column level:
When we define a primary key at single column then it is called Column-level primary key.
create table tblStudent(studentId int primary key,studentName nvarchar(100), Departmenttid int)

Primary key defined at the table level:
when we define a composition key on two or more than two columns then it is called table-level primary key.

‘OR’
If a primary key is a combination of two or more than two columns then it can only be defined at the table level only.

create table tblStudent(studentId int, studentName nvarchar(100), Departmenttid int , primary key (studentId, DepartmentId))

Adding Primary Key constraint using Alter table command:

Suppose there is no primary key defined for the table tblStudent and we want to add a primary key constraints on the column studentId.

 The query for Adding a primary key with the Alter Table command is as follows:-
Syntax:
Alter Table tablename Add constraint constrainname Primary Key (Columnname)
Example:
Alter Table tblStudent add constraint  pk_StuPrimaryKey  primary key(studentId)

Dropping a primary constraint from a table :

Syntax:
Alter Table tablename Drop constraintname

Example:
alter table tblStudent  drop constraint  pk_ StuPrimaryKey

Advantages:
1. It is a unique key on which all the other candidate keys are functionally dependent.
2. It prevents to enter null data.
3. It prevents to enter duplicate data.
4. It helps to force integrety constraints.

Disadvantage:
On primary key index will be created so during updation of table index need to be adjusted accordingly. this process makes the updation slower

Friday, 1 July 2011

What is Constraints ?

Constraint is a mechanism/Property it is used to prevent the invalid data entry in to the table is called constraint. These constraints ensure the accuracy and reliability of the data into the tables.
Constraints can be specified when a table is created (with the CREATE TABLE statement) or after the table is created (with the ALTER TABLE statement).

Difference between Function and StoreProcedure ?

1. functions MUST return a value, procedures need not be.
2. sp takes input,output parameters, function takes only input parameters.
3. sp can not be called directly into DML statements , but functions can be called directly into DML statements.
4. Procedure can return zero or n values whereas function can return one value which is mandatory.
5. Functions can be called from procedure whereas procedures cannot be called from function.
6. Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
7. We can go for transaction management in procedure whereas we can't go in function.
8. Function can be used inside the queries but Store procedure never used inside the queries For Example
      Given below:
      select avg(salary) from employee;// allowed here
      avg(): is function
      Select sp(salary) from employee // Not allowed here
      sp(): is stored Procedure
9. Print function can not be called within the function but it can be called within the stored procedure.
10. A stored procedure can return multiple parameters but a function can return only one value.

String.Empty Vs Empty Quotes ?


The difference between string.Empty and "" is very small. String.empty will not create any object while "" will create a new object in the memory for the checking. Hence string.empty is better in memory management.
But do not forget to make a checking for null value if you are also expecting null value in the comparison.

What's the difference between Response.Write() and Response.Output.Write()?


Response.write() is used to display the normal text and Response.output.write() is used to display the formated text.
Response.write - it writes the text stream.
Response.Write("<h1>"+  DateTime.Now.Tostring() + "</h1>");
 
Response.output.write - it writes the HTTP Output Stream. 
Response.Output.Write("<h2>Process running as {0}</h2>",WindowsIdentity.GetCurrent().Name);
As per ASP.NET 3.5, Response.Write has 4 overloads, while Response.Output.Write has 17 overloads.

What is the Static Member ?


When you declare a member variable as static and when the application starts, the compiler creates a copy of that member. This member would be maintained by the compiler while the program is running. If you declare an instance of a class, the static member is not part of the object: the compiler creates and maintains the static member, whether you use it or not, whether you declare a class variable or not.
When a class has a static member variable, you don't need to declare an instance of that class to access the static member variable. When the application starts, the member variable is automatically available and you can access it when necessary. You can access it either to retrieve its value or to modify it.
Variables and methods marked static belong to the class rather than to any particular instance of the class. These can be used without having any instances of that class at all. Only the class is sufficient to invoke a static method or access a static variable. A static variable is shared by all the instances of that class i.e only one copy of the static variable is maintained.

What is the Static Class ?


We can declare a static class. We use static class when there is no data or behavior in the class that depends on object identity. A static class can have only static members. We cannot create instances of a static class using the new keyword. .NET Framework common language runtime (CLR) loads Static classes automatically when the program or namespace containing the class is loaded.

Here are some more features of static class
  • Static classes only contain static members.
  • Static class cannot create any objects
  • Static classes are sealed.  
  • Static class can have only private constructors 
  • Static loads automatically when the CLR loads the namespace of the class.

What is difference between class and structure ?

1. Classes are reference types and structs are value types.
2. A class variable can be assigned null because classes are reference type. But we cannot assign null to a struct variable because structs are value type.
3. When you instantiate a class, it will be allocated on the heap. When you instantiate a struct, it gets created on the stack.
4. Classes support inheritance. But there is no inheritance for structs.
5. Classes are used for complex and large set data. structs are simple to use.
6. Structures and Enumerations are Value-Types. This means, the data that they contain is stored as a stack on the memory. Classes are Reference-Types, means they are stored as a heap on the memory.
7. Classes can have explicit parameter less constructors. But structs cannot have this.
8. Objects created from classes are terminated using Garbage collector. Structures are not destroyed using GC.
9. By default, all of the members of a class are private and, by default, all of the members of a structure are public.
10.  There is no data hiding features comes with structures. Classes do, private, protected and public.
11.  A structure can't be abstract, a class can.
12.  A structure is contain only data member , but class contain data member and member function.
13.  Struct cannot have default constructor but class have default constructor. 
14.  Structs can't have destructors, but classes can have destructors.
   
Note : a struct is a value type, a class is a reference type.  Value types hold their value in memory where they are declared, but reference types hold a reference to an object in memory. If you copy a struct, C# creates a new copy of the object and assigns the copy of the object to a separate struct instance. However, if you copy a class, C# creates a new copy of the reference to the object and assigns the copy of the reference to the separate class instance. 

Thursday, 23 June 2011

Forcefully excel file generates in .net

//MicroSoft.Office.Interop.Excel (import this as references)
        string filename = "";
        private void CreateExcelSheet()
        {
            try
            {
                //-----------------------------------------------
                DataTable dtExcelImport = new DataTable();
                dtExcelImport = clsApp.getDataTable("select * from student");
                Microsoft.Office.Interop.Excel.Application oXL;
                Microsoft.Office.Interop.Excel._Workbook oWB;
                Microsoft.Office.Interop.Excel._Worksheet oSheet;
                oXL = new Microsoft.Office.Interop.Excel.Application();
                oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); //----- to create new xls
                //oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(Server.MapPath("PreFormated.xls"))); //--- use existing xls
                oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
                string rg = "A1:";
                Microsoft.Office.Interop.Excel.Range range1;
                if (dtExcelImport.Rows.Count > 0)
                {
                    oSheet.Cells[1, 1] = dtExcelImport.Rows[0]["column-1"].ToString();
                    oSheet.Cells[1, 2] = dtExcelImport.Rows[0]["column-2"].ToString();
                    oSheet.Cells[1, 3] = dtExcelImport.Rows[0]["column-3"].ToString();
                    oSheet.Cells[1, 4] = dtExcelImport.Rows[0]["column-4"].ToString();
                    oSheet.Cells[1, 5] = dtExcelImport.Rows[0]["column-5"].ToString();
                }
                oSheet = null;
                range1 = null;
                //========= accessPath to specific folder =======
                filename = DateTime.Now.ToString("dd/MMM/yyyy") + ".xls";
                filename = Server.MapPath("~/myFolder/" + filename);
                //========= Access bin folder =======
                //filename = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
                //filename = filename.Replace(@"file:\", "");
                //filename += "\\myFile" + ".xls"; 
                //=========================
                oWB.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                oWB.Close(Missing.Value, Missing.Value, Missing.Value);
                oWB = null;
                oXL.Quit();
            }
            catch (Exception ex)
            {
            }
        }