Monday, October 10, 2011

How to add arraylist inside of the arraylist in asp.net

ArrayList xxx = new ArrayList();


//////////////Adding inside of arraylist////////////////

for (int g = 1; g <= dt.Rows.Count; g++)
{
xxx.Add(new ArrayList());

}


/////////////////reading the arraylist inside of arraylist/////////////////

for (int g = 0; g < dt.Rows.Count; g++)

{
(xxx[g] as ArrayList).Add(dt2.Rows[j][1+g].ToString());

}

Tuesday, October 4, 2011

How to import data from excel to datatable in c#

protected void button1_Click(object sender, EventArgs e)
{
DataTable test = getDataFromXLS("c:\\xl2xml.xls");
if (test != null)
grid.DataSource = test;
grid.DataBind();
}


protected DataTable getDataFromXLS(string strFilePath)
{
try
{
string strConnectionString = "";
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + strFilePath + "; Jet OLEDB:Engine Type=5;" +
"Extended Properties=Excel 8.0;";
OleDbConnection cnCSV = new OleDbConnection(strConnectionString);
cnCSV.Open();
OleDbCommand cmdSelect = new OleDbCommand(@"SELECT * FROM [Insurance_Aging$]", cnCSV);
OleDbDataAdapter daCSV = new OleDbDataAdapter(); daCSV.SelectCommand = cmdSelect;
DataTable dtCSV = new DataTable();
daCSV.Fill(dtCSV);
cnCSV.Close();
daCSV = null;
return dtCSV;
}
catch (Exception ex)
{
return null;
}
finally { }
}



Import Excel to DataTable
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=911149&SiteID=1
http://support.microsoft.com/kb/815142/en-us
http://msdn2.microsoft.com/en-us/library/ms178685.aspx
http://support.microsoft.com/kb/306572/
http://samples.gotdotnet.com/quickstart/aspplus/doc/configformat.aspx
http://support.microsoft.com/kb/316675/en-us http://msdn.microsoft.com/library/default.asp?url=/library/en-

Sunday, September 25, 2011

bulk import from excel to sql using c#

public partial class _Default : System.Web.UI.Page
{
string strConnection = ConfigurationManager.ConnectionStrings
["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
//Create connection string to Excel work book
string excelConnectionString =
@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Details.xls;
Extended Properties=""Excel 8.0;HDR=YES;""";

//Create Connection to Excel work book
OleDbConnection excelConnection =
new OleDbConnection(excelConnectionString);

//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand
("Select [ID],[Name],[Location] from [Detail$]",
excelConnection);

excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();

SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Details";
//sqlBulk.ColumnMappings.Add("ID", "ID");
//sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
}
}

how to read excel sheet cells using c#

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 Excel = Microsoft.Office.Interop.Excel;

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

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


Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
Excel.Range range ;

string str=string.Empty;
int rCnt = 0;
int cCnt = 0;

HttpPostedFile file = upload.PostedFile;
string fileExt = Path.GetExtension(file.FileName).ToLower();
string fileName = Path.GetFileName(file.FileName);
string filepath = Server.MapPath("./importedfiles/") + fileName;

if (fileExt == ".xls" || fileExt == ".xlsx")
{
if (File.Exists(filepath))
File.Delete(filepath);

file.SaveAs(Server.MapPath("./importedfiles/") + fileName);
//MessageBox.Show(" " + d + " Successfully Uploaded");
}

xlApp = new Excel.ApplicationClass();

xlWorkBook = xlApp.Workbooks.Open("" + filepath + "", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

range = xlWorkSheet.UsedRange;

for (rCnt = 2; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{

if ((range.Cells[rCnt, cCnt] as Excel.Range).Value == null)
{
if (cCnt == 1)
{
str +=" ";
}
else
{
str +=","+" ";
}

}
else
{
if (cCnt == 1)
{
str += (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value.ToString();
}
else
{
str += "," + (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value.ToString();
}

}


}
}

xlWorkBook.Close(true, null, null);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}

private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
// MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();

}
}

}

Tuesday, September 6, 2011

How to get the date of a day from today

DateTime MyDate;
MyDate = Convert.ToDateTime(DateTime.Now);
MyDate = MyDate + TimeSpan.FromDays(7);
string ss = Convert.ToString(MyDate);

Thursday, June 30, 2011

How to implement embedded media player in asp.net c#

Java Script Alert - Run with asp.net update panel

string alertScript = "javascript: alert('Error Occured, Please try again later')";
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript",
alertScript, true);

Friday, June 24, 2011

Export to word from gridview in c#

protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{

Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Individual report of user" + " " + ddlagent.SelectedItem.Text + ".doc"));
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
getgrid();
//Change the Header Row back to white color
//Applying stlye to gridview header cells
DataList1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();


}

Export to Excel from gridview in c#

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
if (chkall.Checked == true)
{
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "calls report of alluser"+txtfromdate.Text+" "+"to"+" "+txttodate.Text+".xls"));
}
else
{
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "calls report of user" + " " + ddlagent.SelectedItem.Text + ".xls"));
}
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
reportgrid.AllowPaging = false;
getgrid();
//Change the Header Row back to white color
reportgrid.HeaderRow.Style.Add("background-color", "#afabc4");
//Applying stlye to gridview header cells
for (int i = 0; i < reportgrid.HeaderRow.Cells.Count; i++)
{
reportgrid.HeaderRow.Cells[i].Style.Add("background-color", "#afabc4");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in reportgrid.Rows)
{
gvrow.BackColor = Color.White;
if (j <= reportgrid.Rows.Count)
{
//if (j % 2 != 0)
//{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#FFFFFF");
}
//}
}
j++;
}

reportgrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();



}

Sunday, June 19, 2011

How to Remove Rendering Function error from asp.net c# program???

Disable the event validations in asp.net page using below:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="Reports.aspx.cs" Inherits="Reports" %>

And Override the Rendering Verification function in c#:


public override void VerifyRenderingInServerForm(Control control)
{

}

Thursday, June 16, 2011

how to execute audio converters using System.Diagnostics in c#(GoldWave)

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo stratInfo = new System.Diagnostics.ProcessStartInfo();
stratInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
stratInfo.FileName = "C:\\Program Files\\GoldWave\\Goldwave.exe";
//stratInfo.Arguments = "/C copy /b image1.jpg + Archive.rar image2.jpg";
stratInfo.Arguments = "/process:MP3 C:\Users\jaganath\Desktop\bosco.VC2";

process.StartInfo = stratInfo;
process.Start();

Thursday, May 26, 2011

how to set datasource for dropdownlist inside of the grid in asp.net

<asp:TemplateField>

<HeaderTemplate>

Client

</HeaderTemplate>

<ItemTemplate>

<asp:Panel ID="pnlClient" runat="server">

<asp:DropDownList ID="ddlClient" runat="server" DataTextField="Clientname" DataValueField="clientid"

DataSource='<%#GetDSfDDL(Eval("client"))%>' AutoPostBack="True" OnSelectedIndexChanged="ddlClient_SelectedIndexChanged">

</asp:DropDownList>

</asp:Panel>

<%-- <asp:Label ID="lblClient" runat="server" Text='<%# bind("Client")%>'></asp:Label>--%>

</ItemTemplate>

<EditItemTemplate>

</EditItemTemplate>

</asp:TemplateField>








public List<clientddl> GetDSfDDL(object client)

{


List<clientddl> values = new List<clientddl>();

string[] cl = client.ToString().Split('/');

 


dt = new DataTable();

dt = bussclass.fnclientlist();


for (int i = 0; i < dt.Rows.Count; i++)

{


clientddl value = new clientddl();

value.Clientid = getint(dt.Rows[i]["client_id"]);

value.Clientname = dt.Rows[i]["client_name"].ToString();

values.Add(value);


}


for (int i = 0; i < values.Count; i++)

{


clientddl temp = new clientddl();

if (values[i].Clientid == getint(cl[0]))

{


if (i > 0)

{


temp = values[0];


values[0] = values[i];


values[i] = temp;


}


}


}


 


return values;

}














Wednesday, May 25, 2011

How to play audio file in asp.net c#

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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.Media;
using WMPLib; //Add this COM Component Reference to your project

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

}

protected void btnPlayMusic_Click(object sender, EventArgs e)
{
string _path = "File Path";

//Method 1 using sound player class
SoundPlayer _sm = new SoundPlayer(_path);
_sm.Play();
//Method 2
Microsoft.VisualBasic.Devices.Audio _mvda = new Microsoft.VisualBasic.Devices.Audio();
_mvda.Play(_path, Microsoft.VisualBasic.AudioPlayMode.Background);


//Method 3 using WindowsMediaPlayer Class
WindowsMediaPlayerClass _wmpc = new WindowsMediaPlayerClass();
_wmpc.openPlayer(_path);
_wmpc.play();


}
}

Monday, May 9, 2011

how to copy files to local to server path using c#

string path="C:\\Users\\prag\\Desktop\\bosco\\test.txt";
string sourceFile = path;
string destinationFile = Server.MapPath("./file/test.txt");
System.IO.File.Copy(sourceFile, destinationFile);

Thursday, May 5, 2011

How to set hyperlink from the code behind using java script:

java script:


Hyperlink in grid row template:



Code Behind:


public string GetScript(object cid)
{
return "javascript:launchDetailsPage(" + cid.ToString() + ")";
}

Wednesday, May 4, 2011

how to create expandable text box in asp.net

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



function setHeight(txtdesc) {


txtdesc.style.height = txtdesc.scrollHeight + "px";


 }



</script>


Design:

<asp:TextBox ID="txtNotes" runat="server" TextMode="MultiLine" Height="70px" Width="230px" onkeyup="setHeight(this)"></asp:TextBox>




Friday, April 29, 2011

how to append text in literal control using c#


dynamic generation of text boxes in button click using c#

static int i=0;

protected void Button2_Click(object sender, EventArgs e)
{
n++;


int i = 0;

TextBox[] tb = new TextBox[n + 1];

for (i = 0; i <= n - 1; i++)
{

tb[i] = new TextBox();
dynsmicpnl.Controls.Add(tb[i]);
dynsmicpnl.Controls.Add(new LiteralControl("
"));

}
}

Tuesday, April 26, 2011

How to Write Case statements in sql view

CREATE view [dbo].[vwcall_master]
as
select
case when Call_Duration is null then 'Enter duration' else Call_Duration end as Call_Duration,
case when Call_To_NumberExtn is null then '00000000' else Call_To_NumberExtn end as Call_To_NumberExtn,
case when Client_Id is null then '0' else Client_Id end as Client_Id,
case when Client_Name is null then ' Enter Clientname' else Client_Name end as Client_Name,

Call_Id,
User_Id,
Call_From_UserName,
Call_From_NumberExtn,
Call_DateTime,
UpLoade_Audio_Call,
Rating,
Rating_UserId
from call_master

Wednesday, April 20, 2011

How to convert ist to est in c#

DateTime time1 = new DateTime(2011,04,20,17,57,33);
// DateTime time1 = new DateTime();// your DataTimeVariable

TimeZoneInfo timeZone1 = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
TimeZoneInfo timeZone2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

DateTime newTime = TimeZoneInfo.ConvertTime(time1, timeZone1, timeZone2);
Response.Write(newTime);

Saturday, April 16, 2011

How to use file system writer in c#

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:\\Documents and Settings\\bosco\\Desktop\\system";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";

// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);

// Begin watching.
watcher.EnableRaisingEvents = true;

}
protected void OnChanged(object sender, FileSystemEventArgs e)
{

string str = e.FullPath;
string[] str1=str.Split('\\');
// Specify what is done when a file is changed, created, or deleted.
MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);
MessageBox.Show(str1[0] + "," + str1[1] + "," + str1[2]);
// Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}

protected void OnRenamed(object sender, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.


//Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
MessageBox.Show("File: " + e.FullPath + " " + e.ChangeType);

}

Thursday, April 7, 2011

how to set attributes in the asp.net tool elements

private void buildcboAuthors()
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM tblAuthors",conn);
this.conn .Open ();
OleDbDataReader rsAutors = cmd.ExecuteReader();
ArrayList Authors = new ArrayList();

while(rsAutors.Read())
{
Authors.Add (new AddValue
(rsAutors.GetString(1),rsAutors.GetInt32 (0)));

}
rsAutors.Close();
this.conn.Close();

this.cboAuthors.DataSource = Authors;
this.cboAuthors .DisplayMember ="Display";
this.cboAuthors.ValueMember = "Value";
AuthorsHaveBeenAdded=true;
}

Wednesday, March 9, 2011

Sql Triggers with some examples



Table creation:

create table general_comments (
comment_id integer primary key,
on_what_id integer not null,
on_which_table varchar(50),
user_id not null references users,
comment_date date not null,
ip_address varchar(50) not null,
modified_date date not null,
content clob,
-- is the content in HTML or plain text (the default)
html_p char(1) default 'f' check(html_p in ('t','f')),
approved_p char(1) default 't' check(approved_p in ('t','f'))
);


Trigger Creation:

create trigger general_comments_modified
before insert or update on general_comments
for each row
begin
:new.modified_date := sysdate;
end;



Another One Type Of Trigger:


create table queries (
query_id integer primary key,
query_name varchar(100) not null,
query_owner not null references users,
definition_time date not null,
-- if this is non-null,
we just forget about all the query_columns

-- stuff; the user has hand edited the SQL
query_sql varchar(4000)
);

create table queries_audit (
query_id integer not null,
audit_time date not null,
query_sql varchar(4000)
);



create or replace trigger queries_audit_sql
before update on queries
for each row
when (old.query_sql is not null and (new.query_sql is null
or old.query_sql <> new.query_sql))
begin
insert into queries_audit (query_id, audit_time, query_sql)
values
(:old.query_id, sysdate, :old.query_sql);
end;

Tuesday, March 1, 2011

Bulk insert in C#

DataTable dt = new DataTable();
string line = null;
int i = 0;
using (StreamReader sr = File.OpenText(@"c:\temp\table1.csv"))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
dt.Rows.Add(row);
}
}
}