Vision

c#

c# Console Progress Bar

by admin on Jan.27, 2010, under c#

    private static void drawTextProgressBar(decimal progress, decimal total)
    {
      //draw empty progress bar
      Console.CursorLeft = 0;
      Console.Write(“["); //start
      Console.CursorLeft = 32;
      Console.Write("]“); //end
      Console.CursorLeft = 1;
      float onechunk = 30.0f / (int)total;

      //draw filled part
      int position = 1;
      for (int i = 0; i < onechunk * (int)progress; i++)
      {
        Console.BackgroundColor = ConsoleColor.Green;
        Console.CursorLeft = position++;
        Console.Write(” “);
      }

      //draw unfilled part
      for (int i = position; i <= 31; i++)
      {
        Console.BackgroundColor = ConsoleColor.Black;
        Console.CursorLeft = position++;
        Console.Write(” “);
      }

      //draw totals
      Console.CursorLeft = 34;
      Console.BackgroundColor = ConsoleColor.Black;
      decimal value = Math.Round  ((progress / total) * 100,0);
      Console.Write(value.ToString () + “%    “); //blanks at the end remove any excess
    }

Leave a Comment more...

c# Create XML Classes from XML Data

by admin on Dec.14, 2009, under c#

Use the following exe.

copy “C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\xsd.exe” “C:\Windows\System32″

xsd file.xml

xsd file.xsd /classes

Leave a Comment more...

Setting Culture

by admin on Dec.03, 2009, under c#

if (CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern != “yyyy/mm/dd”)
      {
        //Registry Logic
        //Open Sub key
        RegistryKey rkey = Registry.CurrentUser.OpenSubKey(@”Control Panel\International”, true);
        ///Set Values
        rkey.SetValue(“sShortDate”, Constants.ShortDatePattern);
        //Close the Registry
        rkey.Close();
        MessageBox.Show(“System has been reconfigured.” + “\r\n\r\n” + “Please restart application.”, Constants.ApplicationTitle, MessageBoxButton.OK, MessageBoxImage.Information);
        Application.Current.Shutdown();
      }

Leave a Comment more...

GetDefault printer

by admin on Nov.10, 2009, under c#

   using System.Management;

public static string GetDefaultPrinter()
    {
      string strQuery = “SELECT * FROM Win32_Printer”;
      ObjectQuery objectQuery = new ObjectQuery(strQuery);
      ManagementObjectSearcher query = new ManagementObjectSearcher(objectQuery);
      ManagementObjectCollection queryCollection = query.Get();
      foreach (ManagementObject managementObject in queryCollection)
      {
        PropertyDataCollection propertyDataCollection = managementObject.Properties;

        if ((bool)managementObject["Default"]) // DEFAULT PRINTER
        {
          return (managementObject["Name"].ToString ());
          //Console.WriteLine(managementObject["Location"]);
        }
      }
      return “”;
    }

Leave a Comment more...

Shut down system using C#

by admin on Nov.10, 2009, under SQL, c#

This code shut downs the operating system using the System.Management assembly, but not before obtaining the required security privileges.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

// Remember to add a reference to the System.Management assembly

using System.Management;
namespace ShutDown
{
public partial class Form1 : Form
{
public Form1()

{

InitializeComponent();

}

private void btnShutDown_Click(object sender, EventArgs e)

{

ManagementBaseObject mboShutdown = null;

ManagementClass mcWin32 = new ManagementClass(“Win32_OperatingSystem”);

mcWin32.Get();

// You can’t shutdown without security privileges

mcWin32.Scope.Options.EnablePrivileges = true;

ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters(“Win32Shutdown”);

// Flag 1 means we want to shut down the system

mboShutdownParams["Flags"] = “1″;

mboShutdownParams["Reserved"] = “0″;

foreach (ManagementObject manObj in mcWin32.GetInstances())

{

mboShutdown = manObj.InvokeMethod(“Win32Shutdown”, mboShutdownParams, null);

}

}

}

}

Leave a Comment more...

What is your Memory Load Percentage?

by admin on Oct.13, 2009, under c#

Here’s a console utility to print it out:

‘ File: MemLoad.vb
imports System.Runtime.InteropServices

Module module_memoryload

 structure MEMORYSTATUSEX
   public Length as Integer
   public MemoryLoad as Integer
   public TotalPhys as LONG
   public AvailPhys as LONG
   public TotalPageFile as LONG
   public AvailPageFile as LONG
   public TotalVirtual as LONG
   public AvailVirtual as LONG
   public AvailExtendedVirtual as LONG
 End Structure

 Declare Function GlobalMemoryStatusEx lib “kernel32″ _
          (ByRef ms As MEMORYSTATUSEX) As Boolean

 sub main(ByVal args() As String)
   dim ms as new MemoryStatusEx
   ms.Length =  Marshal.Sizeof(ms)
   if GlobalMemoryStatusEx(ms) then
      Console.WriteLine(“- Memory Load: {0}%”, ms.MemoryLoad)
   end if
 end sub

end Module

Leave a Comment more...

C# Custom events

by admin on Aug.03, 2009, under c#

Declaring new events:

public class Service
 {

       public delegate void DataArrivalEventDelegate(string e);
       public static event DataArrivalEventDelegate DataArrival; 

}

Firing The event:

DataArrival(“Hallo”);

Subscribing to the event:

Service.DataArrival += new Service.DataArrivalEventDelegate(DataArrival);

 void DataArrival(string message)
{
}

Leave a Comment more...

Google Contact Detail Listing (C# , Google API, ASP.NET)

by admin on Jul.20, 2009, under c#

Check out the following ASP.NET example for listing contact of a gmail account and adding a new contact to it. First download the Google Data API from the specified link and install it

http://code.google.com/p/google-gdata/

Then create a new project and include following references in it

Google.GData.Client.dll
Google.GData.Contacts.dll
Google.GData.Extensions.dll

Then i created the following class
using System;
using System.Collections.Generic;
using Google.GData.Contacts;
using Google.GData.Extensions;

///
/// Summary description for GoogleContactService
///
public class GoogleContactService
{
public static ContactsService GContactService = null;

public static void InitializeService(string username,
string password)
{
GContactService = new ContactsService(“Contact Infomation”);
GContactService.setUserCredentials(username, password);
}

public static List<ContactDetail> GetAllContact()
{
List<ContactDetail> contactDetails = new List<ContactDetail>();
ContactsQuery query = new ContactsQuery(ContactsQuery.
CreateContactsUri(“default”));

ContactsFeed feed = GContactService.Query(query);
foreach (ContactEntry entry in feed.Entries)
{
ContactDetail contact = new
ContactDetail{Name = entry.Title.Text,
EmailAddress1 = entry.Emails.Count >= 1 ? entry.Emails[0].Address : “”,
EmailAddress2 = entry.Emails.Count >= 2 ? entry.Emails[1].Address : “”,
Phone = entry.Phonenumbers.Count >= 1 ? entry.Phonenumbers[0].Value : “”,
Address =  entry.PostalAddresses.Count >= 1 ? entry.PostalAddresses[0].Value : “”,
Details = entry.Content.Content};

contactDetails.Add(contact);
}

return contactDetails;
}

public static void AddContact(ContactDetail contact)
{
ContactEntry newEntry = new ContactEntry();
newEntry.Title.Text = contact.Name;

EMail primaryEmail = new EMail(contact.EmailAddress1);
primaryEmail.Primary = true;
primaryEmail.Rel = ContactsRelationships.IsWork;
newEntry.Emails.Add(primaryEmail);

EMail secondaryEmail = new EMail(contact.EmailAddress2);
secondaryEmail.Rel = ContactsRelationships.IsHome;
newEntry.Emails.Add(secondaryEmail);

PhoneNumber phoneNumber = new PhoneNumber(contact.Phone);
phoneNumber.Primary = true;
phoneNumber.Rel = ContactsRelationships.IsMobile;
newEntry.Phonenumbers.Add(phoneNumber);

PostalAddress postalAddress = new PostalAddress();
postalAddress.Value = contact.Address;
postalAddress.Primary = true;
postalAddress.Rel = ContactsRelationships.IsHome;
newEntry.PostalAddresses.Add(postalAddress);

newEntry.Content.Content = contact.Details;

Uri feedUri = new Uri(ContactsQuery.CreateContactsUri(“default”));

ContactEntry createdEntry = (ContactEntry)GContactService.Insert(feedUri, newEntry);
}
}

public class ContactDetail
{
public string Name { get; set; }
public string EmailAddress1 { get; set; }
public string EmailAddress2 { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
public string Details { get; set; }
}

Leave a Comment more...

C# Read from XML File

by admin on Jul.20, 2009, under c#

private static DataTable GetXMLData(string DataTableToReturn)
{
      XmlDocument doc = new XmlDocument();
      doc.Load(@”c:\filename.xml”);

      DataSet ds = new DataSet();
      ds.ReadXml(new XmlNodeReader(doc));
      return ds.Tables[DataTableToReturn];
 }

Leave a Comment more...

C# Reflection – get attributes

by admin on Jul.14, 2009, under c#

public List<string> GetAvailableSystemAttribute()
    {
      List<string> attributes= new List<string>();
      string systemAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
      string systemAssemblyFilter = “*.exe”
      foreach (var filePath in Directory.GetFiles(systemAssemblyPath, systemAssemblyFilter))
      {
      �
          if (isValidAssembly(filePath,systemAssemblyPath, systemAssemblyFilter))
          {
            System.Reflection.Assembly Assembly = System.Reflection.Assembly.LoadFile(filePath);
            foreach (var type in Assembly.GetTypes())
            {
              foreach (MemberInfo mi in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance ))
              {
                foreach (System.Attribute attribute in System.Attribute.GetCustomAttributes(mi))
                {
                    attributes.add(attribute.ToString());
                }
              }
          }
        }
      }
      return attributes;
    }

Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...