Saturday, June 6, 2009

Microsoft Surface

I've been working for a week now, with the new Microsoft hardware, Microsoft Surface.

Microsoft Surface, is a multi touch product from Microsoft which is developed as a software and hardware combination technology that allows a user, or multiple users, to manipulate digital content by the use of natural motions, hand gestures, or physical objects.

The Microsoft Surface was used by MSNBC during its coverage of the 2008 US presidential election.

Microsoft Surface is a surface computing platform that responds to natural hand gestures and real world objects. It has a 360-degree user interface, a 30-inch reflective surface with a XGA DLP projector underneath the surface which projects an image onto its underside, while four cameras in the machine's housing record reflections of infrared light from objects and human fingertips on the surface.

The surface is capable of object recognition, object/finger orientation recognition and tracking, and is multi-touch and is multi-user. Users can interact with the machine by touching or dragging their fingertips and objects such as paintbrushes across the screen, pictures or by placing and moving placed objects.

Surface has been optimized to respond to 52 touches at a time.

Using the specially-designed barcode-style "Surface tags" on objects, Microsoft Surface can offer a variety of features, for example automatically offering additional wine choices tailored to the dinner being eaten based on the type of wine set on the Surface, or in conjunction with a password, offering user authentication.

A commercial Microsoft Surface unit is $12,500 (unit only), however Microsoft said it expects prices to drop enough to make consumer versions feasible in 2010.

It's being a good experience. You can program it with WPF, with different objects, for that you have to install the Microsoft Surface SDK.

I'll try to put here some examples, and some source code.

Sunday, May 17, 2009

Optimize C# Code... 2

Optimize C# Code... 2

Code optimization is an important aspect of writing an efficient C# application. The following tips will help you increase the speed and efficiency of your C# code and applications.

1. Use of the operator ?: and ??

The conditional operator ?: returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form:

condition ? first_expression : second_expression;

If condition is true, first expression is evaluated and becomes the result; if false, the second expression is evaluated and becomes the result. Only one of two expressions is ever evaluated.


if(i == 0) str = "Zero" else str = "Non Zero";


using the conditional operator, it will be as follow:


string str = x == 0 ? "Zero" : "Non Zero";


The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types.
It returns the left-hand operand if it is not null; otherwise it returns the right operand.


if (string.IsNullOrEmpty(str))
newstr = "i don't wanna be null"
else
newstr = str;



using the conditional operator, it will be as follow:


string newstr = str ?? "i don't wanna be null";


2. TryParse and Parse
The big difference between TryParse and Parse, is that the first one will return a boolean value, indicating if the conversion was successfull or not, and the second one will give you an exception if the convertion was not possible.


string AreYouADeveloper = "true"

if (bool.TryParse(AreYouADeveloper, out boolValue))
{
MessageBox.Show("welcome developer guy")
}
else
{
MessageBox.Show("You Are Not a Developer")
}



3. Exceptions cause performance to suffer significantly
Since exceptions cause performance to suffer significantly, you should never use them as a way to control normal program flow, so the best way is to write code that avoids exceptions. If it is possible to detect in code a condition that would cause an exception, do so. Do not catch the exception itself before you handle that condition.

4. .Net System.Diagnostics.DebuggerStepThrough Attribute
Sometimes when you are running your code in debug mode, you don't want to stop in some methods, maybe because you already know that this method will always return what you want, because is not so important for the job you have in hands, or some other reasons... That's where the DebuggerStepThrough comes in. The compiler will add the necessary metadata preventing the debugger to step into the method. Even if you have this attribute defined, you can stop in, if you define a breakpoint there.


public string Name
{
[System.Diagnostics.DebuggerStepThrough]
get { return name; }
}

Monday, May 11, 2009

Backup / Restore blogger blog

The world of blogging is growing up very fast. You have a lot to choose when you want to start writing your own blog.
I choose Blogger because it's simple, easy to work and via my gmail account.
But if you want to backup your blog, there is no official tool to do it.

I found on Codeplex a tool to backup a blog, very easy to use and very usefull.

The name of the tool is Blogger Backup.

Check it out now!




Monday, May 4, 2009

Optimize C# Code... 1

Optimize C# Code... 1

Code optimization is an important aspect of writing an efficient C# application. The following tips will help you increase the speed and efficiency of your C# code and applications.

1. Knowing when to use StringBuilder
You must have heard before that a StringBuilder object is much faster at appending strings together than normal string types.
The thing is StringBuilder is faster mostly with big strings. This means if you have a loop that will add to a single string for many iterations then a StringBuilder class is definitely much faster than a string type.
However if you just want to append something to a string a single time then a StringBuilder class is overkill. A simple string type variable in this case improves on resources use and readability of the C# source code.
Simply choosing correctly between StringBuilder objects and string types you can optimize your code.

2. Comparing Non-Case-Sensitive Strings
In an application sometimes it is necessary to compare two string variables, ignoring the cases. The tempting and traditionally approach is to convert both strings to all lower case or all upper case and then compare them, like such:

str1.ToLower() == str2.ToLower()

However repetitively calling the function ToLower() is a bottleneck in performace. By instead using the built-in string.Compare() function you can increase the speed of your applications.
To check if two strings are equal ignoring case would look like this:

string.Compare(str1, str2, true) == 0 //Ignoring cases

The C# string.Compare function returns an integer that is equal to 0 when the two strings are equal.

3. Use string.Empty
This is not so much a performance improvement as it is a readability improvement, but it still counts as code optimization. Try to replace lines like:

if (str == "")

with:

if (str == string.Empty)

This is simply better programming practice and has no negative impact on performance.
Note, there is a popular practice that checking a string's length to be 0 is faster than comparing it to an empty string. While that might have been true once it is no longer a significant performance improvement. Instead stick with string.Empty.

4. Replace ArrayList with List<>
ArrayList are useful when storing multiple types of objects within the same list. However if you are keeping the same type of variables in one ArrayList, you can gain a performance boost by using List<> objects instead.
Take the following ArrayList:

ArrayList intList = new ArrayList();
intList.add(10);
return (int)intList[0] + 20;

Notice it only contains intergers. Using the List<> class is a lot better. To convert it to a typed List, only the variable types need to be changed:

List intList = new List();
intList.add(10)
return intList[0] + 20;

There is no need to cast types with List<>. The performance increase can be especially significant with primitive data types like integers.

5. Use && and || operators
When building if statements, simply make sure to use the double-and notation (&&) and/or the double-or notation (||), (in Visual Basic they are AndAlso and OrElse).
If statements that use & and | must check every part of the statement and then apply the "and" or "or". On the other hand, && and || go thourgh the statements one at a time and stop as soon as the condition has either been met or not met.
Executing less code is always a performace benefit but it also can avoid run-time errors, consider the following C# code:

if (object1 != null && object1.runMethod())

If object1 is null, with the && operator, object1.runMethod()will not execute. If the && operator is replaced with &, object1.runMethod() will run even if object1 is already known to be null, causing an exception.

6. Smart Try-Catch
Try-Catch statements are meant to catch exceptions that are beyond the programmers control, such as connecting to the web or a device for example. Using a try statement to keep code "simple" instead of using if statements to avoid error-prone calls makes code incredibly slower. Restructure your source code to require less try statements.

7. Replace Divisions
C# is relatively slow when it comes to division operations. One alternative is to replace divisions with a multiplication-shift operation to further optimize C#. The article explains in detail how to make the conversion

From Visual C# Kicks

Thursday, April 2, 2009

Freeware tools for Developers.

After my last post, about a tool that I use often, I like to put here a list of tools I use daily in my development environment. I'm a freeware software fan, likewise with good development tools and some gadgets.

Source Control:

Tortoise / Subversion Source Control
A Subversion client, implemented as a windows shell extension. It is really easy to use Revision
control / version control / source control software for Windows. Since it's not integrated with a specific IDE you can use it with whatever
development tools you like. Tortoise SVN is free to use.

Some Visual Studio AddIns:


Regionerate
It’s an open-source tool for developers and team leaders that allows you to automatically apply layout rules (regions) on C# code.

ProfileSharp
It’s an open source .NET code, performance and memory profiling software.
It helps pinpoint performance bottlenecks in .NET code and optimize memory usage.

Source Analysis
Also known as StyleCop, analyzes C# source code to enforce a set of best practice style and consistency rules. The differences between the "Source Analysis style" and the "Framework Design Guidelines style" are relatively minor. One of the biggest differences is that the framework style prefixes private and internal fields with an underscore, while Source Analysis style omits the underscore and instead prefixes all class members with this.

Other Development Applications

MSBuildShellExtension
Lets you build .NET projects without ever opening Visual Studio or the command prompt. MSBuild targets can be executed from your favourite file system tool like Windows Explorer or Total Commander. The possibility to extend MSBuildShellExtension with your own targets and editors, makes it a very flexible and useful tool for all .NET developers.

DebugView
It’s an application that lets you monitor debug output on your local system, or any computer on the network that you can reach via TCP/IP. It’s capable of displaying both kernel-mode and Win32 debug output, so you don't need a debugger to catch the debug output your applications or device drivers generate, nor do you need to modify your applications or drivers to use non-standard debug output APIs.

SOAPSonar
It enables users to perform functional and load testing as well as vulnerability assessment to ensure that the Web Services are reliable and robust before they are deployed.

SQL Server Management Studio
Consistent management across all SQL Server Editions.

Development Documentation

Code Signature Add-In for VST
Put a signature header in every code file (I will talk about this one later ;-) )

GhostDoc Free add-in for Visual Studio

Automatically generates XML documentation comments. Either by using existing documentation inherited from base classes or implemented interfaces, or by deducing comments from name and type of e.g. methods, properties or parameters.

Sandcastle Documentation
Console compiler application for managed class libraries, that will output your comments/documentation from Microsoft. Used for creating MSDN style documentation from .NET assemblies and their associated XML comments files. The current version is the March 2007 CTP. It is command line based and has no GUI front-end, project management features, or automated build process.

Sandcastle Help File Builder
Provide a graphical and command line based tool to build a help file in an automated fashion way.

Htmlhelp or VST SDK (Microsoft HTML HELP Workshop - compiler for .CHM files).


Utilities Applications

PSPad
Freeware programmer's editor for Microsoft Windows operating systems. Works with various programming environments, highlighted syntax in source code, handles plain text, rich text formatting functions and user extension capabilities.

WinMerge Open Source (GPL)
Visual text file differencing and merging tool for Windows. It is highly useful for determine what has changed between project versions, and then merging changes between versions.

Launchy
Free windows utility designed to help you forget about your start menu, the icons on your desktop, and even your file manager. Launchy indexes the programs in your start menu and can launch your documents, project files, folders, and bookmarks with just a few keystrokes.

Unlocker
It’s an explorer extension to delete, rename, move a file that is locked. With a simple right-click of the mouse on a file or folder, get rid of error message such as error deleting file or folder, cannot delete folder: it is used by another person or program.

CopyPath
This simple yet effective application quickly captures the full path of a folder or file and places it on your Clipboard for easy access. CopyPath doesn't have a dedicated interface, but using it is as simple as right-clicking a folder or file.

Junction Link Magic
It’s an utility that lets you create junction points (like symbolic links) with Windows 2000, XP or 2003. There is a beta version for Windows Vista and Server 2008.

PuTTY
It’s a free implementation of Telnet and SSH for Win32 and Unix platforms, along with an xterm terminal emulator.

ZipGenius
Free software for Windows that lets you compress files to almost any kind of archive. Supports more than 20 compressed archive formats, including CD/DVD-ROM image files in ISO9660 standard, including RAR, ARJ, ACE, CAB, SQX, OpenOffice.org documents and the excellent 7-zip. Now can precompress executable files going to be added to a ZIP archive through the UPX compressor.

XMLPad
It’s based on the unique custom-developed XML parser engine designed in accordance with the published W3C standards


I hope you find some usefull. If you have another ones you can advice of, please be my guest, always trying to find and work with better freeware software.

Tuesday, March 31, 2009

DebugView for Windows

DebugView for Windows v4.76

If you are a developer, you will find this tool very useful.
DebugView is an application that lets you monitor debug output on your local system, or any computer on the network that you can reach via TCP/IP. It is capable of displaying both kernel-mode and Win32 debug output, so you don't need a debugger to catch the debug output your applications or device drivers generate, nor do you need to modify your applications or drivers to use non-standard debug output APIs.
To use DebugView in your code, put some trace messages where you want to have some log informations, like

System.Diagnostics.Trace.Write("This is my trace log message");

You need to have the application open to see your messages.

Friday, March 27, 2009

Get emails from Hotmail in Gmail account

Lets get a little bit out of this blog topics, and learn how to config a gmail account to receive your @hotmail or @live account emails.

In your Gmail account, go to Settings and choose the accounts tab.

To config the Gmail to Send mail as:
Click on the blue link "Add another email address you own".
Write your Name and your hotmail ou live email address, in the text boxes.
Gmail will make a verification of the email address you just wrote.
After you've made all the steps to verify that you own this email address.
It's all done.

To config the Gmail to Get mail from other accounts:

Click on the blue link "Add another email address you own".
Write the email address you own. And go to the next step.
In here, you have to fill three text boxes: Username, Password and PopServer.
Fill in the Username with your email address, like me@hotmail.com.
Fill the password for this account.
In the PopServer box write pop3.live.com in Port 995.
Check the box "Always use a secure connection (SSL) when retrieving mail".
If you want, label it, so you know when the emails arrived from hotmail.

That's it, it's all setup and running.
Now you can receive and send messages like if you were on the hotmail page.

Hope you find this usefull.

Wednesday, March 11, 2009

Create a MS SQL link to MySQL database

To create a MS SQL link to MySQL database, first be sure to install the MySQL ODBC Connector from here: http://dev.mysql.com/downloads/connector/

Create a new System DNS for the MySQL Database on the ODBC Data Source Administrator from the Control Panel | Administrative Tools

To establish a link to the MySQL database from the Microsoft SQL Server Management Studio, open a query window and run the following SQL statement:

EXEC master.dbo.sp_addlinkedserver
@server = N'MYSQL',
@srvproduct=N'MySQL',
@provider=N'MSDASQL',
@provstr=N'DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=; USER=root; PASSWORD=; OPTION=3'


This script will produce a link to the MySQL database through the ODBC connection.




Wednesday, March 4, 2009

Installing mySql on ubuntu

To install mySql on ubuntu, type the following command on the terminal window
sudo apt-get install mysql-server
To create a new database, type the following mysqladmin command:

mysqladmin create -uroot -p

If you are running PHP you will have to install the php module:
sudo apt-get install php5-mysql

If you want to give Root user logon permissions from any host computer on the network, you will need to update the mysql user table, using the % wildcard. Type the command on the terminal to open the command-line mysql client on the server using the root account.
mysql -uroot -p

to see what the root user host has permissions for, type,
use mysql;
select host, user from user;

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select host, user from user;
+-------------+--------------------------+
| host | user |
+-------------+--------------------------+
| 127.0.0.1 | root |
| localhost| |
| localhost| debian-sys-maint |
| localhost| root |
| ubuntu | |
| ubuntu | root |
+-------------+--------------------------+
6 rows in set (0.00 sec)

to update the ubuntu host to use the wildcard, and then issue the command to reload the privilege tables, type,
mysql> update user set host='%' where user='root' and host='ubuntu';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

Now its possible to connect to the server from any other computer on the network, using the root user account. Doing this has some secure issues, beware to set a password for the root user accont.



Thursday, January 29, 2009

.Net Application Single Instance

If you want to ensure that your application only runs one instance at a time, the best method is to use a Mutex.

Mutex: Short for mutual exclusion object. In computer programming, a mutex is a program object that allows multiple program threads to share the same resource, such as file access, but not simultaneously. When a program is started, a mutex is created with a unique name. After this stage, any thread that needs the resource must lock the mutex from other threads while it is using the resource. The mutex is set to unlock when the data is no longer needed or the routine is finished.

On your program.cs unit, do the following:

  
static class Program
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
bool createdMutex = false;
Process currentProcess = Process.GetCurrentProcess();

Mutex mutex = new System.Threading.Mutex(true,
currentProcess.ProcessName + currentProcess.MachineName + " Mutex", out createdMutex);

if (createdMutex)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());

GC.KeepAlive(mutex);
}
else
{
// Application to topmost window
foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))
{
if (process.Id != currentProcess.Id)
{
SetForegroundWindow(process.MainWindowHandle);
break;
}
}
}
}
}

Tuesday, January 20, 2009

Exception of type 'System.ComponentModel.Design.ExceptionCollection' was thrown

Sometimes I get the message "Exception of type 'System.ComponentModel.Design.ExceptionCollection' was thrown" When trying to open a Form in designer view.
The real problem of the "ExceptionCollection" being thrown is that when there is a WSOD (White Screen of Darn) indicating a designer load issue, the designer gets unloaded. These get caught by the unload method and get displayed in the dialog box you see.
So, to fix this you should:
* Attach a visual studio debugger to VS. Turn on exception catching when first thrown (in the Debug|Exceptions menu).
* Open the designer with the debugger attached
* Determine what component is throwing the exception.

Sometimes you cannot open the form design view because of a missing resource file or an invalid reference in the design code unit.

Thursday, January 8, 2009

Enable remote connection to SQL Server 2005 Express

How many times did you had the following error on SQL Server 2005 Express, "An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connection". Check this post on Linglom’s blog and a step by step solution for the problem.

Another solution is to go to SQL Server Configuration Manager on Microsoft SQL Server 2005 folder at Start menu, under Configuration Tools. Select SQL Server 2005 Services, and change the State and Start Mode of SQL Server Browser item to Running and Automatic.

Hopefully it will solve your problem ;-)