This is a discussion on C# .Net Tips & Tricks within the C# Programming forums, part of the Software Development category; hi... guys.... For my project, I am having table <sample table>. In that table have some null allowable ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| hi... guys.... For my project, I am having table <sample table>. In that table have some null allowable field also. I want to select all (or specific) the records from that table. I am working on .net frame work 2.0. In my project I am using table adapter for handling stored procedures and methods. I got the null exception while I am fetching the records in that table through table adapter.
__________________ The OXYGEN Delivers edgy, intelligent Technology to all... Last edited by Booom : 08-18-2007 at 12:59 AM. |
| Sponsored Links |
| |||
| hi, here is the solution for that, 1.Go to the property window of table adapter, and select particular column(in which null value u need to allow) make the AllowDBNull-true, and NullValue property-Empty or Null(by default it is (Throw exception)) but this tricks works only for varchar column for other column we can go for option 2 2.In our stored procedure Create or ALTER PROCEDURE [dbo].[spName] ( @param uniqueidentifier ) AS SET NOCOUNT ON; SELECT isNull(column2,'') as column3,isNull(column3,'') as column2 FROM TableName where column1=@param in both the case it will send empty string if null value comes |
| |||
| Hi, This is the simple way to convert the jpeg image into gif with high quality. Bitmap img = new Bitmap(200, 100, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(img); Pen p = new Pen(Color.Black, 1); Brush b = new SolidBrush(Color.Green); System.IO.MemoryStream MS = new System.IO.MemoryStream(); g.Clear(Color.White); g.FillRectangle(b, 20, 20, 40, 40); g.DrawRectangle(p, 25, 25, 50, 50); DateTime dt = DateTime.Now; Font drawFont = new Font("Arial", 22); SolidBrush drawBrush = new SolidBrush(Color.Red); PointF drawPoint = new PointF(75F, 50F); g.DrawString(dt.ToString("T", DateTimeFormatInfo.InvariantInfo), drawFont, drawBrush, drawPoint); //Bitmap bitmappal = new Bitmap(MS); img.Save(MS, ImageFormat.Gif); byte[] buffer = new byte[MS.Length]; buffer = MS.ToArray(); Response.Clear(); Response.ContentType = "Image/Gif"; Response.OutputStream.Write(buffer, 0, buffer.Length); Response.End(); Thanks.. S.Balasubramanian.. |
| |||
| Hi, This project will show a different way how to - enter ONLY integer value in a TextBox - enter ONLY the characters you want and avoid certain invalid characters in a TextBox Let's start with TextBox 'textboxInteger'. As mentioned before you can enter here ONLY integer values. Other characters will not be accepted. Here is the method for input integer private void textboxInteger_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if (!Char.IsDigit(e.KeyChar) && e.KeyChar !=(char)8) { this.statusBar1.Text="incorrect key..."; e.Handled=true; // input is not passed on to the control(TextBox) } else this.statusBar1.Text="OK.."; } TextBox 'textboxChars' We want here to avoid entering the user certain invalid characters(i.e. 'a','b','c','#','*','1') To solve this I implemented 3 methods in the Form1.cs * mTextboxCharsKeyPressWithForeach * mTextboxCharsKeyPressWithIF * mTextboxCharsKeyPressWithSwitch that I prefer private void mTextboxCharsKeyPressWithSwitch(object sender, System.Windows.Forms.KeyPressEventArgs e) { this.statusBar1.Text="OK..."; switch(e.KeyChar) { case 'a': case 'b': case 'c': case '#': case '*': case '1': //this is char not int e.Handled=true; //it indicates the event is handled. this.errorProvider1.SetError(this.textboxChars, "not allowed chars: 'a','b','c','#','*','1'"); this.statusBar1.Text="not allowed char..."+e.KeyChar; break; default: this.errorProvider1.SetError(this.textboxChars, ""); //clear error break; } //switch } if the chars you typed are 'a','b','c','#','*','1' then we use an ErrorProvider and ToolTip control on the TextBox. An error icon appears next to the TextBox. If you hold the mouse pointer over the error icon, a ToolTip appears displaying the error message. Thanks... S.Balasubramanian.. |
| |||
| Hi, VB.NET to C# conversion - tips Keywords in C# variables are ByVal by default, so no keyword is used for ByVal use ref instead of VB's ByRef C# also has the in and out keywords that you can use (you can look them up on MSDN) use base in C# instead of VB's MyBase use this in C# instead of VB's Me to the best of my understanding VB's MyClass doesnt exist in C# so you should just use this (correct me if I'm wrong) use null in C# instead of VB's Nothing Some of the things that don't exist in C# Optional parameters don't exist in C#. You can have multiple function definitions or if applicable, use params(scroll down and see the param array example) The Redim keyword does not exist in C# C# doesn't have Modules. Use a class instead C# doesn't support With ... End With blocks Examples: vb: MustInherit class c# abstract class vb: NotInheritable class c#: sealed class vb: Public MustOverride Function foo() As Boolean c#: public abstract bool foo(); vb: Public Shared counter As Integer c#: public static int counter; vb: Shared Function foo() As Boolean c# static bool foo () vb: MustOverride Property name() As String c#: abstract string name{get;set;}
__________________ The OXYGEN Delivers edgy, intelligent Technology to all... |
| |||
| Hi, Vb to C# conversion.. Suppose u got some codings in vb language,if u want to change the language from VB to C# means, U can try this link, Here its, CodeTranslator: Free Code Translation From VB.NET <-> C#
__________________ Krishnakumar.S Beware of Everything -that is un true; stick to the Truth shall succeed slowly but steadily Last edited by krishnakumar : 08-18-2007 at 04:24 AM. |
| |||
| Insert text at a specified line number in a file using C# using System; using System.IO; using System.Collections; namespace InsertLineInTextFile { class Program { static void Main (string[] args) { string strTextFileName = "myFile.txt"; int iInsertAtLineNumber = 2; string strTextToInsert = "3. Apple"; ArrayList lines = newArrayList(); StreamReader rdr = newStreamReader( strTextFileName); string line; while ((line = rdr.ReadLine()) != null) lines.Add(line); rdr.Close(); if (lines.Count > iInsertAtLineNumber) lines.Insert(iInsertAtLineNumber, strTextToInsert); else lines.Add(strTextToInsert); StreamWriter wrtr = newStreamWriter( strTextFileName); foreach (string strNewLine in lines) wrtr.WriteLine(strNewLine); wrtr.Close(); } } } Thanks.. S.Balasubramanian.. |
| |||
| Resize an array in C# In C#, arrays cannot be resized dynamically. One approach is to use System.Collections.ArrayList instead of a native array. Another (faster) solution is to re-allocate the array with a different size and to copy the contents of the old array to the new array. The generic function resizeArray (below) can be used to do that. public static System.Array ResizeArray (System.Array oldArray, int newSize) { int oldSize = oldArray.Length; System.Type elementType = oldArray.GetType().GetElementType(); System.Array newArray = System.Array.CreateInstance(elementType,newSize); int preserveLength = System.Math.Min(oldSize,newSize); if (preserveLength > 0) System.Array.Copy (oldArray,newArray,preserveLength); return newArray; } public static void Main () { int[] a = {1,2,3}; a = (int[])ResizeArray(a,5); a[3] = 4; a[4] = 5; for (int i=0; i<a.Length; i++) System.Console.WriteLine (a[i]); }
__________________ The OXYGEN Delivers edgy, intelligent Technology to all... |
| |||
| Apply Water Mark to Image using C#: 1) Create a C# website. 2) Copy and paste the following code in aspx.cs page. string Filename = ""; int Width, Height; ImageFormat ImgFormat; System.Drawing.Image Img; Bitmap baseMap; protected void Page_Load(object sender, EventArgs e) { Filename = @"D:\strelitzia.jpg"; CreateGraphic(); baseMap.Save(Response.OutputStream, ImageFormat.Jpeg); baseMap.Dispose(); Img = null; Response.End(); } public void CreateGraphic() { SolidBrush letterBrush = new SolidBrush(Color.FromArgb(50, 255, 255, 255)); SolidBrush shadowBrush= new SolidBrush(Color.FromArgb(50, 0, 0, 0)); Font fontTitle= new Font("tahoma", 20, FontStyle.Bold); //Filename = Request.QueryString["filename"]; //Filename = Server.MapPath(Filename); ImgFormat = ImageFormat.Jpeg; Response.ContentType ="image/jpeg"; Img = System.Drawing.Image.FromFile(Filename); Width = Img.Width; Height = Img.Height; baseMap = new Bitmap(Width,Height); Graphics myGraphic= Graphics.FromImage(baseMap); myGraphic.DrawImage(Img, 0,0, Width,Height); myGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; myGraphic.DrawString("WWW.DISCUSSWEB.COM", fontTitle, shadowBrush, 5, 60); myGraphic.DrawString("WWW.DISCUSSWEB.COM", fontTitle, letterBrush, 7, 62); Img.Dispose(); } Thanks.. S.Balasubramanian.. |
| |||
| Apply DropShadow to image using C#: Steps: 1) Create a C# website. 2) Copy and paste the following code string Filename = ""; int Width, Height, shadowSize; ImageFormat ImgFormat; System.Drawing.Image Img; Bitmap baseMap; protected void Page_Load(object sender, EventArgs e) { Filename = @"D:\sample.jpg"; shadowSize = 10; CreateGraphic(); baseMap.Save(Response.OutputStream, ImageFormat.Jpeg); baseMap.Dispose(); Img = null; Response.End(); } public void CreateGraphic() { SolidBrush letterBrush = new SolidBrush(Color.FromArgb(50, 255, 255, 255)); SolidBrush shadowBrush = new SolidBrush(Color.FromArgb(50, 0, 0, 0)); Font fontTitle = new Font("tahoma", 20, FontStyle.Bold); //Filename = Request.QueryString["filename"]; //Filename = Server.MapPath(Filename); ImgFormat = ImageFormat.Jpeg; Response.ContentType = "image/jpeg"; Img = System.Drawing.Image.FromFile(Filename); Width = Img.Width; Height = Img.Height; baseMap = new Bitmap(Width, Height); Graphics myGraphic = Graphics.FromImage(baseMap); myGraphic.FillRectangle(new SolidBrush(Color.White), 0, 0, Width + shadowSize, Height + shadowSize); myGraphic.FillRectangle(new SolidBrush(Color.DarkGray), 10, 10, Width+shadowSize, Height+shadowSize); myGraphic.FillRectangle(new SolidBrush(Color.Black), 0, 0, Width+6, Height+6); myGraphic.DrawImage(Img, 2,2, Width+2,Height+2); Img.Dispose(); }
__________________ The OXYGEN Delivers edgy, intelligent Technology to all... |
| |||
| Hi, This is a sample project to shear the image. Steps: 1) Create a C# project. 2) copy and paste the following code. private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; Bitmap bmp = new Bitmap(@"D:\strelitzia.jpg"); g.FillRectangle(Brushes.White, this.ClientRectangle); Point[] destinationPoints = { new Point(0, 0), // destination for upper-left point of original new Point(300, 0), // destination for upper-right point of original new Point(100, 300)};// destination for lower-left point of original g.DrawImage(bmp, destinationPoints); } private void Form1_Resize(object sender, System.EventArgs e) { Invalidate(); } Thanks.. S.Balasubramanian.. |
| |||
| Hi, This is a sample project to generate a transparency GIF in C#. Steps: 1) Create a C# website. 2) Copy and paste the following code. protected void Page_Load(object sender, EventArgs e) { string message = "Sample WebSite"; GraphicsPath graphicsPath = new GraphicsPath(); graphicsPath.AddString(message, new FontFamily("Arial"), (int)FontStyle.Bold, 20, new Point(0, 0), StringFormat.GenericDefault); RectangleF rect = graphicsPath.GetBounds(); rect.Width += 10; rect.Height += 10; LinearGradientBrush lgb = new LinearGradientBrush(new PointF(0,0), new PointF(rect.Width,rect.Height), Color.DarkOrange, Color.Black); Pen outlinePen = new Pen(lgb, 5); outlinePen.Alignment = PenAlignment.Outset; Bitmap bitmap = new Bitmap((int)rect.Width, (int)rect.Height); Graphics graphics = Graphics.FromImage(bitmap); graphics.Clear(Color.Magenta); graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.DrawPath(outlinePen, graphicsPath); graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.FillPath(Brushes.White, graphicsPath); MemoryStream memoryStream = new MemoryStream(); MakeTransparentGif(bitmap, Color.Magenta).Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif); memoryStream.WriteTo(Response.OutputStream); Response.ContentType = "image/gif"; Response.End(); // Clean up. memoryStream.Close(); graphicsPath.Dispose(); bitmap.Dispose(); graphics.Dispose(); } public Bitmap MakeTransparentGif(Bitmap bitmap, Color color) { byte R = color.R; byte G = color.G; byte B = color.B; MemoryStream fin = new MemoryStream(); bitmap.Save(fin, System.Drawing.Imaging.ImageFormat.Gif); MemoryStream fout = new MemoryStream((int)fin.Length); int count = 0; byte[] buf = new byte[256]; byte transparentIdx = 0; fin.Seek(0, SeekOrigin.Begin); //header count = fin.Read(buf, 0, 13); if ((buf[0] != 71) || (buf[1] != 73) || (buf[2] != 70)) return null; //GIF fout.Write(buf, 0, 13); int i = 0; if ((buf[10] & 0x80) > 0) { i = 1 << ((buf[10] & 7) + 1) == 256 ? 256 : 0; } for (; i != 0; i--) { fin.Read(buf, 0, 3); if ((buf[0] == R) && (buf[1] == G) && (buf[2] == B)) { transparentIdx = (byte)(256 - i); } fout.Write(buf, 0, 3); } bool gcePresent = false; while (true) { fin.Read(buf, 0, 1); fout.Write(buf, 0, 1); if (buf[0] != 0x21) break; fin.Read(buf, 0, 1); fout.Write(buf, 0, 1); gcePresent = (buf[0] == 0xf9); while (true) { fin.Read(buf, 0, 1); fout.Write(buf, 0, 1); if (buf[0] == 0) break; count = buf[0]; if (fin.Read(buf, 0, count) != count) return null; if (gcePresent) { if (count == 4) { buf[0] |= 0x01; buf[3] = transparentIdx; } } fout.Write(buf, 0, count); } } while (count > 0) { count = fin.Read(buf, 0, 1); fout.Write(buf, 0, 1); } fin.Close(); fout.Flush(); return new Bitmap(fout); } Thanks.. S.Balasubramanian.. |
| |||
| Hi, C# Image to Byte Array and Byte Array to Image Converter Class public byte[] imageToByteArray(System.Drawing.Image imageIn) { MemoryStream ms = new MemoryStream(); imageIn.Save(ms,System.Drawing.Imaging.ImageFormat .Gif); return ms.ToArray(); } public Image byteArrayToImage(byte[] byteArrayIn) { MemoryStream ms = new MemoryStream(byteArrayIn); Image returnImage = Image.FromStream(ms); return returnImage; }
__________________ The OXYGEN Delivers edgy, intelligent Technology to all... |
| |||
| Hi, This is the sample project to merge two gif images. Steps: 1)Create a C# Website. 2)Copy and paste the following code in Page_Load. Bitmap oCounter; Graphics oGraphics; oCounter = new Bitmap(23,15); oGraphics = Graphics.FromImage(oCounter); Bitmap objImage = new Bitmap("1.gif"); oGraphics.DrawImage(objImage,0,0); objImage = new Bitmap("2.gif"); oGraphics.DrawImage(objImage,11,0); oCounter.Save(Response.OutputStream,ImageFormat.Jp eg); objImage.Dispose(); oCounter.Dispose(); Thanks.. S.Balasubramanian.. |
| |||
| Hi, Get environment conscious: Create a C# website. Copy and paste the following code // Fully qualified path of the current directory Response.Write("CurrentDirectory:", Environment.CurrentDirectory); // Gets the NetBIOS name of this local computer Response.Write("MachineName:", Environment.MachineName); // Version number of the OS Response.Write("OSVersion:", Environment.OSVersion.ToString()); // Fully qualified path of the system directory Response.Write("SystemDirectory:", Environment.SystemDirectory); // Network domain name associated with the current user Response.Write("UserDomainName:", Environment.UserDomainName); // Whether the current process is running in user interactive mode Response.Write("UserInteractive:", Environment.UserInteractive); // User name of the person who started the current thread Response.Write("UserName:", Environment.UserName); // Major, minor, build, and revision numbers of the CLR Response.Write("CLRVersion:", Environment.Version.ToString()); // Amount of physical memory mapped to the process context Response.Write("WorkingSet:", Environment.WorkingSet); // Returns values of Environment variables enclosed in %% Response.Write("ExpandEnvironmentVariables:", Environment.ExpandEnvironmentVariables("System drive: " + "%SystemDrive% System root: %SystemRoot%")); // Array of string containing the names of the logical drives Response.Write("GetLogicalDrives:", String.Join(", ", Environment.GetLogicalDrives())); Thanks.. S.Balasubramanian.. |
| |||
| Hi, This is the sample website to Zoom the image. Bitmap oImg; System.Drawing.Image oI,oItemp; Graphics oGraphics; oI = System.Drawing.Image.FromFile(fruity.jpg"); oItemp=oI; oImg=new Bitmap(oI.Width,oI.Height,PixelFormat.Format24bppR gb); oGraphics = Graphics.FromImage(oImg); string XPos, YPos; string[] tempArrX=null; string[] tempArrY=null; XPos = 100; YPos = 100; if (XPos!=string.Empty && YPos!=string.Empty) { string delimStr = ","; char [] delimiter = delimStr.ToCharArray(); tempArrX=XPos.Split(delimiter); tempArrY=YPos.Split(delimiter); //we store the x and y positions clicked everytime //by user in a hidden field. //so if user clicks 3 times.. we enlarge the image thrice. //appropriately everytime at the portions user clicked. int iIndex; for(iIndex=0;iIndex<tempArrX.Length ;iIndex++) { //the logic followed here is.. //get the portion around the click areaa.. //60% of the size of actual image ///// //enlarge this portion to the size of the image itself. //get the 60% area around the clik float iPortionWidth=(0.60f*oI.Width); float iPortionHeight=(0.60f*oI.Height); //calculate top x,y of the portion to enlarge. float iStartXpos = float.Parse(tempArrX[iIndex])-(iPortionWidth/2); float iStartYPos = float.Parse(tempArrY[iIndex])-(iPortionHeight/2); //set destination and source rectangle areas RectangleF desRect = new RectangleF( 0, 0, oI.Width, oI.Height); RectangleF sourceRect = new RectangleF( iStartXpos, iStartYPos, iPortionWidth, iPortionHeight); //get the portion of image(defined by sourceRect) //and enlarge it to desRect size...gives a zoom effect. ////if image has high resolution.. effect will be good. oGraphics.DrawImage(oItemp,desRect,sourceRect,Grap hicsUnit.Pixel); //copy the enlarged portion into oItemp //so that further zooming operation uses this image. ////this is to ensure that when image is enlarged multiple times ////it doesnt enlarge from the original everytime. IntPtr hBitmap = oImg.GetHbitmap(Color.Blue); //create pointer to bitmap oItemp=System.Drawing.Image.FromHbitmap(hBitmap); //use pointer and load bitmap into oItemp } } //oGraphics = Graphics.FromImage(oImg); //oGraphics.DrawImage(oItemp,oI.Width, oI.Height); oImg.Save(Response.OutputStream,ImageFormat.Jpeg); oImg.Dispose(); oI.Dispose(); oItemp.Dispose();
__________________ The OXYGEN Delivers edgy, intelligent Technology to all... |
| |||
| Hi, A class implement multiple interfaces containing methods with identical signatures. Two interfaces (I1 & I2) that both contain a Send method with the same signature (identical method name, same return type, same argument types in the same order: public interface I1 { int Send(int id); } public interface I2 { int Send(int id); } If you don't care which interface was used to make the call to the Send method, just implement the method: public class c1 : I1, I2 { int Send(int id) { return 0; } } If you do care about which interface was used to make the Send call, use Explicit Interface Implementation by specifying the interface name before the method name (I1.Send, I2,Send): public class c1 : I1, I2 { int I1.Send(int id) { return 1; } int I2.Send(int id) { return 2; } } Thanks.. S.Balasubramanian.. |
| |||
| Hi, This is the sample for using Treeview in C#. Steps: 1)Create a C# website. 2)Open default.aspx page and paste the following code: <asp:TreeView ID="treeview1" runat="server" ExpandDepth="0" PopulateNodesFromClient="true" ShowLines="true" ShowExpandCollapse="true"></asp:TreeView> 3)Open default.aspx.cs page and paste the following code. protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) PopulateRootLevel(); } public void PopulateRootLevel() { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationMa nager.AppSettings["connect"]); SqlCommand cmd = new SqlCommand("select * from dg", conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); PopulateNodes(dt, treeview1.Nodes); } public void PopulateNodes(DataTable dt,TreeNodeCollection nodes) { foreach(DataRow dr in dt.Rows) { TreeNode tn = new TreeNode(); tn.Text = dr["Sname"].ToString(); tn.Value = dr["id"].ToString(); nodes.Add(tn); tn.PopulateOnDemand = (Convert.ToInt32(dr["id"]) > 0); } } public void PopulateSubLevel(int parentid,TreeNode parentNode) { SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationMa nager.AppSettings["connect"]); SqlCommand cmd = new SqlCommand("select * from dg", conn); cmd.Parameters.Add("@id", SqlDbType.Int).Value = parentid; SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); PopulateNodes(dt, parentNode.ChildNodes); } public void TreeView1_TreeNodePopulate(Object sender,System.Web.UI.WebControls.TreeNodeEventArgs e) { PopulateSubLevel(Convert.ToInt32(e.Node.Value), e.Node); }
__________________ The OXYGEN Delivers edgy, intelligent Technology to all... |
| |||
| Three tier architecture: The three tier software architecture emerged in the 1990s to overcome the limitations of the two tier architecture. There are three layers when we talk about three tier architecture:- User Interface (Client) :- This is mostly the windows user interface or the Web interface but this has only the UI part. Mid layer: - Middle tier provides process management where business logic and rules are executed and can accommodate hundreds of users (as compared to only 100 users with the two tier architecture) by providing functions such as queuing, application execution, and database staging. Data Access Layer: - This is also called by the famous acronym "DAL" component. It has mainly the SQL statement which do the database operation part of the job. The three tier architecture is used when an effective distributed client/server design is needed that provides (when compared to the two tier) increased performance, flexibility, maintainability, reusability, and scalability, while hiding the complexity of distributed processing from the user. Thanks.. S.Balasubramanian.. |
| |||
| Hi, This is the sample project using Three Tier Architecture. Presentation Layer: private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e) { // Object of the Property layer clsStudent objproperty=new clsStudent(); // Object of the business layer clsStudentInfo objbs=new clsStudentInfo(); // Object of the dataset in which we receive the data sent by the business layer DataSet ds=new DataSet(); // here we are placing the value in the property “ID” using the object of the property layer objproperty.id=int.Parse(DataGrid1.SelectedItem.Ce lls[1].T |