Josh's profileJosh's SpaceBlogListsSkyDrive Tools Help

Josh's Space

<LiveSpace owner="Josh" permissions="public" purpose="ramble" />

Josh Martin

Occupation
Location

Custom HTML

No content has been added yet.

ScriptManager.RegisterStartupScript

{
So I just met the static ScriptManager.RegisterStartupScript method!  And it works like a charm!
I was having a terrible time with an AJAX UpdatePanel today!  I had some <script> tags inside of it that would never get executed!  I thought about it for a second, and realize why they didn't - why would they?  I mean the page fully loads, and then there's some javascript action that changes the innerHtml property of a control, of course the content of script tags wouldn't get executed! 
So I did some googling, and it turns out a lot of people had the same question!  How do you execute scripts inside the UpdatePanel?
I was directed to this: ScriptManager.RegisterStartupScript
At first I didn't think it was a static method, so I kept looking around for the method but could find it - and just disregarded the forum posts thinking they were using a BETA version of AJAX.  After doing some digging, I found the methods to be static.
 
My situation involved an UpdatePanel, a RadioButtonList and a MultiView control inside of the Panel.
The RadioButtonList controls the MultiView.ActiveViewIndex.  So there's some really nice updating going on.  However, I needed some javascript code executed if a certain View is active.  I got it working with this static control!  YAY!
 
 

protected void RadioButtonList1_SelectedIndexChange(object sender, EventArgs e)
{

switch (RadioButtonList1.SelectedIndex)
{

case 2:

MultiView1.ActiveViewIndex = 2;

ScriptManager.RegisterStartupScript(UpdatePanel1.FindControl("MultiView1"), typeof(MultiView), "blah", "<script>JavaScriptFunction();</script>", false);

break;

}

}

}

Dictionay<T, K>.Remove(T);

{
Recently I was working on a programming project that required me to periodically loop through a Dictionary collection and check values to determine whether or not to keep those items (KeyValuePair) or not.
 
Without thinking, I went ahead and wrote a foreach(KeyValuePair<T, K> pair in MyDictionary), checking with pair.Value, and if it wasn't any good, then calling MyDictionary.Remove(pair.Key). 
 
Easy enough, right?  No.  As you know (I can see the smirk on your face now!) you can't modify the collection while enumerating through it!  Which after thinking about it, makes perfect sense.  So what do you do?  I read a blog post on the internet about a case like this, and the author suggested a couple of ideas:
1. Loop through the collection, and add the valid values to a new collection, and after the loop, replace the old collection with the new.
2. Two loops, the first loop will - NO.  Not an option.  No more than one loop (this is a very simple operation, the code better be too!)
 
I don't like the first idea either.  Two collections and copying back and forth is not acceptable.  Suddenly I realized something: one of the overloads for List<T> is an IEnumerable<T> object, which in the overload will enumerate through and copy (not reference) to the new List<T>.  We could then effectively enumerate through the List<T> and remove what we want from the Dictionary<T, K>.  Honestly, I don't like the idea of creating a whole new list in memory, but in my application the size of it will be very small at all times.  In conclusion this keeps the code simple and gets the job done, which is all I need at the moment.
 

Dictionary<Guid, string> Users;

...

foreach (Guid id in new List<Guid>(Users.Keys))
   if (Users.ContainsKey(id))
      if(Users[id] == null)
         Users.Remove(id);
 
}

Merry Christmas!

{
Hello everyone, it's been a while!
I really don't have any code to share this time, nor any cool investing stories to talk about.  Tis the most wonderful time of the year, and I've been spending this Christmas season with my special someone, Emily, and hanging out with my family.  It's been a good time to just catch up and relax from the year's work.  Although last night I went to a local .NET Developer's meeting and learned some more on the XNA Frameork.  I must say, the XNA Framework is one of the most exciting packages I have seen Microsoft release (to me.)  Of course, I haven't been around very long ;)  Anyways, I've been building some samples on the XNA Framework, and I love developing on it.  I will post some code when I get a better understanding of the framework.
I just wanted to with you all a very merry Christmas, and a happy new year!
}

Bootstraps Boots

Learn something new everday, right?  Well maybe not everyday, but today I did!
I learned about Bootstrapper, a technology that comes wrapped in Visual Studio.  What is it, you ask?
 
A recent project I just wrapped up is a Tutorial Making software.  Very basic of course, but functional.  In fact, all it does is records whatever you're doing.  I threw this together after realizing we were going to need some good Word, Excel, Powerpoint, etc tutorials on our newly deployed intranet (DNN).
Anyways, the Tutorial Maker makes use of the Windows Media 9 Encoder.  I chose to use ClickOnce for its simplicity, rather than creating a custom setup project.  When deploying with ClickOnce, you can select from a list of prerequisites, such as .NET 2.0, SQL Express, etc.  Unfortunately, Windows Media Encoder 9 was not in the list.
 
Here is a quick walk-through on how to add Windows Media Encoder 9 (or some other MSI installer) to the list of available prerequisites that are required with your ClickOnce application.
 
  1. Navigate to: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\
  2. Create a new folder, name it "WindowsMediaEncoder9"
  3. Within the newly created folder, create a new file "product.xml"
  4. Add the Windows Media Encoder 9 MSI file to the folder (WMEncoder.msi)
  5. Create a new folder, name it "en" (for English)
  6. Within the newly created folder, create two new files:
    • eula.txt
    • package.xml

Ok!  Here are the contents of the two XML files.  I just copied the Windows Media Encoder eula to eula.txt.

product.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Product
  xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper"
  ProductCode="Widows.Media.Encoder.9">

  <RelatedProducts>
    <DependsOnProduct Code="Microsoft.Windows.Installer.3.1" />
  </RelatedProducts>

  <PackageFiles>
    <PackageFile Name="WMEncoder.msi"/>
  </PackageFiles>

  <InstallChecks>
    <RegistryCheck Property="WMEInstalled"
       Key="HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Media\MsiInstall" Value="WMEncoder" />
  </InstallChecks>

  <Commands>
    <Command PackageFile="WMEncoder.msi" Arguments="">

      <InstallConditions>
        <BypassIf Property="WMEInstalled" Compare="ValueEqualTo" Value="Yes"/>
 <FailIf Property="AdminUser" Compare="ValueNotEqualTo" Value="True"
         String="NotAnAdmin"/>
      </InstallConditions>

      <ExitCodes>
        <ExitCode Value="0" Result="Success"/>
        <ExitCode Value="1641" Result="SuccessReboot"/>
        <ExitCode Value="3010" Result="SuccessReboot"/>
        <DefaultExitCode Result="Fail" String="GeneralFailure"/>
      </ExitCodes>
    </Command>
  </Commands>
</Product>

package.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Package
  xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper"
  Name="DisplayName"
  Culture="Culture"
  LicenseAgreement="eula.txt">

  <PackageFiles>
    <PackageFile Name="eula.txt"/>
  </PackageFiles>

  <Strings>
    <String Name="DisplayName">Windows Media Encoder 9</String>
    <String Name="Culture">en</String>
    <String Name="NotAnAdmin">You must be an administrator to install this package.</String>
    <String Name="GeneralFailure">A general error has occurred while
installing this package.</String>
  </Strings>
</Package>

Hello, MAC

I am back!  It's been a while since I've blogged.  I kept saving these drafts but never actually sat down to write about them.
Sorry they all seem to be code related.  That's not really what all this blog is about!  Pretty soon I'll start throwing up pictures and stuff.
But not in this post. 
By the way... Keefe Bruyette & Woods IPO [finally] went public last week.  And boy is it about time!  That'll be an interesting thing to watch.
Again, that's for another post though.  This post is about (believe it or not) more coding!  In one of my [other] recent projects, I needed a good method of tracking individual users.  IP address isn't a good solution, since user's IP address changes. 
 
My project involved creating a web application that would reside on the DHCP server of a LAN, that could either be accessed wirelessly or from our internal network.  I needed a good way to track individual users.   So I decided to go the MAC address route.
I googled around for a while and basically found two ways: from the web application start a new Windows process to query DHCP, or copy the log file and read from the copy every time.  I find both solutions unacceptable.  Starting a new process for every time a user hits the site would severely impact the performance, as would trying to copy the log file and read from it everytime.
 
I tried to read from the log file directly, like so:
StreamReader read = new StreamReader("C:\\WINDOWS\system32\\dhcp\\DhcpSrvLog-Mon.log");
But as the user of the second solution clearly pointed out, you cannot read directly from it because you will get a 'File In Use' exception.
 
Now that stumped me for a while, because I couldn't find anything else on the web.
But then I browsed to the file itself, and opened it up in notepad (as I've done before) and that's when I realized, that there most certainly is a way to read directly from it - otherwise Notepad couldn't open it.
 
After another five minutes of research, I quickly found my solution.
The problem is, when you use "new StreamReader(string)" the StreamReader class attempts to open the file exclusively, but will fail miserably due to DHCP writing to it.
We need to open it so that other files can also open and write to it.  Here's how: the File.Open method provides 3 overloads, one of which allows you to specify whether or not to 'share' the file with other programs.  Here it is:
 
File.Open("C:\\WINDOWS\\system32\\dhcp\\DhcpSrvLog-" + DateTime.Now.DayOfWeek.ToString().Substring(0, 3) + ".log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
 
There is your solution.
First argument is the file to read (which in the above example, is today's log), the second argument tells it to only open the file (don't try to create it if it doesn't exist), third argument says we only want Read access and no more, which is very important; fourth argument - which is the silver doughnut - tells it to share the file with other applications. 
    public string GetMACAddress(string ip)
    {
        string mac = null;
        string line;

        if (File.Exists("C:\\WINDOWS\\system32\\dhcp\\DhcpSrvLog-" + 
DateTime.Now.DayOfWeek.ToString().Substring(0, 3) + ".log")) using (StreamReader read = new StreamReader( File.Open("C:\\WINDOWS\\system32\\dhcp\\DhcpSrvLog-" +
DateTime.Now.DayOfWeek.ToString().Substring(0, 3) + ".log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { while (!read.EndOfStream) { line = read.ReadLine(); if (line.Contains(ip) && line.Length > 12) { mac = line.Substring(line.Length - 13, 12); if (Regex.IsMatch(mac, @"^([A-Z]|\d){12}$")) break; } } read.Close(); } return mac; }
 
Public folders