Search

C#: DATE-TIME FUNCTIONS

// DATE FUNCTIONS
        // Get Current Year
        protected int _currentYear()
        {
            DateTime dtn = DateTime.Now;
            int ret= dtn.Year;
            return ret;
        }//**
 
        // Get Current Month
        protected int _currentMonth()
        {
            DateTime dtn = DateTime.Now;
            int ret = dtn.Month;
            return ret;
        }//**
 
        // Get current month in string
        protected string _curMonthStr()
        {
            string thismonth = String.Format("{0:MMMM}", DateTime.Now).ToString();
            return thismonth;
        }
 
        // Get Current Day
        protected int _currentDay()
        {
            DateTime dtn = DateTime.Now;
            int ret = dtn.Day;
            return ret;
        }//**
 
        // Get Sundays for this month
        protected int[] getSundays(int year, int month, DayOfWeek dayName)
        {
            int[] _sunday = new int[4];
            CultureInfo ci = new CultureInfo("en-US");
            int ai = 0;
            for (int i = 1; i <= ci.Calendar.GetDaysInMonth(year, month); i++)
            {
 
                if (new DateTime(year, month, i).DayOfWeek == dayName)
                {
                    //Response.Write(i.ToString());
                    _sunday[ai] = i; ai += 1;
                }
            }
            return _sunday;
        }//**
 

C#: Get num of days in month

DateTime.DaysInMonth(int year, int month);
 
     //or
 
static int GetDaysInMonth(int year, int month)
{
DateTime dt1 = new DateTime(year, month, 1);
DateTime dt2 = dt1.AddMonths(1);
TimeSpan ts = dt2 - dt1;
return (int)ts.TotalDays;
}
 

C#: Get sundays in month

using System.Globalization;

protected void PrintSundays(int year, int month, DayOfWeek dayName)
{
  CultureInfo ci = new CultureInfo("en-US");
  for (int i = 1 ; i <= ci.Calendar.GetDaysInMonth (year, month); i++)
  {
    if (new DateTime (year, month, i).DayOfWeek == dayName)
      Response.Write (i.ToString() + "
");
  }
}

C#: HttpWebRequest example with error handling using C#

using System;
using System.IO;
using System.Net;
using System.Text;
 
public class HttpWebRequestTool
{
  public static void Main(String[] args)
  {
    if (args.Length < 2)
    {
      Console.WriteLine("Missing argument. Need a URL and a filename");
    }
    else
    {
      StreamWriter sWriter = new StreamWriter(args[1]);
      sWriter.Write(WRequest(args[0], "GET", ""));
      sWriter.Close();
    }
  }
 
  public static string WRequest(string URL, string method, string postData)
  {
    string responseData = "";
    try
    {
      System.Net.HttpWebRequest hwrequest =
        (System.Net.HttpWebRequest) System.Net.WebRequest.Create(URL);
      hwrequest.Accept = "*/*";
      hwrequest.AllowAutoRedirect = true;
      hwrequest.UserAgent = "http_requester/0.1";
      hwrequest.Timeout= 60000;
      hwrequest.Method = method;
      if (hwrequest.Method == "POST")
      {
        hwrequest.ContentType = "application/x-www-form-urlencoded";
        // Use UTF8Encoding instead of ASCIIEncoding for XML requests:
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        byte[] postByteArray = encoding.GetBytes(postData);
        hwrequest.ContentLength = postByteArray.Length;
        System.IO.Stream postStream = hwrequest.GetRequestStream();
        postStream.Write(postByteArray, 0, postByteArray.Length);
        postStream.Close();
      }
      System.Net.HttpWebResponse hwresponse =
        (System.Net.HttpWebResponse) hwrequest.GetResponse();
      if (hwresponse.StatusCode == System.Net.HttpStatusCode.OK)
      {
        System.IO.Stream responseStream = hwresponse.GetResponseStream();
        System.IO.StreamReader myStreamReader =
          new System.IO.StreamReader(responseStream);
        responseData = myStreamReader.ReadToEnd();
      }
      hwresponse.Close();
    }
    catch (Exception e)
    {
      responseData = "An error occurred: " + e.Message;
    }
    return responseData;
  }
}
 

C#: Using inline code in ASP.NET

Using this syntax, you can use inline code in ASP.NET (.aspx) pages. The server-side code will be automatically compiled by the .NET framework the first time the page is requested on the server. The compiled .dll file is stored in the "Temporary ASP.NET Files" system folder. Changing the code in .aspx files will trigger a new compilation, generating new .dll files. The old .dll files are phased out by the framework and eventually deleted.

 

<%@ Import Namespace="System" %>

<%@ Page Language="c#"%>

 

<script runat="server">

  public string ServerSideFunction(string input)

  {

    return "Hello " + input;

  }

</script>

 

<% string pageVariable = "world"; %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />

<title>ASP.NET inline</title>

</head>

<body>

<% =ServerSideFunction(pageVariable) %>

</body>

</html>

C#: Create Bitmap Image

private Bitmap CreateBitmapImage(string sImageText)

{

        Bitmap objBmpImage = new Bitmap(1, 1);

   

       int intWidth = 0;

       int intHeight = 0;

  

       // Create the Font object for the image text drawing.

       Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);

 

       // Create a graphics object to measure the text's width and height.

       Graphics objGraphics = Graphics.FromImage(objBmpImage);

     

       // This is where the bitmap size is determined.

       intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;

       intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;

  

       // Create the bmpImage again with the correct size for the text and font.

       objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));

  

       // Add the colors to the new bitmap.

       objGraphics = Graphics.FromImage(objBmpImage);

  

       // Set Background color

      objGraphics.Clear(Color.White);

       objGraphics.SmoothingMode = SmoothingMode.AntiAlias;

      objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

       objGraphics.DrawString(sImageText, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);

       objGraphics.Flush();

  

       return (objBmpImage);

  }

 

Create Bitmap Image with text input

List All Assembly exceptions

This C# program lists the exceptions available within an assembly. Tip: call it from the command line with C:\ExceptionReflection.exe > Exceptions.txt.

using System;
using System.Collections;
using System.Reflection;
using System.Text;
 
namespace ExceptionReflection
{
 
   class Program
   {
 
      static void Main(string[] args)
      {
         // load the assemblies to analyze
         LoadAssemblies();
         ArrayList ExceptionTree = new ArrayList();
         foreach (Assembly Assembly in AppDomain.CurrentDomain.GetAssemblies())
         {
            foreach (Type Type in Assembly.GetTypes())
            {
               if (!Type.IsClass || !Type.IsPublic) continue;
 
               StringBuilder TypeHierarchy = 
                  new StringBuilder(Type.FullName, 5000);
               Boolean IsDerivedFromException = false;
               Type BaseType = Type.BaseType;
               while ((BaseType != null) && !IsDerivedFromException)
               {
                  TypeHierarchy.Append("-" + BaseType);
                  IsDerivedFromException = (BaseType == typeof(Exception));
                  BaseType = BaseType.BaseType;
               }
 
               if (!IsDerivedFromException) continue;
 
               String[] Hierarchy = TypeHierarchy.ToString().Split('-');
               Array.Reverse(Hierarchy);
 
               ExceptionTree.Add(String.Join
                  ("-", Hierarchy, 1, Hierarchy.Length - 1));
               ExceptionTree.Sort();
               foreach (String Identifier in ExceptionTree)
               {
                  String[] Trace = Identifier.Split('-');
                  Console.WriteLine(new String(' ', 3*Trace.Length) 
                     + Trace[Trace.Length-1]);
               }
            }
         }
            Console.ReadLine();
      }
 
      static void LoadAssemblies()
      {
         String[] Assemblies =
         {
            /* uncomment as needed */
            //"System, PublicKeyToken={0}",
            //"System.Data, PublicKeyToken={0}",
            //"System.Design, PublicKeyToken={1}", 
            //"System.DirectoryServices, PublicKeyToken={1}", 
            //"System.Drawing, PublicKeyToken={1}",
            //"System.Drawing.Design, PublicKeyToken={1}",
            //"System.EnterpriseServices, PublicKeyToken={1}",
            //"System.Management, PublicKeyToken={1}",
            //"System.messaging, PublicKeyToken={1}",
            //"System.Runtime.Remoting, PublicKeyToken={0}",
            //"System.Security, PublicKeyToken={1}",
            //"System.serviceProcess, PublicKeyToken={1}",
            //"System.Web, PublicKeyToken={1}",
            //"System.Web.RegularExpressions, PublicKeyToken={1}",
            //"System.Web.Services, PublicKeyToken={1}",
            //"System.Windows.Forms, PublicKeyToken={0}",
            //"System.Xml, PublicKeyToken={0}",
            "MSCorLib, PublicKeyToken={0}"
         };
 
         // change this if you want to use assemblies that are not from microsoft
         String EcmaPublicKeyToken = "B77A5C561934E089";
         String MSPublicKeyToken   = "B03F5F7F11D50A3A";
 
         // get the newest version
         Version Version = typeof(System.Object).Assembly.GetName().Version;
 
         // load the assemblies
         foreach (String AssemblyName in Assemblies)
         {
            String AssemblyIdentity = 
               String.Format(AssemblyName, EcmaPublicKeyToken, 
               MSPublicKeyToken) + 
               ", Culture=neutral, Version=" + Version;
            Assembly.Load(AssemblyIdentity);
         }
      }
   }
}

List SQL Server databases

This C# code snippet displays all the SQL Server database names.