visual studio 2010 becomes slow after saving on Windows 7

My Visual Studio 2010 has had an issue with running real slow. What I was doing was rebooting my machine to help with the issue. But I have several things loaded and it would get old loading the whole machine again. So finally I looked online and found the following post:

visual studio 2010 becomes slow after saving on Windows 7

By using the following 6 steps if fixed the issue for me:

  1. Right-click the Start button
  2. Choose Properties
  3. Uncheck both checkboxes under the Privacy group
  4. Click the Apply button
  5. Re-check both checkboxes
  6. Press OK

Force update DataGridView when editing new row

I was having an issue that a new row that I was editing was not being updated and saving. It would update if I moved to another row, but from a user friendly view this does not work. I don’t want to have the user move to another row so that the update will work.

I tried several things:

dataGridView1.EndEdit();

Didn’t work!

Tried:

bindingSource1.EndEdit();
dataGridView1.EndEdit();

Didn’t work!

Tried:

dataGridView1.EndEdit();
bindingSource1.EndEdit();

Didn’t Work!

After several google searches I came across a mention of useing the BindingContext.

Why is the default behavior for the DataGridView to not update the changes in a new row when save is done, I am at a total loss. I wonder how many developer hours are lost trying to get this to work!

I finally created an extension method as follows:

public static void EndCurrentEdit(this DataGridView dgv) {
  dgv.BindingContext[dgv.DataSource].EndCurrentEdit();
  dgv.EndEdit();
}

To call it I use the following:

dataGridView1.EndCurrentEdit();

In winforms getting a parent control of a given type

On my baseball scoring application I needed to get a parent control to share data between controls.

Because controls can have several levels between them it takes some recursion to get to the needed control.

The following generic method will get the first control of a given type.

public static T GetParent<T>(this Control ctl) where T : Control {
  var retVal = default(T);
  var parent = ctl;
  while (parent.Parent != null) {
    parent = parent.Parent;
    if (parent is T) {
      retVal = (T)parent;
      break;
    }
  }
  return retVal;
}

C# AppActivate

I wanted to be able to activate an application using C#.

By using the following it will activate the application:

[DllImportAttribute("User32.dll")]
private static extern int SetForegroundWindow(int hWnd);
 
private bool AppActivate(string titleName) {
  var success = true;
  var process = Process.GetProcesses()
                .Where(p => p.MainWindowTitle.StartsWith(titleName))
                .FirstOrDefault();
  if (process != null) {
    SetForegroundWindow(process.MainWindowHandle.ToInt32());
  }
  else {
    success = false;
  }
  return success;
}

First parts setups method for call to User32.dll so SetForegroundWindow can be called from it.

Next is a method that is called to first get the process that starts with the title name passed to it and if found then calls SetForegroundWindow.

To call the Calculator app call AppActivate method as following:

var success = AppActivate("Calc");

Getting a count of checked items in a CheckBoxList

The following function uses JQuery and will get the number of checked items in a CheckBoxList.

<script type="text/javascript">
    function checkBoxListCount() {
        var count = $('input[type=checkbox][id*=CheckBoxListId]:checked').length;
        if (count == 0) {
            return false;
        }
        else {
            return true;
        }            
    }
</script>

Where [id*=CheckBoxListId] is change CheckBoxListId to the name of CheckBoxList.

Adding a index for items in a linq query

It is possible to add a index to a linq query as follows:

var list = new List<string> { "Zero", "One", "Two", "Three", "Four", "Five" };
var indexed = list.Select((l, i) => new { Item = l, Index = i });

Getting a list of files from a ZipPackage

In my current project I needed to get a list of files that were in a zip file. In the past when I needed to do this I would have used J# and just added a reference. Since J# is not included I wanted to see if there was a different way to achieve this.

Microsoft has since added a System.IO.Packaging namespace that includes the ZipPackage class. I added a reference to WindowsBase.dll because that is where the ZipPackage class is.

As I researched about using the class I found that it does not provide a public method to get a list of the files. As I looked at the data I noticed a field named _zipArchive of the type MS.Internal.IO.Zip.ZipArchive. I looked further in the field and noticed a property named ZipFileInfoDictionary which is a System.Collections.Hashtable.

By using reflection I was able to access the _zipArchive and the ZipFileInfoDictionary to retrieve the file list.

I have created the following extension method called GetFileList to return the list of files in the zip file.

public static List<string> GetFileList(this ZipPackage zp)
{
    List<string> list = null;
 
    try
    {
        var zipArchiveProperty = zp.GetType().GetField("_zipArchive", 
                                    BindingFlags.Static 
                                    | BindingFlags.NonPublic 
                                    | BindingFlags.Instance);
 
        var zipArchive = zipArchiveProperty.GetValue(zp);
 
        var zipFileInfoDictionaryProperty = 
            zipArchive.GetType().GetProperty("ZipFileInfoDictionary", 
                                            BindingFlags.Static 
                                            | BindingFlags.NonPublic 
                                            | BindingFlags.Instance);
 
        var zipFileInfoDictionary = 
            zipFileInfoDictionaryProperty.GetValue(zipArchive, null) as Hashtable;
 
        var query = from System.Collections.DictionaryEntry de in zipFileInfoDictionary
                    select de.Key.ToString();
 
        list = query.ToList();
    }
    catch (NotSupportedException nse)
    {
        throw;
    }
    return list;
}

To call the method I used the following:

private List<string> GetFileListFromZipFile(FileInfo zipFileName)
{
    List<string> list = null;
 
    try
    {
        var zp = ZipPackage.Open(zipFileName.FullName, 
                                 FileMode.Open, 
                                 FileAccess.Read, 
                                 FileShare.Read) as ZipPackage;
        list = zp.GetFileList();
    }
    catch (NotSupportedException nse)
    {
        throw;
    }
    return list;
}

I ended up having to use the FileShare.Read because I was getting a file in use exception.

C# version of VB.Net DateAdd

I have been working on a application that is dealing with dates. I wanted to use a function like DateAdd but that is part of VB.Net.

I created a function that is the same as the DateAdd:

public enum DateInterval
{
    Day,
    DayOfYear,
    Hour,
    Minute,
    Month,
    Quarter,
    Second,
    Weekday,
    WeekOfYear,
    Year,
}
 
private DateTime DateAdd(DateInterval interval, double number, DateTime dateValue)
{
    DateTime dtm = dateValue;
    // DateInterval.DayOfYear and DateInterval.Weekday appear the same
    // as DateInterval.Day.
    // Looking at http://msdn.microsoft.com/en-us/library/hcxe65wz(v=vs.71).aspx 
    // also seems to indicate they are the same as DateInterval.Day.
    switch (interval)
    {
        case DateInterval.Day:
        case DateInterval.DayOfYear:
        case DateInterval.Weekday:
            dtm = dateValue.AddDays(number);
            break;
        case DateInterval.Hour:
            dtm = dateValue.AddHours(number);
            break;
        case DateInterval.Minute:
            dtm = dateValue.AddMinutes(number);
            break;
        case DateInterval.Month:
            int months = Convert.ToInt32(number);
            dtm = dateValue.AddMonths(months);
            break;
        case DateInterval.Quarter:
            int quarters = Convert.ToInt32(number);
            dtm = dateValue.AddMonths(quarters * 3);
            break;
        case DateInterval.Second:
            dtm = dateValue.AddSeconds(number);
            break;
        case DateInterval.WeekOfYear:
            int weekOfYear = Convert.ToInt32(number);
            dtm = dateValue.AddDays(weekOfYear * 7);
            break;
        case DateInterval.Year:
            int years = Convert.ToInt32(number);
            dtm = dateValue.AddYears(years);
            break;
    }
    return dtm;
}
 
private DateTime DateAdd(string interval, double number, DateTime dateValue)
{
    Dictionary<string, DateInterval> dct = new Dictionary<string, DateInterval>
    {
        {"d", DateInterval.Day},
        {"y", DateInterval.DayOfYear},
        {"h", DateInterval.Hour},
        {"n", DateInterval.Minute},
        {"m", DateInterval.Month},
        {"q", DateInterval.Quarter},
        {"s", DateInterval.Second},
        {"w", DateInterval.Weekday},
        {"ww", DateInterval.WeekOfYear},
        {"yyyy", DateInterval.Year},
    };
    DateInterval di = DateInterval.Day;
    if (dct.ContainsKey(interval))
    {
        di = dct[interval];
    }
    else
    {
        throw new ArgumentException("Argument 'interval' is not a valid value.");
    }
    return DateAdd(di, number, dateValue);
}

Using a Linq query to group and crosstab/pivot data

I needed to get values from a grid. On the server side I didn’t have a rows collection so I needed to resort to using the Request.Form to get all the values that were sent to the server.

By using Linq with a group by I was able to get the values grouped and crosstabed/pivoted to store the values in the database.

The following is the linq that I used:

private IEnumerable<KeyValuePair<string, string>> KeyValuePair(NameValueCollection nvc) {
    if (nvc == null) {
        throw new ArgumentNullException("Named Value Collection");
    }
    return nvc.Cast<string>().Select(key => new KeyValuePair<string, string>(key, nvc[key]));
}
var query = from KeyValuePair<string, string> kvp in KeyValuePair(Request.Form)
            let index = kvp.Key.IndexOf("_") > 0 ? kvp.Key.IndexOf("_") : kvp.Key.Length
            let Key = kvp.Key.Substring(0, index)
            group kvp by new { Key } into g
            where g.Key.Key.Contains("Results$cell")
            select new
            {
                Key = g.Key.Key,
                id = g.Where(k => k.Key.Contains("id")).First().Value,
                completed = g.Where(k => k.Key.Contains("completed")).First().Value,
                comments = g.Where(k => k.Key.Contains("comments")).First().Value,
            };

How to set the theme programmatically for the whole web site and not just a page

On my current project I am working on I needed a way for when the user selects a theme to set the whole site to the same theme.

Doing it for just one page is pretty straight forward.  Basically by setting a QueryString variable to the name of the theme and then setting the Page.Theme to the name in the Page_PreInit event it will set the page to the given theme.

pagename.aspx?theme=themename
 
protected void Page_Init(object sender, EventArgs e) {
  if (Request.QueryString.AllKeys.Contains("theme") == true) {
    Page.Theme = Request.QueryString["theme"];
  }
}

I did have some issued with using ViewState and Session so QueryString seemed to be the way to get it to work.

Setting the theme for the site and keeping it from page to page presented some issues because of the the ViewState and Session variables.  So I had to find some other method.

I have to give credit to Rick van den Bosch for his blog entry HowTo: Set the Theme for a MasterPage (from code) which is located at http://bloggingabout.net/blogs/rick/archive/2007/10/20/howto-set-the-theme-for-a-masterpage-from-code.aspx.

It had just about everything that I needed to set the theme for the whole site.  The only thing that I needed was to code a method that he called DetermineTheme.  How I accomplished that was as follows:

I first created a BasePage that inherited from System.Web.UI.Page.  Then in the page I added a property called CurrentTheme.  This will store the currently used theme for the web site.  I put that in the App_Code folder of the website.   The class is as follows:

public class BasePage : System.Web.UI.Page {
  public string CurrentTheme {
    get {
      string currentTheme = string.Empty;
      if (Session["CurrentTheme"] != null) {
        currentTheme = Session["CurrentTheme"].ToString();
      }
      return currentTheme;
    }
    set {
      Session["CurrentTheme"] = value;
    }
  }
}

Then every page for the site inherits from the BasePage as follows:

public partial class _Default : BasePage

Then in the Global.asax page in the Application_PreRequestHandlerExecute method I entered the code to set the theme.  The method looks as follows:

void Application_PreRequestHandlerExecute(object sender, EventArgs e) {
 
    var page = Context.Handler as BasePage;
    if (page != null) {
 
        if (Request.QueryString.AllKeys.Contains("theme") == true) {
            page.CurrentTheme = Request.QueryString["theme"];
        }
 
        page.Theme = page.CurrentTheme;
    }
}

This allows the theme to be changed and set for each page of the website.