This is a discussion on C# .Net Tips & Tricks within the C# Programming forums, part of the Software Development category; Hi, This is the sample project to read the pixel colors in the image. Bitmap bitmap = new Bitmap("C:\\...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Hi, This is the sample project to read the pixel colors in the image. Bitmap bitmap = new Bitmap("C:\\sample.jpg"); int width = bitmap.Width; int height = bitmap.Height; int i, j; for (i = 0; i< width; i++) { for (j=0; j<height; j++) { Color pixelColor = bitmap.GetPixel(i, j); } } Thanks... S.Balasubramanian.. |
| Sponsored Links |
| |||
| Hi, This is the simple project to check the values in a HashTable object. Include the namespace System.Collections. Hashtable myHashtable = new Hashtable(); myHashtable.Add("AL", "Alabama"); myHashtable.Add("CA", "California"); myHashtable.Add("FL", "Florida"); myHashtable.Add("NY", "New York"); myHashtable.Add("WY", "Wyoming"); foreach (string myKey in myHashtable.Keys) { Response.Write("myKey = " + myKey); } foreach(string myValue in myHashtable.Values) { Response.Write("myValue = " + myValue); } if (myHashtable.ContainsValue("Florida")) { Response.Write("myHashtable contains the value Florida"); } Thanks... S.Balasubramanian.. |
| |||
| Disable COPY/Paste function on a textbox: function noCopyMouse(e) { var isRight = (e.button) ? (e.button == 2) : (e.which == 3); if(isRight) { alert('You are prompted to type this twice for a reason!'); return false; } return true; } function noCopyKey(e) { var forbiddenKeys = new Array('c','x','v'); var keyCode = (e.keyCode) ? e.keyCode : e.which; var isCtrl; if(window.event) isCtrl = e.ctrlKey else isCtrl = (window.Event) ? ((e.modifiers & Event.CTRL_MASK) == Event.CTRL_MASK) : false; if(isCtrl) { for(i = 0; i < forbiddenKeys.length; i++) { if(forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) { alert('You are prompted to type this twice for a reason!'); return false; } } } return true; } Copy and paste the following in Page_Load Textbox1.Attributes.Add("onmousedown", "return noCopyMouse(event);") Textbox1.Attributes.Add("onkeydown", "return noCopyKey(event);") Thanks.. S.Balasubramanian.. |
| |||
| Hi, This is the easy way to convert a List<T>containing string data (Position types, e.g. Full-time, half-time, project appoint ment etc) to string[]. string[] bar = (string[])foo.ToArray (typeof(string)); Where foo is your List<string> Ex: List<string> li =new List<string>(); li.Add("Test"); li.Add("Test1"); li.Add("Test2"); li.Add("Test3"); string[] si = li.ToArray(); Response.Write(si[0]); Thanks.. S.Balasubramanian.. |
| |||
| Object reference not set to an instance of an object error: Considering the large number of "Object reference not set to an instance of an object" errors abound.. Cause one: Not declaring variables! Yes, I know it sounds obvious, but MAKE SURE that you've explicity declared the variable, and don't forget to use the appropriate scope! One common mistayke is when working with Codebehind Classes, consider: ASP.Net Codebehind Class Code: Public Class PageOne: System.Web.UI.Page String strHello; protected void Page_Load(object sender, EventArgs e) strHello = "Hello!" varOne.Text = strHello End Sub End Class Remember! Codebehinds arn't handled the same way as inline/<script> pages! You need to declare EVERY control you want to interact with in the codebehind class Cause 2: Bad scoping! Indeed... One common cause is this: Code: protected void Page_Load(object sender, EventArgs e) String strHello; This won't work because strHello is accessible only by Sub Page_Load Bad inits/constructs Remember, some classes have constuctors Consider DirectoryInfo: Code: Sub Page_Load() { System.IO.DirectoryInfo dirInfo; dirInfo.GetDirectory("C:\"); } In the above example, we've only defined dirInfo *AS* a DirectoryInfo class, we haven't actually created it So we need to do this instead: Code: Sub Page_Load() .... System.IO.DirectoryInfo dirInfo; dirInfo = New System.IO.DirectoryInfo("C:\");
__________________ The OXYGEN Delivers edgy, intelligent Technology to all... |
| |||
| Hi, This is the simple way to update single row of record with button in gridview.. GridViewRow gvr; string gvDataKey; gvr = GridView1.Rows(e.CommandArgument) gvDataKey = gvr.Cells(1).Text sqlStr = "UPDATE tblUser SET uActive = 1 WHERE uPrimaryId = " + gvDataKey + "" Thanks.. S.Balasubramanian.. |
| |||
| Hi, This the sample to find out the number of sundays between 2 dates in javascript: <script type="text/javascript"> var day1=new Date() var day2=new Date() day2.setFullYear(2007,8,1) // month is declared as jan = 0 feb = 1 etc., Sep 1st 2007 in this instance var numberDays = Math.ceil((day2.getTime() - day1.getTime()) / (86400000)) // 86400000 is number of milliseconds in one day var numberWeeks = Math.ceil(numberDays / 7) document.write("Number of Days between today and September 1st: " + numberDays + "<br />") document.write("Number of Weeks between today and September 1st: " + numberWeeks + "<br />") </script> Thanks.. S.Balasubramanian.. |
| |||
| Hi, This is the simple way to get the environment information in C#. using System; public static void GetEnvironmentInfo() { // Fully qualified path of the current directory Response.Write("CurrentDirectory: {0}", Environment.CurrentDirectory); // Gets the NetBIOS name of this local computer Response.Write("MachineName: {0}", Environment.MachineName); // Version number of the OS Response.Write("OSVersion: {0}", Environment.OSVersion.ToString()); // Fully qualified path of the system directory Response.Write("SystemDirectory: {0}", Environment.SystemDirectory); // Network domain name associated with the current user Response.Write("UserDomainName: {0}", Environment.UserDomainName); // Whether the current process is running in user interactive mode Response.Write("UserInteractive: {0}", Environment.UserInteractive); // User name of the person who started the current thread Response.Write("UserName: {0}", Environment.UserName); // Major, minor, build, and revision numbers of the CLR Response.Write("CLRVersion: {0}", Environment.Version.ToString()); // Amount of physical memory mapped to the process context Response.Write("WorkingSet: {0}", Environment.WorkingSet); // Returns values of Environment variables enclosed in %% Response.Write("ExpandEnvironmentVariables: {0}", Environment.ExpandEnvironmentVariables("System drive: " + "%SystemDrive% System root: %SystemRoot%")); // Array of string containing the names of the logical drives Response.Write("GetLogicalDrives: {0}", String.Join(", ", Environment.GetLogicalDrives())); } Thanks.. S.Balasubramanian.. |
| |||
| Hi, Only allow specific characters to be typed into a RichTextBox or TextBox the following code only allows the user to press digit characters into a TextBox and RichTextBox: private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { e.Handled = e.KeyChar < '0' || e.KeyChar > '9'; } private void richTextBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { e.Handled = e.KeyChar < '0' || e.KeyChar > '9'; }
__________________ S.Balasubramanian Nothing is impossible |
| |||
| Writing to Windows Event Log You have written a cool application server... But as is the case with most servers, it runs in background, either as a Windows Service or may be with a hidden window. Now, how are you going to notify the System Administrator, in case some failures or important events occur? All big-shot server products use the Windows Event log for this purpose. And so should you, with the simple function given below: (Use the relevant EventLogEntryType for your application) using System.Diagnostics; public void WriteEventLog(string sCallerName, string sLogLine) { if (!System.Diagnostics.EventLog.SourceExists(sCaller Name)) System.Diagnostics.EventLog.CreateEventSource(sCal lerName, "Application"); EventLog EventLog1 = new EventLog(); EventLog1.Source = sCallerName; EventLog1.WriteEntry (sLogLine, EventLogEntryType.Warning); }
__________________ H2O Without us, no one can survive.. |
| |||
| Ensure a single instance of your app on a machine Sometimes, users (or QA people) can get really nasty and try to run multiple instances of your beloved little application on a single machine. Now, in case that makes you uncomfortable, just pop in the following code in your Main(). Yes, it is utilizing a Mutex object to make sure the users don’t get too smart. using System.Threading; static void Main() { bool bAppFirstInstance; oMutex = new Mutex(true, "Global\\" + “YOUR_APP_NAME”, out bAppFirstInstance); if(bAppFirstInstance) Application.Run(new formYOURAPP() or classYOURAPP()); else MessageBox.Show("The threatening message you want to go for…", "Startup warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } A techie note from Adam: The '\\Global' thingie ensures that the app should be a single instance on the machine, not just for this user's session.
__________________ H2O Without us, no one can survive.. |
| |||
| Notify users with an e-mail The task is pretty easy with .NET, do have a look at the following function. Please don’t forget to provide the correct sender account for Message.From and a valid SMTP server for SmtpMail.SmtpServer. (Then prepare to receive hugs and flying kisses from elated users.) If you want to get one step ahead of others, here are some more tricks: 1. All cellular phones accept text emails these days. And you can use the same below-mentioned function to send a text mail to the user’s mobile device. Just find out the email ID assigned by his cell provider for his cell, and you are up and running in no time. For example, ‘Idea Cellular’ in India routes incoming email for xxx.yahoo.com to your mobile. Just remember to keep the mail text very short. Tip: The boss characters *love* these sweet email alerts! 2. Text mails get boring after a while. So you can use the MailFormat.Html instead of MailFormat.Text and send neatly formatted messages too. See MSDN for more details. Collapse using System.Web.Mail; private bool SendEmail(string sFrom, string sTo, string sCC, string sBCC, string sSubject, string sMessage, int iMailType) { try { MailMessage Message = new MailMessage(); // If sFrom is blank, system mail id is assumed as the sender. if(sFrom=="") Message.From = "default@myserver.com"; else Message.From = sFrom; // If sTo is blank, return false if(sTo=="") return false; else Message.To = sTo; Message.Cc = sCC; Message.Bcc = sBCC; Message.Subject = sSubject; Message.Body = sMessage; Message.BodyFormat = MailFormat.Text; SmtpMail.SmtpServer = "Put a valid smtp server IP"; SmtpMail.Send(Message); return true; } catch(System.Web.HttpException ehttp) { // Your exception handling code here... return false; } catch(Exception e) { // Your exception handling code here... return false; } catch { // Your exception handling code here... return false; } }
__________________ H2O Without us, no one can survive.. |
| |||
| Getting IP address given the host name You have developed the next big socket application. But your users are not sure about the IP address of the server they want to connect to. They input host name most of the time and you require IP addresses for your code to work well. No problemo… Use the following function to get the IP address of a host, given its name: using System.Net; public string GetIPAddress(string sHostName) { IPHostEntry ipEntry = Dns.GetHostByName(sHostName); IPAddress [] addr = ipEntry.AddressList; string sIPAddress = addr[0].ToString(); return sIPAddress; } To get the IP of the local machine, use the following method before invoking GetIPAddress():
__________________ H2O Without us, no one can survive.. |
| |||
| Writing professional log files you can always dump a few strings into a file and call it a log file. What’s the big deal? The thing is - it does not look, ahem, techie. Here is a sample which creates a log file (one per day & instance) and puts in time-stamped log entries into it. The file names are such that sorting them in Windows File Explorer is very easy for the SysAd. Also note that logging functions will require multithreading support, so I am using the lock thingie here; you can either get rid of it (for ST apps) or use something that suits you better. Kudos to Adam for help with this trick. using System.IO; public void WriteLogLine(string sCallerName, string sLogFolder, long lCallerInstance, string sLogLine) { lock(this) { string sFileName; sFileName = String.Format("{0}_{1:yyyy.MM.dd}_{2:00}.log", sCallerName, DateTime.Now, lCallerInstance); StreamWriter swServerLog = new StreamWriter(sLogFolder + sFileName, true); swServerLog.WriteLine( String.Format("[{0:T}] {1}", DateTime.Now, sLogLine)); swServerLog.Close(); } }
__________________ H2O Without us, no one can survive.. |
| |||
| Maintain the position of the scrollbar on postbacks: In ASP.NET 1.1 it was a pain to maintain the position of the scrollbar when doing a postback operation. This was especially true when you had a grid on the page and went to edit a specific row. Instead of staying on the desired row, the page would reload and you'd be placed back at the top and have to scroll down. In ASP.NET 2.0 you can simply add the MaintainScrollPostionOnPostBack attribute to the Page directive: <%@ Page Language="C#" MaintainScrollPositionOnPostback="true" AutoEventWireup="true" CodeFile="..." Inherits="..." %> ThankQ KiruthikaSambandam |
| |||
| Set the default focus to a control when the page loads: This is another extremely simple thing that can be done without resorting to writing JavaScript. If you only have a single textbox (or two) on a page why should the user have to click in the textbox to start typing? Shouldn't the cursor already be blinking in the textbox so they can type away? Using the DefaultFocus property of the HtmlForm control you can easily do this. <form id="frm" DefaultFocus="txtUserName" runat="server"> ... </form> ThankQ KiruthikaSambandam |
| |||
| Set the default button that is triggered when the user hits the enter key: This was a major pain point in ASP.NET 1.1 and required some JavaScript to be written to ensure that when the user hit the enter key that the appropriate button on the form triggered a "click" event on the server-side. Fortunately, you can now use the HtmlForm control's DefaultButton property to set which button should be clicked when the user hits enter. This property is also available on the Panel control in cases where different buttons should be triggered as a user moves into different Panels on a page. <form id="frm" DefaultButton="btnSubmit" runat="server"> ... </form> ThankQ KiruthikaSambandam |
| |||
| Strongly-typed access to cross-page postback controls: This one is a little more involved than the others, but quite useful. ASP.NET 2.0 introduced the concept of cross-page postbacks where one page could postback information to a page other than itself. This is done by setting the PostBackUrl property of a button to the name of the page that the button should postback data to. Normally, the posted data can be accessed by doing something like PreviousPage.FindControl("ControlID"). However, this requires a cast if you need to access properties of the target control in the previous page (which you normally need to do). If you add a public property into the code-behind page that initiates the postback operation, you can access the property in a strongly-typed manner by adding the PreviousPageType directive into the target page of the postback. That may sound a little confusing if you haven't done it so let me explain a little more. If you have a page called Default.aspx that exposes a public property that returns a Textbox that is defined in the page, the page that data is posted to (lets call it SearchResults.aspx) can access that property in a strongly-typed manner (no FindControl() call is necessary) by adding the PreviousPageType directive into the top of the page: <%@ PreviousPageType VirtualPath="Default.aspx" %> By adding this directive, the code in SearchResults.aspx can access the TextBox defined in Default.aspx in a strongly-typed manner. The following example assumes the property defined in Default.aspx is named SearchTextBox. TextBox tb = PreviousPage.SearchTextBox; This code obviously only works if the previous page is Default.aspx. PreviousPageType also has a TypeName property as well where you could define a base type that one or more pages derive from to make this technique work with multiple pages ThankQ KiruthikaSambandam |
| |||
| Validation groups: You may have a page that has multiple controls and multiple buttons. When one of the buttons is clicked you want specific validator controls to be evaluated rather than all of the validators defined on the page. With ASP.NET 1.1 there wasn't a great way to handle this without resorting to some hack code. ASP.NET 2.0 adds a ValidationGroup property to all validator controls and buttons (Button, LinkButton, etc.) that easily solves the problem. If you have a TextBox at the top of a page that has a RequiredFieldValidator next to it and a Button control, you can fire that one validator when the button is clicked by setting the ValidationGroup property on the button and on the RequiredFieldValidator to the same value. Any other validators not in the defined ValidationGroup will be ignored when the button is clicked. Here's an example: <form id="form1" runat="server"> Search Text: <asp:TextBox ID="txtSearch" runat="server" /> <asp:RequiredFieldValidator ID="valSearch" runat="Server" ControlToValidate="txtSearch" ValidationGroup="SearchGroup" /> <asp:Button ID="btnSearch" runat="server" Text="Search" ValidationGroup="SearchGroup" /> .... Other controls with validators and buttons defined here </form> ThankQ KiruthikaSambandam |
| |||
| How can a class implement multiple interfaces containing methods with identical signatures? For example, you have 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; } } In this case (when using Explicit Interface Implementation) the methods cannot be declared as public, although they are public (they can be called from code outside of the class). In other words, they're public with respect to the interface, but not with respect to the class. ThankQ KiruthikaSambandam |