Remove Special Characters – The RegEx way

A nice a simple code to remove special characters in a string or simply say, convert it alphanumeric string.

Here’s a little piece of code:

static string ConvertAlphaNumeric(string inpString)
{
    string s = System.Text.RegularExpressions.Regex.Replace(inpString, "[^\\w\\.@-]", "");

    return s;
}

Enjoy.

Ping.fm Thingie

ping.fm thingie 
It's just my first attempt of creating a small tool using Ping.fm APIs.

I have thought of making it simpler by posting a message directly to Run Window
runwindow
like from the example above:
pingdotfm - Is the Executable filename which was located in your System32 folder.
your message here ... - The message you want to post in Ping.fm

After pressing OK Button or hitting Enter key
A small Window pops up wherever your mouse pointer is
ping.fm thingie
And that's it .. That automatically close after sending your message! Simple!

And one last thing .. You can also type your message directly to that popup window just running pingdotfm.

Enjoy!

Here's the Download file


Installation
Run
ping.fm.exe 
And a window asking your User Application Key which can be found on YOUR APPLICATION KEY in Ping.fm
user_app_key
Validate it, and after that .. It creates an Executable file called PingdotFm in your System32 folder so you can run it directly in Run window.

Source Code
Adam Duffy (adam@ping.fm) gave away his source code for dealing with Ping.fm APIs .. so i'm giving it away to you too but it already contains some modifications of course to totally wrap up some things for you.

Here's the source:

/*
Copyright © 2008, Ping.fm Inc.
All rights reserved.
http://ping.fm/

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

- Neither the name Ping.fm, nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
* Modified by: Jayson Ragasa
* Baguio City, Philippines
* ----------------------------------
* Added more constructors
* Added enums
* changed api_key variable visibility which was originally set to private..
* Changed some methods to support the enum values.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace PingFM
{
public enum PostMethods
{
Default,
Blog,
MicroBlog,
Status
}

/// <summary>Ping.fm API wrapper for C#.
/// Created by Adam Duffy (adam@ping.fm) 06/18/2008
/// </summary>
public class PingFMApi
{
public PingFMApi() { }
public PingFMApi(string api_key)
{
this.api_key = api_key;
}
public PingFMApi(string user_application_key, string api_key)
{
this.user_application_key = user_application_key;
this.api_key = api_key;
}

private static Version mVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
public static Version Version
{
get { return mVersion; }
}

/// <summary>Ping.fm Developer API Key. See http://ping.fm/developers/</summary>
public string api_key;

/// <summary>User Application Key.
/// The end user will need to enter this. see http://ping.fm/key/
/// </summary>
public string user_application_key;

#region XML Serialization Classes

public class ServiceMethods
{
[XmlAttribute("id")]
public string ID;
[XmlAttribute("name")]
public string Name;
[XmlElement("methods")]
public string Methods;
public override string ToString()
{
if (!string.IsNullOrEmpty(Name))
return Name + " [" + ID + "]";
else
return base.ToString();
}
}
public class Service
{
[XmlAttribute("id")]
public string ID;
[XmlAttribute("name")]
public string Name;
[XmlElement("methods")]
public string Methods;
public override string ToString()
{
if (!string.IsNullOrEmpty(Name))
return Name + " [" + ID + "]";
else
return base.ToString();
}
}
public class Trigger
{
[XmlAttribute("id")]
public string ID;
[XmlAttribute("method")]
public string Method;
[XmlArray("services"), XmlArrayItem("service", typeof(Service))]
public List<Service> Services = new List<Service>();
public override string ToString()
{
if (!string.IsNullOrEmpty(ID))
return ID + " (" + Method + ")";
else
return base.ToString();
}
}
public class Message
{
public struct PingDate
{
[XmlAttribute("rfc")]
public string Rfc;
[XmlAttribute("unix")]
public string Unix;
public override string ToString()
{
if (!string.IsNullOrEmpty(Rfc))
return Rfc;
else
return base.ToString();
}
}
public struct PingContent
{
[XmlElement("title")]
public string Title;
[XmlElement("body")]
public string Body;
public override string ToString()
{
if (!string.IsNullOrEmpty(Title))
return Title;
else if (!string.IsNullOrEmpty(Body))
return Body;
else
return base.ToString();
}
}
[XmlAttribute("id")]
public string ID;
[XmlAttribute("method")]
public string Method;
[XmlElement("date")]
public PingDate Date;
[XmlElement("content")]
public PingContent Content;
[XmlArray("services"), XmlArrayItem("service", typeof(Service))]
public List<Service> Services = new List<Service>();
public void Decode()
{
Content.Body = Base64Decode(Content.Body);
Content.Title = Base64Decode(Content.Title);
}
public override string ToString()
{
if (!string.IsNullOrEmpty(Method))
return Method;
else
return base.ToString();
}
}

[XmlRoot("rsp")]
public class PingResponse
{
[XmlAttribute("status")]
public string Status;
[XmlElement("transaction")]
public string Transaction;
[XmlElement("method")]
public string Method;
[XmlElement("message")]
public string Message;
}

[XmlRoot("rsp")]
public class ServicesResponse : PingResponse
{
[XmlArray("services"), XmlArrayItem("service", typeof(ServiceMethods))]
public List<ServiceMethods> Services;
}

[XmlRoot("rsp")]
public class TriggerResponse : PingResponse
{
[XmlArray("triggers"), XmlArrayItem("trigger", typeof(Trigger))]
public List<Trigger> Triggers;
}

[XmlRoot("rsp")]
public class LatestResponse : PingResponse
{
[XmlArray("messages"), XmlArrayItem("message", typeof(Message))]
public List<Message> Messages = new List<Message>();
public void DecodeMessages()
{
if (Messages == null) return;
foreach (Message m in Messages)
m.Decode();
}
}

[XmlRoot("rsp")]
public class MessageResponse : PingResponse
{
//.net has a problem deserializing this one.
//could un-inherit the class, but i'll leave the bug here.
[XmlElement("message")]
public new Message Message;
}

private bool SerializeObject(XmlTextWriter writer, object o)
{
try
{
XmlSerializer xs = new XmlSerializer(o.GetType());
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", ""); //remove the xmlns tags.
xs.Serialize(writer, o, ns);
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return false;
}
}
private object DeserializeObject(XmlReader reader, Type type)
{
try
{
XmlSerializer xs = new XmlSerializer(type);
return xs.Deserialize(reader);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
DeserializeException = ex;
return null;
}
}

#endregion

private HttpWebRequest CreateHttpWebRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Headers.Add("Accept-Language", "en-us");
request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
request.UserAgent = "PingFM.dll " + Version.ToString(2);
return request;
}

private string GetWebResponse(string url, string PostData)
{
string html = "";
try
{
HttpWebRequest request = CreateHttpWebRequest(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] b = Encoding.Default.GetBytes(PostData);
request.GetRequestStream().Write(b, 0, b.Length);
request.GetRequestStream().Close();
request.Timeout = 10000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
sr.BaseStream.ReadTimeout = 10000;
html = sr.ReadToEnd();
sr.Close();
response.Close();
}
catch (Exception ex)
{
WebException = ex;
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return html;
}

private PingResponse mLastResponse;
/// <summary>Gets the last PingResponse</summary>
public PingResponse LastResponse { get { return mLastResponse; } }

/// <summary>If a web server error occurs, the exception will be stored here for reference.</summary>
public Exception WebException;

/// <summary>If an error occurs during deserialization, the exception will be stored here for reference.</summary>
public Exception DeserializeException;

/// <summary>Clears the LastResponse, WebException, and DeserializeException</summary>
public void Reset()
{
mLastResponse = null;
WebException = null;
DeserializeException = null;
}

/// <summary>Validates the given user’s application key.</summary>
public PingResponse Validate()
{
string url = "http://api.ping.fm/v1/user.validate";
string postdata = "api_key={0}&user_app_key={1}";
postdata = string.Format(postdata, api_key, user_application_key);
System.Diagnostics.Debug.WriteLine(postdata);
string response = GetWebResponse(url, postdata);
XmlReader xr = XmlReader.Create(new System.IO.StringReader(response));
PingResponse r = (PingResponse)DeserializeObject(xr, typeof(PingResponse));
xr.Close();
mLastResponse = r;
return r;
}

/// <summary>Returns a list of services the particular user has set up through Ping.fm.</summary>
public ServicesResponse GetServices()
{
string url = "http://api.ping.fm/v1/user.services";
string postdata = "api_key={0}&user_app_key={1}";
postdata = string.Format(postdata, api_key, user_application_key);
string response = GetWebResponse(url, postdata);
XmlReader xr = XmlReader.Create(new System.IO.StringReader(response));
ServicesResponse r = (ServicesResponse)DeserializeObject(xr, typeof(ServicesResponse));
xr.Close();
mLastResponse = r;
return r;
}

/// <summary>Validates the given user’s application key.</summary>
public TriggerResponse GetTriggers()
{
string url = "http://api.ping.fm/v1/user.triggers";
string postdata = "api_key={0}&user_app_key={1}";
postdata = string.Format(postdata, api_key, user_application_key);
string response = GetWebResponse(url, postdata);
XmlReader xr = XmlReader.Create(new System.IO.StringReader(response));
TriggerResponse r = (TriggerResponse)DeserializeObject(xr, typeof(TriggerResponse));
xr.Close();
mLastResponse = r;
return r;
}

/// <summary>Returns the last 25 messages a user has posted through Ping.fm.</summary>
public LatestResponse GetLatest()
{
return GetLatest(-1, null);
}
/// <summary>Returns the last X messages a user has posted through Ping.fm.</summary>
/// <param name="limit">Number of messages to query</param>
/// <param name="order">Order of results (ASC/DESC)</param>
public LatestResponse GetLatest(int limit, string order)
{
string url = "http://api.ping.fm/v1/user.latest";
string postdata = "api_key={0}&user_app_key={1}";
postdata = string.Format(postdata, api_key, user_application_key);
if (limit > -1) postdata += "&limit=" + limit.ToString();
if (!string.IsNullOrEmpty(order)) postdata += "&order=" + order;
string response = GetWebResponse(url, postdata);
XmlReader xr = XmlReader.Create(new System.IO.StringReader(response));
LatestResponse r = (LatestResponse)DeserializeObject(xr, typeof(LatestResponse));
xr.Close();
if (r != null) r.DecodeMessages();
mLastResponse = r;
return r;
}

/// <summary>Returns data for the specified MessageID.</summary>
/// <param name="MessageID">MessageID to query</param>
[Obsolete("Use user.latest to get a recent message history", true)]
public MessageResponse GetMessage(string MessageID)
{
string url = "http://api.ping.fm/v1/user.message";
string postdata = "api_key={0}&user_app_key={1}&message_id={2}";
postdata = string.Format(postdata, api_key, user_application_key, MessageID);
string response = GetWebResponse(url, postdata);
XmlReader xr = XmlReader.Create(new System.IO.StringReader(response));
MessageResponse r = (MessageResponse)DeserializeObject(xr, typeof(MessageResponse));
xr.Close();
if (r != null && r.Message != null) r.Message.Decode();
mLastResponse = r;
return r;
}

/// <summary>Posts a message to the user’s Ping.fm services.</summary>
public PingResponse Post(string Body)
{
return Post(PostMethods.Default, null, Body, false);
}
public PingResponse Post(PostMethods Method, string Body)
{
return Post(Method, null, Body, false);
}
public PingResponse Post(PostMethods Method, string Title, string Body)
{
return Post(Method, Title, Body, false);
}
public PingResponse Post(PostMethods Method, string Title, string Body, bool debug)
{
string url = "http://api.ping.fm/v1/user.post";
string postdata = "api_key={0}&user_app_key={1}&post_method={2}";
if (string.IsNullOrEmpty((string)Method.ToString())) Method = PostMethods.Default;
postdata = string.Format(postdata, api_key, user_application_key, (string)Method.ToString().ToLower());
if (!string.IsNullOrEmpty(Title)) postdata += "&title=" + UrlEncode(Title);
if (!string.IsNullOrEmpty(Body)) postdata += "&body=" + UrlEncode(Body);
if (debug) postdata += "&debug=1";
string response = GetWebResponse(url, postdata);
XmlReader xr = XmlReader.Create(new System.IO.StringReader(response));
PingResponse r = (PingResponse)DeserializeObject(xr, typeof(PingResponse));
xr.Close();
mLastResponse = r;
return r;
}

/// <summary>Posts a message to the user’s Ping.fm services using one of their custom triggers.</summary>
public PingResponse TPost(string Trigger, string Body)
{
return TPost(Trigger, null, Body, false);
}
public PingResponse TPost(string Trigger, string Title, string Body)
{
return TPost(Trigger, Title, Body, false);
}
public PingResponse TPost(string Trigger, string Title, string Body, bool debug)
{
string url = "http://api.ping.fm/v1/user.tpost";
string postdata = "api_key={0}&user_app_key={1}";
postdata = string.Format(postdata, api_key, user_application_key);
if (!string.IsNullOrEmpty(Trigger)) postdata += "&trigger=" + Trigger;
if (!string.IsNullOrEmpty(Title)) postdata += "&title=" + UrlEncode(Title);
if (!string.IsNullOrEmpty(Body)) postdata += "&body=" + UrlEncode(Body);
if (debug) postdata += "&debug=1";
string response = GetWebResponse(url, postdata);
XmlReader xr = XmlReader.Create(new System.IO.StringReader(response));
PingResponse r = (PingResponse)DeserializeObject(xr, typeof(PingResponse));
xr.Close();
mLastResponse = r;
return r;
}

public static string Base64Encode(string ToEncode)
{
if (string.IsNullOrEmpty(ToEncode)) return ToEncode;
try
{
//this method is a little more work, but supports unicode.
char[] chars = ToEncode.ToCharArray();
byte[] bytes = Encoding.UTF8.GetBytes(chars);
return Convert.ToBase64String(bytes);
}
catch
{
return ToEncode;
}
}

public static string Base64Decode(string ToDecode)
{
try
{
return Encoding.Default.GetString(Convert.FromBase64String(ToDecode));
}
catch { return ToDecode; }
}

private static string UrlEncode(string text)
{
return System.Web.HttpUtility.UrlEncode(text, Encoding.Default);
}

}
}

I also had a problem when running this on XP.
The Form.TransparencyKey did not work since I used a custom irregular shape form..
Here's the workaround.
#region XP TranparencyKey Workaround
{
Bitmap bg = new Bitmap(Properties.Resources.bg1);
Color transparentcolor = bg.GetPixel(0, 0);
bg.MakeTransparent(transparentcolor);

this.BackgroundImage = bg;
}
#endregion

this.BackColor = System.Drawing.Color.Magenta;
this.TransparencyKey = this.BackColor;

Encrypt/Decrypt RDP Password

April 2, 2009 .. I finally Decrypted the RDP hashed password using Data Protection but some little modification and a little help from Remko Weijnen.  I have made a a sample tool RDPPassword_EncryptDecrypt.zip.

image

Here's the full source with a little modification

/*
* Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication
* http://msdn.microsoft.com/en-us/library/aa302402.aspx#secnetht07_topic4
*
* --- March 12, 2009 10:51 am
* NOTES:
* I modified this a little bit to allow us to encrypt/decrypt a password for RDP Files
*
* Changes Made:
* ORG: public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy)
* NEW: public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy, string DataDescription)
*
* ORG:
* retVal = CryptProtectData(ref plainTextBlob, null, ref entropyBlob,
IntPtr.Zero, ref prompt, dwFlags,
ref cipherTextBlob);
* NEW:
* retVal = CryptProtectData(ref plainTextBlob, DataDescription, ref entropyBlob,
IntPtr.Zero, ref prompt, dwFlags,
ref cipherTextBlob);
*
* ORG: Decrypt(byte[] cipherText, byte[] optionalEntropy)
* NEW: Decrypt(byte[] cipherText, byte[] optionalEntropy, string DataDescription)
*
* ORG:
* retVal = CryptUnprotectData(ref cipherBlob, null, ref
entropyBlob,
IntPtr.Zero, ref prompt, dwFlags,
ref plainTextBlob);
* NEW:
* retVal = CryptUnprotectData(ref cipherBlob, DataDescription, ref
entropyBlob,
IntPtr.Zero, ref prompt, dwFlags,
ref plainTextBlob);
*/
using System;
using System.Text;
using System.Runtime.InteropServices;

namespace DataProtection
{
public class DataProtector
{
[DllImport("Crypt32.dll", SetLastError = true,
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool CryptProtectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT
pPromptStruct,
int dwFlags,
ref DATA_BLOB pDataOut);
[DllImport("Crypt32.dll", SetLastError = true,
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private static extern bool CryptUnprotectData(
ref DATA_BLOB pDataIn,
String szDataDescr,
ref DATA_BLOB pOptionalEntropy,
IntPtr pvReserved,
ref CRYPTPROTECT_PROMPTSTRUCT
pPromptStruct,
int dwFlags,
ref DATA_BLOB pDataOut);
[DllImport("kernel32.dll",
CharSet = System.Runtime.InteropServices.CharSet.Auto)]
private unsafe static extern int FormatMessage(int dwFlags,
ref IntPtr lpSource,
int dwMessageId,
int dwLanguageId,
ref String lpBuffer,
int nSize,
IntPtr* Arguments);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct DATA_BLOB
{
public int cbData;
public IntPtr pbData;
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct CRYPTPROTECT_PROMPTSTRUCT
{
public int cbSize;
public int dwPromptFlags;
public IntPtr hwndApp;
public String szPrompt;
}
static private IntPtr NullPtr = ((IntPtr)((int)(0)));
private const int CRYPTPROTECT_UI_FORBIDDEN = 0x1;
private const int CRYPTPROTECT_LOCAL_MACHINE = 0x4;

public enum Store { USE_MACHINE_STORE = 1, USE_USER_STORE };

private Store store;

public DataProtector(Store tempStore)
{
store = tempStore;
}

public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy, string DataDescription)
{
bool retVal = false;
DATA_BLOB plainTextBlob = new DATA_BLOB();
DATA_BLOB cipherTextBlob = new DATA_BLOB();
DATA_BLOB entropyBlob = new DATA_BLOB();
CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
InitPromptstruct(ref prompt);
int dwFlags;
try
{
try
{
int bytesSize = plainText.Length;
plainTextBlob.pbData = Marshal.AllocHGlobal(bytesSize);
if (IntPtr.Zero == plainTextBlob.pbData)
{
throw new Exception("Unable to allocate plaintext buffer.");
}
plainTextBlob.cbData = bytesSize;
Marshal.Copy(plainText, 0, plainTextBlob.pbData, bytesSize);
}
catch (Exception ex)
{
throw new Exception("Exception marshalling data. " + ex.Message);
}
if (Store.USE_MACHINE_STORE == store)
{//Using the machine store, should be providing entropy.
dwFlags = CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN;
//Check to see if the entropy is null
if (null == optionalEntropy)
{//Allocate something
optionalEntropy = new byte[0];
}
try
{
int bytesSize = optionalEntropy.Length;
entropyBlob.pbData = Marshal.AllocHGlobal(optionalEntropy.Length); ;
if (IntPtr.Zero == entropyBlob.pbData)
{
throw new Exception("Unable to allocate entropy data buffer.");
}
Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData, bytesSize);
entropyBlob.cbData = bytesSize;
}
catch (Exception ex)
{
throw new Exception("Exception entropy marshalling data. " +
ex.Message);
}
}
else
{//Using the user store
dwFlags = CRYPTPROTECT_UI_FORBIDDEN;
}
retVal = CryptProtectData(ref plainTextBlob, DataDescription, ref entropyBlob,
IntPtr.Zero, ref prompt, dwFlags,
ref cipherTextBlob);
if (false == retVal)
{
throw new Exception("Encryption failed. " +
GetErrorMessage(Marshal.GetLastWin32Error()));
}
//Free the blob and entropy.
if (IntPtr.Zero != plainTextBlob.pbData)
{
Marshal.FreeHGlobal(plainTextBlob.pbData);
}
if (IntPtr.Zero != entropyBlob.pbData)
{
Marshal.FreeHGlobal(entropyBlob.pbData);
}
}
catch (Exception ex)
{
throw new Exception("Exception encrypting. " + ex.Message);
}
byte[] cipherText = new byte[cipherTextBlob.cbData];
Marshal.Copy(cipherTextBlob.pbData, cipherText, 0, cipherTextBlob.cbData);
Marshal.FreeHGlobal(cipherTextBlob.pbData);
return cipherText;
}

public byte[] Decrypt(byte[] cipherText, byte[] optionalEntropy, string DataDescription)
{
bool retVal = false;
DATA_BLOB plainTextBlob = new DATA_BLOB();
DATA_BLOB cipherBlob = new DATA_BLOB();
CRYPTPROTECT_PROMPTSTRUCT prompt = new
CRYPTPROTECT_PROMPTSTRUCT();
InitPromptstruct(ref prompt);
try
{
try
{
int cipherTextSize = cipherText.Length;
cipherBlob.pbData = Marshal.AllocHGlobal(cipherTextSize);
if (IntPtr.Zero == cipherBlob.pbData)
{
throw new Exception("Unable to allocate cipherText buffer.");
}
cipherBlob.cbData = cipherTextSize;
Marshal.Copy(cipherText, 0, cipherBlob.pbData,
cipherBlob.cbData);
}
catch (Exception ex)
{
throw new Exception("Exception marshalling data. " +
ex.Message);
}
DATA_BLOB entropyBlob = new DATA_BLOB();
int dwFlags;
if (Store.USE_MACHINE_STORE == store)
{//Using the machine store, should be providing entropy.
dwFlags =
CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN;
//Check to see if the entropy is null
if (null == optionalEntropy)
{//Allocate something
optionalEntropy = new byte[0];
}
try
{
int bytesSize = optionalEntropy.Length;
entropyBlob.pbData = Marshal.AllocHGlobal(bytesSize);
if (IntPtr.Zero == entropyBlob.pbData)
{
throw new Exception("Unable to allocate entropy buffer.");
}
entropyBlob.cbData = bytesSize;
Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData,
bytesSize);
}
catch (Exception ex)
{
throw new Exception("Exception entropy marshalling data. " +
ex.Message);
}
}
else
{//Using the user store
dwFlags = CRYPTPROTECT_UI_FORBIDDEN;
}
retVal = CryptUnprotectData(ref cipherBlob, DataDescription, ref
entropyBlob,
IntPtr.Zero, ref prompt, dwFlags,
ref plainTextBlob);
if (false == retVal)
{
throw new Exception("Decryption failed. " +
GetErrorMessage(Marshal.GetLastWin32Error()));
}
//Free the blob and entropy.
if (IntPtr.Zero != cipherBlob.pbData)
{
Marshal.FreeHGlobal(cipherBlob.pbData);
}
if (IntPtr.Zero != entropyBlob.pbData)
{
Marshal.FreeHGlobal(entropyBlob.pbData);
}
}
catch (Exception ex)
{
throw new Exception("Exception decrypting. " + ex.Message);
}
byte[] plainText = new byte[plainTextBlob.cbData];
Marshal.Copy(plainTextBlob.pbData, plainText, 0, plainTextBlob.cbData);
Marshal.FreeHGlobal(plainTextBlob.pbData);
return plainText;
}

private void InitPromptstruct(ref CRYPTPROTECT_PROMPTSTRUCT ps)
{
ps.cbSize = Marshal.SizeOf(typeof(CRYPTPROTECT_PROMPTSTRUCT));
ps.dwPromptFlags = 0;
ps.hwndApp = NullPtr;
ps.szPrompt = null;
}

private unsafe static String GetErrorMessage(int errorCode)
{
int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100;
int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
int messageSize = 255;
String lpMsgBuf = "";
int dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS;
IntPtr ptrlpSource = new IntPtr();
IntPtr prtArguments = new IntPtr();
int retVal = FormatMessage(dwFlags, ref ptrlpSource, errorCode, 0,
ref lpMsgBuf, messageSize,
&prtArguments);
if (0 == retVal)
{
throw new Exception("Failed to format message for error code " +
errorCode + ". ");
}
return lpMsgBuf;
}
}
}



and the wrapper to make things easier

/*
Author: Jayson Ragasa | aka: Nullstring
Application Developer - Anomalist Designs LLC
*
* --
* Made a wrapper for DataProtector so I could
* Encrypt/Decrypt valid password for RDP
*
* TAKE NOTE:
* This can't Decrypt MSTSC Password!
*/
using System;
using System.Collections.Generic;
using System.Text;

namespace DataProtection
{
public class DataProtectionForRDPWrapper
{
static DataProtection.DataProtector dp = new DataProtector(DataProtector.Store.USE_MACHINE_STORE);

public static string Encrypt(string text_password)
{
byte[] e = dp.Encrypt(GetBytes(text_password), null, "psw");
return GetHex(e);
}

public static string Decrypt(string enc_password)
{
byte[] b = ToByteArray(enc_password);
byte[] d = dp.Decrypt(b, null, "psw");
return GetString(d);
}

static byte[] GetBytes(string text)
{
return UnicodeEncoding.Unicode.GetBytes(text);
}

static string GetString(byte[] byt)
{
System.Text.Encoding enc = System.Text.Encoding.Unicode;
return enc.GetString(byt);
}

static string GetHex(byte[] byt_text)
{
string ret = string.Empty;

for (int i = 0; i < byt_text.Length; i++)
{
ret += Convert.ToString(byt_text[i], 16).PadLeft(2, '0').ToUpper();
}

return ret;
}

static byte[] ToByteArray(String HexString)
{
try
{
int NumberChars = HexString.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
{
bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
}
return bytes;
}
catch (Exception ex)
{
throw new Exception("Problem converting Hex to Bytes", ex);
}
}
}
}

Multi Remote Desktop Client .NET - Stable

Contents Moved Here

Multi Remote Desktop Client .NET (Open Source)

Contents Moved Here

Start Menu Cleaner for Windows XP

Start Menu Cleaner for Windows XP is a small utility that scans all dead shortcuts and empty folders on your Programs in Start menu.

Hope am not late for this since everyone is switching to Vista. But anyway, I came across with a problem again (I'm a "When there's a problem, I make the solution" guy) where I used a tool to manage my programs in start menu, and I organize them the way I can easily open them (e.g. my Visual Studio and other Software development program are in Developer Tools folder) instead of having my programs scattered or sorted and viewed on a 2 or more columns of installed programs.. Yuck! That's a great tool by the way ... BUT!!

Talk about CONS from that tool.. Since I managed them so perfect, the problem sets in when I started to uninstall lots of my unused applications. Why what is that? You could guess ... DEAD SHORTCUT LINKS! Their Uninstaller leave a dead shortcut files in my start menu, because the uninstaller didn't found them and just leaved it there. Well it's a user's fault ;)

So just to save my time tracking down those dead shortcuts, I wrote small utility, an open source and free for all program.. Since it grows a bit, I also added a feature to scan empty folders.

Here's the screen shot, and I intentionally renamed the target files from those shortcuts for demo since I accidentally deleted them all using that utility I made. I forgot to write the condition where it deletes only the checked items .. but don't worry, that was already fixed ;)
start program cleaner 
Hope this could help someone too. :D

Enjoy! Sorry guys, no release for Vista yet since I still use Windows XP in my laptop. Planning to install Vista Ultimate on Virtual PC

Download the latest release in CodePlex > http://startmenucleanerxp.codeplex.com/
Download the latest source code > http://startmenucleanerxp.codeplex.com/SourceControl/ListDownloadableCommits.aspx

Code For Today: Textbox Required Field Wrapper in Windows Forms

Now most of the time when developing a Windows Forms applications. These important text boxes can be so .. a little bit of .. a lot of work .. specially when checking if the required fields(textbox) (e.g. First Name, Last Name, etc ..., Address, or whatever).

We HAVE to check if the user entered a value on those required fields. Now we probably use a possible shortest method or just check them one by one (that could be really painfull :P and it's ugly).

Now even in Windows Forms .NET, they don't provide any special controls or methods for us. So that's why I created my own wrapper for that and it is called TextboxRequiredWrapper

Here's the code:

/*
Author: Jayzon Ragasa | aka: Nullstring
Application Developer - Anomalist Designs LLC

* --
* TextboxRequiredWrapper 1.0
* --

*/
using System;
using System.Collections.Generic;
using System.Text;

namespace RemoteDesktopClient
{
using System.Windows.Forms;

public class TextboxRequiredWrapper
{
TextBox[] _textbox;
string reqFieldMessage = "This field is required";

public TextboxRequiredWrapper()
{
}

public void AddRange(TextBox[] textbox)
{
this._textbox = textbox;

foreach (TextBox tbox in this._textbox)
{
if (tbox.Text == string.Empty)
{
tbox.Text = reqFieldMessage;
tbox.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
}

tbox.LostFocus += new EventHandler(tbox_LostFocus);
tbox.GotFocus += new EventHandler(tbox_GotFocus);
tbox.TextChanged += new EventHandler(tbox_TextChanged);
}
}

void tbox_TextChanged(object sender, EventArgs e)
{
TextBox tbox = (TextBox)sender;

if (tbox.Text != reqFieldMessage)
{
tbox.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
}
}

void tbox_LostFocus(object sender, EventArgs e)
{
TextBox tbox = (TextBox)sender;

if (tbox.Text == string.Empty)
{
tbox.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
tbox.Text = reqFieldMessage;
}
}

void tbox_GotFocus(object sender, EventArgs e)
{
TextBox tbox = (TextBox)sender;

if (tbox.Text == reqFieldMessage)
{
tbox.Text = string.Empty;
}
}

public bool isAllFieldSet()
{
bool ret = true;

foreach (TextBox tbox in this._textbox)
{
if (tbox.Text == reqFieldMessage)
{
ret = false;
break;
}
}

return ret;
}
}
}


How to use it? Simple!!
TextboxRequiredWrapper trw = new TextboxRequiredWrapper();
trw.AddRange(new TextBox[] {
txServername,
txComputer,
txUsername,
txDescription
});


And here's the code to check if these textboxes has a user input value:
if (!trw.isAllFieldSet())
{
MessageBox.Show("One of the required field is empty", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}


and my last post Multi Remote Desktop Client .NET using that wrapper.

Here's the preview:

textboxwrapper

Cheers! beer