Wednesday, November 30, 2011

Row edit,delete,update in grid view in asp.net using c#

Title: Edit,Delete,Update Data in Grid view in Asp.net using c#.net

Description:
As per previous articles we have seen how to export grid view data to excel in asp.net and how to bind data to drop down list in grid view.Now i would like to explain how to do edit,update in grid view using c#.Before going to start we have to set the grid view properties i:e(AutogenerateDeleteButton,AutogenerateEditButton,AutogenerateUpdateButton) to enable the auto generate Edit,Delete,Update buttons. The given example will show how to do the CRUD functionality on grid view data
Grid View properties:
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" AutoGenerateSelectButton="True">
</asp:GridView>

Bind the data to grid view:
//page load event
if(page.isPostback==false)
{
dataset ds=null;
ds=(dataset)session["ds1"];
//session will contain dataset ds1 with data selected by user
if(ds!=null)
{
gvemp.datasource=ds.Tables["employee"];
gvemp.DataBind();
}
}      
Row Editing:
When user clicks on edit button post backtakes place,row editing event of grid view will be executed.This event will provide row index
protected void gremp_rowediting(object sender,EventArgs e)
{
dataset ds=(dstaset)session["ds1"];
gvemp.editindex=e.new editindex;
//e.newedit index:- will be provide index of row for which edit button is selected
gvemp.Datasource=Ds.Table["employee"];
gvemp.Databind();
}
Row Updating:
This will perform post back,row-updating event procedure of grid view will be executed
protected void gvemp-rowupdating(Object sender,EvenArgs e)
{
Textbox txt=(Textbox)gvemp.Rows[e.RowIndex].cells[3].controls[0];
//here i will update the third cell data in grid view
int avg=int.parse(txt.Text);
Dataset ds=(dataset)session["ds1"]; 
ds.Tables["employee"].rows[e.Rowindex]["Average"]=avg;
ds.Tables["employee"].AcceptChanges();
session["Ds1"]=ds;
//it will overwrite the session of Dataset
//Rearrange Gridview
gvemp.editIndex=-1;
gvemp.Datasource=Ds.Tables["employee"];
gvemp.DataBind();
}
Row Deleting:
This will perform post back,row-deleting event procedure of grid view will be executed
protected void gvemp-rowdeleting(Object sender,EvenArgs e)
{
Dataset ds=(dataset)session["ds1"]; 
ds.Tables["employee"].rows[e.Rowindex].Delete();
ds.Tables["employee"].AcceptChanges();
session["Ds1"]=ds;
gvemp.Datasource=Ds.Tables["employee"];
gvemp.DataBind();
}

How to upload a file in asp.net using c#

Title:How to use upload control in asp.net

Description:
We can say "Sending file from client system to server system" as a definition .Mostly this control can be used as in  practical for uploading resume,image and attachment towards email.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>How to upload a file in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpLoad id="Fud" AlternateText="You cannot upload files" runat="server" />
<asp:Button id="btnupload" Text="Upload File" OnClick="btnupload_Click" runat="server" />
<asp:Label runat="server" Id="lblmessage" />
</form>
</body>
</html>

The properties and methods of File upload:

*has file--true-->File is upload
false-->File is not uploaded
*posted file--content type-->it returns file types
text/plain--->normal text file
text/xml---->XML file
application/msword-->doc file
save as(file path)--->it will save upload file in server system
Here i will shown to allow user to upload photos(image file type of gif) .For this i have taken file upload control and button server control in aspx page.


Code behind:

protected void btnupload_Click(object sender, EventArgs e)
{
Response.write(Fud.Hasfile);
Response.write(Fud.filename);
Response.write(Fud.posted file contenttype);
if(Fud.Hasfile)
{
if(Fud.Postedfile.ContentType=="image/gif")
{ 
Fud.postedfile.saveAs(server.mappath(".")+"\\"+Fud.filename);
lblmessage.text="upload successfully";
}
else
lblmessage.text="upload gif file";
}
else
lblmessagetext="file required";
}
}
Note:File upload control supports maximum of 4mb file size for uploading to server

Tuesday, November 29, 2011

Export data to excel in c#

Title:How to export grid view data to excel in asp.net using c#.net

Description:
Basically we can export the data to excel in two ways in asp.net with c#. One is using Download Format and Other one is using Microsoft.Office.Interop.Excel .In the Download format ,it  will render the grid view and export in XLST format.It is used when the data is export from grid view to excel.In Interop.Eexcel will create excel file dynamically and load the data into it.Exporting data to excel its pretty simple. Let's see how this can be done.For this i have taken data from database first then fill the existing data set.The following name space i have used for excel properties
Asp.Net Export to excel:
using Microsoft.Office.Interop.Excel;
Create Excel document:
Excel.Application App;
Excel.Workbook WorkBook;
Excel.Worksheet WorkSheet;
object misValue = System.Reflection.Missing.Value;
App = new Excel.Application();
WorkBook = App.Workbooks.Add(misValue);
WorkSheet = (Excel.Worksheet)WorkBook.Worksheets.get_Item(1);
Load the data into Excel file:
Here i will get the data into data set then it will load in to excel file using the following iteration.
for (int col = 0; col < dsreportdata.Tables[0].Columns.Count; col++)
{
for (int row = 0; row < dsreportdata.Tables[0].Rows.Count; row++)
{
WorkSheet.Cells[row + 12, col + 3] = dsreportdata.Tables[0].Rows[row].ItemArray[col].ToString();
}
}

Monday, November 28, 2011

uncheck the check box if another check box checked in check box list or radio button list

Here i will unchecked  items  in radio button list server control or check box list server control when we select on any item in this  .For this i have used a  singleitemcheck() function for each item in list control .This function makes functionality is very quick in your application

Aspx Page:
<asp:radiobuttonlist id="contentcheck" repeatdirection="Horizontal" runat="server">
<asp:listitem onclick="singleitemcheck(this);">Home</asp:listitem>
<asp:listitem onclick="singleitemcheck(this);">Pages</asp:listitem>
</asp:radiobuttonlist>

Java Script:
function singleitemcheck(ch) {
            var chkList = ch.parentNode.parentNode.parentNode;
            var chks = chkList.getElementsByTagName("input");
            for (var i = 0; i < chks.length; i++) {
            if (chks[i] != ch&& ch.checked) {
                chks[i].checked = false;

Static methods in csharp

A method declaring using the static keyword is a static method rest of all instance only.While defining static methods,we should not refer to any instance member of class directly,but we can use them by creating the object of the class.Non static members of a class cannot be referred from static blocks with out object reference.
Example:
class example
{
 int x=10;
 static int y=20;
 static void add()
  {
    example e=new example();
    console.writeline(e.x+y);
  }
}


Extension Methods in c#

It is an approach which can be used for extending the functionalities of a class even if the source code of the class is not available.Extension methods can be used for adding new methods to a class using static class.After defining an extension method these methods can be accessed using in object of the actual class to which they were added.To define an extension method we need to fallow the below rules and regulations

1.An extension method should always per-defined under a static class
2.As a methods are defined under the static class they need to be defined as static methods.but when they are found to actual class they can converted to instance methods.Every extension methods should have one mandatory parameters.e The class to which the method should be bound.A single static class can add extension methods to any no of classes

Example:
class extension
{
  public int a=10;
  public void display1()
   {
    console.writeline("method1");
   }
  public void display2()
   { 
    console.writeline('method2");
   }
  static void main()
   {
    extension e=new extension();
    e.display1();
    e.display2();
    console.readline();
   }
}
Add one more class to project naming it as Staticclass.cs.In this
public static void display3(this extension e)
{
 console.writeline("method3");
}
public static void display(this extension e,int x)
{
console.writeline("method4+"x");
}
public static void display(this extension e)
{
console.writeline("methods5"+e.a);
}
After defining three extension methods now the class extension contains five methods in it .you can test it by adding a new class the project and naming it as text extension.cs and with fallowing
static void main()
{
extension e=new extension();
e.display1();
e.display2();
e.display3();
e.displa4(10);
e.display5();
}

Sunday, November 27, 2011

how to convert data types in csharp

The Microsoft .net providing a class "Converting" which can be used to convert from any data type into any other data type.Converting is a predefined class which is a part of FCL[Framework Class Library]converting class contains a collection of methods

convert.ToByte(value)
convert.ToChar(value)
convert.ToString(value)
convert.ToFloat(value)
convert.ToDouble(value)
Example on converting:
main()
{
for(i=65;i<=90;i++)
{
char c=convert.Tochar(i);
console.write(c);
}

Difference between value type and reference type data types in c#

Title: What is difference between Value and Reference type in C#.net

Description:While using  the c#.net we have to know some basic concepts such as data types.Now i would like to describe the features and difference of data types
Value Type:
1.Value type holds the data directly
2.value type doesn't contain default value
3.Value type should be in STACK memory at compile time
4.STACK is not accessible with Garbage collection(GC)
5.Example for value types:Structures,Enums etc
Reference Type:
1.Reference type holds the address but not data
2.Reference type holds the default value
3.Reference type will be stored in HEAP memory at run time
4.HEAP memory is accessible with GC
5.Example for Reference type:Classes,objects,arrays.Interfaces etc

Friday, November 25, 2011

XML data into Gridview in asp.net

Title:how to bind XML data in grid view in asp.net using C#.net

Description:
We have seen different examples on  how to bind data to Grid view in asp.net ,Import XML data to Grid View,bind data table to Grid view.Now i would like show how to bind the XML data to grid view.Before going to start  you may think we have to use XML classes to read the data,But we will not use any XML classes .In asp.net Data set has property to read the XML data which is Readxml().
XML Data:
<?xml version="1.0" encoding="utf-8" ?>
<Orders>
<Order>
<OrderId>1</OrderId>
<OrderName>Asp.net</OrderName>
<Phone>0000000000</Phone>
<Address>Hyd</Address>
<Amount>100</Amount>
</Order>
<Order>
<OrderId>2</OrderId>
<OrderName>Sharepoint</OrderName>
<Phone>1111111111</Phone>
<Address>USA</Address>
<Amount>200</Amount>
</Order>
<Order>
<OrderId>3</OrderId>
<OrderName>Jquery</OrderName>
<Phone>2222222222</Phone>
<Address>UK</Address>
<Amount>200</Amount>
</Order>
<Order>
<OrderId>4</OrderId>
<OrderName>Mvc</OrderName>
<Phone>4444444444</Phone>
<Address>AUS</Address>
<Amount>300</Amount>
</Order>
</Orders>

Aspx Page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Bind XML data to Gridview in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GVdynamicXML" runat="server" AutoGenerateColumns="False"
>
<Columns>
<asp:BoundField DataField="OrderID" HeaderText="OrderID"
 SortExpression="OrderID" />
<asp:BoundField DataField="OrderName" HeaderText="OrderName"
 SortExpression="OrderName" />
<asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:BoundField DataField="Amount" HeaderText="Amount"
SortExpression="Amount" />
</Columns>
</asp:GridView>
</form>
</body>
</html>

Code behind:
using System;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class _XMLbindGridviewDefault3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet myDataSet = new DataSet();
myDataSet.ReadXml(Server.MapPath("~/XMLFile.xml"));
GVdynamicXML.DataSource = myDataSet;
GVdynamicXML.DataBind();
}
}
}
We should give a specific path of XML file to read the data using Readxml().Then bind the data  to grid view "gd_view"

How to delete Duplicate Rows from Table

Title:How to delete duplicate rows in table using SQL Server

Description:
While working with we applications ,we have to maintain the data base is unique.Now i will describe one example on data redundancy.We just take one registration site ,which is used to register the personal details .When the user give the details multiple times ,we have to check whether the data is exist or not.If the records are exit we can delete using below query.
Note:The Duplication rows in Database tables will exists by running the data repeatedly With out  having the primary key on table.Here i have shown an example to remove the duplicate records in table

Example:
DELETE FROM Employee e1 WHERE ROW_NUMBER()<>(SELECT MIN( ROW_NUMBER())FROM EMployee e2 WHERE e1.empname= e2.empname) 

Thursday, November 24, 2011

how to select data from multiple tables in sql server

Title:How to retrieve the data from set of tables in SQL server

Description:
As per recent articles we have seen how to get the data from single table in SQL server.Now i want explain the same concept with multiple tables.The SQLserver has provided a Keyword which is used to get data from set of  tables using SQL query i:e"INTERSECT" keyword.Here i will show to get empid ,name from employee table by comparing with empid column in Department table

SELECT empid, name FROM Employee
WHERE empid IN
SELECT empid FROM Employee INTERSECT SELECT empid FROM Department) 
Here i have shown one more query to get the data from different table with out join
SELECT em.empid,em.name FROM Employee em,Department de WHERE em.empid=de.empid 

Wednesday, November 23, 2011

An object reference is required for the non-static field, method, or property

Title: An object reference is required for the non-static field

Description:
Each console application has it's own static main method. If we want to call a non static method in a static method it is not possible straight away because the static methods can be called without instantiate and non-static methods should need object instantiated before it get called. So, For this reason we have to create an object of class in main method to call the non-static methods. Now I will show you a simple example to call the non static method in static method.

A small example:
//Program Class
class Program
{ 
public int add(int n1,int n2)
{
int result=n1+n2;
return result;
} 
}

//Main method
static void main()
{
Program p=new Program();
p.add(n1,n2);
//logic 
}

Difference between Read(),Readline() and ReadKey in C#

Title:Difference between Read(),Readline() and ReadKey in C#

Description:
These methods can be used to read the values from the console and done some specific functionality on it.Each of the property is used to return the different values .The declaration of  static methods in console application as below

Read()        :accept the string value and return the string value.
Readline() :Accept the string and return Integer
ReadKey() : Accept the character and return Character


Declaration In Application:
Console.Read();
Console.Readline();
Console.ReadKey();
If we use Read line or Read() we need press Enter button to come back to code.If we using Read key() we can press any key to come back code in application

Add Server control using Drag and Drop in Ektron

Here i will shown how to  add some server controls to Template page.For doing this the fallowing steps to be need to do this.
1.We should add the Ektron.Control dll to get the server controls in to tool box
2.Go to visual studio Tool box(View-->Tools)
3.Click on Ektron Server controls.Then the server controls are appeared like as below
4.To add the Ektron server controls to desirable place  using Drag and drop

Tuesday, November 22, 2011

Update an INDEX in sql

we can use ALTER INDEX command to modify then name of index on table.Here i will show how to change the name of Employee_phone to Employee_phone_number

Query:
ALTER INDEX Employee_phone RENAME TO Employee_phone_number;

Create B-tree Index in Oracle


CREATE [UNIQUE] INDEX maxamount ON
Sales(amount)
TABLESPACE tab_space;
where
UNIQUE means that the values in the indexed columns must be unique.
index_name is the name of the index.
table_name is a database table.
column_name is the indexed column. You can create an index on multiple columns
(these kind of  index is known as a composite index).
tab_space is the tablespace for the index. If you don’t provide a tablespace, the index
is stored in the user’s default tablespace.

Note:
For performance reasons, you should typically store indexes in a
different tablespace from tables.

Changing column name and Datatype in Table in Sql

Title:How to Change column name and datatype in SQL server

Description:
This kind scenario will happen when we have to change the data base filed name or data type as per requirement.As per my application i need change the column type to Null.The SQL server provides a default stored procedure "sp_changename",which can make the things easier.Here i have used ALTER command To change the column name and data type in the table

Syntax:
Alter table TableName alter column ColumnName DataType NULL/NOT NULL
EXEC sp_changename        
@objname = ' TableName. OldColumnName’,
@newname = 'New ColumnName',
@objtype = 'COLUMN'

Example:
Alter table Organisation alter column name int null
EXEC sp_changename
@objname = 'Oraganisation.name',
@newname = 'name',
@objtype = 'COLUMN'

Changing column datatype size in sql

I think all of know how to change column name and column data type  . But   the how to change the size of data type of particular row in table . Let me give an example here how to change the Column Data type size using sql ALTER Command .The given example will change the var char(10) to var char(100)

Syntax:
alter table TableName alter column ColumnName DataType(Size)
Example:
alter table Retails alter column Address varchar(100);

Custom pager inside the gridview pager template using c#

In previous articles how to sort and paging in gridview in asp.net,The pager template in gridview is a certain layout. it would be to show the current page and number of pages[index].For this I have used a HTML table to create a custom page in side the grid view Pager template.We have two more function in this code which are create page numbers in grid view pager template
Aspx page:


<asp:gridview allowpaging="True" autogeneratecolumns="False" autogenerateselectbutton="True" cellpadding="4" font-names="Verdana" gridlines="None" id="GdvMainmasters" ondatabound="GdvMainmasters_DataBound" onpageindexchanging="GdvMainmasters_PageIndexChanging" onrowcommand="GdvMainmasters_RowCommand" runat="server">

<columns>



<asp:templatefield headertext="CODE">
<itemtemplate>
<asp:label id="lblmaincode" runat="server" text="<%# Bind("MAINCODE") %>"></asp:label>
</itemtemplate>
</asp:templatefield>

<asp:templatefield headertext="NAME">
<itemtemplate>
<asp:label id="lblmainnanme" runat="server" text="<%#  Bind("MAINNAME")%>"></asp:label>
</itemtemplate>
<itemstyle width="300px">
</itemstyle></asp:templatefield>


<asp:templatefield headertext="STATUS">
<itemtemplate>
<asp:label id="lblstatus" runat="server" text="<%# Bind("STATUS")%>"></asp:label>
</itemtemplate>
<itemstyle width="300px">
</itemstyle></asp:templatefield>

</columns>

<pagerstyle backcolor="White" borderstyle="Double" forecolor="Black" horizontalalign="Center">
<pagertemplate>
</pagertemplate>
</pagerstyle>

</asp:gridview>


<table class="pagerOuterTable" id="pagerOuterTable" runat="server"><tbody>
<tr><td><br />
<br />
<table cellpadding="2" cellspacing="1" id="pagerInnerTable" runat="server"><tbody>
<tr>
<td class="pageCounter">
<br />
<asp:label id="lblPageCounter" runat="server" text=""></asp:label></td> <td class="pageFirst"><br />
<br />

<img align="middle" alt="" src="Images/firstpage.gif" /><br />

<asp:linkbutton commandargument="First" commandname="Page" cssclass="pagerLink" id="lnkFirstPage" runat="server">First</asp:linkbutton></td>   <td class="pagePrevtNumber"><br />

<asp:linkbutton commandargument="Prev" commandname="Page" cssclass="pagerLink" id="linkprevpage" onclick="linkprevpage_Click" runat="server">Prev</asp:linkbutton></td>   <td class="pageNextNumber"><br />

<asp:linkbutton commandargument="next" commandname="Page" cssclass="pagerLink" id="linknextpage" onclick="linknextpage_Click" runat="server">Next</asp:linkbutton></td>   <td class="pageLast"><br />

<asp:linkbutton commandargument="Last" commandname="Page" cssclass="pagerLink" id="lnkLastPage" runat="server">Last</asp:linkbutton>&nbsp;<img align="middle" alt="" src="Images/lastpage.gif" /></td>     </tr>

</tbody>
</table>
</td>
<td class="pageGroups" visible="false">
<br />
Pages:<asp:dropdownlist autopostback="true" id="ddlPageGroups" onselectedindexchanged="ddlPageGroups_SelectedIndexChanged" runat="server"></asp:dropdownlist>
</td>
</tr>
</tbody>
</table>

Code Behind:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Collections.Generic;
using dpant;
using System.Drawing;
using System.Threading;

public partial class _Default : System.Web.UI.Page
{

 public static string connection = ConfigurationManager.ConnectionStrings  ["Con"].ToString();
 public static SqlConnection con = new SqlConnection(connection);
 public static SqlCommand cmd = null;
 protected FullGridPager fullGridPager;
 protected int MaxVisible = 10;
   
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
fullGridPager = new FullGridPager(GdvMainmasters,MaxVisible, "Page", "of");
fullGridPager.CreateCustomPager(GdvMainmasters.BottomPagerRow);
}
}
protected void GdvMainmasters_PageIndexChanging(object sender,GridViewPageEventArgs e)
{
GdvMainmasters.PageIndex = e.NewPageIndex;
GdvMainmasters.DataBind();        
}

protected void GdvMainmasters_DataBound(object sender, EventArgs e)
{
if (Excelbtn != "ABC" )
{
if (fullGridPager == null)
{
fullGridPager = new FullGridPager(GdvMainmasters, MaxVisible, "Page", "of");
}
fullGridPager.CreateCustomPager(GdvMainmasters.BottomPagerRow);
fullGridPager.PageGroups(GdvMainmasters.BottomPagerRow);
}
}

protected void ddlPageGroups_SelectedIndexChanged(object sender,EventArgs e)
{
if (fullGridPager == null)
{
fullGridPager = new FullGridPager(GdvMainmasters, MaxVisible, "Page", "of");
}
fullGridPager.PageGroupChanged(GdvMainmasters.BottomPagerRow);
}

protected void linknextpage_Click(object sender, EventArgs e)
{
GdvMainmasters.PageIndex = GdvMainmasters.PageIndex + 10;
GdvMainmasters.DataBind();
}

protected void linkprevpage_Click(object sender, EventArgs e)
{
if (GdvMainmasters.PageIndex > 10)
{
GdvMainmasters.PageIndex = GdvMainmasters.PageIndex - 10;
GdvMainmasters.DataBind();
}
else
GdvMainmasters.PageIndex = 0;
GdvMainmasters.DataBind();
}
}

Here i have created a class protected FullGridPager fullGridPager;
to develop the custom paging,and number for grid view.Because i have multiple pages with same grid view pager.
protected FullGridPager fullGridPager class;
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace dpant
{


public class FullGridPager
{
    private const int DEFAULT_MAX_VISIBLE = 0;
    private const string DEFAULT_COUNTER_TEXT = "";
    private const string DEFAULT_TOTAL_TEXT = "";
                
    protected int maxVisiblePageNumbers;
    protected int firstPageNumber;
    protected int lastPageNumber;
    protected string pageCounterText;
    protected string pageCounterTotalText;
    protected GridView theGrid;
    protected GridViewRow theGridViewRow;
    

public FullGridPager(GridView TheGrid)
{
// Default Constructor  
maxVisiblePageNumbers = DEFAULT_MAX_VISIBLE;
pageCounterText = DEFAULT_COUNTER_TEXT;
pageCounterTotalText = DEFAULT_TOTAL_TEXT;
theGrid = TheGrid;
}

public FullGridPager(GridView TheGrid, int MaxVisible, string CounterText, string TotalText)
{
// Parameterized constructor
maxVisiblePageNumbers = MaxVisible;
pageCounterText = CounterText;
pageCounterTotalText = TotalText;
theGrid = TheGrid;
}
    
public int MaxVisiblePageNumbers
{
get { return maxVisiblePageNumbers; }
set { maxVisiblePageNumbers = value; }
}

public string PageCounterText
{
get { return pageCounterText; }
set { pageCounterText = value; }
}
  
public string PageCounterTotalText
{
get { return pageCounterTotalText; }
set { pageCounterTotalText = value; }
}
       
public GridView TheGrid
{
get { return theGrid; }
}
   
public void CreateCustomPager(GridViewRow PagerRow)
{
// Create custom pager inside the Grid's pagerTemplate.
// An html table is used to format the custom pager.
// No data to display.
if (PagerRow == null) return;
theGridViewRow = PagerRow;
HtmlTable pagerInnerTable = (HtmlTable)PagerRow.Cells[0].FindControl("pagerInnerTable");
if (pagerInnerTable != null)
{
// default dynamic cell position. 
// (after the pageCount, the "First" and the "Previous" cells).            
int insertCellPosition = 2;
if (theGrid.PageIndex == 0)
{
// The first page is currently displayed.
// Hide First and Previous page navigation.
pagerInnerTable.Rows[0].Cells[1].Visible = false;
pagerInnerTable.Rows[0].Cells[2].Visible = false;
// Change the default dynamic cell to 1.
insertCellPosition = 0;
}

CalcFirstPageNumber();
CalcLastPageNumber();
CreatePageNumbers(pagerInnerTable, insertCellPosition);
int lastCellPosition = pagerInnerTable.Rows[0].Cells.Count - 1;
if (theGrid.PageIndex == theGrid.PageCount - 1)
{
// The last page is currently displayed.
// Hide Next and Last page navigation.                
pagerInnerTable.Rows[0].Cells[lastCellPosition - 1].Visible = false;
pagerInnerTable.Rows[0].Cells[lastCellPosition].Visible = false;
}
UpdatePageCounter(pagerInnerTable);
}
}

private void CreatePageNumbers(HtmlTable pagerInnerTable, int insertCellPosition)
{
for (int i = firstPageNumber, pos = 1; i <= lastPageNumber; i++, pos++)
{
// Create a new table cell for every data page number.
HtmlTableCell tableCell = new HtmlTableCell();
if (theGrid.PageIndex == i - 1)
tableCell.Attributes.Add("class", "pageCurrentNumber");
else
tableCell.Attributes.Add("class", "pagePrevNextNumber");
// Create a new LinkButton for every data page number.
LinkButton lnkPage = new LinkButton();
lnkPage.ID = "Page" + i.ToString();
lnkPage.Text = i.ToString();
lnkPage.CommandName = "Page";
lnkPage.CommandArgument = i.ToString();
lnkPage.CssClass = "pagerLink";
// Place link inside the table cell; Add the cell to the table row.                
tableCell.Controls.Add(lnkPage);
pagerInnerTable.Rows[0].Cells.Insert(insertCellPosition + pos, tableCell);
}
}

private void CalcFirstPageNumber()
{
// Calculate the first, visible page number of the pager.             
firstPageNumber = 1;
if (MaxVisiblePageNumbers == DEFAULT_MAX_VISIBLE)
MaxVisiblePageNumbers = theGridPageCount;
if (theGrid.PageCount > MaxVisiblePageNumbers)
{
// Seperate page numbers in groups if necessary.
if ((theGrid.PageIndex + 1) > maxVisiblePageNumbers)
{
// Calculate the group to display.
// Example: 
//      GridView1.PageCount = 12
//      maxVisiblePageNumbers = 4
//      GridView1.PageIndex+1 = 7
//      --> pageGroup = 2       (Page numbers: 5, 6, 7, 8)
decimal pageGroup = Math.Ceiling((decimal)(theGrid.PageIndex + 1) / MaxVisiblePageNumbers);
// Calculate the first page number for the group to display.
// Example :
//      if pageGroup = 1 (Page numbers: 1,2,3,4) --> firstPageNumber = 1
//      if pageGroup = 2 (Page numbers: 5,6,7,8) --> firstPageNumber = 5
//      if pageGroup = 3 (Page numbers: 9,10,11,12) --> firstPageNumber = 9               firstPageNumber = (int)(1 + (MaxVisiblePageNumbers * (pageGroup - 1)));
}
}
}

private void CalcLastPageNumber()
{
// Calculate the last, visible page number of the pager.
lastPageNumber = theGrid.PageCount;
if (MaxVisiblePageNumbers == DEFAULT_MAX_VISIBLE)
MaxVisiblePageNumbers = theGrid.PageCount;
if (theGrid.PageCount > MaxVisiblePageNumbers)
{
lastPageNumber = firstPageNumber + (MaxVisiblePageNumbers - 1);
if (theGrid.PageCount < lastPageNumber)
lastPageNumber = theGrid.PageCount;
}
}

private void UpdatePageCounter(HtmlTable pagerInnerTable)
{
// Display current page number and total number of pages.        
Label pageCounter = (Label)pagerInnerTable.Rows[0].Cells[0].FindControl("lblPageCounter");
pageCounter.Text = " " + PageCounterText + " " + (theGrid.PageIndex + 1).ToString() + " " + PageCounterTotalText + " " + theGrid.PageCount.ToString() + " ";
}

public void PageGroups(GridViewRow PagerRow)
{
// Display page groups in pager if GridView.PageCount is greater than the maxVisiblePageNumbers.
        
// No data to display.
if (PagerRow == null) return;
theGridViewRow = PagerRow;
HtmlTable pagerOuterTable = (HtmlTable)PagerRow.Cells[0].FindControl("pagerOuterTable");I
If (MaxVisiblePageNumbers == DEFAULT_MAX_VISIBLE)
MaxVisiblePageNumbers = theGrid.PageCount;
int maxPageGroups = (int)Math.Ceiling((decimal)theGrid.PageCount / MaxVisiblePageNumbers);
if (theGrid.PageCount > MaxVisiblePageNumbers)
{
int lastCellPosition = pagerOuterTable.Rows[0].Cells.Count - 1;
decimal pageGroup = Math.Ceiling((decimal)(theGrid.PageIndex + 1) / MaxVisiblePageNumbers);

DropDownList ddlPageGroups = (DropDownList)pagerOuterTable.Rows[0].Cells[lastCellPosition].FindControl("ddlPageGroups");
 for (int pg = 1; pg <= maxPageGroups; pg++)
{
int groupFirstPageNumber = (int)(1 + (maxVisiblePageNumbers * (pg - 1)));
int groupLastPageNumber = groupFirstPageNumber + (maxVisiblePageNumbers - 1);
if (theGrid.PageCount < groupLastPageNumber)
groupLastPageNumber = theGrid.PageCount;
string group = String.Format("{0} ... {1}", groupFirstPageNumber.ToString(), groupLastPageNumber.ToString());
ListItem groupItem = new ListItem(group, groupFirstPageNumber.ToString());
if (pageGroup == pg)
groupItem.Selected = true;
ddlPageGroups.Items.Add(groupItem);
}
 //Make the dropdownlist visible;
pagerOuterTable.Rows[0].Cells[lastCellPosition].Visible = false;
}
}
public void PageGroupChanged(GridViewRow PagerRow)
{
 // Change the page group.        
if (PagerRow != null)
{
 HtmlTable pagerOuterTable = (HtmlTable)PagerRow.Cells[0].FindControl("pagerOuterTable");
 int lastCellPosition = pagerOuterTable.Rows[0].Cells.Count - 1;
  DropDownList ddlPageGroups = (DropDownList)pagerOuterTable.Rows[0].Cells[lastCellPosition].FindControl("ddlPageGroups");
  this.theGrid.PageIndex = Int32.Parse(ddlPageGroups.SelectedValue) - 1;
}
}
}
}

Monday, November 21, 2011

Converting DATETIME() to string in Oracle

oracle database Provide some special functions to convert the value from one data type to another data type.To_CHAR() function will be using to convert the DATE TIME() to string .

The syntax for TO_CHAR():

use TO_CHAR(x([,format]) to convert the date time x to string.here i want to get the full name of month ,2 digit day format and 4 digit year
SELECT student_id, TO_CHAR(dob, 'MONTH DD, YYYY')
FROM students;

note:The conversion of string to date time will be get by using TO_DATE () function.





Latest version and features of Ektron CMS

Ektron CMS .net 8.5 is the latest version which has been released by September 29 2011
In this version the work area is more optimized so the users to be more productive.It is the first enterprise .NET web content management to deliver a 3-tier architecture.

New Features in this version:

             1.Expanded developer API
             2.3-tier architecture
             3..NET 4.0 support
             4.Enhanced search capabilities
             5.e Sync enhancements
             6.Microsoft Fast search which is supported for  all types of web content like Microsoft office and multimedia
            
Content target:

The Content Targeting PageBuilder widget is available to  users to target content based on user form submission data.

 

Sunday, November 20, 2011

Update or Insert the rows into Table or VIew using Oracle || MERGE Class in Oracle

Oracle database has one class to update or insert the rows into table or view which is "MERGE".
MERGE class can do this kind of operations very easily.Now i will shown a simple example in below

Example:

MERGE  into Employee USING Users
         ON(Employee.name=Users.name)
        WHEN matched  then UPDATE SET Employee.role=Users.role,Employee.Add=Users.Add
        WHEN matched  Then Insert(name,role,add,phno) values (Users.name,Users.role,Users.add,Users.phno)

Difference between Oracle 9i and 10g

9i is based on Internet technology and 10g is grid based one.

In 10g has some extra features are introduced comparing with 9i those are Automated storage management(ASM),
Automatic Database Diagnostic monitor(ADDM),
Automatic workload repository,
Automatic Checkpoint Tunning,
Streams Technology(STREAMS POOL),
Automatic SQL Tunning,Recovery Manager Enhancements(RMAN).
Built-in packages—(DBMS_SCHEDULER, DBMS_CRYPTO, DBMS_MONITOR)
Compile-time warnings
Number data type behaviors
An optimized PL/SQL compiler
Regular expressions
Set operators
Stack tracing errors
Wrapping PL/SQL stored programs

we can rollback after drop in 10g but in 9i can't rollback

10g is web based database management

Saturday, November 19, 2011

Get the file name and change the active menu item css settings using J query


Here i have sample menu list.Now i want change the color of active item in menu comparing the file name for the which page is loaded at that time.Based on these information i can change the active link item settings.This all  happen when the page is loading
$(document).ready(function () {
    // $(function () {
    var urlFile = $.trim($.url.attr("file").replace(/([^.]*)\.(.*)/, "$1"));
    $('.Mainul li a').each(function () {
        var arrPath = $(this).attr('href').replace(/([^.]*)\.(.*)/, "$1").split('/');
        anchorFile = $.trim(arrPath[arrPath.length - 1]);
        //alert(urlFile + " == " + anchorFile);
        //alert(urlFile.length + " == " + anchorFile.length);
        if (urlFile == anchorFile) {
            $(this).css('color', 'Orange');
            divId = $(this).attr('id');
            $('#toggleText_' + divId).show();
        } else {
            $(this).css('color', 'green');
        }
    });

Allow only numeric values from Keyboard using jquery

Title: How to allow only number in asp.net using JQuery

Description:As we know this is the validation kind of functionality of a control in any web application.the below example will describe how to allow only number when you click on the keyboard.So the required field will not the characters from the board

function NumericOnly(e) {
var presskey;
if (navigator.appName.lastIndexOf("Microsoft Internet Explorer") > -1)
presskey= e.keyCode;else
presskey= e.which;if ((presskey== 0 || presskey== 8 || presskey== 9))       
return true;
if ((presskey> 47 && presskey< 58))
return true;
else { e.returnValue = null; return false;
}
}

Jquery div inline datepicker

In previous post i have given example on how to develop jquery autocomplete. In this post i will given how to use jquery date picker library on Div.The jquery  date picker would be  assign to the different controls and div's  using below jquery function.Here i will shown how to assign the data picker to div using jquery.
function(tar, inst) {
var divSpan = $(tar);
if (divSpan.hasClass(this.markerClassName))
return;
divSpan.addClass(this.markerClassName).append(inst.dpDiv).
bind("setData.datepicker", function(event, key, value){
inst.settings[key] = value;
}).bind("getData.datepicker", function(event, key){
return this._get(inst, key);
});
$.data(target, PROP_NAME, inst);this._setDate(inst, this._getDefaultDate(inst));
this._updateDatepicker(inst);
this._updateAlternate(inst);
}

Transaction handling in .net

Transaction is a unit of manipulation on the basis of all .This is recommended when the manips are interrelated
Ado .net is providing transaction class and begin transaction method with connection class to implement transaction handling.

I have given a simple example on transaction handling .For this i have used three text boxes and  one button in windows application.

Transaction.aspx.cs :
Dim con As New SqlConnection("userid=sa;passed=;databse=invetary")
Dim cmd As New SqlCommand()
Dim t As SqlTransaction

Try
con.open()
t=con.BeginTransaction()
cmd.connection=con
cmd.Transaction=t
cmd.commandText="insert into trans values("&t1.text&","&t2.text&","&t3.text&")"
cmd.excutionQuery()
cmd.CommandText="update item set Qoh=qoh="&t3.text&" where itemno="&t2.text""
Dim n As byte
n=cmd. excutenonQuery()
if n=0 then
Throw New invalidTransException("item not found")
End if
t.Commit()
msgbox("Transaction Successfully")

Catch ex As Exception
t.rollback()
msgbox("Trans failed"&ex.message)

Finally
con.close()

EndTrancation
End Sub
End Class

Friday, November 18, 2011

“don’t allow remote connections ” error


 In previous articles i explained how to solve a network related or instance specific error .If we get error like “don’t allow remote connections ”or A connection was successfully established with the server, but then an error occurred during the login process in sql server 2005,we have to change the remote connections ,we have to change the Remote Connections in sql server.

Do the below steps to resolve this issue:
1.Goto MicrosoftSqlServer2005->Configuration Tools
2.select SqlServer Surface Area Configuration
3.select the data base what you have used in sytem
4.Then select the remote connection.Here we can see three options,In these we have to select using both TCP/IP and names pipes


Thursday, November 17, 2011

Create a Page layout(aspx page) in ektron CMS

In this article i will shown how to create Page lay out in ektron cms .For doing this  we have to login into cms work area.Then select the Content tab which is at top of the work area page.
 Then Select the page layout option in new tab in content area.Whenever click on that option we will get a pop up  to select the master page lay out for this page .Here  we can change the folder path which one we will want to add to  this  page lay out


There is a button to go for the next step .When ever click on the next button we will get one more pop which is contains the options to give a name of the page ,taxonomy and meta data.The page will be created when we complete these steps

Bind the data to label control which in data grid using c#

Here i want to bind the data to labels which are placed in grid view .For this i will put the binding property instead of label text property .In the below example i was bind the Id ,name to label's etc
Default.aspx:
In the grid view control, go to the <Item Template> element for the ID Column. Change the asp:Label control to display the ID for the current row in the grid view by replacing the Label text with the data binding

  <%# DataBinder.Eval(Container.DataItem, "ID") %>


  <%# DataBinder.Eval(Container.DataItem, "Name") %>
 

Create dynamic control using c#

Here i will create two text boxes and one hyperlink dynamically using csharp.Whenever create a new server control in code behind we have to instantiated for each server control.The properties of each control will be given by using the object of control

Default.aspx:
<html><head></head>
<body>
<asp:label id="lbl" runat="server" ></asp:label> 
</body>
</html>

Defalut.aspx.cs:
textbox t1=new textbox();
t1.Id="txtname";
//set textmode propety
t1.TextMode = TextBoxMode.MultiLine;
this.controls.add(t1);
textbox2 t2=new textbox();
t2.id="txtpas";
this.controls.add(t2);
button bt=new button();
bt.id="hyp";
bt.text="submit";
this.controls.add(bt);
Hyperlink h1=new Hyperlink();
h1.id="hyp";
h1.NavigateUrl="test.aspx";
this.controls.add(hyp);

how to add the web application to iis

We have a shortcut option to open the IIS in our system.Just open run command prompt  and type the inetmgr  then click it opens the IIS.Here we can see the IIS in local system
The right click on the sites and select the add website option.Then the pop will be opened .The pop up contain the option to enter the site name ,physical path(path of the application file),application pool and port .The physical path of the application should in the  wwroot folder which in the path c-->inetpub-->wwroot
Note:Before going to do this process we have place the application folder in wwroot folder.

Get the file name from browser url using c#

In previous post we have seen how to pass java script variables to serverside.In this posti wll show how to get the browser information using csharp.Comparing to javascript there is no direct piece of code to get the file name with out extension in code behind using csharp.For this first we get the Absolute path from url then GetFileNameWithoutExtension property is used to remove the extension from path.using Here i have shown to get the file name using path in csharp

Code Behind:
string urlname=Request.Url.AbsolutePath;
string filename= System.IO.Path.GetFileNameWithoutExtension(urlname);
Java Script:
var fname= window.location.href;
var fname=window.location.href.substr(window.location.href.lastIndexOf("/") + 1); 
The sub string is used to get the file name with out extension.For example if path of the page is "defalut.aspx" then the output will be "Default"
If you want to get the raw url of from browser ,you need to write the below line of code.
 string Rawurlmain = HttpContext.Current.Request.RawUrl;
 string  Substringurl = urlmain.Substring(Rawurlmain .LastIndexOf('=') + 1);

Wednesday, November 16, 2011

How to avoid duplicate insertion of records in sql

The redundancy in database occur due to duplication records insertion.For this Here i have shown a simple stored procedure to prevent  the duplicate insertion of records  into database table.

Stored Procedure:
USE [DBname]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[TableName]
    @Month [nvarchar](50),
    @Name[nvarchar](max),
    @ordr [nvarchar](max),
    @Region [nvarchar](50),
    @Country [nvarchar](50),
    @Col_Id [int],
    @Order_id [int],
    AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    -- Insert statements for procedure here
    IF  NOT EXISTS(SELECT * FROM [dbo].[Dfp_Main_Data] WHERE
      [Month] = @Month AND
      [Name] = @NameAND
      [ordr] = @ordr AND
      [Region] = @Region AND
      [Country] = @Country AND
      [Col_Id] = @Col_Id AND
      [Order_id] = @Order_id AND
   )   
        BEGIN
         INSERT INTO [dbo].[Dfp_Main_Data]
           ([Month]
           ,[Col]
           ,[ordr]
           ,[Region]
           ,[Country]
           ,[Col_Id]
           ,[Order_id]
           )
         VALUES
           (@Month
           ,@Col
           ,@ordr
           ,@Region
           ,@Country
           ,@Col_Id
           ,@Order_id
          )
         END
        END

Tuesday, November 15, 2011

Create a widget in Ektron Cms

Before going to Create a widget we have a basic knowledge on web user controls in asp.net .Because the web user controls are used to create a widget in ektron Cms .The widget has its own properties which are created by user and get the information of ektron controls from Ektron Api.For this we will create an user control in web application .This use control has to add to the work area .The fallowing steps to be needs to add the control workarea.In this work area we have tab options which are content,library,settings ,reports.To add the user control we should go to
1. settings -->Personalisation-->widgets

Here we have a synchronization to add the user controls to work area .After adding the user control we can add the widgets to desirable pages by using template page configuration

Show the page host and drop zone on page in ektron CMS

The pagehost has widgets which are placed on webpages.These widgets are user control which is developed using asp .net web application.These user controls are added to ektron work area in widget synchronization folder .Here we have an option to add the widgets to pages in work area.Then we can see the drop zone which is used place the widgets on pages.The given image is the dropzone on the page

This the drop zone area on page to place the widgets .Here i placed a collection widget.To select the collections here we have an edit button on top most of the drop zone .By this way we can place the widgets on page on ektron CMS

Handle the unhandled exception in application in c#

Unhandled exception within an application should be caught managed in a consistent and safe manner.This can be best achieved by using global safe error handler that can be trap all unhandled exception ,log the details ,then present a safe error page to the user.The unhandled exception handling is very important to  development any application . Mainly the unhandled exception are arises at database connection,file loading etc.These exceptions are come when the data base connection state is closed and file is not found.For this i have shown a solution to  handle the unhandled exception

This fallowing piece  of code  have to place in main () of entire application
AppDomain.CurrentDomain.UnhandledException +=UnhandledException.UnhandledExceptionTrapper;
Code behind:
Then we will create a separate class to trap the unhandled exception

public static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e)
      {
          Console.WriteLine(e.ExceptionObject.ToString());
          Console.WriteLine("Press Enter to continue");
          Console.ReadLine();
          Environment.Exit(1);
      } 

Transfer the data from CSV file to Data table in c#

Here i transferred the data from text file(using path of the file ) into LIST<>lidata..The count of list will be used for to run the transfer process.Because If the count is equal  zero means there is no data in the list .For this i will show a simple message "liData File Appears to be Empty".If the count is >0 then have to check whether the data having the row headers or not .if the data having row headers the header fields are transfer into data table.Then the remaining data in the list<> will be transfer to Data table

Code behind:
DataTable DT = new DataTable();
String[] liData = File.ReadAllLines(textfilepath);
if (liData .Length == 0)
{
throw new Exception("liData File Appears to be Empty");
}
String[] headings = liData [0].Split('\t');
int index = 0;
if (isRowOneHeader)
{
index = 0;
for (int i = 0; i < headings.Length; i++)
{
headings[i] = headings[i].Replace(" ", "_");
DT.Columns.Add(headings[i], typeof(string));
}
}
else
{
for (int i = 0; i < headings.Length; i++)
{
DT.Columns.Add("col" + (i + 1).ToString(), typeof(string));
}
}
char[] delimiterChars = { '"' };
for (int i = index; i < liData .Length; i++)
{
if (liData [i] == "'")
continue;
else
{
DataRow row = DT.NewRow();
for (int j = 0; j < headings.Length; j++)
{
string[] rowData = liData [i].Split('\t');
if (rowData.Length <= j)
continue;
row[j] = rowData[j].Trim(delimiterChars);
if (liData [i] != "'" && liData [i] != "")
{
string s = row[j].ToString();
s = s.Replace("'", "");
row[j] = s.Replace(",", "");
}
}
DT.Rows.Add(row);
}
}
return DT;
}

Passing the values from App.config to code behind page using c# || Get key values from config file in asp.net

In this post i will show how to fetch the values from configuration file using C#.net.If we want to use the parameter value for entire application in csharp we have a key value  option in  app.config file.I have shown a simple example for giving the  server name to application using key value.

App.config :
<add key="Email" value="servername"/>

Code Behind:
string servername=ConfigurationManager.AppSettings["servername"].ToString(); 

Passing the javascript variable value to code behind Using C#

In previous post we have seen how to pass variable from server side to client side,get filename from path in javascript,Is there any method to pass JavaScript value to server side?This query raised when i work with java variable in asp.net.Here i will also give an simple tip for new one's which are workd on javascript in asp.net.Many of that get doubt "how to write java script" in asp.net .We can write java script in asp.net as write in html page. "Using hidden field we can pass v javascript  variable from client side to server side".For this i just write a simple javascript function to assign the java variable to asp hidden control.Then we can access the hidden field value and assign to text box .

Function test()
{
  int i=10;
  var hiddentest = '';
document.getElementById('<%= hiddentest.ClientID%>').value = i;
 }
Default.aspx
<asp:HiddelFiled runat="server" id="test"></asp:Hiddenfield>
<asp:textbox runat="server" id="eletext"></asp:textbox>
The id of the hidden field is used to assign the JavaScript variable value
Code behind Page(.cs):
protected void Page_Load(object sender, EventArgs e)
{
eletext.text=test.value; 
}






Create a collection widget in EKtron cms

Collection is list of links to the user on a webpage.It is used to display content links like Latest news and releases.Here i will explain how to create a collection  widget In ektron Cms. There is an option to create a collection  in work area under desirable path.The default id is generated for any element which are  created in work area .Each  collection can manage number of content blocks which  is having the information what we are provided to that.The collection server control having the DefaultDisplaystyle property for display the collection in different appearance using XSLT .The following name spaces have to add to  web application for  creating a collection widget using ektron work area
Add the Collection.ascx to Work Area(Widgets):

Now the  collection user control will be added to widget folder which is under Personalization folder in work area.The below screen shots will give the idea to add the this control to work area
It has the path of personalization folder in work area and synchronization option for user controls which are created in widget folder in application



 It has the widget folder path under personalization
After selecting this folder we have a option synchronization which has shown in above figure -1 to add the user controls which are created in widget  folder in application.Here we have an edit option for every control in work area which can be using to change the title and label name etc.
Namespaces which are added to application to develop the collection widget:
Ektron.Cms.Widget;
Ektron.Cms;
Ektron.Cms.API;
Ektron.Cms.Common;
Ektron.Cms.Controls.CmsWebService;
Ektron.Cms.PageBuilder;
Get the id of collection:
Ektron.Cms.Controls.Collection Collection1 = new Ektron.Cms.Controls.Collection();
Collection1.Page = Page;
Collection1.DefaultCollectionID = CollectionId;
By this way we will allocate the remaining values of collection dynamically.then we will generate events for edit ,cancel the collection wiget.

Bel