Community Coding Contest 2010 - Looking for Input and Prizes

4. January 2010

Now that it's 2010, and over a year since the first Community Coding Contest came to an end, I'm thinking about running the contest again in 2010.

Last time it ran for 3 months and we had 6 really great entries. This time around I'm thinking that it may be better to accept entries for 6 months, and have the voting run for a full month. This will give much more time for entries to be submitted, and for people to work on their entries before submitting and/or voting begins.

These are just some initial thoughts, and I'm going to need input on everything from YOU (the community) before I can make a final decision as to when and how to run the contest again. I'd really appreciate if you could fill out the following survey and tell us what you think.

Community Coding Contest 2010 Pre-Contest Survey

Also, we will need some prizes donated before the contest will be able to go on. If you or your company are interested in donating prizes or monetary support (web hosting fees, mailing expenses, etc.) for the contest, please contact the contest directly here: http://communitycodingcontest.org/contact.aspx

You can view the official contest website here: http://communitycodingcontest.org

Thanks, and I look forward to hearing more about what everyone thinks!

asp.net, ASP.NET MVC, Bing Maps, C#, General, Silverlight, vb.net , , , ,

.NET Framework: Communicate through NAT Router via UPnP (Universal Plug and Play)

5. February 2009

I've been working on an application recently that needs to be able to communicate through a router/firewall using TCP. I've read/heard a bit of information about NAT Routers and UPnP; the technoligies used in almost every router sold commercially. So, I knew that you could use the Universal Plug and Play (UPnP) features of the NAT Router to automatically open up the firewall via Port Forwarding to allow other computers on the Internet to connect directly to the one your application is running on. One thing I didn't know what that Windows (since Windows XP) has the NATUPnP 1.0 Type Library (NATUPNP.DLL) COM Component that you can utilize within your applications to do this for you.

I haven't found very many articles online (via Google search) on using the NATUPnP 1.0 Type Library; there's pretty much only small code snippets available. So, I've decided to explain a little further, in this article, the What and Why of communicating through a NAT Router utilizing UPnP.

What is NAT (Network Address Translation)?

Network Address Translation is the method employed by a Network Router (and Wireless Routers) that allows you to have multiple computers connected to the internet using your home/work broadband internet connection. Your Router gets assigned an Internet IP Address by your Internet Service Provider, and then the Router assigns a Private IP Address to each computer on your network. The Router then "routes" Incoming and Outgoing network traffic from the Internet to the appropriate computer on your Private Network. This technique is also known as "IP masquerading", since it hides your entire Private Network from the Internet making it appear as if it were only a single computer connected to the Internet.

One of the biggest side effets of NAT is that it essentially turns your Router into a Firewall. This is because when any unsolicited incoming traffic gets sent you the Router, it has no idea which computer on the Private Network might be the intended recipient. So, consiquentially, it just ignores or blocks the unsolicited incoming traffic. This is also the feature that allows you to safely enable File and Printer Sharing between the computers on the Private Network without the risk of any computer/server on the Internet being able to copy your files.

Also worth noting that NAT can be implemented by other devices than a Network Router, such as: a computer running Windows with Internet Connection Sharing and Windows Firewall, or a computer running software that provides NAT.

You can read more about NAT at the following links:

http://en.wikipedia.org/wiki/Network_address_translation

http://en.wikipedia.org/wiki/NAT_traversal

What is Port Forwarding / Static NAT?

Port Forwarding, also called "Static NAT", allows computers on the Internet to connect directly to a specific computer on your Private Network. This works by configuring your NAT Router to forward any incoming traffic on a specific Port to a specific computer on your network. For example you can run a Web Server by setting the NAT Router to forward all incoming traffic on Port 80 to your Web Server on your Private Network.

You can read more aboug Port Forwarding at the following link:

http://en.wikipedia.org/wiki/Port_forwarding

What is Universal Plug and Play (UPnP)?

Universal Plug and Play (UPnP) is a simple communications mechanism that allows computers and network appliances to auto-configure Port Forwarding on a NAT Router. This greatly simplifies the setup of P2P networks such that the user doesn't need to configure the NAT Router, instead the computer can connect directly to the Router and setup the appropriate Port Forwarding to allow it to accept direct connections from external computers on the Internet.

This is essentially the technology that allows Peer-to-Peer Software (like Bit Torrent) to communicate through a NAT Router (Firewall) and connect directly to other computers across the Internet. There is also alot of Software and Devices that rely on this to function, such as Windows Live Messenger and XBox 360.

You can read more about UPnP at the following link:

http://en.wikipedia.org/wiki/Universal_Plug_and_Play

Other Resources on Network Address Translation (NAT)

Including the above links there are many articles online that discuss in further detail what NAT and UPnP is. One resource that I really recommend is Episode #42 of the Security Now Podcast with Steve Gibson. If you prefer not to listen to the podcast, there is also a full transcript available for you to read. I really encourage you to read or listen to this.

Security Now! #42 - NAT Traversal

Using the NATUPnP 1.0 Type Library to Setup Port Forwarding

The NATUPnP 1.0 Type Library (NATUPNP.DLL) COM Component, which is part of Windows (since Windows XP), makes it possible to easily manage Network Address Translation (NAT) through Universal Plug and Play (UPnP). This library provides the ability to configure port mappings on a remote Gateway Device (IGD) that uses NAT. It is worth mentioning that the remote Gateway Device could be another computer running Windows with Internet Connection Sharing and Windows Firewall, or a dedicated hardware device.

The API Reference for the NATUPnP 1.0 Type Library can be found here: http://msdn.microsoft.com/en-us/library/aa366276(VS.85).aspx

In order to use the NATUPnP Library you need to first add a reference to it to your project within Visual Studio. To do so open the Add Reference dialog, click the COM tab and select the "NATUPnP 1.0 Type Library". The resulting reference that's added will be named "NATUPNPLib" and will be the namespace that contains all the functionality contained within the library (all Interfaces and Classes).



The NATUPnP 1.0 Type Library makes it so easy to setup Port Forwarding it literally only requires a couple lines of code.

Get a listing of all existing Static Port Mappings

To get a list of all the Static Port Mappings that are already setup in your NAT enabled Internet Gateway Device (such as Router) you simply create an instance of the UPnPNATClass object and access its StaticPortMappingCollection property.

NATUPNPLib.UPnPNATClass upnpnat = new NATUPNPLib.UPnPNATClass();
NATUPNPLib.IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection;

Once you get the collection of existing port mapping, you can iterate through them just as you would any normal Collection of objects:

foreach(NATUPNPLib.IStaticPortMapping portMapping in mappings)
{
    // do something with the port mapping, such as displaying it in a listbox
}

Add New Static Port Mapping

To add a new Static Port Mapping you simply call the Add method of the IStaticPortMappingCollection object that is returned by the UPnPNATClass.StaticPortMappingCollection property.

// Here's an example of opening up TCP Port 80 to forward to a specific Computer on the Private Network
mappings.Add(80, "TCP", 80, "192.168.1.100", true, "Local Web Server");

// Here's an example of forwarding the UDP traffic of Internet Port 80 to Port 8080 on a Computer on the Private Network
mappings.Add(80, "UDP", 8080, "192.168.1.100", true, "Local Web Server");

Remove Existing Static Port Mapping

To remove an existing Static Port Mapping you simply call the Remove method of the IStaticPortMappingCollection object that is returned by the UPnPNATClass.StaticPortMappingCollection property.

// Remove TCP forwarding for Port 80
mappings.Remove(80, "TCP");

// Remove UDP forwarding for Port 8080
mappings.Remove(8080, "UDP");

Example Port Forwarding Management Application

While working with the NATUPnP 1.0 Type Library I created a simple application that allows you to maintain the Static Port Mappings that are setup on your Private Networks NAT Router.

Download Sample: NATUPnPPortForwardManager.zip (20.68 kb)


Conclusion

Setup up Port Forwarding on your local router via UPnP makes it extremely convenient for users of your networking application. Instead of requiring them to manually setup Port Forwarding, we can automatically set it up for them. Many popular P2P applications have utilized this functionality for years, and I'm positive you've used at least one of these applications already at some point.

C#, vb.net, Win32API , , ,

Simple Port Scanner Written in VB.NET 2003/2008

20. January 2009

I was looking over some of the old prototypes I've written in the past, and I can across a Simple Port Scanner that I originally wrote in VB.NET 2003. I originally wrote this back in 2004 (I think), and even posted a compiled version on my website that I have since removed/deleted. So, since it's just sitting on my hard drive collecting virtual dust, I thought I'd post it here in case anyone else can find it usefull.

This Port Scanner implements Multi-Threading via the ThreadPool class in the .NET Framework, so at the very least it can be used as an example of how to use the ThreadPool class to queue up "work units" to be executed asynchronously.

Also, as you see in the screenshot below, there is a "Service" column shown in the Grid. This column tells you what Protocol/Service is normally run on that specific port. It doesn't check for that Protocol/Service on that port, but it helps as a quick reference as to what Protocol/Service may be running there. It's nice sometimes to not be required to memorize all the possible Protocols/Services that run on some of the most common ports used. This list of Port Numbers and Services is stored in th eApp.Config file.

Here's a couple download links for the source code in VB.NET 2003 and VB.NET 2008 Solution/Project files:

VB.NET 2003 - Simple Port Scanner Source Code (15kb)

VB.NET 2008 - Simple Port Scanner Source Code (16kb)

General, vb.net , ,

A Couple VB.NET Language Tips for C# Developers

31. October 2008

Originally, I started out as a Visual Basic developer, and have since moved mostly to C#. However, when doing consulting work, I do need to cross back and forth quite often. Here are a couple VB.NET tips that you probably aren't aware of if you're mostly a C# developer. Some VB.NET developers may not even know about then either.

Null Coalesce

Null Coalescing is really simple in C#:

// If "someValue" is Null then set "i" to 0 (zero)
// otherwise set it to the value of "someValue"
int? i = someValue ?? 0;

But what about VB.NET?

<code:VB>

Dim i = If(someValue, 0)

</code>

Granted the VB.NET Null Coalesce is a method call, but at least there's still an equivalent available in the language. Also, I believe this is something that was introduced in VB.NET 9.0.

Ternary Conditional Operator

This is the ability have a complete If..Else..Then statement on a single line and have it return a value. This is really simple in C#:

// This performs the same logical operation as the Null Coalesce example above
int? i = (someValue == null ? 0 : someValue);

How about in VB.NET?

<code:VB>

Dim i = If(someValue = Nothing, 0, someValue)

'' The above can be simplified, since if the first parameter is equal to "Nothing"
'' then the "true" (second) parameter is return, otherwise the
'' "false" (third) parameter is returned.
Dim i = If(someValue, 0, someValue)

'' Also to further simplify, you can just pass in the "false" (second) parameter
'' and if its equal to "Nothing" then the "false" (second) parameter is returns,
'' otherwise the value itself is returned.
Dim i = If(someValue, 0) 

</code>

Lock Statement

You may be familiar with the lock statement in C#, especially if you're used to worrying about concurrency.

lock (expression)
{

    ...Some Code...

}

At first it appears to not exist in VB.NET, but they just named it SyncLock instead:

<code:VB>

SyncLock (expression)

    ...Some Code...

End SyncLock

</code>

 

Please, excuse the bad syntax highlighting for the VB.NET code, it seems that my instance of BlogEngine.NET doesn't like to highlight too many blocks of code within the same post.

General, vb.net, C# , ,

C#/VB.NET: Extension Methods

13. March 2007

Over a year ago I posted a question about doing a SQL-like IN operation in .NET. Here's the examples I posted of how it could work:

Dim arrNames() AS String = New Array{"CHRIS", "TOM", "TYLER"}
If strName IN arrNames Then
   'do something
End If

Now, this would be a powerful feature since you wouldn't be required to write code that loops through the array or collection. Well, I saw some good news today posted by Scott Guthrie.

Scott posted about a new feature in .NET "Orcas" (I believe it's going to be v3.5 but I'm note sure.), it's called Extension Methods.

Extension Methods allow you (the developer) to add new functionality to existing .NET object type. And, you can do it without inheritance or recomiling the original type. This means you can add your own custom fuctionality to any third party object or framework object you want. This sounds really neat!

I saw this, and I thought to myself, Sweet you will now be able to do something similar to a SQL IN operation just as easily as it's done in SQL. In fact, Scott even posted an example of how to do it. (however, he didn't compare it to SQL IN like I am.)

The code for the IN method goes like this:

namespace SqlInMethodExtension
{
    public static class SqlInMethodExtension
    {
        public static bool IN(this object o, IEnumerable c)
        {
            foreach (object i in c)
            {
                 if (i.Equals(o)) return true;
            }
            return false;
        }
    }
}

Now using the method is as simple as this:

using SqlInMethodExtension;
public class Test
{
    void Test(string myValue)
    {
        string [] values = {"Chris","John","Sam"};
        if (myValue.IN(values))
        {
            // Do something here
        }
    }
}

Isn't that cool!?

You've probably read about the new LINQ features that are also coming in .NET "Orcas". According to ScottGu LINQ uses Extension Methods pretty heavily. So, if you ever wonder why this feature is being added, just think about the coolness of LINQ.

To read more about Extension Methods:
New "Orcas" Language Feature: Extension Methods

General, vb.net, C#

VB.NET: RegEx Syntax Highlighting RichTextBox

3. July 2006

RegEx Syntax HighlighterHere is a version of my code for syntax highlighting in a RichTextBox that incorporates regular expressions.

 

Download RegEx Syntax Highlighting RichTextBox Source Code

Source Code Listed:

Public Class SyntaxRTB

Inherits System.Windows.Forms.RichTextBox

Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, _

ByVal lParam As Integer) As Integer

Private Declare Function LockWindowUpdate Lib "user32" _

(ByVal hWnd As Integer) As Integer

Private _SyntaxHighlight_CaseSensitive As Boolean = False

Friend Words As New DataTable

'Contains Windows Messages for the SendMessage API call

Private Enum EditMessages

LineIndex = 187

LineFromChar = 201

GetFirstVisibleLine = 206

CharFromPos = 215

PosFromChar = 1062

End Enum

Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)MyBase.OnTextChanged(e)

ColorVisibleLines()

End Sub

Public Sub New()

Me.AcceptsTab = True

AddSQLSyntax()

End Sub

Function AddSQLSyntax()

ClearSyntaxWords()

AddSyntaxWord(
"\b(select|text|ntext|date|datetime|order by|" & _

"group by|smalldatetime|cursor|on|as|for|filename|" & _

"database|drop|function|delete|insert|update|int|" & _

"varchar|nvarchar|bit|binary|table|inner|where|from|" & _

"out|procedure|view|trigger|set)\b", Color.Blue)

AddSyntaxWord("\b@@identity\b", Color.Pink)AddSyntaxWord(

"\b(in|join|outer|and|or)\b", Color.Gray) AddSyntaxWord("\bsp_refreshview\b", Color.Red)

Return True

End Function

Public Function ClearSyntaxWords() Words = New DataTable

''Load all the keywords and the colors to make them

Words.Columns.Add("Word")

Words.PrimaryKey = New DataColumn() {Words.Columns(0)}Words.Columns.Add(

"Color")

Return True

End Function

Public Function AddSyntaxWord(ByVal strWord As String, ByVal clrColor As Color)Dim MyRow As DataRow

MyRow = Words.NewRow()

MyRow("Word") = strWordMyRow(

"Color") = clrColor.Name

Words.Rows.Add(MyRow)

Return True

End Function

Public Sub ColorRtb()

Dim FirstVisibleChar As Integer

Dim i As Integer = 0While i < Me.Lines.Length

FirstVisibleChar = GetCharFromLineIndex(i)

ColorLineNumber(i, FirstVisibleChar)

i += 1

End While

End Sub

Public Sub ColorVisibleLines()

Dim FirstLine As Integer = FirstVisibleLine()

Dim LastLine As Integer = LastVisibleLine()

Dim FirstVisibleChar As Integer

If (FirstLine = 0) And (LastLine = 0) Then

'If there is no text it will error, so exit the sub

Exit Sub

Else

While FirstLine < LastLine

FirstVisibleChar = GetCharFromLineIndex(FirstLine)

ColorLineNumber(FirstLine, FirstVisibleChar)

FirstLine += 1

End While

End If

End Sub

Public Sub ColorLineNumber(ByVal LineIndex As Integer, ByVal lStart As Integer)

Dim i As Integer = 0

Dim SelectionAt As Integer = Me.SelectionStart Dim MyRow As DataRow

Dim MyI As Integer

' Lock the update

LockWindowUpdate(Me.Handle.ToInt32)

MyI = lStart

''Turn the whole link black before applying RegEx Syntax matching.

Me.SelectionStart = MyI

Me.SelectionLength = Lines(LineIndex).Length

Me.SelectionColor = Color.Black

''Check for matches in a particular line number

Dim rm As System.Text.RegularExpressions.MatchCollection

Dim m As System.Text.RegularExpressions.Match

For Each MyRow In Words.Rows

'"( |^)1.*2( |$)"

rm = System.Text.RegularExpressions.Regex.Matches(Me.Text, MyRow("Word"))

For Each m In rm

Me.SelectionStart = m.Index

Me.SelectionLength = m.Length

Me.SelectionColor = Color.FromName(MyRow("color"))

Next

Next

' Restore the selectionstart

Me.SelectionStart = SelectionAt

Me.SelectionLength = 0

Me.SelectionColor = Color.Black

' Unlock the update

LockWindowUpdate(0)

End Sub

Public Function GetCharFromLineIndex(ByVal LineIndex As Integer) As Integer

Return SendMessage(Me.Handle, EditMessages.LineIndex, LineIndex, 0)

End Function

Public Function FirstVisibleLine() As Integer

Return SendMessage(Me.Handle, EditMessages.GetFirstVisibleLine, 0, 0)

End Function

Public Function LastVisibleLine() As Integer

Dim LastLine As Integer = FirstVisibleLine() + (Me.Height / Me.Font.Height)

If LastLine > Me.Lines.Length Or LastLine = 0 Then

LastLine = Me.Lines.Length

End If

Return LastLine

End Function

Public Property CaseSensitive() As Boolean

Get

Return _SyntaxHighlight_CaseSensitive

End Get

Set(ByVal Value As Boolean)

_SyntaxHighlight_CaseSensitive = Value

End Set

End Property

End Class

General, vb.net

ASP.NET 2.0: Use VB.NET and C# within the App_Code folder

30. March 2006

When I was creating my new blog site (this site your looking at), I chose to write it in C#. I had a problem with the App_Code folder because I had some code in VB.NET code and some C# code I needed to put in there. I didn't want to rewrite my VB.NET code in the App_Code folder just so I could write the rest of the code for the site in C#.

Luckily, the ASP.NET Team had already thought about just this kind of circumstance. They implemented a way to partition the App_Code folder into sub-folders, one for each set of code files written in the same programming language. Awesome, I didn't have to spend a couple hours converting code from VB.NET to C#!

Even if you don't use multiple different programming languages for your code files in the App_Code folder, you could use this feature to organize your sets of related code files into sub-folders.

Step 1: Add the following lines to the web.config


<configuration>

    <system.web>

        <compilation>

            <codeSubDirectories>

                <add directoryName="VB_Code"/>

                <add directoryName="CS_Code"/>

            </codeSubDirectories>

        </compilation>

    </system.web>

</configuration>

Step 2: Create a sub-folder in the App_Code folder for each language you want to support.
For Example:
/App_Code/VB_Code
/App_Code/CS_Code

Step 3: Place your VB.NET code in the VB_Code folder and place C# code in the CS_Code folder.

General, vb.net, C#

VB.NET: Syntax Highlighting in a RichTextBox control

24. May 2005

This last weekend I expirimented a little bit with extending the functionality of the RichTextBox control. Below you'll find an example of a small class that enherits from the RichTextBox control and allows you to implement syntax highlighting (with the use of a couple Win32 API call to smooth over the process of course.) The code pretty much speaks for itself.

Public Class SyntaxRTB

   Inherits System.Windows.Forms.RichTextBox

   Private
Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
      
(ByVal hWnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer

   Private Declare Function LockWindowUpdate Lib "user32" (ByVal hWnd As Integer) As Integer

   Private _SyntaxHighlight_CaseSensitive As Boolean = False

   Private Words As New DataTable

   'Contains Windows Messages for the SendMessage API call
   Private Enum EditMessages
      LineIndex = 187
      LineFromChar = 201
      GetFirstVisibleLine = 206
      CharFromPos = 215
      PosFromChar = 1062
   End Enum

   Protected Overrides Sub OnTextChanged(ByVal e As System.EventArgs)
      
ColorVisibleLines()
   
End Sub

   Public Sub ColorRtb()
      
Dim FirstVisibleChar As Integer
      
Dim i As Integer = 0

      
While i < Me.Lines.Length
         FirstVisibleChar = GetCharFromLineIndex(i)
         ColorLineNumber(i, FirstVisibleChar)
         i += 1
      End While
   
End Sub

   Public Sub ColorVisibleLines()
      
Dim FirstLine As Integer = FirstVisibleLine()
      Dim LastLine As Integer = LastVisibleLine()
      Dim FirstVisibleChar As Integer

      
If (FirstLine = 0) And (LastLine = 0) Then
         
'If there is no text it will error, so exit the sub
         
Exit Sub
      
Else
         While FirstLine < LastLine
            FirstVisibleChar = GetCharFromLineIndex(FirstLine)
            ColorLineNumber(FirstLine, FirstVisibleChar)
            FirstLine += 1
         
End While
      
End If

   
End Sub

   Public Sub ColorLineNumber(ByVal LineIndex As Integer, ByVal lStart As Integer)
      
Dim i As Integer = 0
      
Dim Instance As Integer
      
Dim LeadingChar, TrailingChar As String
      
Dim SelectionAt As Integer = Me.SelectionStart
      
Dim MyRow As DataRow
      
Dim Line() As String, MyI As Integer, MyStr As String

      
' Lock the update
      
LockWindowUpdate(Me.Handle.ToInt32)

      MyI = lStart

      
If CaseSensitive Then
         
Line = Split(Me.Lines(LineIndex).ToString, " ")
      
Else
         
Line = Split(Me.Lines(LineIndex).ToLower, " ")
      
End If

      
For Each MyStr In Line
         
Me.SelectionStart = MyI
         Me.SelectionLength = MyStr.Length

         
If Words.Rows.Contains(MyStr) Then
            
MyRow = Words.Rows.Find(MyStr)
            
If (Not CaseSensitive) Or (CaseSensitive And MyRow("Word") = MyStr) Then
               
Me.SelectionColor = Color.FromName(MyRow("Color"))
            
End If
         Else
            
Me.SelectionColor = Color.Black
         
End If

         
MyI += MyStr.Length + 1
      Next

      ' Restore the selectionstart
      
Me.SelectionStart = SelectionAt
      
Me.SelectionLength = 0
      
Me.SelectionColor = Color.Black

      
' Unlock the update
      
LockWindowUpdate(0)
   
End Sub

   Public Function GetCharFromLineIndex(ByVal LineIndex As Integer) As Integer
      
Return SendMessage(Me.Handle, EditMessages.LineIndex, LineIndex, 0)
   
End Function

   Public Function FirstVisibleLine() As Integer
      
Return SendMessage(Me.Handle, EditMessages.GetFirstVisibleLine, 0, 0)
   
End Function

   Public Function LastVisibleLine() As Integer
      
Dim LastLine As Integer = FirstVisibleLine() + (Me.Height / Me.Font.Height)

      
If LastLine > Me.Lines.Length Or LastLine = 0 Then
         
LastLine = Me.Lines.Length
      End If

      
Return LastLine
   
End Function

   Public Sub New()
      
Dim MyRow As DataRow
      
Dim arrKeyWords() As String, strKW As String

      
Me.AcceptsTab = True

      
''Load all the keywords and the colors to make them 
      
Words.Columns.Add("Word")
      Words.PrimaryKey =
New DataColumn() {Words.Columns(0)}
      Words.Columns.Add("Color")

      arrKeyWords =
New String() {"select", "insert", "delete", _
         "truncate", "from", "where", "into", "inner", "update", _
         "outer", "on", "is", "declare", "set", "use", "values", "as", _
         "order", "by", "drop", "view", "go", "trigger", "cube", _
         "binary", "varbinary", "image", "char", "varchar", "text", _
         "datetime", "smalldatetime", "decimal", "numeric", "float", _
         "real", "bigint", "int", "smallint", "tinyint", "money", _
         "smallmoney", "bit", "cursor", "timestamp", "uniqueidentifier", _
         "sql_variant", "table", "nchar", "nvarchar", "ntext", "left", _
         "right", "like","and","all","in","null","join","not","or"}

      For Each strKW In arrKeyWords
         MyRow = Words.NewRow()
         MyRow("Word") = strKW
         MyRow("Color") = Color.LightCoral.Name
         Words.Rows.Add(MyRow)
      
Next

   
End Sub

   Public Property CaseSensitive() As Boolean
      
Get
         
Return _SyntaxHighlight_CaseSensitive
      
End Get
      
Set(ByVal Value As Boolean)
         _SyntaxHighlight_CaseSensitive = Value
      
End Set
   End Property

 

End Class   

 

Update July 8th, 2008: Here's a link that shows a couple tips that may help in writing your own Syntax Highlighting RichTextBox control:

http://codebetter.com/blogs/patricksmacchia/archive/2008/07/07/some-richtextbox-tricks.aspx

General, vb.net, Win32API

VB.NET: Make a Form semi-transparent when moving and resizing it

17. February 2005

Here's a little VB.NET code snippet that I wrote to make a Form semi-transparent when moving and resizing it. I think this is a neat little effect to add to an application.

 

Public Class frmTransparentMoveResize

Inherits System.Windows.Forms.Form

Private _OpacityResize As Double = 0.5 Private _OpacityMove As Double = 0.5

Private _OpacityOriginal As Double

Private Const WM_NCLBUTTONDOWN As Long = &HA1

Private Const WM_NCLBUTTONUP As Long = &HA0

Private Const WM_MOVING As Long = &H216

Private Const WM_SIZE As Long = &H5

Protected Overrides Sub DefWndProc(ByRef m As System.Windows.Forms.Message)

Static LButtonDown As Boolean

'Check the state of the Left Mouse Button

If CLng(m.Msg) = WM_NCLBUTTONDOWN Then

'set LButtonDown to True is Left Mouse Button is down

LButtonDown = True

ElseIf CLng(m.Msg) = WM_NCLBUTTONUP Then

'set LButtonDown to False is Left Mouse Button is not down

LButtonDown = False

End If

If LButtonDown Then

If CLng(m.Msg) = WM_MOVING Then

'Set the forms opacity to 50% if user is draging the window

If Me.Opacity <> _OpacityMove Then

_OpacityOriginal = Me.Opacity Me.Opacity = _OpacityMove

End If

ElseIf CLng(m.Msg) = WM_SIZE Then

'Set the forms opacity to 50% if user is resizing the window

If Me.Opacity <> _OpacityResize Then

_OpacityOriginal = Me.Opacity Me.Opacity = _OpacityResize

End If

End If

ElseIf Not LButtonDown Then

If Me.Opacity <> _OpacityOriginal Then Me.Opacity = _OpacityOriginal

End If

MyBase.DefWndProc(m)

End Sub

Public Property OpacityMove() As Double

Get

Return _OpacityMove

End Get

Set(ByVal Value As Double)

_OpacityMove = Value

End Set

End Property

Public Property OpacityResize() As Double

Get

Return _OpacityResize

End Get

Set(ByVal Value As Double)

_OpacityResize = Value

End Set

End Property

End Class

 

General, vb.net

Write to the Event Log in .NET (VB.NET and C#.NET)

24. August 2004

It is as simple as this to write to the Windows Event Log in .NET

Declaration:

Imports System.Diagnostics

Code:

Public Function WriteToEventLog(ByVal Entry As String, _
Optional ByVal AppName As String = "APlusFeeCalc", _
Optional ByVal EventType As EventLogEntryType = EventLogEntryType.Information, _
Optional ByVal LogName As String = "Application") As Boolean
     Dim objEventLog As New EventLog
     Try
          'Register the App as an Event Source
          If Not objEventLog.SourceExists(AppName) Then
               objEventLog.CreateEventSource(AppName, LogName)
          End If
          objEventLog.Source = AppName
          'WriteEntry is overloaded; this is one of 10 ways to call it
         objEventLog.WriteEntry(Entry, EventType)
          Return True
     Catch Ex As Exception
          Return False
     End Try
End Function

C#, General, vb.net