Sep 14
Using C# to update windows registry
Posted by Wei in C# on 09 14th, 2009| | No Comments »

Here's the code to update the registry:

string strPath = "Software\\Path\\To\\Registry\\Location";
RegistryKey regKeyAppRoot = Registry.CurrentUser.OpenSubKey(strPath, true);
regKeyAppRoot.SetValue("Key1", "Value1");
regKeyAppRoot.SetValue("Key2", "Value2");
regKeyAppRoot.Close();

If the key doesn't exist, then you will get a null exception error: "System.NullReferenceException: Object reference not set to an instance of an object." This just means that you have to create the key before you can update it.

RegistryKey rk = Registry.CurrentUser.CreateSubKey(strPath);
rk.Close();

Initially, I thought it was a permission issue with updating the registry. So I added owner permissions to pretty much anyone and everyone. But I still got the issue. Finally figured out that all I had to do was create the Subkey. Hopefully I just saved someone hours of work.

Aug 25

This code will take a file as an input from the file system and add a watermark to that file.

    string FileLocation = "c:\\Temp\\SomeFile.pdf";
    string WatermarkLocation = "c:\\Temp\\watermark.gif";

    Document document = new Document();
    PdfReader pdfReader = new PdfReader(FileLocation);
    PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf","[temp][file].pdf"), FileMode.Create));

    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
    img.SetAbsolutePosition(250,300); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)

    PdfContentByte waterMark;
    for (int page = 1; page <= pdfReader.NumberOfPages; page++)
    {
        waterMark = stamp.GetUnderContent(page);
        waterMark.AddImage(img);
    }
    stamp.FormFlattening = true;
    stamp.Close();

    // now delete the original file and rename the temp file to the original file
    File.Delete(FileLocation);
    File.Move(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileLocation);

For the above to work, you need to make sure that the script has permissions to read and write from the C:\Temp folder. You also need to reference iTextSharp.dll.

Jul 24

Here's the code to download files of a certain type (in the example, I set it to find documents in the list with the .doc extension) from a document library to your hard drive.

    SPWeb mySite = SPContext.Current.Web;
    mySite.AllowUnsafeUpdates = true;
    SPList oList = mySite.Lists[<ListName>];
    SPQuery oQuery = new SPQuery();
    oQuery.Query = "<Where><Eq><FieldRef Name='DocIcon'/><Value Type='Computed'>doc</Value></Eq></Where>";
    SPListItemCollection listItems = oList.GetItems(oQuery);

    for (int i = 0; i < listItems.Count; i++) {
            SPListItem item = listItems[i];

            // copy this file to the temp folder
            byte[] binfile = item.File.OpenBinary();

            FileStream fs = new FileStream("C:\\Temp\\" + item["Name"], FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(binfile);
            bw.Close();
    }

May 1
Sorted List with multiple DateTime keys
Posted by Wei in C# on 05 1st, 2009| | No Comments »

What I needed to do was to sort a list of dates and corresponding names in order of date. Problem was that sometimes the dates duplicate and as a result, a standard SortedList would crash (since keys need to be unique). Anyway, here's a workaround to that problem. We create a new class for the project as follows:

    public class ComparableDateTime : IComparable
    {
        private DateTime mDT;

        public int CompareTo(object obj)
        {
            if (mDT.Ticks < ((ComparableDateTime)obj).mDT.Ticks) return -1;
            return 1;
        }

        public ComparableDateTime(DateTime myDate)
        {
            mDT = myDate;
        }
    }

Then once we have the class, we can declare a SortedList with that class:

using System.Collections.Generic;

SortedList<ComparableDateTime, string> mySortedList = new SortedList<ComparableDateTime,string>();

DateTime someDate = DateTime.Today;

mySortedList.Add(new ComparableDateTime(someDate,"someString");
mySortedList.Add(new ComparableDateTime(someDate,"someString2");

for (int i = 0; i < mySortedList.Count; i++)
{
    writer.Write(mySortedList.Values[i].ToString());
}

Apr 20

Here's a little function that I wrote to return you the Monday's date for this week, next week, etc...

GetNextWeekDates(DayOfWeek.Monday, 0);

Change DayOfWeek.Monday to any day of the week and it will return you the next date on that particular day. The integer represents which date you want to return. 0 means that you want this week's Monday. Set it to 1, then it's the coming Monday. Set it to 2 and you get the date of the Monday after.

        private DateTime GetNextWeekDates(DayOfWeek targetDay, int weekNumber)
        {
            int daysDifference = (int)targetDay - (int)DateTime.Today.DayOfWeek;

            if (daysDifference == 0) weekNumber++;

            DateTime returnDate;

            if (daysDifference < 0)
            {
                returnDate = DateTime.Today.AddDays(daysDifference + 7 + ((weekNumber - 1) * 7));
            }
            else
            {
                returnDate = DateTime.Today.AddDays(daysDifference + ((weekNumber - 1) * 7));
            }

            return returnDate;
        }

« Previous Entries Next Entries »