Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, July 13, 2012

GDI+ .NET Color & HatchStyle Chart

Color Chart

HatchStyle Chart

Monday, September 5, 2011

Using comparison operators in a unsafe way

// Using operators in a unsafe way

// declare a variable to null
string s = null;
// for the 'or'  operator comparison
// if left side get true the right side will never be invoke
// if left side get false, the right side will come.
// in this example below will be fine because the right side won't be invoke when
left side is true.
if(s == null || s.Length == 0)

// for 'and' operator comparison
//
if left side get true the right side will invoke
// if left side get false the right side will never invoke
// this example below will be throw a exception while right side is execute.

if(s == null && s.Length == 0)


// declare functions
func1(param){return param;}
func2(param){return param;}

//                                                which function being call
if(func1(true) && func2(true))     func1   func2
if(func1(false) && func2(true))    func1
if(func1(true) || func2(true))         func1
if(func1(false) || func2(true))        func1   func2


// the concept above can also apply to C/C++, java and javascript ....

Sunday, July 10, 2011

How to sned mail using gmail SMTP in c#

string subject = "gmail test ";
        string message = "<h3>test sending gmail message content in HTML body</h3>";
        MailMessage mailMsg = new MailMessage();
        mailMsg.From = new System.Net.Mail.MailAddress("sender@gmail.com", "display name", System.Text.Encoding.UTF8);
        mailMsg.To.Add(new MailAddress("reciver@gmail.com"));
        mailMsg.SubjectEncoding = System.Text.Encoding.UTF8;
        mailMsg.BodyEncoding = Encoding.UTF8;
        //
        mailMsg.Subject = subject;
        mailMsg.Body = message;
        mailMsg.IsBodyHtml = true;
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
        // user name and password to SMTP
        client.Credentials = new System.Net.NetworkCredential("sender", "1234");
        //gmail smtp port: 587
        client.Port = 587;
        client.Host = "smtp.gmail.com";
        // gmail required SSL
        client.EnableSsl = true;
        client.Send(mailMsg);

Saturday, December 11, 2010

Convert List or Array to String

 
// Sample 1
StringBuilder builder = new StringBuilder();
foreach (string value in array)
{
    builder.Append(value);
    builder.Append(',');
}
// Sample 2
string result = string.Join(",", array);

Monday, October 4, 2010

DateTime and Number Format in C#

int intNum = 13; 
String.Format("{0:d4}", intNum);          // "0013"
intNum.ToString("D4");                    // "0013"

Decimal
// fixed two decimal part

String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"

String.Format("{0:0.00}", 123.0);         // "123.00"
// maximum two decimal part
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"

String.Format("{0:0.##}", 123.0);         // "123"
// at least two digits at integer part
String.Format("{0:00.0}", 123.4567);      // "123.5"
String.Format("{0:00.0}", 1.4567);        // "01.5"

String.Format("{0:00.0}", -1.4456);       // "-03.4"
// Align numbers with spaces
// To align numbers to the left use negative number of spaces
String.Format("{0,10:0.0}", 123.4567);    // "     123.5"
String.Format("{0,-10:0.0}", 123.4567);   // "123.5     "
String.Format("{0,10:0.0}", -123.4567);   // "    -123.5"

String.Format("{0,-10:0.0}", -123.4567);  // "-123.5    "

Currency
123.456 ("C3", en-US) -> ($123.456)
-123.456 ("C3", fr-FR) -> -123,456 €
-123.456 ("C3", ja-JP) -> -¥123.456

Decimal

1234 ("D") -> 1234
-1234 ("D6") -> -001234

Fixed-point

1234 ("F1", en-US) -> 1234.0
1234 ("F1", en-US) -> 1234.0


General
-123.456 ("G", en-US) -> -123.456
-1.234567890e-25 ("G", sv-SE) -> -1,23456789E-25


Number
1234.567 ("N", en-US) -> 1,234.57
1234 ("N", en-US) -> 1,234.0


Percent
1 ("P", en-US) -> 100.00 %
-0.39678 ("P1", en-US) -> -39.7 %


Round-trip
123456789.12345678 ("R") -> 123456789.12345678
-1234567890.12345678 ("R") -> -1234567890.1234567


Hexadecimal
255 ("X") -> FF
-1 ("x") -> ff
255 ("x4") -> 00ff
-1 ("X4") -> 00FF


 
 
DateTime.ToString() Patterns
 
ddd, dd MMM yyyy HH':'mm':'ss 'GMT'      Tue, 22 Aug 2006 06:30:07 GM
dddd, dd MMMM yyyy HH:mm:ss              Tuesday, 22 August 2006 06:30:07

yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK   2006-08-22T06:30:07.7199222-04:00 


// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            minute
String.Format("{0:s ss}",          dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   time zone
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE)

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008" 
 
String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortableDateTime 


d Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero
dd Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero
ddd Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc)
dddd Represents the full name of the day of the week (Monday, Tuesday etc)
h 12-hour clock hour (e.g. 7)
hh 12-hour clock, with a leading 0 (e.g. 07)
H 24-hour clock hour (e.g. 19)
HH 24-hour clock hour, with a leading 0 (e.g. 19)
m Minutes
mm Minutes with a leading zero
M Month number
MM Month number with leading zero
MMM Abbreviated Month Name (e.g. Dec)
MMMM Full month name (e.g. December)
s Seconds
ss Seconds with leading zero
t Abbreviated AM / PM (e.g. A or P)
tt AM / PM (e.g. AM or PM
y Year, no leading zero (e.g. 2001 would be 1)
yy Year, leadin zero (e.g. 2001 would be 01)
yyy Year, (e.g. 2001 would be 2001)
yyyy Year, (e.g. 2001 would be 2001)
K Represents the time zone information of a date and time value (e.g. +05:00)
z With DateTime values, represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6)
zz As z but with leadin zero (e.g. +06)
zzz With DateTime values, represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. (e.g. +06:00)
f Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value.
ff Represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.
fff Represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.
ffff Represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. While it is possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffff Represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. While it is possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
ffffff Represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. While it is possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffffff Represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. While it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
F Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero.
: Represents the time separator defined in the current DateTimeFormatInfo..::.TimeSeparator property. This separator is used to differentiate hours, minutes, and seconds.
/ Represents the date separator defined in the current DateTimeFormatInfo..::.DateSeparator property. This separator is used to differentiate years, months, and days.
" Represents a quoted string (quotation mark). Displays the literal value of any string between two quotation marks ("). Your application should precede each quotation mark with an escape character (\).
' Represents a quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters.
%c Represents the result associated with a c custom format specifier, when the custom date and time format string consists solely of that custom format specifier. That is, to use the d, f, F, h, m, s, t, y, z, H, or M custom format specifier by itself, the application should specify %d, %f, %F, %h, %m, %s, %t, %y, %z, %H, or %M. For more information about using a single format specifier, see Using Single Custom Format Specifiers.
 

Related Link
http://www.csharp-examples.net/string-format-double/

Sunday, July 11, 2010

How to request URL with login credential in C#

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = new NetworkCredential(user, password);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Saturday, July 10, 2010

How To Create XML Object in C#




XmlDocument xDoc = new XmlDocument();
XmlElement root = null;
XmlElement node = null;
XmlAttribute att = null;

// Create XML declaration
XmlNode declaration = xDoc.CreateNode(XmlNodeType.XmlDeclaration, null, null);
declaration.Value = "version=\"1.0\" encoding=\"utf-8\"";
xDoc.AppendChild(declaration);


// Create Child Element with two attributes id and name
node = xDoc.CreateElement("node");

att = xDoc.CreateAttribute("id");
att.Value = "100";
node.Attributes.Append(att);

att = xDoc.CreateAttribute("name");
att.Value = "data_100";
node.Attributes.Append(att);

// Create data content which encapesole in <![CDATA[[ ]]> section.
XmlCDataSection CData = xDoc.CreateCDataSection("This text contains some xml escape characters & < > ' \" which encapsolete in CDATA.");

node.AppendChild(CData);

// Create root Element
root = xDoc.CreateElement("root");


root.AppendChild(node);

xDoc.AppendChild(root);



// Get XML string from XmlDocument
string xmlStr = xDoc.outerXml;

the result of xmlStr will be like this:
<?xml version="1.0" encoding="utf-8"?>
<root>
    <node id="100" name="data_100" >
        <![CDATA [This text contains some xml escape characters & < > ' " which encapsolete in CDATA.]]>
    </node>
</root>

Wednesday, May 6, 2009

Build Windows Service with Setup Project using VS2008

To create a windows service with a setup project for a service can easy way to install and start up the service after the service is installed.
here both windows service and  setup project are more works have to do.
first of all we have to create a windows service project and add some code for setup program so that
it capable installation the windows service and then to start it up.

Create a Windows Service Project


  1. In the Add new projcet dialog select Windows Service Template to create new service project.
  2. Right click service1.cs and click View Code
  3. In the OnStart event handler, replace the comments with anything code you want the service to run.
  4. In the OnStop event handler, replace the comments with the code if you need to free the resources.
  5. For the service installation, double click service1.cs to open Design View, In the Design View Right click and select Add Installer in this step a new class ProjectInstaller.cs will add to the project, two elements serviceProcessInstaller1 and serviceInstaller1 you can see in the ProjectInstaller.cs Design View.
  6. In the Properties of serviceInstaller1, change the ServiceName, DisplayName and Description properties for you need.
  7. In the Properties of serviceProcessInstaller1, change the Account to LocalSystem.
    Note: If you want override OnShutdown Event in the Service, you have to use LocalService Account, Otherwise like LocalSystem the OnShutdown Event will never be invoke.
    (LocalService and NetworkService values are available only in Microsoft Windows XP)
  8. If you want the service start up automatical at every tiems system start, you have to change the property StartType to Automatic.

    If you want the service startup when the service end of it installation, there more steps start from step 9 below you have to do.
  9. Add new class as a Install class into the project, open it in code view, Override the Comit Method as below:
        [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
        public override void Commit(System.Collections.IDictionary savedState)
        {
            base.Commit(savedState);
            ServiceController[] scServices = ServiceController.GetServices();
            foreach(ServiceController sc in scServices)
            {
                if(sc.ServiceName == "yourServiceName")
                {
                    if(sc.Status == ServiceControllerStatus.Stopped)
                    {
                        sc.Start();
                        break;
                    }
                }
            }
        }
Create a Setup Project for Windows Service
1. In the Add new projcet dialog select Setup Project Template to create new setup project.
2. Open the properties panel of the project, in the properties panle change the Manufacturer, ProductName to your fit, through the
    installation all the files will copy to the default folder which is composite from Program file/[Manufacturer]/[ProductName].
    but you can change the default install location setting in Properties of File System->Application Folder.
    the RemovePreciousVersions is false by default, indicate when you reinstall the program, the old version won't be uninstall.
    there are some more properties have to concern like Version, Author, Description, Subject etc.
2. In the Solution Explorer, Right click the projcet name and select View->File System, right click in the Application Folder
    and select Add->File or Add->Folder to add anything files you want to add to the folder where you service installed. you also
    can select Add->Project Output to specific any other projects output file into this setup project.
3. This step can install mySev.exe to windows system as a service. In the Solution Explorer, Right click the projcet name and select
    View->Custom Actions, Now a Select item dialog will show up to you, in the Look In Dropdown list select the file of
    window service mySev.exe in the Application Folder and then select ok. the file must been add by step 2.
4. In the Solution Explorer right click Project Name and select Properties to open the Project Properties Page, Click the buttom
    Prerequister, checked all .NET Framework version you need and uncheck the all you don't.
    If any version you select in the prerequist is missing in the installation computer, the install program will popup dialog to installing
    user to request install the properly version of .NET Framework.

For debug or some reason you can use Installutil.exe to install or uninstall the windows service by manual
Installutil.exe is only for .net, can not be uses in earlier windows service develop by C or C++.