venerdì 19 dicembre 2008

iPhoneUI on msdn

Now you can find my iPhoneUI (codeproject article) on the msdn.
here[^], take a look.

iPhoneUI on codeplex

Many thanks to dkackman that add my iPhone UI to codeplex.
He put a modified version up on codeplex and begins a fascinating trip into it.
You can find it directly here: http://www.codeplex.com/iPhoneUI/[^] take a look.

lunedì 15 dicembre 2008

OfficeServ Unico is out

OfficeServ Unico is one of my last work on mobile.
TELCEN (my company) prepared for Samsung a commercial software that turns smartphone into a single terminal capable of handling all types of communications, GSM-UMTS-HSDPA and VoIP.

I'll add the direct link to Samsung, where you can see the product, here[^].

sabato 13 dicembre 2008

martedì 9 dicembre 2008

String & P/Invoke with C#

Sometime I hear about c# problem with the P/Invoke and string.
Here I add a very simple usage of it, it describe C++ CString and c# String.

1. SetWindowText
First I begin with a sample really simple. How to set a string of a dialog. I invoke the SetWindowTextW.
You can define this for mobile app
[DllImport ("coredll.dll", EntryPoint="SetWindowTextW")]
private static extern void SetWindowText(IntPtr hWnd, string lpString);
You can define this for desktop app
[DllImport("user32.dll"), EntryPoint="SetWindowTextW")]
private static extern bool SetWindowText(IntPtr hWnd, string lpString);

Call the function with this code snippet
public bool SetText(IntPtr hWnd, String text)
{
System.text.StringBuilder NewWindowText = new System.text.StringBuilder(text);
return (SetWindowText(hWnd, NewWindowText) != 0);
}
GetWindowText
The second example is one that creates more problems. The fault probably is derived from the fact that many people use the String for these conversions instead of the StringBuild. To do this I need two P/Invoke the first for retrieve the lenght the second to retrieve the text.

You can define this for mobile app
[DllImport("coredll.dll", CharSet = CharSet.Auto, SetLastError = true), EntryPoint="GetWindowTextW")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("coredll.dll", SetLastError = true, EntryPoint="GetWindowTextLength")]
static extern int GetWindowTextLength(IntPtr hWnd);

You can define this for desktop app
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true), EntryPoint="GetWindowTextW")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true, EntryPoint="GetWindowTextLength")]
static extern int GetWindowTextLength(IntPtr hWnd);
Call the function with this code snippet
public string GetText(IntPtr hWnd)
{
int length = GetWindowTextLength(hWnd);
StringBuilder TheWindowText = new StringBuilder(length + 1);
GetWindowText(hWnd, TheWindowText, TheWindowText.Capacity);
return TheWindowText.ToString();
}
If anybody knows any more graceful solution, I'd like to know it.
I hope my suggestions are useful to someone.

martedì 2 dicembre 2008

Simple event logging

With this class your application can write in the event log.
The class use the
System.Diagnostics to write the message into the Event log.

using System.Diagnostics;

public class Logging

{

static string Source = "My Application";

public static void WriteEventLog(string Message, System.Diagnostics.EventLogEntryType EntryType)

{

try

{

if (!EventLog.SourceExists(Source))

{

EventLog.CreateEventSource(Source, "Application");

}

EventLog.WriteEntry(Source, Message, EntryType);

}

catch(Exception ex)

{

System.Diagnostics.Debug.WriteLine(ex.Message);

}

}

}


Usage:

Logging.WriteEventLog(System.Diagnostics.EventLogEntryType.Information,"Message Error");

martedì 25 novembre 2008

File attributes with C#

The class I've posted shows how to use the fiel attributes with c#.
To get file attributes (in .Net) you need more steps, with this class you have immediatly all you need.
I covered the 4 standard attribute but you can extend the class with other attributes. The file is .called FileAttributeEx.cs and this it the code.

using
System;
using System.IO;

namespace FileAttributeEx
{
class FileAttributesEx
{
private string filepath = string.Empty;

public string FilePath
{
get { return filepath; }
set { filepath = value;}
}

public FileAttributesEx() { }
public FileAttributesEx(string path)
{
FilePath = path;
}

public bool isReadOnly ()
{
return (File.GetAttributes(FilePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
}

public bool isHidden()
{
return (File.GetAttributes(FilePath) & FileAttributes.Hidden) == FileAttributes.Hidden;
}

public bool isArchive()
{
return (
File.GetAttributes(FilePath) & FileAttributes.Archive) == FileAttributes.Archive;
}

public bool isSystem()
{
return (File.GetAttributes(FilePath) & FileAttributes.System) == FileAttributes.System;
}

public void AddSystem()
{
File.SetAttributes(FilePath, File.GetAttributes(FilePath) | FileAttributes.System);
}

public void AddReadOnly()
{
File.SetAttributes(FilePath, File.GetAttributes(FilePath) | FileAttributes.ReadOnly);
}

public void AddHidden()
{
File.SetAttributes(FilePath, File.GetAttributes(FilePath) | FileAttributes.Hidden);
}

public void AddArchive()
{
File.SetAttributes(FilePath, File.GetAttributes(FilePath) | FileAttributes.Archive);
}

public void Clear()
{
File.SetAttributes(filepath, File.GetAttributes(filepath)
& ~(FileAttributes.Archive |
FileAttributes.ReadOnly| FileAttributes.System|FileAttributes.Hidden));
}
}
}

To use it in your project simply, add the file to your project, add a new instance of it and call the metods you need.
Here a sample:

FileAttributesEx fileAttr = new FileAttributesEx(sFileName);

if (fileAttr.isArchive())
//Do something
if (fileAttr.isHidden())
//Do something

fileAttr.Clear();

fileAttr.AddReadOnly();

Have fun.

venerdì 14 novembre 2008

How to convert string to byte array and viceversa

The way to convert a string to byte array are a lot. Here I show you one I use over all, UnicodeEncoding.
Sample:

char[] arrUnicodeSample = new char[] { '\uAAAA', '\uBBBB', '\uCCCC', '\uDFFF' };
string strUnicode = new string(arrUnicodeSample);

{
UnicodeEncoding encUnicode = new UnicodeEncoding ();
byte[] encodedBytes = encUnicode.GetBytes(strUnicode);
String decodedString = encUnicode.GetString(encodedBytes, 0, encodedBytes.Length);
}

You can also use:
  • Encoding
  • ASCIIEncoding
  • UnicodeEncoding
and Decoder to come back.

giovedì 13 novembre 2008

My new article on Code Project: Mobile TouchPad

Finally I've found some free time to write a full article.
The article describe how to write a mobile program and show you how it's simple. In particular Mobile TouchPad lets you control your PC through your touch pad phones.
MobileTouchPad[^]
Have fun.

martedì 4 novembre 2008

How to convert class/struct to a byte array

With this class you can easy convert your class/struct to a byte array.
Very useful when using the socket.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

class CommonConvertion
{
public static byte[] StructureToByteArray(object obj)
{
int Length = Marshal.SizeOf(obj);
byte[] bytearray = new byte[Length];
IntPtr ptr = Marshal.AllocHGlobal(Length);
Marshal.StructureToPtr(obj, ptr, false);
Marshal.Copy(ptr, bytearray, 0, Length);
Marshal.FreeHGlobal(ptr);
return bytearray;
}

public static void ByteArrayToStructure(byte[] bytearray, ref object obj)
{
int Length = Marshal.SizeOf(obj);
IntPtr ptr = Marshal.AllocHGlobal(Length);
Marshal.Copy(bytearray, 0, ptr, Length);
obj = Marshal.PtrToStructure(ptr, obj.GetType());
Marshal.FreeHGlobal(ptr);
}
}

Have fun.

Windows Mouse Control

With this class you can easy control the mouse from c#. For the click event it's use the P/Invoke of mouse_event API. To move the cursor positon use directly the managed code.
(Only for x86.)

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace MouseMov
{
public class MouseHook
{
[DllImport("user32.dll")]
private static extern void mouse_event(UInt32 dwFlags, UInt32 dx, UInt32 dy, UInt32 dwData, IntPtr dwExtraInfo);
private const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;
private const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;

internal static void SendDoubleClick()
{
SendClick();
SendClick();
}

internal static void SendClick()
{
SendDown();
SendUp();
}

internal static void SendUp()
{
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, new System.IntPtr());
}
private void MoveMouse(Point p)
{
Cursor.Position = new Point(Cursor.Position.X + p.X, Cursor.Position.Y + p.Y);
}


internal static void SendDown()
{
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, new System.IntPtr());
}
}
}

Have fun.

martedì 30 settembre 2008

CSharp NumericTextBox control

I've post here a simple custom control that it accepts only numeric input.
The only one methods in the OnKeyPress (overrided) and accept only digit or the backspace
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

using DrLuiji.Controls
{
public class NumericTextBox : TextBox
{
protected
override void OnKeyPress(KeyPressEventArgs e)
{
base.OnKeyPress(e);
if (!((Char.IsDigit(e.KeyChar))||(e.KeyChar.Equals('\b'))))
{
e.Handled = true;
ErrorBeep();
}
}
public void ErrorBeep()
{
//Console.Beep();
}
}
}

To use it you just drag & drop the control from the toolbox to your form.

Have fun.

lunedì 22 settembre 2008

Retrieve system folder c#

Here you can find a way to retrieve the system folder.
Very simple, call the System.Environment.GetFolderPath with the corrisponding enum System.Environment.SpecialFolder.See the sample below.

private string GetSystemSpecialFolderDirectory()
{
//Program files
string sProgramFilesFolder = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ProgramFiles);

//Personal
string sPersonalFolder = System.Environment.GetFolderPath (
System.Environment.SpecialFolder.Personal);

//Desktop
string sDesktopFolder = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.DesktopDirectory);

//Application Data
string sApplicationDataFolder = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ApplicationData);

//System:
string sSystemFolder = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.System);


MessageBox.Show("Program files: " + sProgramFilesFolder +
"\r\nPersonal: " + sPersonalFolder +
"\r\nDesktop: " + sDesktopFolder +
"\r\nApplication Data: " + sApplicationDataFolder +
"\r\nSystem: " + sSystemFolder);
}

Very simple isn't it ?

venerdì 29 agosto 2008

NSIS and MFC dependency

Hi all, I've post here a way wich NSIS can support an automatic distribution for the MFC ( in my case v8). You can use the Clickonce part with other installer e.g. Inno Setup.

Introduction
The NSIS not support an automatic distribution for the MFC program . This post solve this problem.

Backgroung
First of all I use Visual Studio 2005 to deploy my MCF application and I use NSIS installer to redistribute it. The SO target are Windows Xp and Vista.

I solve the problem in a very easy way.
I build a ClickOnce setup on my solution, and i use it in silent mode inside the NSIS.

Info: I use the ClickOnce to install all the redistributable file instead vcredist_x86.exe becouse with the vcredist_x86.exe you need other istructions, like register some files.
With my solution after install it the program is ready to use.

The step needed are 2
1 Create the ClickOnce setup and modify it a bit.
2 Add it to NSIS

1 ClickOnce
Create the ClickOnce setup on your solution. Simply I add a new project to my solution I use the Setup Wizard Project inside Other Project Types. I follow the steps needed and I only add the primary output to the output group at step 3 (Figure 1).
Figure 1

I've left all the other page as default. At the end the result solution is like this (Figure 2).
Figure 2

Now I don't need to distribute the the primary output, and I exclude it (Figure 3), Unfortunatly this not avoid the creation of installation dir.
Figure 3

I don't install anything else, and I don' need the default location for the app. I haven't find a way to delete this key but a way to change it to an existing one, i choose the root, so to do that i change in the File sistem editor the property of the application folder to c:\ (Figure 4) you can change it with %TEMP% or %APPDATA% or what you want.
Figure 4

The last step is to delete all the page inside the wizard. Go to the UI editor (Figure 5)
Figure 5

and delete all the page (Figure 6) .
Figure 6

2 NSIS
Silent mode:
Now you have the installation ready but the progress bar before the start of the installation still appears. To hide that dialog I use the msiexec comman. For the Installation command :'msiexec /quiet /i MicrosoftMFC8Runtime.msi'.For the unistall command 'msiexec /quiet /x MicrosoftMFC8Runtime.msi'
Adding the command line to NSIS
:
The process is very simple. I need to copy the file MicrosoftMFC8Runtime.msi and execute it waiting the installer til the installer finish, after i Delete it.
Section MFCRUNTIME
SetOutPath "$INSTDIR"
File "MicrosoftMFC8Runtime.msi" "Step 1 Install Microsoft MFC8 Runtime"
ExecWait "msiexec /quiet /i MicrosoftMFC8Runtime.msi"
"Step 2 Install Microsoft MFC 8 Runtime"
delete
"MicrosoftMFC8Runtime.msi" #Step 3 Install Microsoft MFC 8 Runtime"
SectionEnd
For the uninstall section you only need to uninstall the MicrosoftMFC8Runtime like you can do in the Add/Remove program. You can do this with the right GUID of MicrosoftMFC8Runtime.
The Guid is the
'ProductCode' In your ClickOnceSetup, is a property value.

In my case I need only this line for unistall it
Section unMFCRUNTIME
ExecWait "msiexec /quiet /i{843A5D8A-2FD3-4E51-AFBA-A1551D8F41B9}"
SectionEnd

Well now compile your NSIS file and try it.

Conclusion
I've try it under few Windows Vista and a lot of Windows Xp without problem.
Have fun.
Let me know if you have any problems regarding this short tutorial.
Kind regards.

giovedì 7 agosto 2008

Convert string to Hex

A chunk of code how to convert string (unicode or not) to long Hexadecimal (base-16)

CString sUnicode = _T("A123F");

CStringA sASCII(sUnicode);
char * pNotConverted=NULL;
long lHex = strtol (sASCII.operator LPCSTR(),&pNotConverted,16);
if(strlen(pNotConverted)>0)
return false;

  • For unicode directly without conversion use wcstol the wide-character version
  • For better range (__int64) use _strtoi64 or _wcstoi64
Remarks

Remember the long limits

Type Name

Bytes

Range of Values

long4–2,147,483,648 to 2,147,483,647
__int648–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807










sabato 2 agosto 2008

Creating Vista Gadgets



This is my first book review on amazon, take a look here[^].

New blog style

Before it begins, my presonally arrange (a little bit) to this blog.
Hope you like it.

giovedì 31 luglio 2008

Hello The Code Is Art!

A blog about c and c# coding and some tips and triks found during the programming.