.net.devcity.weekly ---
If you are unable to see the message, visit http://www.devcity.net/newsletter/archive/devcity/devcity20050715.htm

Advertisement

AdvertisementAdvertisement

The newsletter is compiled by DevCity.NET NewsMasters Ged Mead and Mike McIntyre

Advertisement

Table Of Content:

Advertisement
Diary of a .NET Newbie: Don't Quote Me

by Ged Mead

Some time ago, I created a small demo using XML as the data source of a very simple address book. As is the way of these things, I didn't have the sense to stop at the point where the list of names, addresses, phone numbers, etc, were all displayed correctly. Of course not, that would have been far too sensible. No, I had to add just one more tweak. And just one more. And...

This was fine until I came to the point where I wanted to display only those names which began with a particular letter of the alphabet. The user could click on a listbox containing all 26 letters (or an asterisk) and the Like operator was employed to refine the Filter for a DataView. I like DataViews generally but I did get quite frustrated with the arcane syntax that was required to get just the right permutation of single and double quotation marks to make it all work.

Maybe it's just me. Perhaps I'm dysquotesic (well, hey, we've already got dyslexic and dyscalculic - so why not ?) . After what seemed like an extremely long time spent cutting and pasting those single and double quotation marks around the strings , my mind just seemed to go a total blank.

This particular project had a DataView named dvAddresses, associated with a DataSet that had LastName as one of its fields.
It also had, as I mentioned, a ListView which listed the letters of the alphabet for the user to select from. The code which applied the selected letter as the filter looked like this:

dvAddresses.RowFilter = "LastName Like '" & CStr(lstLetters.SelectedItem) & "%'"

In case you are having difficulty in sorting out the singles from the doubles as they appear in your browser, this is:-
doublequote LastName Like singlequote doublequote & CStr(lstLetters.SelectedItem) & doublequote % singlequote doublequote.

The core concept in this spaghetti is that the Like operator needs to be passed its information inside single quotes; the RowFilter property of the DataView needs to be passed its information inside double quotes.

The splitting of the code line using ampersands to allow the insertion of the CStr method in the middle unfortunately serves to make things even harder to unscramble. Essentially though, the breakdown is this:
doublequote1_Starts LastName Like singlequote doublequote2_Ends & CStr(lstLetters.SelectedItem) & doublequote2_Starts % singlequote doublequote2_Ends.

So the Like Operator is being passed the first letter of the search string plus the wildcard percentage sign. The RowFilter string is split into two parts to allow the insertion of the CStr code.

Round about this point in the proceedings, it did occur to me (belatedly as usual) that maybe another (easier?) way would be to employ the StartsWith property of a string as the search string. However, I was way too far down the red misty road to give up at this stage and anyway I had plans for a more sophisticated search later - one where the search string would not be limited to a single letter of the alphabet.

Speaking of which, here it is:

dvAddresses.RowFilter = ColToCheck & " Like '%" & Trim(txtSearchPhrase.Text) & "%'"

In this variation, the user is able to select a column from the DataGrid (OK, a field from the DataSet in reality, but the choices they are given relate visually to the DataGrid they can see). They can then enter any string or partial string they want and the search will look for any occurrences of that string in the chosen column.

The variable ColToCheck therefore is obviously the result of the user's choice and is a string representation of the column name in the DataView. txtSearchPhrase is a textbox into which the user enters their chosen string or substring to search for.

So the breakdown of the code that applies the search criteria to the DataView's RowFilter is something like:
"look for any entry in the chosen column which is Like (any text) followed by (the user's input search phrase) followed by (any text)"

The use of the ColToCheck variable at the start of the RowFilter description means that the first double quote gets shunted to the right. Apart from that minor tweak, the logic is the same as in the earlier example - all the RowFilter description is held inside two sets of double quotes. And the Like operator's information (wildcard plus user's phrase plus second wildcard) is tucked away neatly inside the required pair of single quotes.

Once I'd really got my head round the need to contain the various parts inside the correct type of quotation marks it all pretty much fell into place and made sense. (Easy to say that now ! The learning curve at the time seemed to be of Everest proportions.)

Anyway, if you ever need to concoct a search code routine along these general lines, I hope that the above might be of some small help. If or when you reach the stage where you never, ever want to see a damn quotation mark of any variety ever again then maybe you'll remember this small article.

I'm now feeling quite smug that I finally nailed it. Being right-handed, I may not be ambidextrous, but I'm pretty sure I'd be ambiquotestrous ... if there was such a thing.

- Junior (Ged Mead aka XTab, xtab@vbcity.com)

by Mike McIntyre

This is the fifth installment of an article which discusses evolving to VB.NET from a previous version of Visual Basic. This article continues where part four left off - presenting even more .NET features that MAY be of use to you. Read Part three of this article to understand why these features are being presented.

.NET TechnologyFeatureExample Benefit
.NET FrameworkGenerate cryptographic random numbers with the RNGCryptoServiceProvider from the .NET Frameworks Cryptography namespace. Create powerful encryption keys encrypting your application's data.
Visual BasicUse the 'When' clause in a Visual Basic exception handling block to conditionally catch application exceptions. Create dynamic exception handlers that catch and handle exceptions based on conditions in your application - not just because an application exception occurs.
.NET FrameworkPerform administrative functions on a Windows Active Directory with the .NET DirectoryServices namespace. Programmatically administer user accounts.
Visual BasicVisual Basic's unique background compilation provides squigglies - error detection feedback - as you enter code. Be a more efficient programmer. Write correct code the first time without having to compile and backtrack to find errors.
Visual BasicUse Visual Basic, the most readable and easy-to-write programming language available, to learn and use object-oriented programming (OOP). Learn and user object-oriented programming faster with Visual Basic's readable OOP keywords.
.NET FrameworkCreate your own collections from the .NET Framework's generic collections classes. Create faster collections with less code. (Visual Basic 2005)
Visual BasicUse the My feature of Visual Basic to write applications faster. Find and use functionality from the .NET Framework faster with the My feature 'shortcuts'. (Visual Basic 2005)
.NET FrameworkPerform aspect-oriented programming (AOP) with the .NET Framework. Create a feature - such as logging - you can apply to any object in your application.
Application Configuration FilesUse a .NET configuration file to store and retrieve an encrypted database connection string. Protect your database.
Microsoft .NET Application BlocksUse the free Microsoft Security application block to implement security in your .NET application. Use this professionally written and tested code to check authentication, authorization, role membership and access profile information. Use 'as is' or modify - source code is included.
.NET Create reusable code with inheritance. Create a base class containing common functionality and properties then use it to create one or many new classes.
.NET CLRCreate and execute managed code to prevent many common application exploits. Prevent buffer overflow exploits in your application.

by Fadzai Chamba

Ever noticed how you never know how something is done especially when you need it done yourself? It is only then that you understand what they mean by 'necessity is the mother of invention.'

I have just been working on a small project that had as a requirement a feature that enabled it's administrators to disable the most famous key combination to date, Ctrl+Alt+Del. I went on coding without any idea of how this is done, until I got to the part that required this to be implemented.

This article demonstrates one of the methods that can be used which uses surprisingly little code. The funny part of it all is that I came across it just as I was giving up and as I was investigating something to do with Windows Media Player. First though, I will go into a little history for those who like to be nostalgic.

In the .OLD days

Anyone who tried this back in the day when XP still meant eXtreme Programming would have tried passing SPI_SETSCREENSAVERRUNNING to the API function SystemParametersInfo along with an argument of 'True'. This in effect told the operating system in question that your program was the screen saver and Windows would not bother processing Ctrl+Alt+Del.

The latter versions of the OS, namely Windows NT4, Windows 2000 and Windows XP required us to be honest. This meant that these old fashioned tricks would not fool Windows and we had to honestly state our business if we didn't want Ctrl+Alt+Del. Lying just wouldn't work any more and this is what discouraged most of us.

How does Windows Media Player relate to this?

Well, I had to set some policies for Windows Media Player on a number of machines using gpedit.msc when I looked under the Administrative Templates | System folder and saw a sub folder called Ctrl+Alt+Del Options. I found something there that says Remove Task Manager and I enabled it and tried the combination. Windows politely gave me this message in a message box:

Task manager has been disabled by your Administrator

All that was left was finding out what editing that policy did to my system and mimicking it in my application.

If the amount of code that I eventually wrote is proportional to the amount of time it took me to figure out what to do, I would have written about 3000 lines, excluding the simple interface. But to spare you the details this is what I found.

Show me the code!

All you have to do with your code is to edit a registry value which can be found in the following path:

HKEY_CurrentUser\Software\Microsoft\Windows\CurrentVersion\Policies\System\

The value is a DWORD called "DisableTaskMgr". A value of 1 disables the task manager, while 0 or deleting this key altogether is equivalent to allowing it (Task Manager that is). What makes it especially hard to find with a registry search is that when you enable Task Manager, the System key is removed.

The code is here just for those who want to find a way to read and write to the registry. I created a class called TaskManager in VB.NET (could have been in C# but a coin toss selected VB). There are two methods, one for setting the value, the other for reading it. I will just paste the methods that manipulate this value. The rest of the code is available from the link at the end of the article.

Public Sub SetTaskManager(ByVal _state As TaskManagerState)
    Dim reg As RegistryKey = _hkcu.OpenSubKey(_subKey, True)
    ' If we got nothing, and we are supposed to be disabling it, create the key
    If reg Is Nothing AndAlso _state = TaskManagerState.Disabled Then
        reg = _hkcu.CreateSubKey(_subKey)
    ElseIf reg Is Nothing Then
        'Only come here if we are enabling. We don't need to create the key
        Exit Sub
    End If
    ' Change the value...
    reg.SetValue("DisableTaskMgr", CInt(_state))
End Sub

Public Function GetTaskManagerState() As TaskManagerState
    Dim _val As Integer = -1
    Dim _reg As RegistryKey = _hkcu.OpenSubKey(_subKey)
    'If we got nothing then the task manager is enabled
    If _reg Is Nothing Then
        Return TaskManagerState.Enabled
    Else
        _val = CInt(_reg.GetValue("DisableTaskMgr"))
    End If
    ' If we got here there was a value and we need to decode it...
    ' A value of 1 indicates a disabled task manager...
    Return CType(IIf(_val = 1, TaskManagerState.Disabled, _ 
      TaskManagerState.Enabled), TaskManagerState)
End Function

TaskManagerState is an enumeration defined at the top of the class to make the code more readable. The rest can be found in TaskMismanager, the application that I wrote.

Conclusion

I hope this has been useful to at least one person. I will be sending my bank details to that one person in that case. As I mentioned earlier, this is just one way of doing it. Another way is to trap the system keys and do your own thing when Ctrl+Alt+Del comes up, or just swallowing it. You can replace an entire Dll which is part of Windows with your own. The latter is not something too many of us would like to bother our pretty little heads with at the moment. Let's just say it has something to do with a lady called Gina from the Dynamic Link Library clan. As far as the method in this article is concerned, you can include the TaskManager class in a Dll of your own, or directly in your applications. You decide whether to use it to keep malicious users from accessing the running tasks or for whatever other honest uses that will be of assistance to you.

Happy coding.

Editor's Note: The full project that accompanies this article has been posted in the VB.NET forum and can be accessed here

CodeIt.Once Beta 2 - Refactoring Add-In for VS 2003 and VS 2005 is available by Serge Baranovsky

Counting Unique Characters in a String by Shandy

Workaround: SQL 2005 Beta 2 sqlservr.exe hogs CPU by Serge Baranovsky

My first VB.NET application! by Stuart Parr

SQL Server 2005 on vbCity server by Serge Baranovsky

Shareware Starter Kit by Serge Baranovsky

Computer Languages History by Serge Baranovsky

How To Get The Forms Closing And Closed Events To Execute When Exiting An Application by Shandy

How To Enumerate Through All Controls On A Form by Shandy

What happened during June 2005 at vbCity by Shandy

Lastest devCity .NET Newsletter Is Now Available by Shandy

Wrox VB.NET 3rd Edition by Arno Vyncke

First Windows Mobile .NET Application Idea by Shandy

Tutorials for Smartphones with Windows Mobile 2003 Second Edition software by Shandy

How To Find Out What Version Of Windows Mobile .NET Framework Is Running On An i-mate SP3 by Shandy

Windows Mobile 5.0 Developer Evaluation Kit - Struggling To Get A Copy by Shandy

i-mate SP3 : First Impressions by Shandy

Gadgets - New Category For My Blog by Shandy

I now have my i-mate SP3 connected to the internet through Dialog GMS's network in Sri Lanka by Shandy

MVP Login Screen - Still Using Old Logo ... by Shandy

We Have Aquired A New Clock - Bugger! by Shandy

I Suspect This Is Pretty Geeky by Shandy

New 'Toy' i-Mate SP3 by Shandy

Type My Name Into Google And My Blog Is Shown As The Top Entry by Shandy

My MVP Logo Kit Has Arrived Today by Shandy

http://blogs.vbcity.com/
Advertisement

by Newsletter Staff

Thanks for voting for vbCity.com!

Vote for vbCity!

Support vbCity in the .NET Developer's Journal 2004 Readers' Choice Awards Voting Ballot.

We've worked hard to make vbCity and DevCity.NET the best VB and .NET Community on the Net. Show your support by casting your vote in the .NET Developer's Journal Readers Choice Awards.

Click here to cast your vote for vbCity in the "Best .NET Web Sites" Section.

Thank you!
DevCity.NET Team

http://dndj.sys-con.com/general/readerschoice.htm
Advertisement

We encourage you to pass this issue of
.net.devcity.weekly on to anyone you know with an interest in .NET technology and News You Can Compile

Manage Your Subscription Here.

You are currently subscribed as '*EMAIL*' to .net.devcity.weekly.

Click here to unsubscribe.

Thanks for reading!

Contact:
vbCity.com, LLC
4957 Lakemont Blvd SE C4 #331
Bellevue, WA 98006


DevCity.NET is hosted by FullControl.NET

Copyright vbCity.com, LLC 2003. All Rights Reserved.