Thursday, October 20, 2016

To run Sql script in C#

To run sql script in C# and the script is executed at the back end. Use a File upload control in the apsx page with button.
 protected void UploadButton_Click(object sender, EventArgs e)
 {
 if (FileUpload1.HasFile)
 {
 try
 {
 string filename = Path.GetFileName(FileUpload1.FileName); FileUpload1.SaveAs(Server.MapPath("~/SQL/") + filename);
 string script = File.ReadAllText(Server.MapPath("~/SQL/") + filename);
 using (SqlConnection conn = new SqlConnection(CS))
 {
 SqlCommand sqlCmd = new SqlCommand(script, conn);
 conn.Open();
 Server server = new Server(new ServerConnection(conn)); server.ConnectionContext.ExecuteNonQuery(script);
 StatusLabel.Text = "Upload status: "+filename+" is uploaded successfully!";
 }
 }
 catch (Exception ex)
 {
 StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
 }
 }
 }

Saturday, March 7, 2009

SpinningImage in Windows appln

Hi,
We need to create this class file
public partial class ImageRotator
{
Image img=null;
public bool Rotate(RotationType type, string path)
{
try
{

FileStream fs1 = new FileStream(path, FileMode.Open, FileAccess.Read);
img = Image.FromStream(fs1);
img.Save(AppDomain.CurrentDomain.BaseDirectory + "output1.bmp", ImageFormat.Bmp);
fs1.Close();
fs1.Dispose();
// File.Delete(path);
ImageCodecInfo usedIC = this.GetEncoderInfo("image/bmp");
Encoder encoder = Encoder.Quality;
EncoderParameters encparams = new EncoderParameters(1);
EncoderParameter encparam = new EncoderParameter(encoder, (long)100);
encparams.Param[0] = encparam;
Image test = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "output1.bmp");
img.Dispose();
img = null;
if (type == RotationType.Rotate90)
test.RotateFlip(RotateFlipType.Rotate90FlipNone);
else if (type == RotationType.Rotate180)
test.RotateFlip(RotateFlipType.Rotate180FlipNone);
else if (type == RotationType.Rotate270)
test.RotateFlip(RotateFlipType.Rotate270FlipNone);
test.Save(AppDomain.CurrentDomain.BaseDirectory + "output1.bmp", usedIC, encparams);
// File.Delete(AppDomain.CurrentDomain.BaseDirectory + "cute1.jpg");
// usedIC = this.GetEncoderInfo("image/jpeg");
test.Save(path, usedIC, encparams);
File.Delete(AppDomain.CurrentDomain.BaseDirectory + "output1.bmp");
GC.Collect();

}

catch { }
{
return false;
}
}
private ImageCodecInfo GetEncoderInfo(string p)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codecInfo in encoders)
{
if (codecInfo.MimeType == p)
return codecInfo;
}
return null;
}
}
We need RotationType class file,
public enum RotationType
{
Rotate90,
Rotate180,
Rotate270
}

Create UserControl using this code,
public partial class SpinningImage : UserControl
{
private Boolean completeImage = true;
private static Single angle = 0;
double dw;
double dh;
Image img = null;
Image resizedImage = null;
public SpinningImage()
{
InitializeComponent();
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
}
private string imgPath;

public string ImagePath
{
get { return imgPath; }
set { imgPath = value; }
}

public void setImage()
{

//InitializeComponent();
FileStream fs1 = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
img = Image.FromStream(fs1);
fs1.Close();
fs1.Dispose();
dw = pictureBox1.Width;
dh = pictureBox1.Height;
resizedImage = (Image)QDOES.ImageOptimizer.ResizeToMaxSize(img, dw, dh, 96, 96);

}
public void startTimer()
{ if (completeImage == true)
{
if (enableTimer())
{
pictureBox1.Width = (int)dh;
pictureBox1.Height = (int)dw;
dw = pictureBox1.Width;
dh = pictureBox1.Height;

timer1.Start();
timer1.Interval = 10;

pictureBox1.Refresh();
}
}
}

private void timer1_Tick(object sender, EventArgs e)
{



completeImage = false;
// angle = 0;
angle += 1;

if ((angle >= 0) && (angle < 90))
{
angle++;
}
else if ((angle >= 90) && (angle < 180))
{
if (angle < 180)
angle++;
}
else if ((angle >= 180) && (angle < 270))
{
if (angle < 270)
angle++;
}
else if ((angle >= 270) && (angle < 360))
{
if (angle < 360)
angle++;
}
if (angle == 90)
{
timer1.Stop();completeImage = true;
SaveImage();
}
else if (angle == 180)
{
timer1.Stop();completeImage = true;
SaveImage();
}
else if (angle == 270)
{
timer1.Stop();completeImage = true;
SaveImage();
}
else if (angle == 360)
{
SaveImage();
timer1.Stop(); completeImage = true;
angle = 0;
}
pictureBox1.Invalidate();
}

public bool enableTimer()
{
//string inputPath = AppDomain.CurrentDomain.BaseDirectory + "cute1.jpg";
timer1.Enabled = true;
//timer1.Start();
/* ImageRotator ir = new ImageRotator();
if (String.IsNullOrEmpty(imgPath))
throw new ArgumentException("Invalid input image path.");
if (!File.Exists(imgPath))
throw new FileNotFoundException("Input file not find.");
if (imgPath != null)
{
return ir.Rotate(RotationType.Rotate90, imgPath);
}*/
return false;
}
public void SaveImage()
{
ImageRotator ir = new ImageRotator();
if (String.IsNullOrEmpty(imgPath))
throw new ArgumentException("Invalid input image path.");
if (!File.Exists(imgPath))
throw new FileNotFoundException("Input file not find.");
if (imgPath != null)
{
ir.Rotate(RotationType.Rotate90, imgPath);
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
//resizedImage = (Image)QDOES.ImageOptimizer.ResizeToMaxSize(img, dw, dh, 96, 96);
if(resizedImage !=null)
{
Bitmap bm = new Bitmap((int)dw, (int)dh);
Graphics g = Graphics.FromImage((Image)bm);
g.DrawImage(resizedImage, new Rectangle((bm.Width - resizedImage.Width) / 2, (bm.Height - resizedImage.Height) / 2, resizedImage.Width, resizedImage.Height), new Rectangle(0, 0, resizedImage.Width, resizedImage.Height), GraphicsUnit.Pixel);
resizedImage = (Image)bm;
TextureBrush tex = new TextureBrush(resizedImage, WrapMode.Clamp);
float x = (float)dw / 2;
float y = (float)dh / 2;
tex.TranslateTransform(-x, -y);
tex.RotateTransform(angle, MatrixOrder.Append);
tex.TranslateTransform(x, y, MatrixOrder.Append);
e.Graphics.FillRectangle(tex, e.ClipRectangle);
}
}
}


This will give u the spinning effect

Monday, February 2, 2009

To load data in dropdownlist

Hi,

Using the following code, you can load the data in dropdownlist and make the desired value selected in the dropdown list while loading.

clientDropDownList.DataSource = client;
clientDropDownList.DataTextField = "ClientName";
clientDropDownList.DataValueField = "ClientID";
clientDropDownList.Items.Insert(0, new ListItem("select", "0"));
clientDropDownList.DataBind();
clientDropDownList.Items.FindByText(clientList.ClientName).Selected = true;

Thursday, January 22, 2009

To create Dynamic DataTable and display in GridView

Hi,
We can create DataTable dynamically and display the content either in GridView or DataList or in Repeater.


DataTable dataTable = new DataTable();
DataRow dataRow;
dataTable.Columns.Add(new DataColumn("Title", typeof(string)));
dataTable.Columns.Add(new DataColumn("Description", typeof(string)));
dataTable.Columns.Add(new DataColumn("Author", typeof(string)));
if (_post != null)
{
dataRow = dataTable.NewRow();
dataRow[0] = _post.Title;
dataRow[1] = _post.Description;
dataRow[2] = _user.DisplayName;
dataTable.Rows.Add(dataRow);
}

myDataList.DataSource = dataTable;
myDataList.DataBind();

Wednesday, January 21, 2009

To Convert HTML Text to Normal Text

Hi,

If you want to remove the html tag from the text and replace as normal text use the following coding in Javascript.
using
System.Text.RegularExpressions;

private string StripTags(string HTML)
{
// Removes tags from passed HTML
Regex objRegEx = new Regex("<[^>]*>");
return objRegEx.Replace(HTML, "");
}

Friday, December 26, 2008

To avoid overflow of div without using overflow:hidden

Hi,
If you are using div. Sometimes the div may overflow in IE6 browser.This is due to nesting of various div.So check the div top position.If u find placing of any div, overflows the existing div. Plz change the top to margin-top property to avoid overflow of particular div.

Friday, December 19, 2008

Refresh() method in Windows Application

Hi,
Refresh() -Forces the control to Invalidate its client area and Immediately redraw itself and its child control.

we can use either Refresh() or invalidate() methods to redraw the client area with the updated position. If you want to drag an image inside the picturebox,you must use any one of these methods.

Wednesday, December 17, 2008

To get ShortMonth in C#.net

Hi,
Use the below coding to get the short month,
public static string GetShortMonth(object aDate)
{
DateTime actualDate = (DateTime)aDate;
int day = actualDate.Day;
int monthNumber = actualDate.Month;
string month = "";
if (monthNumber == 1)
{
month = "Jan,";
}
else if (monthNumber == 2)
{
month = "Feb,";
}
else if (monthNumber == 3)
{
month = "Mar,";
}
else if (monthNumber == 4)
{
month = "Apr,";
}
else if (monthNumber == 5)
{
month = "May,";
}
else if (monthNumber == 6)
{
month = "Jun,";
}
else if (monthNumber == 7)
{
month = "Jul,";
}
else if (monthNumber == 8)
{
month = "Aug,";
}
else if (monthNumber == 9)
{
month = "Sep,";
}
else if (monthNumber == 10)
{
month = "Oct,";
}
else if (monthNumber == 11)
{
month = "Nov,";
}
else if (monthNumber == 12)
{
month = "Dec,";
}
int year = actualDate.Year;
return month + " " + day.ToString() + " " + year.ToString();
}

To Get ShortDate in C#.net

Hi,
we can get the ShortDate using the following function,

public string GetShortDate(object aDate)
{
DateTime actualDate = (DateTime)aDate;
string shortDate = "";
string month = actualDate.ToLongDateString();
string[] mon = month.Split(',');
string date = mon[1];
string year = mon[2];
shortDate = date + year;
return shortDate;
}

To GetSubString in C#.net

Hi,
We can reduce the length of the string using getSubString function, so that the length of the string is reduced to our required length.

public string GetSubString(Object str,int len)
{
string name="";
name=str+"";
if(name.Length>len)
{
name=name.Substring(0,len);
}
return name;
}

Implementing Paging in Datalist

Hi,
To implement paging concept in DataList use the following coding.
Here PagedDataSource is used to do paging in DataList.
Consider u r having one label named lblPagingTop to list no.of.records per page(eg. 2/6),
two hyperlinks topNextHyperLink,topPrevHyperLink for Paging.


In Code-behind have the following,

public void sampleStudPaging()
{
PagedDataSource sampleStudPagedDataSource = new PagedDataSource();
int currentPage;
try
{
if (sampleStuds.Length == 0)
{
topPrevHyperLink.Visible = false;
topNextHyperLink.Visible = false;
topLinkLabel.Visible = false;
}
if (sampleStuds.Length > 0)
{
sampleStudPagedDataSource.DataSource = sampleStuds;
sampleStudPagedDataSource.PageSize = 2;
sampleStudPagedDataSource.AllowPaging = true;
if (Request.QueryString["p"] != null)
{
currentPage = int.Parse(Request.QueryString["p"].ToString());
}
else
{
currentPage = 1;
}
sampleStudPagedDataSource.CurrentPageIndex = currentPage - 1;
if (!sampleStudPagedDataSource.IsFirstPage)
{
topPrevHyperLink.NavigateUrl = Request.CurrentExecutionFilePath + "?p=" + Convert.ToInt32(currentPage - 1);
}
else
{
topPrevHyperLink.NavigateUrl = "#";
}
if (!sampleStudPagedDataSource.IsLastPage)
{
topNextHyperLink.NavigateUrl = Request.CurrentExecutionFilePath + "?p=" + Convert.ToInt32(currentPage + 1);
}
else
{
topNextHyperLink.NavigateUrl = "#";
}
lblTopPaging.Text = "Page: " + (currentPage).ToString() + " of " + sampleStudPagedDataSource.PageCount.ToString();
SampleStudDataList.DataSource = sampleStudPagedDataSource;
SampleStudDataList.DataBind();
if (currentPage == 1)
{
topPrevHyperLink.Visible = false;
topLinkLabel.Visible = false;
}
if (currentPage == sampleStudPagedDataSource.PageCount)
{
topNextHyperLink.Visible = false;
topLinkLabel.Visible = false;
}
if (sampleStudPagedDataSource.PageCount == 1)
{
topPrevHyperLink.Visible = false;
topLinkLabel.Visible = false;
}
}
}
catch (Exception ex)
{
}
}

Monday, December 15, 2008

To drag image inside PictureBox

Hi,
we can drag image inside the pictureBox.
Please follow the steps one by one.
  1. Place PictureBox in the form.
  2. Set the following Properties for the PictureBox
  • BackColor -> Transparent
  • BackgroundImage->Give the image path of PNG file from your system.
  • BackgroundImageLayout ->Stretch
  • SizeMode -> Autosize
3. Create the Class named DraggableImage and write the following coding that
contains details
about Image,Width,Height and Location.
class DraggableImage
{
public Bitmap img;
public Point Loc;
public int Width;
public int Height;
public DraggableImage(Bitmap bmpImg,Point loc)
{
this.img = bmpImg;
this.Loc = loc;
this.Width = bmpImg.Width;
this.Height = bmpImg.Height;
}
}

4. In the Form use the following coding,
public partial class Form1 : Form
{
DraggableImage di = new DraggableImage(Properties.Resources._1, new Point(0, 0));
int mx, my;
[Category("Property")]
[Description("Get and Set the draggable Image")]
public Bitmap DragImage
{
get { return di.img; }
set { di.img = value; Refresh(); }
}

public Form1()
{
InitializeComponent();
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
}

private void Form1_Load(object sender, EventArgs e)
{

this.DragImage =(Bitmap)QDOES.ImageOptimizer.ResizeToMaxSize(di.img,
pictureBox1.Width, pictureBox1.Height, 96, 96);

di.Loc = new Point(pictureBox1.Left,pictureBox1.Top);
this.MouseMove += new MouseEventHandler(Form1_MouseMove);
this.MouseDown += new MouseEventHandler(Form1_MouseDown);
this.pictureBox1.MouseDown += new MouseEventHandler(pictureBox1_MouseDown);
this.pictureBox1.MouseMove += new MouseEventHandler(pictureBox1_MouseMove);

}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
di.Loc.X = e.X - mx + di.Loc.X;
di.Loc.Y = e.Y - my + di.Loc.Y;
mx = e.X;
my = e.Y;
Refresh();
}
}

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
mx = e.X;
my = e.Y;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (di != null)
{
e.Graphics.DrawImage(di.img, di.Loc);
}
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
di.Loc.X = e.X - mx + di.Loc.X;
di.Loc.Y = e.Y - my + di.Loc.Y;
mx = e.X;
my = e.Y;
Refresh();
}
}

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
mx = e.X;
my = e.Y;

}


}

Saturday, December 6, 2008

To Show Tooltip during mouseover of GridView

Hi,
During mouseover, we can dynamically bind the tooltip for the GridView using Javascript.
Download :http://www.walterzorn.com/tooltip/tooltip_e.htm (Javascript:tip_centerwindow.js,wz_tooltip.js)

Include necessary Javascript file and CSS,
In the GridView use the following coding in the ItemTemplete,
Inside Div tag include the following
"style="cursor:pointer;" onmouseover="Tip('<%#DataBinder.Eval(Container.DataItem,"sname")%>', BORDERWIDTH, 1, BGCOLOR, '#f3e0f3', FONTWEIGHT, 'bold', FONTCOLOR, '#00AA00',BORDERCOLOR,'black')" onmouseout="UnTip()"><%#DataBinder.Eval(Container.DataItem,"sname")%>"

Thursday, December 4, 2008

To get confirm using javascript while deleting a Row in GridView in C#, asp.net

Hi,
I want to get confirmation from the user while deleting particular record from the GridView.
In code-behind, we can do this by inserting the javascript.This can be written in the RowDataBound Event(OnRowDataBound=
sampleStudGridView_RowDataBound) of the GridView.

In Code-Behind,
protected void sampleStudGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton deleteLinkButton = (LinkButton)e.Row.FindControl("deleteLinkButton");
if (deleteLinkButton != null)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
deleteLinkButton.Attributes.Add("onClick","javascript:return "+ "confirm('Are you sure you want to delete this record ? "+DataBinder.Eval(e.Row.DataItem,"sname")+"')");
}
}
}

To create GridView with alternate rowcolor during mouseover and mouseout

Hi,
I want to create the GridView with Alternate RowBackColor when the
mouse is over.

This can be written in the
OnRowCreated="studGridView_RowCreated"
Event of GridView.

Code-Behind

string onmouseoverstyle = "this.style.backgroundColor='#f1f5e4'";
string onmouseoutstyle = "this.style.backgroundColor='@BackColor'";
string rowBackColor = String.Empty;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Alternate)
{
rowBackColor = System.Drawing.ColorTranslator.
ToHtml(sampleStudGridview.AlternatingRowStyle.BackColor).ToString();

}
else
{
rowBackColor = System.Drawing.ColorTranslator.
ToHtml(sampleStudGridview.AlternatingRowStyle.BackColor).ToString();

}
e.Row.Attributes.Add("onmouseover", onmouseoverstyle);
e.Row.Attributes.Add("onmouseout",onmouseoutstyle.
Replace("@BackColor",rowBackColor));

}

Javascript to validate textbox with alphanumeric

Hi,

Need:Textbox should contain only AlphaNumeric.
I want to validate whether the textbox is empty or contains any special characters.If so, i want to generate proper error message .We can do validation in javascript by using Regular Expression.
Here is the code,
function ValidateTextBox()
{
document.getElementById("snameSpan").innerHTML="";
var s1=document.getElementById("snameTextBox").value;
var re=new RegExp("^[a-zA-Z,0-9]+$");
if(s1=="")
{
document.getElementById("snameSpan").innerHTML="Enter your name";
}
else if(s1 != "")
{
if(!re.test(s1))
{
document.getElementById("snameSpan").innerHTML="Invalid name";
}
}
}

Monday, December 1, 2008

To Filter Files using extension in C# Windows Application

Hi,
DirectoryInfo di1 = new DirectoryInfo(textBox1.Text);
fi1 = di1.GetFiles("*.JPEG");

We can filter the files using the GetFiles(arg) method.

To save and rotate the JPEG Image without affecting the quality

Hi,
If we rotate and save the JPEG Image often.The quality get reduced and the image seems to be blur.we can overcome this using the following,

public bool Rotate(RotationType type, string path)
{
try
{
img = Image.FromFile(path);
img.Save(AppDomain.CurrentDomain.BaseDirectory + "output1.bmp", ImageFormat.Bmp);
ImageCodecInfo usedIC = this.GetEncoderInfo("image/bmp");
Encoder encoder = Encoder.Quality;
EncoderParameters encparams = new EncoderParameters(1);
EncoderParameter encparam = new EncoderParameter(encoder, (long)100);
encparams.Param[0] = encparam;
Image test = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "output1.bmp");
img.Dispose();
img = null;
if (type == RotationType.Rotate90)
test.RotateFlip(RotateFlipType.Rotate90FlipNone);
else if (type == RotationType.Rotate180)
test.RotateFlip(RotateFlipType.Rotate180FlipNone);
else if (type == RotationType.Rotate270)
test.RotateFlip(RotateFlipType.Rotate270FlipNone);
test.Save(AppDomain.CurrentDomain.BaseDirectory + "output1.bmp", usedIC, encparams);
test.Save(path, usedIC, encparams);
File.Delete(AppDomain.CurrentDomain.BaseDirectory + "output1.bmp");
GC.Collect();
return true;

}

Here rotationtype->Indicates rotationtype by 90-Degree,180-Degree,270-Degree or 360-Degree

Windows Application - To retrieve folder Path

Hi,
To retrieve the path of the folder location in Dotnet.We have folderbrowseDialog similar to File BrowserDialog control..

DialogResult result=folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
}