Code Repo    |     RSS
MD's Technical Sharing



Saturday, January 31, 2009

Retrieve all current IP addresses of the machine

For i As Integer = 0 To IPEntry.AddressList.Length - 1
Try
Dim thisEntry As IPAddress = IPEntry.AddressList(i)
If thisEntry.AddressFamily = Sockets.AddressFamily.InterNetwork Then
Debug.WriteLine(thisEntry.ToString + " " + thisEntry.AddressFamily.ToString)
End If
Catch ex As Exception
Debug.WriteLine("Error: " + ex.Message)
End Try
Next

Read More »

Thursday, January 29, 2009

XML Serializable Dictionary in .NET

For some reason, the generic Dictionary in .NET 2.0 is not XML serializable. The following code snippet is a XML serializable generic dictionary. The dictionary is serializable by implementing the IXmlSerializable interface.

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

[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue>
: Dictionary<TKey, TValue>, IXmlSerializable
{
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}

public void ReadXml(System.Xml.XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

bool wasEmpty = reader.IsEmptyElement;
reader.Read();

if (wasEmpty)
return;

while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
reader.ReadStartElement("item");

reader.ReadStartElement("key");
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();

reader.ReadStartElement("value");
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();

this.Add(key, value);

reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}

public void WriteXml(System.Xml.XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));

foreach (TKey key in this.Keys)
{
writer.WriteStartElement("item");

writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();

writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();

writer.WriteEndElement();
}
}
#endregion
}

Another convenient way around it is to use a .NET class called KeyedCollection. KeyedCollection derives from the iList interface instead of iDictionary, and is therefore serializable, but also allows you to specify a key. This class is an abstract type, so you must derive your own custom class, but as we’ll see in a second, that’s a snap.

KeyedCollection must be inherited because it has to be a list of a specific object type. Then, instead of specifying your own key value for each item in the list, you indicate which of the object’s fields you want to be used as the key.

Public Class SourceTypeList
Inherits System.Collections.ObjectModel.KeyedCollection(Of Long, SourceType)
Protected Overrides Function GetKeyForItem(ByVal item As SourceType) As Long
Return item.SourceTypeID
End Function
Sub New()
MyBase.New()
End Sub
End Class

What does this code do? It tells Visual Basic to create a new type collection derived from KeyedCollection, where the key is a long integer and the value is an object of type SourceType (SourceType represents information about a type of syndication file, such as Atom 0.3 or RSS 2.0). You then overried the function GetKeyForItem and tell VB which field you want to use as the key.

Reference:
www.myboogpages.com/2006/12/net-dictionary-serialization-problem.html
Read More »

Saturday, January 24, 2009

Show a Listview's context menu at the location of the selected item

Me.ContextMenu1.Show(PointToScreen(New Point(Me.ListView1.FocusedItem.Position.X, Me.ListView1.FocusedItem.Position.Y + Me.ListView1.Location.Y)))


An alternative is to post a WM_RBUTTONDOWN message to the control.

Read More »

Saturday, January 17, 2009

Upload a file to FTP

See: http://msdn.microsoft.com/en-us/library/ms229715.aspx


'upload a file via FTP
'return TRUE if OK, FALSE if error
'subdir: the sub-directory (to be created on the server) to put the uploaded file in
Function UploadFileToFTP(ByVal fileToUpload As String, ByVal FTPHost As String, ByVal FTPUsername As String, ByVal FTPPassword As String, ByVal FTPPassive As Boolean, ByVal subdir As String) As Boolean
Try
If Not FTPHost.EndsWith("/") Then FTPHost += "/"
If Not subdir.EndsWith("/") Then subdir += "/"
Dim request As FtpWebRequest

'create subfolder if requested
If subdir <> String.Empty Then
Try
request =
CType(WebRequest.Create(FTPHost + subdir), FtpWebRequest)
request.Credentials =
New NetworkCredential(FTPUsername, FTPPassword)
request.UsePassive = FTPPassive

request.UseBinary =
True
request.Method = WebRequestMethods.Ftp.MakeDirectory
Dim resp As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)
Catch ex As Exception
'Folder couldn't be created, or already exists
End Try
End If

'now upload the file
request =
CType(WebRequest.Create(FTPHost + subdir + Path.GetFileName(fileToUpload)), FtpWebRequest)
request.UsePassive = FTPPassive
request.UseBinary =
True
request.Method = WebRequestMethods.Ftp.UploadFile
request.Credentials =
New NetworkCredential(FTPUsername, FTPPassword)

Dim myStreamWriter As Stream = request.GetRequestStream()
Dim contentLen As Integer
Dim buffLength As Integer = 2048
Dim buff(buffLength) As Byte

Dim fi As New FileInfo(fileToUpload)
Dim fs As FileStream = fi.OpenRead()
contentLen = fs.Read(buff, 0, buffLength)
While (contentLen <> 0)
myStreamWriter.Write(buff, 0, contentLen)
contentLen = fs.Read(buff, 0, buffLength)
End While

myStreamWriter.Close()

Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
response.Close()
Return True
Catch ex As Exception
Console.WriteLine("ERROR: FTP Upload FAILED - " + ex.Message)
Return False
End Try
End Function

Read More »

Sunday, January 11, 2009

MessageBox with Help button

Showing a four-button message box with the default set to the fourth button:


int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstPrev,
LPSTR lpCmdLine, int nShowCmd)
{
return MessageBox(NULL, TEXT("Four buttons!"), TEXT("Title"), MB_ABORTRETRYIGNORE | MB_HELP | MB_DEFBUTTON4);
}


Clicking on the Help button (MB_HELP) is documented as sending a WM_HELP message to your program. Since there is nothing to catch that message, it does nothing. The other buttons return the ID value of that button, dismissing the message box.


Reference:

msdn.com/oldnewthing/archive/2008/12/19/9239267.aspx

Read More »

Thursday, January 8, 2009

C++ Read/Write files

Write binary data to file


using namespace std;

BYTE* buffer;

ofstream fout("file.dat", ios::binary);

fout.write((char *)(&buffer), sizeof(number));

fout.close();


Reference:

Simple File I/O Using C++, http://www.gamedev.net/reference/articles/article1127.asp


Write text to file

std::ofstream writer;

writer.open(L"file.txt");

if (!writer.is_open()) //Error writing file

{

}

else //open OK, now write file

{

writer << "Hello world";

writer.close();

}


Read from text file by token

std::ifstream inp;

inp.open(L"file.txt", std::ifstream::in);

if (!inp.fail()) //open ok, read text

{

LPCWSTR str = new wchar_t[100];

inp >> str;

inp.close();

}


Open a text file and read it contents into a string

char* readText(char* fileName)

{

std::ifstream infile;

infile.open(fileName, std::ios_base::in|std::ios_base::ate);

if (infile) //read OK

{

//prepare file for input

long file_length = infile.tellg();

infile.seekg(0, std::ios_base::beg);

infile.clear();

//read text file into string

char *str = new char[file_length];

infile.read(str, file_length);

infile.close();

return str;

}

else //read FAILED

{

return NULL;

}

}


Read More »