Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, November 16, 2009

[.NET] How to swallow warnings

Well aware this is against all best practices, here's how you suppress all warnings coming from a given region of code:

#pragma warning disable

//All the warnings in here are swallowed!

#pragma warning restore

This is way beyond cool - and might help you out when you can't change your code but you're being hovered by a frustrating policy of ZERO WARNING TOLERANCE.

Go forth and get it done.

Sunday, November 1, 2009

[.NET] How to bring window upfront

The stuff on this post can be easily integrated with a previous post:
How to Check if App is Already Running.

In order to bring a window upfront you need to mess with win32 API calls - no easy way around (if you know any please give me a shout). Here's how to import the calls we'll be using:
//Win32 API calls to raise a given processs main window
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);

private const int SW_RESTORE = 9;
Here's a static method to bring a Window upfront in a given winApp (can be easily integrated with the previous post linked above):
static class Program
{

// all the rest of the stuff ... Main other methods etc.

public static void BringOnFront()
{
Process myProcess = Process.GetCurrentProcess();

string myAsseblyName = Assembly.GetExecutingAssembly().GetName().Name;

foreach (Process processId in Process.GetProcessesByName(myAsseblyName))
{
if (myProcess.Id != processId.Id)
{
IntPtr hWnd = processId.MainWindowHandle;

if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, SW_RESTORE);
}

SetForegroundWindow(hWnd);

break;
}
}
}


}
That'd be all - knock yourself out (tested on a number of XP and Vista machines).

Sunday, October 25, 2009

[.NET] How to check if app is already running

Here's a quick and dirty snippet (and sample usage) to check if your app is already running (using a Mutex).
static class Program
{
private static Mutex mutex;

public static bool IsThisProcessAlreadyRunning()
{
bool createdNew;
mutex = new Mutex(false, Application.ProductName, out createdNew);
return !createdNew;
}


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

[STAThread]
static void Main()
{
if (!IsThisProcessAlreadyRunning())
{
// whatever you might be doing
// here's some default form initialization
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
// do something!
// usually smt like --> BringOnFront();
}
}

}
Bringing the app to the foreground is usually what you'll want to do next in scenarios like this. A post about that might follow soon enough.

Side note - if you're using VB.NET I believe there is a check-box you can tick under application properties somewhere that does the job. I'll avoid making jokes about VB.NET 'cause life is tough enough for the suckers who use it without me being a jerk.

EDIT: 2009-11-01 --> posted How to Bring Window Upfront

Saturday, March 28, 2009

Typing Monkeys and Genetic Algorithms

Recently I spent time playing with generic algorithms. I was looking for something easy enough to implement (read: PLAIN LAZY) and I found the Hello World! (literally) of genetic algorithms.

Gathering the algorithm itself from the C++ example (in the link above), I re-designed and re-coded the whole thing in C#.

TypingMonkey is a very simple application which uses a number (defined by the user) of random strings to evolve the user input text.

From the screen-shot below you can see how it took the algorithm 87 generations to evolve the string ".NET Butchering" from an initial population of 2500 random 15-characters strings:



Why "typing monkey"? Inspired by the Infinite Monkey Theorem, I am pretending our population of random string is generated by a typing monkey:

/// The Typing monkey generates random strings - can't be static 'cause it's a monkey.
/// If you wait long enough it will eventually produce Shakespeare.
class TypingMonkey
{
private const string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.";

static Random random = new Random();

/// The Typing Monkey Generates a random string with the given length.
public string TypeAway(int size)
{
StringBuilder builder = new StringBuilder();
char ch;

for (int i = 0; i < size; i++)
{
ch = legalCharacters[random.Next(0, legalCharacters.Length)];
builder.Append(ch);
}

return builder.ToString();
}
}

You can find the source code here: http://github.com/JohnIdol/typingmonkey/tree/master

Feel free to contribute or despise.

Thursday, January 22, 2009

[C#, C++] Cascading Constructors

In C# you can call a constructor of your class from another constructor of the same class to do something like this:

class Cake
{
private string name;
private int price;

public Cake(int price, string cakeName)
{
this.name = cakeName;
this.price = price;
//init stuff
}

public Cake(int price):this(price, "Cheesecake")
{
//init other stuff
}
}

Unfortunately there's no way to do this in good old C++, but there are two common ways for simulating a similar behavior:

1) Combine two (or more) constructors via default/optional parameters:

class Cake
{
private:
string name;
int price;

public:
//combines Cake() and Cake("whatever")
Cake(int price, string name = "Cheesecake Giovacchia")
{
this->name = name;
this->price = price;
}
}

2) Use an Init method to share common code:

class Cake
{
private:
int price;
string name;

init(int price, string name)
{
//do crazy common stuff with price and name
}

public:
Cake(int price)
{
this->init(price, "Cheesecake Giovacchia");
}

Cake(int price, string cakeName)
{
this->init(price, cakeName);
}

}

That's about it, I prefer the first solution (the second kinda sucks) but if anyone knows better I am all ears.

I am done sucking for today.

Wednesday, December 3, 2008

[.NET] How to sort DataTable

There's no way to automatically sort a DataTable after it's populated.

A way around this is to sort the DefaultView of the DataTable (or any other DataView associated with the DataTable).

You can achieve this using the Sort property of the DataView. This is a string which specifies the column (or columns) to sort on, and the order (ASC or DESC).

myDataTable.DefaultView.Sort = "myColumnOfChoice DESC";

The DefaultView can now be used as datasource for stuff or to do whatever you need it for.

Wednesday, October 15, 2008

[.NET] Why are Exceptions not Checked in C#?

Going from Java to C#, I've been stunned by the absence of  the "throws" clause in the declaration of a method, in which you want to throw a particular exception.
Actually it hasn't caused me so much pain, but the knowledge at compile time of the possibility that an exception could be thrown sounded very useful to me.
Asking to the StackOverflow community, I found out Java is one of the few programming languages where exceptions are "caught" at compile time.
The philosophy behind C# is that what is useful about exceptions is not handling them, but mostly cleaning resources, implementing the IDisposable pattern (The trouble with Checked expcetions).
If you know that a particular method can throw an exception, you also know what it does and how to handle it, otherwise you will handle a generic exception, without need to specify it at compile time; moreover handling exceptions is something that comes near the caller of a method reather than the method itself, so there is no need to specify a chain of "throws" declarations, and that is so useful in versioning, because adding a new exception (or removing an old one) doesn't require a refactoring of your lib.
It is worth noting that C# supports the <exception> tag in the documentation section, with which the compiler informs you that an exception (whose type is anyway checked for existence) can be thrown, without any further constraints.
If you have other issues or different opinions I'd like to hear them.

Good butchering!

Thursday, October 2, 2008

[.NET] How to Programmatically Create and Access Custom ConfigurationSections

.NET app.config and web.config are powerful instruments to store simple key value pairs and connections strings.When you need to store config data in some specific format and key value pairs are not enough you can use Custom Configuration Sections as they are not complex to use (unless you need a fairly complex section):

1) Define your custom section:

public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("LastName", IsRequired = true,DefaultValue = "TEST")]
public String LastName
{
get { return (String)base["LastName"]; }
set { base["LastName"] = value; }
}

[ConfigurationProperty("FirstName", IsRequired = true, DefaultValue = "TEST")]
public String FirstName
{
get { return (String)base["FirstName"]; }
set { base["FirstName"] = value; }
}

public CustomSection()
{

}
}



2) Programmatically create your section (if it doesn't already exist):

// Create a custom section.
static void CreateSection()
{
try
{

CustomSection customSection;
// Get the current configuration file.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(@"ConfigurationTest.exe");

// Create the section entry
// and the
// related target section
if (config.Sections["CustomSection"] == null)
{
customSection = new CustomSection();
config.Sections.Add("CustomSection", customSection);
customSection.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);
}
}
catch (ConfigurationErrorsException err)
{
//manage exception - give feedback or whatever
}

}



Following CustomSection definition and actual CustomSection will be created for you:

<configuration>
<configsections>
<section name="CustomSection" type="ConfigurationTest.CustomSection, ConfigurationTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowlocation="true" allowdefinition="Everywhere" allowexedefinition="MachineToApplication" overridemodedefault="Allow" restartonexternalchanges="true" requirepermission="true">
</section>
</configsections>
<customsection lastname="TEST" firstname="TEST">
</customsection>
</configuration>


3) Now Retrieve your section properties:

CustomSection section=(CustomSection)ConfigurationManager.GetSection("CustomSection");
string lastName = section.LastName;
string firstName = section.FirstName;


This is all good stuff - nice and easy as you can see.

P.S. This post orginally appeared on this  StackOverflow link, but since I wrote it I thought it would do no harm to recycle my own rubbish here.


kick it on DotNetKicks.com

Sunday, September 21, 2008

[.NET vs Java] Event Handling: Are you sure pure OOP is always the simplest?


After a long time I'm again here for another post!
I will talk about event handling, focusing at first on .NET way to supply it, and then spending 2 words about the Java style.
What I want to talk about is delegates and how are they used...I know old good Giovacchia has already spoken about them in a previous post (here) but I wanna talk about them again.
Why?
I'm leaving for a while the Java world and walking through the .NET Framework (I have to take some Microsoft Certifications, 2 or maybe 3 exams in just 1 month and a half...sounds crazy but it's my task in the short term): this means I have to study, as for now, 2 book of about 1000 pages each one.
I'm not taking part in the war between Open Source Multi Platforms Java Conding and Mama Microsoft Windows-Platform Framework yet, but in this path toward the MS certifications I will try to catch what's good and what's not in both frameworks.
At a first sight (I'm about at the half of the first book) 2 years of experience in Java programming has helped me a lot, but I stopped a while learning about delegates.
I don't want to explain what actually they are (Giovacchia in his post said it perfectly), let's just say delegates are a kind of function pointers, and you have to subscribe a delegate to a particular event in order to make it running when that event is raised.
Because my memory is so short term (could it be Google's fault?), during the reading I made a simple schema to remember which key words to use when declaring a delegate and rasing your own event.


namespace HereIsMyDelegateNamespace{
. . .

public delegate void MyEventHandler(object o, System.EventArgs ev);

. . .

public class MyClass{
. . .
public event MyEventHandler MyEvent;
. . .

/* this method raises an event */
publlic ReturnType RaisingMethod()
{
System.EventArgs ev = new System.EventArgs();
. . .
MyEvent(this,ev);
. . .
}
}
}

namespace ConsumerNamespace{

public class Consumer{

public static void Main(string[] args)
{
. . .
MyClass m = new MyClass();
m.MyEvent += MyEventHandler(m_MyEvent);
. . .
/* from now on we can call a method
* or make an action which causes MyClass to
* raise the MyEvent event */

m.SomeMethodThatRaisesTheEvent();
. . .
}

public static void m_MyEvent(object o, System.EventArgs ev)
{
. . .
/* handles the event */
}
}

}


You have to remember few things:


  • The signature of the delegate has to be the same of your own handling method

  • The signature of the delagete has to contain 2 parameters: the first one is an object reference, that refers to the object that launches the event, and the second one must be a subclass of System.EventArgs (there are a lots of them implemented for the common events)

  • You can subscribe to an event using the overloaded operator += but you can also unsubscribe by using the -=

  • For common applications, you won't need to raise yourself an event, but just supply a method and subscribe it to the event (the method, as said, has to have the same signature of the needed delegate)


And what about Java?
Learning Java I actually never had the need to write down some code to remember how Event Handling works.
Why? There are no delegates, in the sense you need to specify an entire class as the delegate for that event. What does it happen when you need to subscribe to an event?
In that situation Java is more OO then .NET, indeed you only use your Handler Class (such as MouseListener class, but for the common events, e.g. such as Mouse and Keyboard, you have at your disposal tons of ready-to-use classes) to manage the event. In this scenario you call directly by the object that throws the event, an addXXXListener() or removeXXXListener(), and inside your class, in which you surely have an array of potential listeners, when you want to raise the event, you have to iterate manually by calling all the needed methods of the listeners subscribed.
IMHO Java is straightforward to the OOP, but you need more code, and .NET allow you by using delegate and event keywords not to think to the propagation of the event. Moreover, in .NET you won't need to specify an entire class to handle the event, bringing to a more concise code style.

I'm not as experienced in .NET as I'm in Java, so maybe in few weeks I will post the exact opposite kind of opinion, but as for now I'm feeling better using C#, as it seems it has taken the good in Java and brought it to a more powerfull level (I'm refering to the whole framework ofcourse and not to the language itself).


kick it on DotNetKicks.com

Saturday, September 20, 2008

[.NET] How to send debug text to output (or file)

If you landed here because you want to send debug text to the output console do not worry, it's piss-easy:
//////////////////////////////////////////////////////////
// you can choose between this:
// first par: "a description of the importance of the message"
// second par: text 'category'
Debugger.Log(2, "Test", "this text in the output console - 1");
//or this
Debug.Write("this text in the output console - 2");
//or this
Debug.WriteLine("this text in the output console - 3");
//or this
Trace.Write("this text in the output console - 4");
//////////////////////////////////////////////////////////


Obviously you have to build in debug mode to see any output (if you do not know this you're a really lousy developer && human being).

If you feel sophisticated of you have some obscure reason to send your debug text not only to the output console but to a log file, you do like the following:
//////////////////////////////////////////////////////////
// clean-up the mess
Trace.Listeners.Clear();
//create new listener
DefaultTraceListener yourListener = new DefaultTraceListener();
//add new listener to trace
Trace.Listeners.Add(yourListener);
//set log file path
yourListener.LogFileName = @"log_test.txt";
//send text to console && log file like this
Trace.Write("butchers will be butchers"); 
//////////////////////////////////////////////////////////

In the case above you can use the Debug class the same way you use Trace (so you could write Debug.Write instead of Trace.Write and so on). Difference between the two is that Trace is implemented in Release build as well while Debug only in Debug mode (will be ignored if you build in Release).

P.S. Lately I've been to lazy to properly format the code - suck it up


kick it on DotNetKicks.com

Thursday, September 11, 2008

[.NET] How to create a shared folder in C#

To cut a not so long story even shorter, this can be done with the following snippet: 

//////////////////////////////////////////////
using System.IO;
using System.Management;

//...

//First create your directory
DirectoryInfo myDir = new DirectoryInfo(@"C:\shared");
myDir.Create();

//...

// Create an instance of ManagementClass
ManagementClass managementClass = new ManagementClass("Win32_Share");
// ManagementBaseObjects reference for in and out parameters
ManagementBaseObject inParams;
ManagementBaseObject outParams;
inParams = managementClass.GetMethodParameters("Create");
// Set input parameters
inParams["Description"] = "Shared directory";
inParams["Name"] = "shared";//this needs to match with folder name!
inParams["Path"] = @"C:\shared";
inParams["Type"] = 0x0; // Disk Drive
// InvokeMethod call on the ManagementClass object
outParams = managementClass.InvokeMethod("Create", inParams, null);
// Check outcome
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
   //Unable to share directory
}
////////////////////////////////////////

The above solution is quite sweet and seems to work perfectly - for further details see the article where I originally found the snippet to share the directory: http://www.sarampalis.org/articles/dotnet/dotnet0002.shtml

Man - do I suck!?!


kick it on DotNetKicks.com

Thursday, September 4, 2008

[.NET] C# 'is' operator

The C# 'is' operator looks like a boring little fella at first, but once you get to know it you will eventually appreciate it - it checks if you can safely cast an instance of an object to a type:
///////////////////////////////////////
//example 1
string testStr = "";
object obj = testStr;

//..somewhere else in your code
string newStr;

if (obj is String)
{
   newStr = (string)obj;
   //go nuts with your string
}
///////////////////////////////////////


It is important to understand that since the 'is' operator is just checking if it is safe to cast the following expression will always be true for any type:
///////////////////////////////////////
//example 2
string var = "whatever";

if(var is object) //<-always true (for var of any type)
{
    //always executed 
}
 /////////////////////////////////////// 
The above is always true for any type because everything in .NET inherits from object. This means you can safely cast to object (box) value types for example, and even if quite obvious it helps understanding how the 'is' operator works. 

You can obtain a result similar to example 1 using GetType and typeof if you're resolving types down to an inheritance line with this code: 
/////////////////////////////////////// 
//example 3 
string testStr = ""; 
object obj = testStr; 

//..somewhere else in your code 
string newStr; 

if (obj.GetType().Equals(typeof(String))) 
   newStr = (string)obj; 
   //have fun with your string 
/////////////////////////////////////// 
But here you're just checking for equality and not for safe casting in general, as you do with operator 'is' (i.e. example 2 with GetType Equals typeof returns false - because GetType returns string does not equal object). For an insight on GetType and typeof see this post.

Closing - a probably more efficient way - depending on your taste - to check if casting is safe is to go ahead and cast using the operator 'as', like this:
///////////////////////////////////////
//example 4
MyClass test =  new MyClass("read between the lines");
object obj = test;

//..somewhere else in your code
MyClass newTest = (obj as MyClass);

if (newStr != null)
{
   //do CRAZY stuff with YourClass
}
///////////////////////////////////////

For more details about the 'as' operator have a look right here.

kick it on DotNetKicks.com

Monday, September 1, 2008

[.NET] Difference between GetType and typeof

GetType and typeof come in useful when you need to mess with objects types before casting and so forth.

The difference between the two is the following:
GetType is a method of the object class - from which everything inherits in .NET - while typeof is an expression that operates on a type (same as you declare variables with).
While GetType takes into account inheritance and gives you back the actual Type of your instance at runtime - typeof just resolves the type into a System.Type object (jeez) at compiletime.

To cut a long story short: GetType extracts the Type from the object - typeof extracts the correspondent System.Type object from a type (declaration).


Have a look @ an example and it will be clearer:
////////////////////////////////////////////////
Type myType;
//the following blocks of code are equivalent
{
myType = typeof(int);
}

{
int i;
myType = i.GetType();
}
/////////////////////////////////////////////////

Good stuff - ain't it? No, it ain't - this post is child of absolute boredom.

kick it on DotNetKicks.com

Friday, August 29, 2008

[.NET] Difference between casting and 'as' operator in C#

This is an easy one - but it can be useful to someone so here it comes:

The 'as' operator in C# is a tentative cast - if it's impossible to cast (types are not compatible) instead of throwing an exception as the direct cast the 'as' operator sets the reference to null.

So you can have something like:

MyClass myObj = new MyClass();
MyOtherClass myOtherObj = myObj as MyOtherClass;
if (obj != null)
{
//cast was successful
}
else
{
//a little bit of a fuck-up
}

The correspondent in VB is the TryCast (usage is the same as DirectCast but it doesn't throw any exception).

Thursday, March 6, 2008

Silverlight vs. Flash and .NET integration


Two words about this new Technology by Microsoft.
I saw it for the first time near the end of 2007, but I gave it no importance: yeah, cool graphics but, as I'm not a graphic designer and having so little taste in graphics :), I had no interest in learning the fundamentals.
This is the same thing in Flash: in fact in the field I develop, Flash could help me only in the presentation step of my applications, because in the development step server techologies with javascript are enough.

Some weeks ago I came across the 1.1 alpha version of SilverLight, a complete version of the plugin, that can run on all main platforms (Win, MacOS, and a developing version for Linux) and on all main browsers (with only one plugin!!).

The main problem using FLASH with other technologies, such as .NET, is that you need a completely different environment to develop your applet (Flex) and have to use another language for your script (Action Script): moreover it's pretty difficult to generate both ASP.NET code and Flash code server-side, as they are in complete different domains. This can be done using third party solutions (such as SWFSource.NET, from this link) that allow you to generate SWF files server side, but at a too low level and of course without a complete intergration with the .NET technology.

At Microsoft Labs they wrote a scaled down version of the .NET platform to make Silverlight working: this allow you to write your client application in the same way you write your server pages, thus using the same data structures, objects and languages (C#, VB.NET, managed C++, ...), coming in help to the poor butcher programmer.

The framework, fully included in Visual Studio with few operations, comes with a completetly 2D rich model for drawing and responding to events (mouse click and this kind of stuff), some interesting streaming object for the mainly used video/audio standards (and Microsoft offers a 4Giga service of media storage and streaming server functionality in this link for free) fully customizable, a complete animation model and really interesting a full support for web services: this is what you will find in the 1.1 version, as the 1.0 is still something mostly related to graphical and animation manipolations.

No doubt that beeing an alpha release, I bet, there are still a lot of bugs and all the framework is missing some usefull objects not yet implemented, anyway this alpha is paving the way for a great new and useful technology.

Stay tuned for further readings, from your preferred butcher's shop!

Wednesday, March 5, 2008

[.NET] VB - C# Type Conversion Differences

There are some basic differences between VB.NET and C# when it comes to type conversion.

In both VB and C# widening conversions are implicit. Widening means that the destination type can represent all the possible values of the source type:


' VB sample
Dim myInteger As Integer = 1
Dim d As
myDouble = 1.007
myDouble = myInteger

'Helluva Implicit conversion allowed

// C# sample
int myInteger = 1;
double myDouble = 1.0001;
myDouble = myInteger;

//Implicit Conversion
//allowed


For narrowing conversion - let's say assigning a double to an int, when the destination type cannot represent all possible values of the source type - things change: you need to explicitly cast in C# while in VB the conversion keeps being implicit (don't come asking for an example plz... ).
If you want VB to behave as C# in case of narrowing conversions you have two options: either write at the very top of the code Option Strict On to enable the option at page level, or set the same Options Strict from the project properties to enable it at project level.

This difference reflects VB's wannabe-user-friendly attitude that often ends up messing-up things for people who's learning; but since every .NET developer is called once in a while to do some quick and dirty job using VB (there's a whole lot of frightening VB code out there) we certainly gotta deal with it.

That's all - Kick ass.

Thursday, January 31, 2008

[.NET] How to Retrieve Application Path - quick reference

Problem: You need to retrieve the application path but You don't remember (or you never knew) how to do it.

Solution: there are at least 3 well-known ways of ways to do this in .NET, let's see them in detail:

(1) the System.IO.Path way - more code but you always get what you're looking for; let's look at simple sample:

You start by using System.Reflection to get the application path comprehensive of the file name, either this way:

string pathWithFileName;
pathWithFileName=System.Reflection.Assembly.GetExecutingAssembly().Location;


Or this Way:

pathWithFileName=System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.Replace("file:/", "");


Then you pass the pathWithFileName string to System.IO.Path.GetDirectoryName:


string pathWithoutFileName;
pathWithoutFileName = System.IO.Path.GetDirectoryName(code_Base);


(2) the Sytem.IO.Directory way - it's easier to type (since you'll be copy-pasting like a good butcher I don't see the catch) and to get but there is a severe drawback:

pathWithoutFileName=System.IO.Directory.GetCurrentDirectory();

What's the severe drawback? Well if you previously changed the Current Directory using the SetCurrentDirectoy method you'll be getting that result instead of the the directory from where your assembly is being executed. If you're the only one working on your app, maybe that's ok, but if we're talking about huge banks of code... up to you, butcher.

(3) the System.Windows.Forms.Application way - if you're using windows forms you can use the StartupPath property:

pathWithoutFileName=System.IO.Forms.Application.StartupPath;

Enough - have a good butcherin' day; You bet I will.