Friday, November 13, 2009

PNG Fix

<!--[if lt IE 7]>

<script language="JavaScript">

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.

{

   var arVersion = navigator.appVersion.split("MSIE")

   var version = parseFloat(arVersion[1])

   if ((version >= 5.5) && (document.body.filters))

   {

      for(var i=0; i<document.images.length; i++)

      {

         var img = document.images[i]

         var imgName = img.src.toUpperCase()

         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")

         {

            var imgID = (img.id) ? "id='" + img.id + "' " : ""

            var imgClass = (img.className) ? "class='" + img.className + "' " : ""

            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "

            var imgStyle = "display:inline-block;" + img.style.cssText

            if (img.align == "left") imgStyle = "float:left;" + imgStyle

            if (img.align == "right") imgStyle = "float:right;" + imgStyle

            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle

            var strNewHTML = "<span " + imgID + imgClass + imgTitle

            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"

            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"

            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"

            img.outerHTML = strNewHTML

            i = i-1

         }

      }

   }   

}

window.attachEvent("onload", correctPNG);

</script>

<![endif]-->

Thursday, September 3, 2009

Javascript to get querystring

function to fetch querysting values:

function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}


to get the value of parameter:

var author_value = getQuerystring('parameter_Name');

Wednesday, August 12, 2009

Bravenet Links

Following are the bravenet links containing some JQuery code:

1) http://nitindhiman.bravehost.com/TableChart.htm

2) http://nitindhiman.bravehost.com/dropdown.htm

3) http://nitindhiman.bravehost.com/puzzle.htm

4) http://nitindhiman.bravehost.com/TooltipBubble.htm

5) http://nitindhiman.bravehost.com/horizontalAccordion.htm

6)

Thursday, May 21, 2009

To get the names of the latest altered storedprocedures in SQL.

following is the query:
declare @date1 datetime
set @date1 = '1-sep-2008'

select specific_name,last_altered,created from information_schema.routines
where datediff(day,@date1, last_altered) > 0
or
datediff(day,@date1, created) > 0

Sunday, May 17, 2009

Textbox validation for numeric and other key codes.

function fncInputNumericValuesOnly()
{
if(!(event.keyCode==45||event.keyCode==46||event.keyCode==48||event.keyCode==49||event.keyCode==50||event.keyCode==51||event.keyCode==52||event.keyCode==53||event.keyCode==54||event.keyCode==55||event.keyCode==56||event.keyCode==57))
{
event.returnValue=false;
}
}

< asp:TextBox id="txtQty" runat="server" onkeypress= "fncInputNumericValuesOnly('')"/>

Or add any other ascii code as keyCode to allow like:

8=backspace
190=dot
37=left arrow
39=right arrow
16=shift

Friday, March 13, 2009

get data from .txt file and insert into sql table.

protected void button_click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("ACCOUNT", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("CUSTOMER", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("TRADES", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("SHARES", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("COMMISSION", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("TRADES1", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("SHARES1", typeof(System.String));
dt.Columns.Add(dc);
dc = new DataColumn("COMMISSION1", typeof(System.String));
dt.Columns.Add(dc);

string con = "Data Source=SERVERNAME;Database=DATABASENAME;Persist Security Info=True;User ID=USERNAME;Password=PWD";
SqlConnection myConnection = new SqlConnection(con);
const string strSQL = "select * from praveen";
SqlCommand myCommand = new SqlCommand(strSQL, myConnection);
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
SqlCommandBuilder cb = new SqlCommandBuilder(myAdapter);
myConnection.Open();

System.IO.StreamReader sr = new System.IO.StreamReader(@"C:/Documents and Settings/nitin.dhiman/Desktop/NYSE_MERGE_ORDER_LOG.doc");
string line;
int i = 0;
while (sr.Peek() != -1)
{
i++;
line = sr.ReadLine();
if (line.Contains("MTD TRADES"))
{
flage = 1;
}
if (line.Contains("/PAGE"))
{
flage = 0;
}
if (line.Contains("TOTALS"))
{
flage = 0;
}
if (flage == 1)
{
if (line == "" || line == " " || line == " ACCOUNT CUSTOMER TRADES SHARES COMMISSION TRADES SHARES COMMISSION " || line == "---------- ------------------------------ ---------- --------------- --------------- --------- --------------- --------------- " || line == " ---------- MTD TRADES ---------- ---------- MTD SETTLES ---------- ")
{

}
else
{
string value = line;
value = value.Replace(" ", "~");
value = value.Replace("~~~~~~~~~", "~");
value = value.Replace("~~~~~~~~", "~");
value = value.Replace("~~~~~~~", "~");
value = value.Replace("~~~~~~", "~");
value = value.Replace("~~~~~", "~");
value = value.Replace("~~~~", "~");
value = value.Replace("~~~", "~");
value = value.Replace("~~", "~");
string[] text = value.Split('~');

DataRow dr = dt.NewRow();
dr[0] = text[0];
dr[1] = text[1];
dr[2] = text[2];
dr[3] = text[3];
dr[4] = text[4];
dr[5] = text[5];
dr[6] = text[6];
dr[7] = text[7];
dt.Rows.Add(dr);

myAdapter.Update(dt);
dt.AcceptChanges();
}
}
}
Response.Write(i);
}

get data from xml file.

call following function:


public void abc()
{
StreamReader stream1 = new StreamReader("C:\\Inetpub\\wwwroot\\PR\\TreeNormal\\books.xml");
XmlTextReader reader = null;
reader = new XmlTextReader(stream1);

while (reader.Read())
{
// Do some work here on the data.
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an Element.
Response.Write("<" + reader.Name);
Response.Write(">
");
break;
case XmlNodeType.Text: //Display the text in each element.
Response.Write("
" + reader.Value);
break;
case XmlNodeType.EndElement: //Display end of element.
Response.Write(" Response.Write(">
");
break;
}

//Response.Write(reader.Name + " ");
}

while (reader.Read())
{
// Do some work here on the data.
//Console.WriteLine(reader.Name);
Response.Write(reader.Name);
}



}

Bind TreeView to sql database.

Call the following function in page_load event:


void fill_Tree()
{
//Database db = DatabaseFactory.CreateDatabase("ConStr");
//string sqlCommandName = "Select * from ParentTable";
//DbCommand dbCmd = db.GetSqlStringCommand(sqlCommandName);
//SqlDataReader Sdr = dbCmd.ExecuteReader();

/ SqlCon = new SqlConnection("Data Source=DATABASENAME;Initial Catalog=GKTraining;Persist Security Info=True;User ID=USERID;Password=gK@t#a!n!^T)");

SqlCon.Open();

/*
* Query the database
*/

SqlCommand SqlCmd = new SqlCommand("Select * from a_tbl_parent", SqlCon);

/*
*Define and Populate the SQL DataReader
*/

SqlDataReader Sdr = SqlCmd.ExecuteReader();

/*
* Dispose the SQL Command to release resources
*/

SqlCmd.Dispose();

/*
* Initialize the string ParentNode.
* We are going to populate this string array with our ParentTable Records
* and then we will use this string array to populate our TreeView1 Control with parent records
*/

string[,] ParentNode = new string[100, 2];

/*
* Initialize an int variable from string array index
*/

int count = 0;

/*
* Now populate the string array using our SQL Datareader Sdr.

* Please Correct Code Formatting if you are pasting this code in your application.
*/

while (Sdr.Read())
{

ParentNode[count, 0] = Sdr.GetValue(Sdr.GetOrdinal("ParentID")).ToString();
ParentNode[count++, 1] = Sdr.GetValue(Sdr.GetOrdinal("ParentName")).ToString();

}

/*
* Close the SQL datareader to release resources
*/

Sdr.Close();

/*
* Now once the array is filled with [Parentid,ParentName]
* start a loop to find its child module.
* We will use the same [count] variable to loop through ChildTable
* to find out the number of child associated with ParentTable.
*/

for (int loop = 0; loop < count; loop++)
{

/*
* First create a TreeView1 node with ParentName and than
* add ChildName to that node
*/

TreeNode root = new TreeNode();
root.Text = ParentNode[loop, 1];
root.Target = "_blank";

/*
* Give the url of your page
*/

root.NavigateUrl = "mypage.aspx";

/*
* Now that we have [ParentId] in our array we can find out child modules

* Please Correct Code Formatting if you are pasting this code in your application.

*/

SqlCommand Module_SqlCmd = new SqlCommand("Select * from a_tbl_child where ParentId =" + ParentNode[loop, 0], SqlCon);

SqlDataReader Module_Sdr = Module_SqlCmd.ExecuteReader();

while (Module_Sdr.Read())
{

// Add children module to the root node

TreeNode child = new TreeNode();

child.Text = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString();

child.Target = "_blank";

//child.NavigateUrl = "your_page_Url.aspx";
child.NavigateUrl = Module_Sdr.GetValue(Module_Sdr.GetOrdinal("ChildName")).ToString()+".aspx";

root.ChildNodes.Add(child);

}

Module_Sdr.Close();

// Add root node to TreeView
TreeView1.Nodes.Add(root);

}

/*
* By Default, when you populate TreeView Control programmatically, it expends all nodes.
*/
TreeView1.CollapseAll();
SqlCon.Close();

}

Asp calendar DayRender event.

Hi,

Here is the asp:calendar DayRender event example:



protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
string fontWeight = "normal";
if (isThereEvent(e.Day.Date))
fontWeight = "bold";

string color = "black";
if (e.Day.IsOtherMonth)
color = this.Calendar1.OtherMonthDayStyle.ForeColor.Name;

e.Cell.Text = String.Format("<a href="http://www.blogger.com/Default.aspx?day=%7B0:d%7D" style="text-decoration: none;">{1}</a>", e.Day.Date, e.Day.Date.Day);
}

private bool isThereEvent(DateTime date)
{
DateTime today = DateTime.Now;
DateTime tomorrow = today.AddDays(1);
DateTime anotherDay = today.AddDays(3);

// there are events today
if ((date.DayOfYear == today.DayOfYear) && (date.Year == today.Year))
return true;

// there are events tomorrow
if ((date.DayOfYear == tomorrow.DayOfYear) && (date.Year == tomorrow.Year))
return true;

// there are events on another day
if ((date.DayOfYear == anotherDay.DayOfYear) && (date.Year == anotherDay.Year))
return true;

return false;
}

Thursday, March 12, 2009

Data Scraping.

Call following function for scraping:


protected void GetValueofFirstPage()
{
DataTable dt = new DataTable();
dt = CreateTable();
string strURL = "http://wsa2009.expoplanner.com/plsearch.wcs?searchby=all&seekword=null&alpha=all&filter=";
String strResult;
WebResponse objResponse;
WebRequest objRequest = HttpWebRequest.Create(strURL);
objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
//strResult = sr.ReadToEnd();

while ((strResult = sr.ReadLine()) != null)
{
if (strResult.Contains("Booth"))
{
flage = 1; ;
}
if (flage == 1)
{
if (strResult.Contains("href") && strResult.Contains("?"))
{
DataRow dr = dt.NewRow();
string[] str = strResult.Split('>');
string[] path = str[0].Split('\"');
str[1] = str[1].Replace("ANCHOR TAG END ~<~/~A~", "");
dr[0] = str[1];
dr[1] = "http://wsa2009.expoplanner.com/" + path[1];
dt.Rows.Add(dr);
Response.Write(str[1] + ' ' + path[1]);
Response.Write("LINE BREAK <~B~R~/~>");
//Session["dt"] = dt.ToString();
Session["dt"] = dt;
}
}
}

sr.Close();
flage = 0;
}
grd.DataSource = dt;
grd.DataBind();
}

Managing treeview in asp.net

TreeView1.Nodes.Clear();


TreeNode ndHome = new TreeNode("Home", "Home", "~/closebox.png", "~/Home.aspx", "");
TreeNode ndSplitter = new TreeNode("Splitter", "Splitter", "~/closebox.png", "~/Splitter.aspx", "");
TreeNode ndCheckPage = new TreeNode("Check Page", "Check Page",
"~/closebox.png", "~/CheckPage.htm", "");
TreeNode ndSearch = new TreeNode("Search", "Search", "~/closebox.png", "~/Search.aspx", "");
TreeNode ndAdvancedSearch = new TreeNode("Advanced Search", "Advanced Search",
"~/closebox.png", "~/AdvancedSearch.aspx", "");
TreeNode ndTxtChk = new TreeNode("TextBox", "TextBox", "~/closebox.png", "~/TextCheck.aspx", "");
TreeNode ndLogout = new TreeNode("Logout", "Logout", "~/closebox.png", "~/Logout.aspx", "");
TreeNode ndExtra = new TreeNode("Extra", "Extra", "~/closebox.png", "#", "");
TreeView1.Nodes.Add(ndHome);
TreeView1.Nodes[0].ChildNodes.Add(ndCheckPage);
TreeView1.Nodes.Add(ndSplitter);
//TreeView1.Nodes[0].ChildNodes.Add(ndAdvancedSearch);
TreeView1.Nodes.Add(ndSearch);
TreeView1.Nodes[2].ChildNodes.Add(ndAdvancedSearch);
TreeView1.Nodes.Add(ndLogout);
TreeView1.Nodes.Add(ndExtra);
TreeView1.Nodes[4].ChildNodes.Add(ndTxtChk);

Read data from xml file.

public void abc()
{
StreamReader stream1 = new StreamReader("C:\\Inetpub\\wwwroot\\PR\\TreeNormal\\books.xml");
XmlTextReader reader = null;
reader = new XmlTextReader(stream1);

while (reader.Read())
{
// Do some work here on the data.
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an Element.
Response.Write("<" + reader.Name); Response.Write(">
");
break;
case XmlNodeType.Text: //Display the text in each element.
Response.Write("
" + reader.Value);
break;
case XmlNodeType.EndElement: //Display end of element.
Response.Write("
");
break;
}

//Response.Write(reader.Name + " ");
}

while (reader.Read())
{
// Do some work here on the data.
//Console.WriteLine(reader.Name);
Response.Write(reader.Name);
}
}

Incorporate Google Map to page.

SCRIPT START HERE src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAchOdSzCPe0fgAm8Ow24YYhQZMjxVy-0fy3B1JroJth17tbEUrRQwDlqM1PUlwiawvBO4RMVpYVIfLA"
type="text/javascript"
/SCRIPT END HERE

2ND SCRIPT TAG START HERE

var map = null;
var geocoder = null;

function load()
{
if (GBrowserIsCompatible())
{
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

geocoder = new GClientGeocoder();
var address =document.getElementById('TextBox1').value;

showAddress(address);
}
return false;
}
function showAddress(address)
{
if (geocoder)
{
geocoder.getLatLng(address,function(point) {
if (!point) {alert(address + " not Valid Address ");}
else {
map.setCenter(point, 13);

var baseIcon = new GIcon();
baseIcon.shadow = "images/star_location.gif";

baseIcon.iconSize = new GSize(19, 18);
baseIcon.shadowSize = new GSize(19, 18);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
function createMarker(point, index) {
// Create a lettered icon for this point using our icon class
var letter = String.fromCharCode("A".charCodeAt(0) + index);
var icon = new GIcon(baseIcon);
icon.image = "images/star_location.gif";
var marker = new GMarker(point, icon);

GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(address);});
return marker;
}

map.addOverlay(createMarker(point, 13));
}
}
);
}
}
/2ND SCRIPT TAG END HERE.


//DIV IN HTML PAGE

divSTART id="map" style="width: 600px; height: 600px;">
/divEND

//BUTTON BODY:

asp:button id="Button1" onclientclick="javascript:return load();" runat="server" text="Button"

Google Search in asp.net page.

asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server"
//put the following line in script:

putScriptHere src="http://www.google.com/jsapi?key=ABQIAAAAchOdSzCPe0fgAm8Ow24YYhQZMjxVy-0fy3B1JroJth17tbEUrRQwDlqM1PUlwiawvBO4RMVpYVIfLA"
type="text/javascript"

//put following also in script tag

google.load("search", "0");

function OnLoad() {
// Create a search control
var searchControl = new google.search.SearchControl();

// Add in a full set of searchers
var localSearch = new google.search.LocalSearch();
searchControl.addSearcher(localSearch);
searchControl.addSearcher(new google.search.WebSearch());
searchControl.addSearcher(new google.search.VideoSearch());
searchControl.addSearcher(new google.search.BlogSearch());

// Set the Local Search center point
localSearch.setCenterPoint("New Delhi, INDIA");

// Tell the searcher to draw itself and tell it where to attach
searchControl.draw(document.getElementById("searchcontrol"));

// Execute an inital search
searchControl.execute("");
}
google.setOnLoadCallback(OnLoad);


divSTART id="searchcontrol"
Loading.../divEND
/asp:content

javascript to find day difference.

HTML START
HEAD START HERE
SCRIPT START HERE language="javascript" type="text/javascript"
today = new Date();
todayEpoch = today.getTime();

target = new Date("1 Jan, 2009");
targetEpoch = target.getTime();

daysLeft = Math.floor(((targetEpoch - todayEpoch) / (60*60*24)) / 1000);
SCRIPT END HERE

HEAD END
BODY START HERE
FROM START method="get" action="http://www.google.com/search"

DoD inspection in

SCRIPT START HERE document.write(daysLeft); SCRIPT TAG END HERE

days. Are you ready?

FORM END
BODY END
HTML END

Create bound control column in a grid.

public void createBoundCols()
{
DataTable dt = ds.Tables[0];

int countDt = 0;
foreach (DataColumn col in dt.Columns)
{
if (countDt < 12)
{
BoundField bfield = new BoundField();
bfield.DataField = col.ColumnName;
bfield.HeaderText = col.ColumnName;
GrdDynamic.Columns.Add(bfield);
countDt = countDt + 1;
}

}

CommandField cf = new CommandField();
cf.HeaderText = "print";

cf.ShowSelectButton = true;
cf.SelectText = "Print";
cf.Visible = true;


GrdDynamic.Columns.Add(cf);

}



// and on grid row command so that we can fire the event associated with the created bound column.



protected void GrdDynamic_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);

// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = GrdDynamic.Rows[index];
int rowid = Convert.ToInt32(row.Cells[0].Text.ToString());
Response.Redirect("RecordDetails.aspx?rID=" + rowid);

}
}

print all data on a page.

Hi,

Here is the javascript code to print all the data on the page:

scriptSTART language="javascript" type="text/javascript"

function printdoc()
{
var div=document.getElementById("DivPrint");

//to hide the undesired DIV from print page.
div.style.display='none';
window.print();
return true;
}

/scriptEND


asp:button id="btnPrint" runat="server" width="90px" text="Print" onclientclick="printdoc();"

Export to excel, word in .net

Hi,

Here is the code to export the grid data to excel or word:

// create an enum
public enum ExportType
{

EXCEL,

PDF,

WORD
}

//source can be DataSet, DataTable and etc
public void ExportDataGrid(object source, ExportType type)
{
try
{
// setting temporarily datagrid
DataGrid dg = new DataGrid();
dg.ID = "GridView1";
dg.DataSource = source;
dg.AutoGenerateColumns = true;
dg.AllowPaging = false;
dg.AllowSorting = false;
dg.DataBind();
// export selected format
Response.Clear();
Response.Buffer = true;
switch ((type))
{
case ExportType.EXCEL:
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "ExportedGridData"));
break;
case ExportType.PDF:
break;
// TODO
case ExportType.WORD:
Response.ContentType = "application/ms-word";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.doc", "ExportedGridData"));
break;
}
Response.Charset = "";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
dg.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
catch (Exception ex)
{
if ((ex.Message != "Thread was being aborted."))
{
Response.Write(("Error occur while exporting excel. For more information:" + ex.Message));
}
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];

if (ds.Tables[0].Rows.Count > 0)
{
ExportDataGrid(ds, ExportType.EXCEL);
}
}
protected void btnExportToWord_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];

if (ds.Tables[0].Rows.Count > 0)
{
ExportDataGrid(ds, ExportType.WORD);
}
}

protected void btnExportToPDF_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];

if (ds.Tables[0].Rows.Count > 0)
{
ExportDataGrid(ds, ExportType.PDF);
}
}

Get 1st day of week using C#.

Hi,

Here is the code to get date on 1st day of week, we just need to call this function with date:


private static DateTime firstDayOfWeek(DateTime day, DayOfWeek weekStarts)
{
DateTime d = day;
while (d.DayOfWeek != weekStarts)
{
d = d.AddDays(-1);
}

return d;
}


and to call this function:


DateTime myDate = firstDayOfWeek(DateTime.Now, DayOfWeek.Sunday);

from Excel file to Sql table.

Hello again,

Here is the code to fill sql table from data in excel file:

protected void button_click(object sender, EventArgs e)
{
string sqlTblName = "nitinSongs";
string excelFileName = "WT_codes.xls";
string workBook = "[nitin$]";
string exlConStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("WT_codes.xls") + ";" + "Extended Properties=Excel 8.0;";
string sqlConStr = "Data Source=SERVER NAME;Database=DATABASE NAME;Persist Security Info=True;User ID=LOGINID;Password=PASSWORD";

SqlConnection sqlCon = new SqlConnection(sqlConStr);
SqlCommand sqlCom = new SqlCommand("DELETE FROM " + sqlTblName, sqlCon);
sqlCon.Open();
sqlCom.ExecuteNonQuery();
sqlCon.Close();

OleDbConnection oleCon = new OleDbConnection(exlConStr);
OleDbCommand oleCom = new OleDbCommand("select * from " + workBook, oleCon);
oleCon.Open();
OleDbDataReader dr = oleCom.ExecuteReader();
SqlBulkCopy bCopy = new SqlBulkCopy(sqlConStr);
bCopy.DestinationTableName = sqlTblName;
bCopy.WriteToServer(dr);
oleCon.Close();
}

Tuesday, February 10, 2009

Upload and resize image.

Hi again,

And now we are face 2 face again, and now we'll upload a image to the server in desired size and resolution. here is the code for that.

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.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

protected void Button1_Click(object sender, EventArgs e)
{
try
{
Boolean fileOK = false;
String path = Server.MapPath("~/Uploads/");
if (FileUpload1.HasFile)
{
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
}
}
}

if (fileOK)
{
UploadImage(FileUpload1);
}
else
{
Page.RegisterStartupScript("", "");
}
}
catch (Exception Ex)
{
throw Ex;
}
}
protected void UploadImage(FileUpload fileUploader)
{
try
{
if (fileUploader.HasFile)
{
int newX = 0, newY = 0;

int bmpH = 300;// //New Image target height
int bmpW = 300;// //New image target width

if (fileUploader.HasFile)
{
Random rnd = new Random();
Int32 i = rnd.Next();

String filePath = "Uploads/" + i + ".jpeg";

Bitmap upBmp = (Bitmap)Bitmap.FromStream(fileUploader.PostedFile.InputStream);

Decimal reDuce;

if (upBmp.Width > upBmp.Height)
{
reDuce = (Decimal)bmpW / (Decimal)upBmp.Width;

bmpH = ((Int32)(upBmp.Height * reDuce));
}
else
{
if (upBmp.Width < upBmp.Height)
{
reDuce = (Decimal)bmpH / (Decimal)upBmp.Height;

bmpW = ((Int32)(upBmp.Width * reDuce));
}
else
{
if (upBmp.Height == upBmp.Width)
{

reDuce = bmpH / upBmp.Height;

bmpW = ((Int32)((upBmp.Width * reDuce)));
}
}
}

Bitmap newBmp = new Bitmap(bmpW, bmpH, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

newBmp.SetResolution(200, 200);

Graphics newGraphic = Graphics.FromImage(newBmp);
newGraphic.Clear(Color.Gray);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.DrawImage(upBmp, newX, newY, bmpW, bmpH);
newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
catch (Exception Ex)
{
throw Ex;
}
}

Sql function to get first day of the week.

Hello pals,

How r you??

Today we are going to create a user defined function in SQL 2005, to fetch first day of the week.


GO
/****** Object: UserDefinedFunction [dbo].[F_START_OF_WEEK] Script Date: 02/05/2009 18:19:51 by Nitin Dhiman ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create function [dbo].[F_START_OF_WEEK]
(
@DATE datetime,
– Sun = 1, Mon = 2, Tue = 3, Wed = 4
– Thu = 5, Fri = 6, Sat = 7
– Default to Sunday
@WEEK_START_DAY int = 1
)
/*
Find the fisrt date on or before @DATE that matches
day of week of @WEEK_START_DAY.
*/
returns datetime
as
begin
declare @START_OF_WEEK_DATE datetime
declare @FIRST_BOW datetime

– Check for valid day of week
if @WEEK_START_DAY between 1 and 7
begin
– Find first day on or after 1753/1/1 (-53690)
– matching day of week of @WEEK_START_DAY
– 1753/1/1 is earliest possible SQL Server date.
select @FIRST_BOW = convert(datetime,-53690+((@WEEK_START_DAY+5)%7))
– Verify beginning of week not before 1753/1/1
if @DATE >= @FIRST_BOW
begin
select @START_OF_WEEK_DATE =
dateadd(dd,(datediff(dd,@FIRST_BOW,@DATE)/7)*7,@FIRST_BOW)
end
end

return @START_OF_WEEK_DATE

end

Sending mail containing attachements using CDONTS in .Net

Hi,

Chalo aaj attachement wali mail send karte hai Using CDONTS and asp.net.

Here are the steps to send mail using CDONTS:

1) Add refrence to the CDONTS.dll.

2) Register the dll using:

Start + Run, regsvr32 c:\cdonts.dll

3) Code to sned email:
s1 = FileUpload1.PostedFile.FileName;
Response.Write(s1+” s1
”);
Response.Write(s2 + “ s2
”);
Response.Write(s3 + “ s3
”);
NewMailClass Obj = new NewMailClass();
Obj.MailFormat = 0;
Obj.BodyFormat = 0;

// we can use physical path of any file on the place of FileUpload1.PostedFile.FileName. And ‘my file’ will be the name of the file sent.

Obj.AttachFile(FileUpload1.PostedFile.FileName, “my file”, 1);

Obj.Send(”nitin.sender@anyfakeid.com”, “nitin.reciever@anyrealid.com”, “mail subject”, “mail message body”, 1);

thanks,

Nitin Dhiman.

To get the complete physical path of the file on firefox.

Hi,
Yesterday i was working with some page to upload files using asp.net uploader, tht was working well on IE but not on firefox.

FileUpload1.PostedFile.FileName file uploader does not provide physical path of the file, if we are using firefox.

It works well on internet explorer but if we are using firefox then it will return just file name of the posted file.

u can use following code for same:

System.IO.Directory.GetParent(FileUpload1.PostedFile.FileName).ToString() + “//” + FileUpload1.FileName;

Thanks,

Nitin Dhiman.