Archive for the ‘programming’ category

How to use the My Namespace in C#

February 22nd, 2011

When I was first trying to transition from VB.NET to C# I found it pretty odd that the “My” Namespace wasn’t available in C#.  If you aren’t aware of what I’m talking about, the Microsoft.VisualBasic.MyServices namespace (My in Visual Basic) provides easy and intuitive access to a number of .NET Framework classes, enabling you to write code that interacts with the computer, application, settings, resources, and so on.

After a little hunting I discovered that by simply adding a reference and a using statement that I could be up and running with my beloved My classes that I had come to know and love.  Here’s how you do it…

Add a Reference

  1. In Solution Explorer, right-click the References node, and select Add Reference.
  2. When the References dialog box appears, scroll down the list, and select Microsoft.VisualBasic.dll.You might also want to include the following line in the using section at the start of your program.
    using Microsoft.VisualBasic.Devices;

Example

This example calls various static methods contained in the MyServices namespace. For this code to compile remember that we added a reference to Microsoft.VisualBasic.DLL in the step above.

using System;
using Microsoft.VisualBasic.Devices;
 
class TestMyServices
{
    static void Main()
    {
        // Play a sound with the Audio class:
        Audio myAudio = new Audio();
        Console.WriteLine("Playing sound...");
        myAudio.Play(@"c:\WINDOWS\Media\chimes.wav");
 
        // Display time information with the Clock class:
        Clock myClock = new Clock();
        Console.Write("Current day of the week: ");
        Console.WriteLine(myClock.LocalTime.DayOfWeek);
        Console.Write("Current date and time: ");
        Console.WriteLine(myClock.LocalTime);
 
        // Display machine information with the Computer class:
        Computer myComputer = new Computer();
        Console.WriteLine("Computer name: " + myComputer.Name);
 
        if (myComputer.Network.IsAvailable)
        {
            Console.WriteLine("Computer is connected to network.");
        }
        else
        {
            Console.WriteLine("Computer is not connected to network.");
        }
    }
}

Not all the classes in the MyServices namespace can be called from a C# application. You can visit this MSDN article that details more on what’s not supported.

Use ASP.NET and DotNetZip to Create and Extract ZIP Files

February 16th, 2011

I recently came across this article from Scott Mitchell, that shows how to use DotNetZip to create and extract ZIP files in an ASP.NET application, and covers advanced features like password protection and encryption.

The article details all that you can do with the feature-rich, free, open source ZIP implementation for .NET - DotNetZip. Using DotNetZip and a dash of .NET code you can:

  • Create a new ZIP file and add one or more files or folders,
  • Read the contents of a ZIP file,
  • Extract all (or some) of the contents of a ZIP file to a specified folder,
  • Use advanced ZIP file format features, such as encrypting the contents of the ZIP and protecting them with a password.

This is definitely something that will come in handy.  I’ve tried working with zip files in the past and it has never been this easy.  Dealing with a ZIP file is definitely something that you will need to do at some point if you program long enough.  With this article, it will definitely be something that you won’t bang your head against the wall trying to accomplish!

Easily Disable JavaScript Debugging in Visual Studio 2008

December 15th, 2010

Visual Studio 2008 is not without its faults.  They did however add some nice features in the 2008 release such as JavaScript debugging.  This feature is great when you need it, but can drastically slow down your debugging experience if you don’t need it or use quite a few “script heavy” controls like Telerik Radcontrols.

So after dealing with this for a while and taking enough productivity hits I decided to find a way to disable the Script Documents folder that shows up when running in debug mode.

It didn’t take long to stumble across this blog post where the blogger made a VisualStudio add-in to make turning this on and off as needed easy via a toolbar button.  After reading the post and downloading the utility I was debugging without the old lag that I had before caused by all of the JavaScript documents that were loaded.

If you’ve run into this and feel this would be helpful, I can say that it seems to be working fine for me.  I was a little worried too considering I run Windows 7 but it seems to still work well without any permissions issues.

CMAP Main Meeting – Tuesday, December 7th – IIS Express, Razor, and WebMatrix, OH my!

December 7th, 2010
CMAP Main Meeting – Tuesday, December 7th – IIS Express, Razor, and WebMatrix, OH my! – G. Andrew Duthie

When: Tuesday, November 7th, 6:30 PM – 9:00 PM

Where: HCC Business Training Center, 6751 Columbia Gateway Drive, MD, 21046

Topic: IIS Express, Razor, and WebMatrix, OH my!

Does the announcement of so many new technologies make you wonder where the yellow brick road is that will lead you to the Oz of understanding? Well, there’s no denying that there’s a lot to keep up with these days if you’re a web developer. So let Microsoft Developer Evangelist G. Andrew Duthie give you an overview of Microsoft WebMatrix, ASP.NET Web Pages, the new Razor syntax, and IIS Express, and how they fit in with the existing offerings in Microsoft’s web stack.

Learn how and when you’d want to leverage these new technologies, and when existing technologies may be a better choice. Expect discussion and demo, and bring your questions, so we can make this an interactive and dynamic session!

Presenter: G. Andrew Duthie

G. Andrew Duthie, aka .net DEvHammer, is the Developer Evangelist for Microsoft’s Mid-Atlantic States district, where he provides support and education for developers working with the .net development platform. In addition to his work with Microsoft, Andrew is the author of several books on ASP.NET and web development, and has spoken at numerous industry conferences from VSLive! and ASP.NET Connections, to Microsoft’s Professional Developer Conference (PDC) and Tech-Ed. Andrew is also the creator and developer of Community Megaphone, a site designed for promoting and finding developer community events. Andrew can be reached through his blog at http://blogs.msdn.com/gduthie or on Twitter at @devhammer.

For more information about the meeting, please visit the CMAP website.

Forcing a user to read (or scroll through) all text before accepting terms

December 10th, 2009

If you’ve used a computer before you’ve undoubtedly scrolled through and agreed to some sort of agreement.  Most likely it was some sort of software license agreement that you didn’t read about some website you were signing up on or an application that you were installing.

Maybe, if you’ve installed enough software or been on enough websites you’ve come across an instance where they actually forced you to scroll all the way down to the bottom of the text before you were able to click “I Agree” or whatever acknowledgment they wanted you to use.

Well I was recently faced with creating this exact situation in a web application and ended up using jQuery to accomplish this in my ASP.NET application.  For my particular situation I ended up putting my content inside a scrollable div.  This can easily be done by using a textbox if you wanted without much effort.

Basically, here’s what you’ll need.

  1. Reference jQuery (I’m not going to go into that, you can easily find that out here)
  2. Put a DIV on your page containing your text that needs to scroll (obviously you’re putting more than a few sentences or you wouldn’t be in this boat)
  3. Put a button on your page that, once enabled, will log the user’s acceptance and redirect them accordingly
  4. Some simple JavaScript to tie the DIV’s scrolling event to your button

Here’s our DIV:

<div style="width: 400px; height: 400px; overflow: auto; id="Terms">
<p>Lots of text to read.</p>
<p>Lots more text to read</p>
</div>

Here’s our button:

<asp:Button ID="ContinueButton" runat="server" Text="Continue" />

Here’s our JavaScript:

<head runat="server">
<script type="text/javascript" src="js/jquery-1.3.1.min.js"></script>
<script type="text/javascript">
     $(document).ready(function() {
 
          // Initially disable the button
          $("#ContinueButton").attr("disabled", "disabled");
 
          // Map the function below to the scroll event of our Terms DIV
          $("#Terms").scroll(function() {
               if ($("#Terms").AtEnd()) {
                    // Enable the button once we reach the end of the DIV
                    $("#ContinueButton").removeAttr("disabled");
               }
           });
     });
 
     $.fn.AtEnd = function() {
         return this[0].scrollTop + this.height() >= this[0].scrollHeight;
     } 
</script>
</head>

And that’s it. This code is light weight and works in IE, Firefox, Chrome and Safari. Have any feedback or suggestions on how to make it better? Let me know.

CMD HTTP Request – command line HTTP request utility

December 9th, 2009

More and more I find that I need to setup some kind of job or scheduled task to accomplish something in .NET on a reoccurring basis.  Typically in the past I’ve written Windows Services to accomplish this.  While effective, these definitely take longer to write and are harder to debug than say a simple ASP.NET page.  What I’ve done lately is started to move these non-critical, non-security sensitive processes into ASP.NET pages that can be called on a specific schedule via Windows Task Scheduler.

When I started moving this way I realized that I wanted to find a small utility that I could run from a command line to initial a web page request.  It had to be something I could run from a scheduled task and something that I could use to save or log the results.  After doing my due diligence Googling I realized there wasn’t such a utility that I could easily run from within Windows without installing all kinds of libraries and non-Windows based tools.  So, like any good programmer, I made my own.  Enter CMD HTTP Request.

As I said, this utility is small, light weight and runs on Windows via the .NET Framework.  You don’t need any special commercial programs to run it and it will even check your pages for keywords you specify and save the request’s results to disk as a HTML file.  This, essentially, is your log of what happened during that request on that date and time.

I won’t go into too much more detail here.  I think you get the main idea.  You can  download the source code or executable from the project page on Codeplex and learn more about it.  As always, feel free to leave me any feedback or suggestions either here or via the project page on Codeplex.

CMD Email v2.0 released

November 14th, 2009

CMD Email, the email command line utility I developed (originally discussed here) has been updated to version 2.0.

Here are new features for v2.0:

  • Updated to target .NET 3.5 Framework
  • Added support for message body being loaded from a file
  • Added support for multiple file attachments
  • Added support for logging to the Windows Application Event Log

You can download the latest runtime or source from the project page on CodePlex.

Dynamically re-size an iFrame’s height across browsers

July 8th, 2009

A while back I had a need to dynamically re-size an iFrame’s height and found a solution using a jQuery plug-in called autoHeight.  What I later found was that this solution provided poor results with Internet explorer when my iFrame’s contents were fairly large and frequently changing (i.e. via navigation inside the iFrame).

It took quite a bit of tinkering but I was able to come up with a solution that works (and works well) in IE, Firefox, Safari and Chrome.  It still uses jQuery but doesn’t depend on a plug-in.  Here’s the code in case you’re looking for the same thing:

First, the iFrame…

<iframe src="Page1.htm" id="MyFrame" 
frameborder="0" marginheight="0" marginwidth="0" 
width="800px" height="100px" scrolling="no"></iframe>

Next, the JavaScript to resize it…

<script type="text/javascript">
 
     function sizeFrame() {
          jQuery("#MyFrame", top.document).css({ height: 0 });
          var heightDiv = jQuery("#MyFrame", top.document).contents().find('body').attr('scrollHeight');
          jQuery("#MyFrame", top.document).css({ height: heightDiv });
     }
 
     jQuery(function() {
          sizeFrame();
          jQuery("#MyFrame").load(sizeFrame);            
     });
 
</script>

This line is needed to initially initialize the height so that it works in Safari and Chrome. Without this line the window will never shrink to fit smaller content, it will just retain the last biggest height.

jQuery("#MyFrame", top.document).css({ height: 0 });

Visual Studio 2008 is a piece of shit!

July 3rd, 2009

It’s been one of those weeks :(

visual-studio-wait

It should be noted that I was able to take a screen shot, upload it to WordPress and make this blog post before that message went away and I was able to interact with Visual Studio.NET again!

July 2009 Baltimore SQL Server Users Group Meeting

July 2nd, 2009

Passing along the Baltimore SQL Server Users Group July 2009 Meeting Announcement.  I’m considering attending since we use Reporting Services and SQL Server 2008 here at work.  Here’s the information in case you may be interested in attending.  Don’t forget to RSVP via email as noted below.

General Meeting Information

Presentation Information

  • Title: SQL Server Reporting Services Report Builder 2.0
  • Speaker: Craig Guyer of Microsoft
  • Abstract: Authoring reports for SQL Server Reporting Services is even easier than before using the new stand-alone application Report Builder 2.0 (RB2). In this session we will walk through creating some basic reports, show how RB2 fits in with other report authoring applications, and discuss other new report authoring features in SQL Server 2008.