Tuesday, December 7, 2010

VB.NET : Check TextBox For Non-Numeric Values

Public Function CheckTextBox(ByVal textb As TextBox, ByVal key As KeyPressEventArgs, Optional ByRef err As String = "") As Boolean
 
       Select Case Asc(key.KeyChar)
           Case 8 To 15
               Return True
           Case 48 To 57
               Return True
           Case 127
               Return True
           Case Else
               err = "Illegal characters have been put in!" + vbCrLf + "Please only use numeric characters."
               Return False
       End Select
   End Function

VB.NET : Sort Collection Made Easy

  
Public Function SortStringCollection(ByVal Col As Collection) As Collection
        ArrayList.Adapter(Col).Sort()
        Return Col
    End Function

Wednesday, November 3, 2010

Test if Integer has been set : Nullable Value Types

For example, let's say that you have an integer for tracking some value and it can be positive and negative.
It is also possible for the value to be not set yet.
How do you detect that the value hasn't been set yet?
You typically come up with some arbitrary number like 99999999 and hope that the real value is never actually 999999999.

A better way since .NET 2.0, Nullable Value Types
Class [MyClass]
 
Private someValue As System.Nullable(Of Integer)
    Public Sub New()someValue = Nothing
End Sub
 
Public Function GetSomeValue() As Integer
    If someValue IsNot Nothing Then
        Return someValue
    Else
        Throw New Exception("Some Value has not been set")
    End If
End Function
 
End Class

This is a much cleaner and safer way than checking for some arbitrary number like 999999999.

Following snippet from Microsoft explains :
http://msdn.microsoft.com/en-us/library/ms235245(v=VS.100).aspx




So what are Nullable Value Types ?




Sometimes you work with a value type that does not have a defined value in certain circumstances.
For example, a field in a database might have to distinguish between having an assigned value
that is meaningful and not having an assigned value.
Value types can be extended to take either their normal values or a null value. Such an extension is called a nullable type.

Each nullable type is constructed from the generic Nullable(Of T) structure.
Consider a database that tracks work-related activities.
The following example constructs a nullable Boolean type and declares a variable of that type.
You can write the declaration in three ways:


Dim ridesBusToWork1? As Boolean
Dim ridesBusToWork2 As Boolean?
Dim ridesBusToWork3 As Nullable(Of Boolean)

The variable ridesBusToWork can hold a value of True, a value of False, or no value at all. Its initial default value is no value at all, which in this case could mean that the information has not yet been obtained for this person. In contrast, False could mean that the information has been obtained and the person does not ride the bus to work.

You can declare variables and properties with nullable types, and you can declare an array with elements of a nullable type.
You can declare procedures with nullable types as parameters, and you can return a nullable type from a Function procedure.

You cannot construct a nullable type on a reference type such as an array, a String, or a class.
The underlying type must be a value type. For more information, see Data Type Implementation (Visual Basic).

 



How to Use a Nullable Type Variable?




The most important members of a nullable type are its HasValue and Value properties.
For a variable of a nullable type, HasValue tells you whether the variable contains a defined value.
If HasValue is True, you can read the value from Value.
Note that both HasValue and Value are ReadOnly properties.


Default Values
When you declare a variable with a nullable type, its HasValue property has a default value of False. This means that by default the variable has no defined value, instead of the default value of its underlying value type. In the following example, the variable numberOfChildreninitially has no defined value, even though the default value of the Integer type is 0.



Dim numberOfChildren? As Integer

A null value is useful to indicate an undefined or unknown value.
If numberOfChildren had been declared as Integer, there would be no value that could indicate that the information is not currently available.


Storing Values

You store a value in a variable or property of a nullable type in the typical way. The following example assigns a value to the variable numberOfChildren declared in the previous example.


numberOfChildren = 2

If a variable or property of a nullable type contains a defined value, you can cause it to revert to its initial state of not having a value assigned. You do this by setting the variable or property to Nothing, as the following example shows.


numberOfChildren = Nothing

Note

Although you can assign Nothing to a variable of a nullable type, you cannot test it for Nothing by using the equal sign.
Comparison that uses the equal sign, someVar = Nothing, always evaluates to Nothing.
You can test the variable's
HasValue property for False, or test by using the Is or IsNot operator.


Retrieving Values
To retrieve the value of a variable of a nullable type, you should first test its HasValue property to confirm that it has a value.
If you try to read the value when HasValue is False, Visual Basic throws an InvalidOperationException exception.
The following example shows the recommended way to read the variable numberOfChildren of the previous examples.


If numberOfChildren.HasValue Then
    MsgBox("There are " & CStr(numberOfChildren) & " children.")
Else
    MsgBox("It is not known how many children there are.")
End If

A database is one of the most important places to use nullable types.
Not all database objects currently support nullable types, but the designer-generated table adapters do.
See "TableAdapter Support for Nullable Types" in TableAdapter Overview.


See Also


Tasks
Troubleshooting Data Types (Visual Basic)

Reference
InvalidOperationException
If Operator (Visual Basic)
Is Operator (Visual Basic)
IsNot Operator (Visual Basic)
HasValue

Concepts
Data Types in Visual Basic
TableAdapter Overview
Local Type Inference (Visual Basic)
Other Resources
Data Type Implementation (Visual Basic)

techPhile: Using VB keywords as Variables

techPhile: Using VB keywords as Variables

Credits goto : Cody Schouten


Using VB keywords as Variables

In C#, a name of a get/set accessor was not a keyword but in VB.Net it was. No matter what libraries or how many different online code converters I tried, I could not get it to work. I finally resorted to google and found out that you can surround a keyword with brackets ([ ]) and than you can use that keyword however you need. In my case it allowed me to use custom sinks in .NET Remoting. Here's an example:

Dim [New] as String
New = "Blah"

As a very BIG note: Be careful when using it. When you can name something other than a reserved keyword, do so. It can cause many issues if you use this unwisely.

Sunday, October 31, 2010

VB .NET, C# Code Converter - Fryan's Digital World

VB .NET, C# Code Converter - Fryan's Digital World

I already had plenty of .NET projects where I use either VB.NET or C# language to write codes. If a client wishes to convert existing VB project to C# or vice-versa then I usually use free VS Studio add-in to do it. But aside from add-ins, there are several web apps that can perform the same task. Here is a list of VB .NET to C# and C# to VB.NET converters I've used in the past.


1. Developer Fusion VB.NET to C#
Convert VB.NET to C# and Vice-Versa

2. KamalPatel.Net - Convert C# to VB .NET. An offline version with full source code is also available for download.


3. Code Translation for .NET (C#-VB.NET)


Take note that all this web apps doesn't make a copy of your sourcode to protect your intellectual right. Everything is processed in the server's memory and returned immediately to the browser.

Wednesday, October 6, 2010

mRemote : multi-tab remote connections manager

image

image mRemote is a full-featured, multi-tab remote connections manager.

http://www.mremote.org/wiki/

It allows you to store all your remote connections in a simple yet powerful interface.

Currently these protocols are supported:

RDP (Remote Desktop)
VNC (Virtual Network Computing)
ICA (Independent Computing Architecture)
SSH (Secure Shell)
Telnet (TELecommunication NETwork)
HTTP/S (Hypertext Transfer Protocol)
Rlogin (Rlogin)
RAW

image

mRemote is a multi-tab, multi-protocol remote connections mananger written mainly in VB.NET and some bits in C# 2.0.

External Programs can be used, for example Dameware :

clip_image001[4]

Features


Free and Open Source, released under the GPL
Panels and tabs allow to group certain connections together, dock them to any side of the window or completely undock them and move them to another screen for example
Multiple supported protocols (RDP, VNC, ICA, SSH, Telnet, RAW, Rlogin and HTTP/S)
Easy to organize and maintain list of connections
Inheritance makes it possible to store properties on folder basis and let the underlying connections inherit this info
Support for importing connections from Active Directory
Allows creating nested containers (folders) to categorize connections
"Quick Connect" feature to quickly open a connection without creating an entry
"Quick Search" feature to quickly find a connection while typing
Support for SCP/SFTP (SSH) file transfers
Assign icons to connections to easily identify purpose
Screenshot manager allows to collect multiple screenshots and save them all together or copy them to the clipboard
View remote session info and log off sessions (RDP)
Portable
Auto-Reconnect feature
"Auto-Update" feature
SQL Server support
Show description tooltips when hoovering over connections
System tray icon with connection menu
Fullscreen (Kiosk) mode
Assign global credentials to use when no information is provided on connection basis
Host Up/Down (Ping) feature shows if the selected host answers to a ping

System Requirements


Supported Operating Systems:
Windows XP
Windows Vista

Prerequisites:


Microsoft .NET Framework 2.0
Microsoft Terminal Services Client 6.0
Needed if you use RDP. mstscax.dll and/or msrdp.ocx must be registered.
PuTTY
Needed if you use Telnet, SSH, Rlogin or RAW. Included in all packages.
Citrix ICA Client
Needed if you use ICA. wfica.ocx must be registered.

ATTENTION!
mRemote was only tested under 32bit environments, so 64bit systems are unsupported but may run mRemote just as usual.

Download mRemote (Change Log)
Downloads are provided in four packages, the setup package, binary package, portable package and the source package.

The setup package is the compiled version of mRemote which comes in the form of a NSIS generated setup. (The common/fastest way to get mRemote up and running)

The portable package consists of the same files as the bin package but contains an modified version of the executable which stores and loads all your settings from files in the application's directory. This package can be used to run mRemote from an USB stick an preserve your configuration wherever you go.

The binary package is a zip package and contains the same files as the setup package but has no automated installer.

The source package is a zip package and contains the mRemote source code.

English Release:

Setup Package

Download V1.50

Portable Package

Download V1.50

Binary Package

Download V1.50

Source Package

Download V0.50

http://www.mremote.org/wiki/Edit.aspx?Page=Downloads&Section=5

Licensing
mRemote is released under the GPL (GNU General Public License)

Licensing

mRemote is released under the GPL (GNU General Public License)

Friday, October 1, 2010

Windows Tip of the Day: Finding the MAC Address of Remote Computer (Advanced)

Windows Tip of the Day: Finding the MAC Address of Remote Computer (Advanced)

Every device on a TCP/IP network has a unique number assigned to it called the MAC (Media Access Control) address. The MAC address is used by the network hardware such as routers, switches, etc. to send traffic from one device to another device on your network.

Your computer uses a service called ARP (Address Resolution Protocol) to resolve and track the TCP/IP and MAC address of the remote devices that you're communicating with. This information is handy for doing semi-low level network troubleshooting. It can also be used for granting or denying permissions to a network segment or device on that network.

To determine the MAC address of a remote device:

  • Open the MS-DOS prompt (From the Run... command, type "CMD" and press Enter).
  • Ping a remote device that you want to find the MAC address (for example: PING 192.168.0.1).
  • Type "ARP -A", and press Enter.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\WINDOWS>arp -a


Interface: 192.168.1.100 --- 0x10004
Internet Address Physical Address Type

192.168.1.1 aa-fb-c8-34-da-7a dynamic

Tuesday, September 21, 2010

Make your application extensible with Reflection

Public Shared Function LoadAll(Of T)() As List(Of T)
Dim services As New List(Of T)()

For Each type As Type In Assembly.GetCallingAssembly().GetTypes()
If type.IsSubclassOf(GetType(T)) AndAlso Not type.IsAbstract AndAlso Not type.IsInterface Then
services.Add(DirectCast(Activator.CreateInstance(type), T))
End If
Next

Return services
End Function

Monday, September 20, 2010

Start a Process as a Different User - developer Fusion

Start a Process as a Different User - developer Fusion: "Function ConvertToSecureString(ByVal str As String)

Another usefull code snippet
Credits go to Peter Rekdal Sunde at developerfusion.com

Function ConvertToSecureString(ByVal str As String)
Dim password As New SecureString
For Each c As Char In str.ToCharArray
password.AppendChar(c)
Next
Return password
End Function
Sub Main()
dim username as string = "Administrator"
dim password as SecureString = ConvertToSecureString("my password")
dim domain as string = Nothing
dim filename as string = "notepad.exe" ' %SYSTEMROOT%\system32
Try
System.Diagnostics.Process.Start(filename,username, password, domain)
Catch ex As Win32Exception
MessageBox.Show("Wrong username or password.", _
"Error logging in as administrator", MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Try
End Sub

Deep clone an object in .NET - developer Fusion

Deep clone an object in .NET - developer Fusion

A code snippet that could be very useful, so I though I'd share this with you...

Credits go to James Crowley at developerfusion.com


There are two types of object cloning; deep and shallow.
A shallow clone creates a new instance of the same type as the original object, with all its value-typed fields copied. However, the reference type fields still point to the original objects; and so the "new" object and the original reference to the same object. On the other hand, a deep clone of an object contains a full copy of everything directly or indirectly referenced by the object - and so you get a "true" copy.
One of the easiest ways to deep-copy an object is to serialize the object into memory and de-serialize it again - although this does require the object graph to be serializable. Here's a handy code snippet to do this:
public static object CloneObject(object obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter(null, 
new StreamingContext(StreamingContextStates.Clone));
binaryFormatter.Serialize(memStream, obj);
memStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(memStream);
}
}
You could then implement the ICloneable interface on your object like so:
public class MyObject  : ICloneable {
public object Clone()
{
return ObjectUtility.CloneObject(this);
}
...
}

Thursday, September 16, 2010

InCtrl 5 Application Analysys Tool – Download and Enjoy | Simon Todd's Free Technical Blog!

InCtrl 5 Application Analysys Tool – Download and Enjoy | Simon Todd's Free Technical Blog!


InCtrl 5 is an amazing application, it is very simple to use and simple in the results it give but it is very very powerful. InCtrl 5 looks for all of the differences before and after an application is installed.


InCtrl 5 is a great tool for those that build XPe (XP Embedded) development, Application Virtulisation or Terminal Services/Citrix. It allows you to look and see what is added into the Registry and file system, it also shows you what was edited and changed during the installation the the application you are testing.
I have used this product to components XPe applications, work out where an application tries to install its self on a Terminal Server and to double check the tools for Application Visualisation.
A really good an useful tool.

Tuesday, September 14, 2010

Printer Driver Generator 1.3.0.0 | Novell User Communities

Printer Driver Generator 1.3.0.0 | Novell User Communities: "Printer Driver Generator 1.3.0.0"


Nice little tool to regenerate a printer INF file...





license:
Free
This is a small tool that I wrote out of need. I do believe that this tool may be of use to others, but it's still in beta phase, and I need feedback from users, Please :-)
Problem:
I have a printer that did not come with an INF-based printer driver,but instead with a setup.exe-based driver / or integrated with Windows. I don't run iPrint, but only Point-And-Print, or NDPS. How do I distribute this driver?
Answer:
Install this program on your PC, and run PDrvGen.exe, select the printer, and select "Generate".An INF-based driver will now be generated!
What's new in version 1.3.0.0:
  • Gray Cash from the USA had a small, but nice request, that I preserved the version info in the driver, if it was present in the origen driver.
    That way, troubleshooting would be a lot easier to do.
PDrvGen will now extract and save the Driver Version info"
What's new in version 1.2.0.0:
  • Theo Pluym found an HP Driver that wasn't written that well, since it didn't liked a space between the parameters. Since I figured, that other drivers might suffer from the same problem, I corrected PDrvGen to generate inf-files without this.

    Download : PDRVGen.zip

Monday, September 13, 2010

Ghostcript PDF Reference & Tips — Milan Kupcevic

Ghostcript PDF Reference & Tips — Milan Kupcevic


Basic Usage
Convert PostScript to PDF:
gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=fileout.pdf \     filein.ps 
Merge/combine PDF and/or PostScript files:
gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -sOutputFile=fileout.pdf \     filein.ps filein2.pdf 
Extract a page from a PostScript or a PDF document:
gs -q -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dFirstPage=3 -dLastPage=3 \     -sOutputFile=fileout.pdf filein.ps 

Additional Options

PDF optimization level selection options

-dPDFSETTINGS=/screen   (screen-view-only quality, 72 dpi images) -dPDFSETTINGS=/ebook    (low quality, 150 dpi images) -dPDFSETTINGS=/printer  (high quality, 300 dpi images) -dPDFSETTINGS=/prepress (high quality, color preserving, 300 dpi imgs) -dPDFSETTINGS=/default  (almost identical to /screen) 

Paper size selection options

-sPAPERSIZE=letter -sPAPERSIZE=a4 -dDEVICEWIDTHPOINTS=w -dDEVICEHEIGHTPOINTS=h (point=1/72 of an inch) -dFIXEDMEDIA (force paper size over the PostScript defined size) 

Other options

-dEmbedAllFonts=true -dSubsetFonts=false -dFirstPage=pagenumber -dLastPage=pagenumber -dAutoRotatePages=/PageByPage -dAutoRotatePages=/All -dAutoRotatePages=/None -r1200 (resolution for pattern fills and fonts converted to bitmaps) -sPDFPassword=password

Thursday, September 9, 2010

Hackers Guide to Being Hacked: How “Bad Guys” Take Control, and How to Take it Back. - hacked, hackers, security, recovery, repair, attack

Hackers Guide to Being Hacked: How “Bad Guys” Take Control, and How to Take it Back. - hacked, hackers, security, recovery, repair, attack

I've found an interesting blog about preventing/dectecting an attack. So let's blog it, you never know when this will come in handy...

How to Recover from an Attack.


Find the Affected Machine(s).

In some cases, like the website hijack or the "attack page" example, you'll know which machine has been affected. In most cases, however, you're going to have to find it.

The best tool for figuring out which computer has been compromised is netstat. Netstat reveals all the incoming and outgoing connections on a computer, and is available on Linux, Windows, and Mac.

Methodically check all the computers in your network using one of the netstat commands below:

Windows
1:
netstat -an | find "ESTABLISHED"

Mac / Linux
1:
netstat -an | grep ESTABLISHED

This command will show you all the established connections to the computer. It will be fairly obvious which machine is infected when you find it. For example, a Linux server infested with an SSH scanner (a script that breaks into your network, then tries to break into everyone else's) will have tons of connections to other networks with a destination port of 22.

A spam relay will have tons of connections to everywhere with a destination port of 25.

An FTP brute force attacker will have tons of connections to destination port 21.

...and so on.

When you find a machine that you suspect has been infected, run the same command as above again, only this time leave out the n switch:

Windows
1:
netstat -a | find "ESTABLISHED"

Mac / Linux
1:
netstat -a | grep ESTABLISHED

This will allow the system to resolve the IP addresses previously shown to their rDNS equivalents. We're looking for a dead giveaway here: connections to foreign countries. When you see 17 connections from Romania, Russian, Taiwan or some other foreign country, and you are not in that country, it is a dead giveaway.

Lastly, run netstat a final time to find the offending processes:

Windows
1:
netstat -ao | find "ESTABLISHED"

Mac / Linux
1:
netstat -ap | grep ESTABLISHED

Write down the offending processes. We'll need this list later.


Blockade your Network.

By now, you should have already downloaded m0n0wall - as I mentioned, you should have a firewall in the prevention steps. A hardware firewall is your best friend in mitigating the effects of a hack attack. While we originally implement a hardware firewall to keep bad guys out, if you've been compromised, you have a duty to mitigate the damage you are doing by keeping the probes, scans, spam, and other garbage in.

Turn on the outbound firewall, and set it to disallow all outbound traffic except traffic with a destination port of 80 or 443. This allows you to keep surfing the web and access secure sites to get more help and information to recover from the attack, but it keeps all the spam (destination port 25), port scans (many different ports), DoS attacks (ping), BotNets (usually IRC ports), and other nasty stuff from being able to leave your network, which renders them effectively useless to the attacker.

Thursday, August 26, 2010

Some Useful Functions


Sometimes you may want to convert a string into a byte array, or vice versa, especially when you are using the Cryptographic APIs. I have provided three functions here to help you make the conversions. The three functions are:

stringcharToByteArray(): converts a string of characters to a byte array.
stringToByteArray(): converts a string of numbers into a byte array.
byteArrayToString(): converts a byte array into a string.

    Public Function stringcharToByteArray(ByVal str As String) As Byte()
        'e.g. "abcdefg" to {a,b,c,d,e,f,g}
        Dim s As Char()
        s = str.ToCharArray
        Dim b(s.Length - 1) As Byte
        Dim i As Integer
        For i = 0 To s.Length - 1
            b(i) = Convert.ToByte(s(i))
        Next
        Return b
    End Function
 
    Public Function stringToByteArray(ByVal str As String) As Byte()
        ' e.g. "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16" to 
        '{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
        Dim s As String()
        s = str.Split(" ")
        Dim b(s.Length - 1) As Byte
        Dim i As Integer
        For i = 0 To s.Length - 1
            b(i) = Convert.ToByte(s(i))
        Next
        Return b
    End Function
 
    Public Function byteArrayToString(ByVal b() As Byte) As String
        Dim i As Integer
        Dim s As New System.Text.StringBuilder()
        For i = 0 To b.Length - 1
            Console.WriteLine(b(i))
            If i <> b.Length - 1 Then
                s.Append(b(i) & " ")
            Else
                s.Append(b(i))
            End If
        Next
        Return s.ToString
    End Function