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
}
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
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();
}
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 “”;
}
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);
}
}
}
}
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
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)
{
}
SSD Optimisations
by admin on Jul.23, 2009, under Windows 7
Increase System Speed
Disable indexing
Description: Indexing creates and maintains a database of file attributes. This can lead to multiple small writes when creating/deleting/modifying files. Searching for files will still work.
Instructions: Start Menu -> Right-Click Computer -> Manage -> Services and Applications -> Services – > Right-Click Windows Search -> Startup type: Disabled -> OK
Disable defragmentation
Description: Defragmenting a hard disk’s used space is only useful on mechanical disks with multi-millisecond latencies. Free-space defragmentation may be useful to SSDs, but this feature is not available in the default Windows Defragmenter.
Instructions: Start Menu -> Right-Click Computer -> Manage -> Services and Applications -> Services – > Right-Click Disk Defragmenter -> Startup type: Disabled -> OK
Disable Write Caching
Description: There is no cache on the SSD, so there are no benefits to write caching. There are conflicting reports on whether this gains speed or not.
Instructions: Start Menu -> Right-Click Computer -> Manage -> Device Manager -> Disk drives -> Right-Click STEC PATA -> Properties -> Policies Tab -> Uncheck Enable write caching -> OK
Configure Superfetch
Description: Frees up RAM by not preloading program files.
Instructions: On second glance, I would recommend leaving this one alone. However, there are some customizations that you can follow in the post below.
Firefox – Use memory cache instead of disk cache
Description: If you use Firefox, there’s a way to write cached files to RAM instead of the hard disk. This is not only faster, but will significantly reduce writes to the SSD while using the browser.
Instructions: Open Firefox -> Type about:config into the address bar -> Enter -> double-click browser.cache.disk.enable to set the value to False -> Right-Click anywhere -> New -> Integer -> Preference Name “disk.cache.memory.capacity” -> value memory size in KB. Enter 32768 for 32MB, 65536 for 64MB, 131072 for 128MB, etc. -> restart Firefox
Free up extra drive space
Disable the Page File
Description: Eliminate writing memory to the SSD, free over 2GB of disk space. Warning – If you run out of memory the program you’re using will crash.
Instructions: Start Menu -> Right-Click Computer -> Properties -> Advanced System Settings -> Settings (Performance) -> Advanced Tab -> Change -> Uncheck Automatically manage -> No paging file -> Set -> OK -> Restart your computer
Alternatively, if you want to play it safer, you can set a custom size of 200MB min and max.
Disable System Restore
Description: Don’t write backup copies of files when installing new programs or making system changes. Can free up between a few hundred MB to a couple GB. Warning – Although unlikely, if a driver installation corrupts your system, there won’t be an automatic way to recover.
Instructions: Start Menu -> Right-Click Computer -> Properties -> Advanced System Settings -> System Protection Tab -> Configure -> Turn off system protection -> Delete -> OK
Disable Hibernate
Description: You may free up 1GB of space on the SSD if you have 1GB of memory, 2GB of space if you have 2GB memory. You will lose the hibernation feature which allows the equivalent of quick boots and shutdowns.
Instructions: Start Menu -> Type cmd -> Right-Click the cmd Icon -> Run as Administrator -> Type powercfg -h off -> Type exit
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; }
}
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];
}