Friday, July 10, 2009

crrating csv in c# and asp.net

public void getHBRemindercsvFile()
{
if(dsBdayReminder.Tables[0].Rows.Count<1)
{
LblError.Visible=true;
LblError.Text="You have no reminders !";
}
string attachment = "attachment; filename=BirthdayReminder.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
WriteColumnName(" Name , Day , Month ");
foreach (DataRow drt in dsBdayReminder.Tables[0].Rows)
{
WriteHBReminder(drt);
}

HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
private void WriteHBReminder(DataRow drt)
{
StringBuilder stringBuilder = new StringBuilder();

AddComma(drt["reminder_name"].ToString(), stringBuilder);
AddComma(drt["reminder_day"].ToString(), stringBuilder);
AddComma(GetMonthName(Convert.ToInt32(drt["reminder_month"])), stringBuilder);

HttpContext.Current.Response.Write(stringBuilder.ToString());
HttpContext.Current.Response.Write(Environment.NewLine);
}

private void AddComma(string value, StringBuilder stringBuilder)
{
stringBuilder.Append(value.Replace(',', ' '));
stringBuilder.Append(", ");
}

private void WriteColumnName(string columnNames)
{
HttpContext.Current.Response.Write(columnNames);
HttpContext.Current.Response.Write(Environment.NewLine);
}

making thumbnil in asp.net

public class MakeThumbnail : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// get the file name -- fall800.jpg
string file = Request.QueryString["file"];

// create an image object, using the filename we just retrieved
System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(file));

// create the actual thumbnail image
System.Drawing.Image thumbnailImage = image.GetThumbnailImage(160, 120, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

// make a memory stream to work with the image bytes
MemoryStream imageStream = new MemoryStream();

// put the image into the memory stream
thumbnailImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg);//Imaging.Imageformat.Jpeg);

// make byte array the same size as the image
byte[] imageContent = new Byte[imageStream.Length];

// rewind the memory stream
imageStream.Position = 0;

// load the byte array with the image
imageStream.Read(imageContent, 0, (int)imageStream.Length);

// return byte array to caller with image type
Response.ContentType = "image/jpeg";
Response.BinaryWrite(imageContent);
}
public bool ThumbnailCallback()
{
return true;
}

HTML tag
img src='wallpaper/MakeThumbnail.aspx?file=<%# DataBinder.Eval(Container.DataItem,"image_path") %>'

Creating Rss in asp.net

private void WriteXmlForRSS(string Id)
{
try
{

getReminderData(Id);
Response.Clear();
Response.ContentType = "text/xml";
XmlTextWriter objX = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
objX.WriteStartDocument();
objX.WriteStartElement("rss");
objX.WriteAttributeString("version","2.0");
objX.WriteStartElement("channel");
objX.WriteElementString("title", "HappyBirthday");
objX.WriteElementString("link","https://www.happybirthday.com/Account/rss.aspx?id="+Id);
objX.WriteElementString("description","The latest birthday's and others reminder from the HappyBirthday.com");
objX.WriteElementString("copyright","(c) 2009, HappyBirthday,com, All rights reserved.");
objX.WriteElementString("ttl","5");
//image
objX.WriteStartElement("image");
objX.WriteElementString("url","https://www.happybirthday.com/home3/logo2.gif");
objX.WriteElementString("title","HappyBirthday");
objX.WriteElementString("link","http://www.happybirthday.com");
objX.WriteEndElement();

//title
objX.WriteStartElement("item");
objX.WriteElementString("title","Birthday Reminders");
//objX.WriteElementString("description","Your Birthday Reminders" );
objX.WriteEndElement();

//Reminders
foreach(DataRow dr in dsBdayReminder.Tables[0].Rows)
{
objX.WriteStartElement("item");
objX.WriteElementString("title",dr["reminder_name"]+"'s birthday ( "+dr["reminder_day"]+" "+GetMonthName(Convert.ToInt32(dr["reminder_month"]))+")");
objX.WriteElementString("category",dr["reminder_month"].ToString());
objX.WriteElementString("description"," "+dr["reminder_name"]+"'s happy birthday is on "+dr["reminder_day"]+ " "+ GetMonthName(Convert.ToInt32(dr["reminder_month"])));
objX.WriteElementString("link","https://www.happybirthday.com/Account/rss.aspx?id="+Id);
objX.WriteElementString("pubDate",DateTime.Now.ToLongDateString());

objX.WriteEndElement();
}
//title
objX.WriteStartElement("item");
objX.WriteElementString("title","Other Reminders");
//objX.WriteElementString("description","Your Other Reminders" );
objX.WriteEndElement();
// other Reminders
foreach(DataRow dr in dsOtherReminder.Tables[0].Rows)
{
objX.WriteStartElement("item");
objX.WriteElementString("title",dr["other_reminder_name"]+"'s "+dr["other_reminder_description"]+" ("+dr["other_reminder_day"]+" "+GetMonthName(Convert.ToInt32(dr["other_reminder_months"]))+")");
objX.WriteElementString("category",dr["other_reminder_months"].ToString());
objX.WriteElementString("description",dr["other_reminder_name"]+"'s "+dr["other_reminder_description"]+" is on "+dr["other_reminder_day"] +" "+GetMonthName(Convert.ToInt32(dr["other_reminder_months"])));
objX.WriteElementString("link","https://www.happybirthday.com/Account/rss.aspx?id="+Id);
objX.WriteElementString("pubDate",DateTime.Now.ToLongDateString());

objX.WriteEndElement();
}


//
objX.WriteEndElement();
objX.WriteEndElement();
objX.WriteEndDocument();
objX.Flush();
objX.Close();

}
catch(Exception ex)
{
Response.Write("Error Occour!");
return;
}
Response.End();
}

html tag


/td vAlign="top" align="center" height="78">

Reminder Feed

Wednesday, July 8, 2009

crating pager in datalist



private void LoadImage(string FolderName)

{

try {

string wallFolderPath = Server.MapPath(FolderName);

string[] FilesColl = Directory.GetFiles(wallFolderPath);

if (FilesColl.Length > 0) {

int tempLength = FilesColl.Length;

for (int i = 0; i < extn =" Path.GetExtension(FilesColl[i]).ToLower();" extn ="=" extn ="=" extn ="=" fs =" new" fn="fs.Name;" fktitle="Path.GetFileName(FilesColl[i]).Replace(extn," drow =" dtWall.NewRow();" imagepath =" FilesColl[i];" imagepath="imagePath.Substring(imagePath.IndexOf(parentImageDir)+parentImageDir.Length+1);" datasource="dtWall.DefaultView;" allowpaging="true;" pagesize =" 16;" currentpageindex =" CurrentPage;" enabled =" !pds.IsLastPage;" enabled =" !pds.IsFirstPage;" datasource="pds;" text="dtWall.Rows.Count.ToString();">0) {




LnlBack.Visible=false;

}

}

catch(Exception ex)

{

ShowError(ex.Message);

}

}




public int CurrentPage

{




get

{

if (this.ViewState["CurrentPage"] == null)

return 0;

else

return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());

}




set

{

this.ViewState["CurrentPage"] = value;

}




}

private void doPaging()

{

DataTable dt = new DataTable();

dt.Columns.Add("PageIndex");

dt.Columns.Add("PageText");

for (int i = 0; i < dr =" dt.NewRow();" datasource =" dt;" currentpage =" Convert.ToInt16(e.CommandArgument.ToString());" wallfoldername =" ViewState[" lnkbtnpage =" (LinkButton)e.Item.FindControl(" enabled =" false;" bold =" true;" wallfoldername =" ViewState[" wallfoldername =" ViewState[">
HTML
asp1:datalist1 id="dlPaging" runatr="serverr" RepeatDirection="Horizontal" Height="15px">

ItemTemplate1>
asp1:LinkButton1 ID="lnkbtnPaging" runatr="serverr" CommandArgument=<# DataBinder.Eval(Container.DataItem,"PageIndex") > CommandName="lnkbtnPaging" Text=<# DataBinder.Eval(Container.DataItem,"PageText") >'> /asp1:LinkButton1 /ItemTemplate1> /asp1:datalist

Wednesday, March 25, 2009

Maximum Date in a group of records

Sort command and groupins i am ok but i need to select only the records that
has the latest enddate


eg-: select h.component_fixed_id ,h.date_added,h.factory_price from history_manufacturer_components as h
where manufacturer_code='arv001' and
date_added =(select max(date_added) from history_manufacturer_components where component_fixed_id=h.component_fixed_id)

or
This query returns row(s) with the latest Enddate for each ID but the row
for ID='B' isn't the one you highlighted.


SELECT id, startdate, enddate
FROM SomeTable AS S
WHERE enddate =
(SELECT MAX(enddate)
FROM SomeTable
WHERE id = S.id)

Wednesday, December 3, 2008

import from excel in c#

private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
path = openFileDialog1.FileName;
}

private void btnImport_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "excel file |*.xls";
openFileDialog1.FilterIndex = 1;
openFileDialog1.InitialDirectory = "%My Documents%";
openFileDialog1.ShowDialog(this);
// path = openFileDialog1.FileName;
if (path != "")
{
try
{
oledbConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + @"; Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""";
olebdConn.ConnectionString = oledbConnectionString;
oledbCmmd.Connection = olebdConn;
oledbCmmd.CommandText = "Select * FROM [Sheet1$]";
olebdConn.Open();
da =new OleDbDataAdapter(oledbCmmd);
da.Fill(ds);

dgvExcelData.Visible = true;
////dt = dr.GetData(4);
int count = ds.Tables[0].Rows.Count;
label2.Text = count.ToString();
////dgvExcelData.Rows.Clear();

dgvExcelData.DataSource = ds.Tables[0];
////dgvExcelData.Visible = true;
olebdConn.Close();
}

Export into excel in c# through COM

  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, click New, and then click Project. Select Windows Application from the Visual C# Project types. Form1 is created by default.
  3. Add a reference to the Microsoft Excel Object Library. To do this, follow these steps:
    1. On the Project menu, click Add Reference.
    2. On the COM tab, locate Microsoft Excel Object Library, and click Select.
-----------------------------------------------------------------------------------------------
using System.Reflection;
Excel._Application oxl;
Excel._Workbook owb;
Excel._Worksheet oWs;
Excel.Range oRange;
methord( )
{
oxl = new Excel.Application();
oxl.Visible = true;
//Get a new workbook.
owb = (Excel._Workbook)(oxl.Workbooks.Add(Missing.Value));
oWs = (Excel._Worksheet)owb.ActiveSheet;
//Add table headers going cell by cell
oWs.Cells[1, 1] = "First Name";
oWs.Cells[1, 2] = "Last Name";
oWs.Cells[1, 3] = "Full Name";
oWs.Cells[1, 4] = "Salary";

//Format A1:D1 as bold, vertical alignment = center.
oWs.get_Range("A1", "D1").Font.Bold = true;
oWs.get_Range("A1", "D1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[1, 1] = "Brown";
saNames[2, 0] = "Sue";
saNames[2, 1] = "Thomas";
saNames[3, 0] = "Jane";
saNames[3, 1] = "Jones";
saNames[ 4, 0] = "Adam";
saNames[ 4, 1] = "Johnson";
//Fill A2:B6 with an array of values (First and Last Names).
oWs.get_Range("A2", "B6").Value2 = saNames;
//Fill C2:C6 with a relative formula (=A2 & " " & B2).
oRange = oxl.get_Range("C2", "C6");
oRange.Formula = "=A2 &\" \"& B2";
//Fill D2:D6 with a formula(=RAND()*100000) and apply format.
oRange = oxl.get_Range("D2", "D6");
oRange.Formula = "=RAND()*10000";
oRange.NumberFormat = "$0.00";
//AutoFit columns A:D.
oRange = oWs.get_Range("A1", "D1");
oRange.EntireColumn.AutoFit();
//Manipulate a variable number of columns for Quarterly Sales Data.
//DisplayQuarterlySales(oWs);

//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oxl.Visible = true;
oxl.UserControl = true;