Tuesday, April 27, 2010

VS 2008 SP1 deletes .dbml designer file – a solution

Also me was surprised after installation Visual Studio 2008 SP1. every little change in dbml hierarchy give raise to deleting designer file. Short googling return elegant solution:
In partial class move all using statements after namespace
Linq

Original code:
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;

namespace Test
{
partial class DataClassesDataContext
{
//...
}
}



New Code:

namespace Test
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;

partial class DataClassesDataContext
{
//...
}
}



Right click on the .dbml  file and run “Run Custom Tool”.

Enjoy!

Thursday, February 11, 2010

Twice calling Render in ASP.NET page

I have web page, which use HtmlTextWriter for creating HTML in client. List<T> get data from DB and start in loop to add HTML tags, attributes and more.  I hoped to create page with div’s, images and text, but in the debug phase i saw the Render() method called twice. After long tests and researches was found out what is a problem. In creating image <img>, a attribute “src” get value from DB and in one images “accidently” a value was …null. You can say “so what?” A problem exist not in HTML page, a problem concealing in IIS. If page has attribute <…src=”” …/> or<… src=”#” …> that makes IIS load the page twice. Good luck!


kick it on DotNetKicks.com

Wednesday, January 06, 2010

Object Property as Key in Collection

A innovation of Dictionary got excellent solution in stocking data. After countless uses I decided to find alternative method in combination of key and object and now I offering KeyedCollection. Little example will present a using of aforementioned object:

Simple classes:

public class User
   {
       public int Id { get; set; }
       public string Name { get; set; }
       public Address Address { get; set; }
   }

   public class Address
   {
       public string Country { get; set; }
       public string City { get; set; }
       public string Zip { get; set; }
   }

Two object that inherits abstract KeyedCollections:

/// <summary>
///A key is ID of player
/// </summary>
public class UserCollection : KeyedCollection<int, User>
{
    //Implementing member
    protected override int GetKeyForItem(User item)
    {
        return item.Id;
    }
}

/// <summary>
/// A key is User Name
/// </summary>
public class UserCollection1 : KeyedCollection<string, User>
{
    //Implementing member
    protected override string GetKeyForItem(User item)
    {
        return item.Name;
    }
}

 

Little example to using:

public class Test
{
    public TestById()
    {
        var userCollection = new UserCollection();
        userCollection.Add(new User
                               {
                                   Id = 5,
                                   Name = "John Smith",
                                   Address = new Address
                                                 {
                                                     City = "NY",
                                                     Country = "USA",
                                                     Zip = "12345"
                                                 }
                               });

        userCollection.Add(new User
                               {
                                   Id = 17,
                                   Name = "James Brown",
                                   Address = new Address
                                                 {
                                                     City = "LA",
                                                     Country = "USA",
                                                     Zip = "54321"
                                                 }
                               });

        Console.Write(userCollection[6]);
    }
     public void  TestByName()
    {
        var userCollection = new UserCollection1();
        userCollection.Add(new User
                               {
                                   Id = 5,
                                   Name = "John Smith",
                                   Address = new Address
                                                 {
                                                     City = "NY",
                                                     Country = "USA",
                                                     Zip = "12345"
                                                 }
                               });

        userCollection.Add(new User
                               {
                                   Id = 17,
                                   Name = "James Brown",
                                   Address = new Address
                                                 {
                                                     City = "LA",
                                                     Country = "USA",
                                                     Zip = "54321"
                                                 }
                               });

        Console.Write(userCollection["John Smith"]);
    }
}

 

 

If a project in VS 2008 you can run in heritable object LINQ requests and more. Enjoy!

kick it on DotNetKicks.com

Sunday, October 25, 2009

SQL to LINQ Cheat Sheet

Excellent explanation how to covert SQL query to LINQ. Click HERE to article.

LINQ Syntax

Sunday, July 12, 2009

C# And Accepting Parameters

Have you ever written a function that looked similar to the following – Passing in an array of a value? To interesting solution click here.

 

via DotNetKicks.com

Wednesday, June 17, 2009

Debug windows service

In the time, when you work on development a windows service not possible to debug it. A solution is a converting service to console application or creating additional service runner or anymore. I want to present very simple, effective and easy way how to resolve this. In debug mode will run application and in not debug mode will run service.

[RunInstaller(true)]
public partial class ServiceRunner : ServiceBase
{
[STAThread]
static void Main()
{
#if !DEBUG
//Run Windows Service
Run(new ServiceRunner());
#else
//Run Application
new YourServiceBody();
#endif
}
public ServiceRunner()
{
InitializeComponent();

}
protected override void OnStart(string[] args)
{
new YourServiceBody();
}

protected override void OnStop()
{}
}

Good luck!
kick it on DotNetKicks.com

Sunday, April 05, 2009

Clone an object in C# using reflection for system and generic types

public object Clone()
{
object newObject = Activator.CreateInstance(GetType());
PropertyInfo[] propertyInfos = GetType().GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (propertyInfo.PropertyType.IsGenericType)
{
if (propertyInfo.PropertyType.GetInterface("IList", true) != null)
{
IList oldList = propertyInfo.GetValue(this, null) as IList;
if (oldList != null && oldList.Count > 0 &&
oldList[0].GetType().GetInterface("ICloneable", true) != null)
{
IList newList = (IList)propertyInfo.GetValue(newObject, null);
foreach (object obj in oldList)
{
ICloneable clone = (ICloneable)obj;
newList.Add(clone.Clone());
}
}
else
{
propertyInfo.SetValue(newObject, oldList, null);
}
}
if (propertyInfo.PropertyType.GetInterface("IDictionary", true) != null)
{
IDictionary oldDic =
propertyInfo.GetValue(this, null) as IDictionary;
if (oldDic != null && oldDic.Count > 0 &&
oldDic[0].GetType().GetInterface("ICloneable", true) != null)
{
IDictionary newDic =
(IDictionary)propertyInfo.GetValue(newObject, null);
foreach (DictionaryEntry entry in oldDic)
{
ICloneable clone = (ICloneable)entry.Value;
newDic[entry.Key] = clone.Clone();
}
}
else
{
propertyInfo.SetValue(newObject, oldDic, null);
}
}
}
else
{
//Clone IClonable object
if (propertyInfo.GetType().GetInterface("ICloneable", true) != null)
{
ICloneable clone = (ICloneable)propertyInfo.GetValue(this, null);
propertyInfo.SetValue(newObject, clone.Clone(), null);
}
else
{
propertyInfo.SetValue(
newObject, propertyInfo.GetValue(this, null), null);
}
}
}
return newObject;
}



Thursday, September 25, 2008

Snippet Designer for Visual Studio 2008

The Snippet Designer is a plugin which enhances the Visual Studio IDE to allow a richer and more productive code snippet experience.

Home Page

Thursday, August 14, 2008

Multi Sorting array of objects

A method sort (asc and desc) array of objects by properties and return sorted array.
private static T[] MultiSortObjectArray<T>(T[] objects,
bool isReverseSort, params string[] propertyNames)
{
//Get array object type
PropertyInfo[] propertiesInfo = (typeof (T)).GetProperties();
//Define list of properties for sorting
List<PropertyInfo> lstProperties2Compare = new List<PropertyInfo>();

//Check sorting properties one by one
foreach (string sortPropertyName in propertyNames)
{
//Find sorting property in Object property
PropertyInfo sortProperty =
Array.Find(propertiesInfo,
delegate(PropertyInfo property)
{
return (
string.Compare(property.Name, sortPropertyName,
true) == 0
);
}
);

//Add existing property to sorting list
if (sortProperty != null)
lstProperties2Compare.Add(sortProperty);
}

if (lstProperties2Compare.Count == 0)
return null;

Array.Sort(objects,
delegate(T x, T y)
{
int result = -1;
foreach (PropertyInfo propInfo2Compare in
lstProperties2Compare)
{
result = (!isReverseSort)
? //Sort by asc
(new CaseInsensitiveComparer()).Compare(
propInfo2Compare.GetValue(x, null),
propInfo2Compare.GetValue(y, null)
)
: //Sort by desc
(new CaseInsensitiveComparer()).Compare(
propInfo2Compare.GetValue(y, null),
propInfo2Compare.GetValue(x, null)
);
//If x equals y continue compare process
if (result != 0)
break;
}

return result;
}
);

return objects;
}





kick it on DotNetKicks.com

Wednesday, May 14, 2008

Sys.WebForms.PageRequestManagerParserError in MS AJAX

Thanks to Al Pascual to solution.

On top of the webform add:

enableEventValidation="false"



To full article lick Here

Monday, April 28, 2008

Get column info in MS SQL

Existing some ways how to get column information, but Joe Webb offered very simple and effective query:

SELECT 
ORDINAL_POSITION
,COLUMN_NAME
,DATA_TYPE
,CHARACTER_MAXIMUM_LENGTH
,IS_NULLABLE
,COLUMN_DEFAULT
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME ='TABLE_NAME'
ORDER BY
ORDINAL_POSITION ASC;

Tuesday, April 08, 2008

VS 2005 Intellisense in web.config files stop work

Now one annoying gotcha:

There is one gotcha to be aware of, though, that can sometimes cause intellisense for the web.config file to stop working in the IDE. This happens when a default namespace is added to the root <configuration> element. For example, like so:

<configuration xmlns=
"http://schemas.microsoft.com/.NetConfiguration/v2.0">





This doesn’t cause any runtime problems – but it does stop intellisense completion happening for the built-in .NET XML elements in the web.config file.

The bad news is that the built-in web admin tool (launched via the WebSite->ASP.NET Configuration menu item in VS 2005 and Visual Web Developer) always adds this xmlns namespace when it launches – so if you use this tool to manage users/roles you’ll end up having it added to your web.config file for you.

How to fix this gotcha:

To get intellisense back when you are editing the web.config file in the IDE, just delete the xmlns reference and have the root configuration element look like so:

<configuration>



Everything will then work fine again.


via


Thursday, March 27, 2008

HttpWebRequest over SSL

public static bool
AcceptAllCertificatePolicy(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}

The returned value determines whether the specified certificate is accepted for authentication.

Then set:

ServicePointManager.ServerCertificateValidationCallback
+= AcceptAllCertificatePolicy;

From here



Tuesday, March 18, 2008

Sunday, March 09, 2008

Singleton Factory in C#

    // this is the class for which
// I want to maintain a single instance
public class MyClass
{
private MyClass()
{
/* private constructor ensures that
callers cannot instantiate an
object using new() */
}
}

// Singleton factory implementation
public static class Singleton<T> where T : class
{
// static constructor,
//runtime ensures thread safety
static Singleton()
{
// create the single instance
// of the type T using reflection
Instance = (T)Activator.CreateInstance(
typeof(T),true);
}

// serve the single instance to callers
public static T Instance { private set; get; }
}

class Program
{
public static void Main()
{
// test
Console.WriteLine(
Object.ReferenceEquals(
Singleton<MyClass>.Instance,
Singleton<MyClass>.Instance));
}
}




via Cognitive Coding

Thursday, March 06, 2008

Monday, February 18, 2008

Enum Utilities

In this article I will discuss some classes I've written to simplify working with enumerations. The primary thrust of these classes is added functionality, but in some cases there are performance improvements as well.

Click here

Download source

The zip file contains:
EnumDefaultValueAttribute.cs
EnumTransmogrifier.cs
LibEnum.cs
build.bat
csc.rsp
EnumDemo1.cs
EnumDemo2.cs
EnumDump.cs
MonthEnum.cs
PolyglotAttribute.cs
WeekdayEnum.cs

Once you extract the files to a directory you should be able to execute build.bat to compile the demo programs. (They are console applications.)

To use the methods in your own projects, simply add the appropriate files.

Sunday, February 17, 2008

Directives in Asp.Net

Directives are used to pass optional settings to the ASP.NET pages and compilers.

Click here to read article.

Tuesday, February 12, 2008

Custom Controls: Extra Property Tab

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace Elsehemy.Controls
{
[Designer(typeof(UserControlDesigner))]
[PropertyTab(typeof(ExtraSuperTab),
PropertyTabScope.Component)]
public partial class TestUserControl : UserControl
{
public TestUserControl()
{
InitializeComponent();
}
int _x;

public int XXX
{
get { return _x; }
set { _x = value; }
}
}


public class ExtraSuperTab :
System.Windows.Forms.Design.PropertyTab
{
public override PropertyDescriptorCollection
GetProperties(object component,
Attribute[] attributes)
{
PropertyDescriptor pd =
TypeDescriptor.CreateProperty(
component.GetType(),
"XXX",
typeof(int),
new CategoryAttribute("Super Properties"));

return (
new PropertyDescriptorCollection(
new PropertyDescriptor[]{pd}
));
}

public override string TabName
{
get { return "Super Tab"; }
}

public override System.Drawing.Bitmap Bitmap
{
get
{
return (System.Drawing.Bitmap)System.
Drawing.Image.FromFile(@"C:\icon.jpg");
}
}
}
}




 

And in the control don't forget the attribute

[PropertyTab(typeof(ExtraSuperTab),
PropertyTabScope.Component)]
public partial class TestUserControl : UserControl
 
Via Amr Elsehemy's Blog





Sunday, February 10, 2008

How to use delegates to remove duplicated code

Click Here

Static Extension Methods

DateTime d = DateTime.Yesterday();
//...
public static DateTime Yesterday<this DateTime>()
{
return DateTime.Today.AddDays(-1);
}
 


Via Mabstrerama

Tuesday, February 05, 2008

101 Design Patterns & Tips for Developers

Full guide for developer how to create your application in the using   a "design patterns", that include next parts:

  • Creational Patterns
  • Structural Patterns
  • Behavioral Patterns
  • Composing Methods of Refactoring
  • Moving Features Between Objects
  • Organizing Data
  • Simplifying Conditional Expressions
  • Making Method Calls Simpler
  • Dealing with Generalization
  • Big Refactorings

Click here to read.

Monday, January 28, 2008

The Chart free generation for Web Application from Google

Google Provided addition tool for Web developers  - The Google Chart API.

You can create a charts in very simple way - build necessary URL and will receive chart in one of 5 types (Line, Bar, Pie, Venn or Scatter).

A simple "pie" for example:

URL = "http://chart.apis.google.com/chart?
cht=p3&chco=4C8ED6&chs=250x120&
chl=Sun|Mon|Tue|Wed|Thu|Fri|Sat&chd=s:ABCDEFG"

and a result:

 

 

In your control next chart parameters: Data, Type, Colors, Labels, Style, Character mappings and several optional parameters.

To Home Page click HERE

Sunday, January 20, 2008

Find all tables, which includes column name

Get all table names for a specific column name

SELECT sysobj.name as Table_Name
FROM sysobjects sysobj
INNER JOIN syscolumns syscol
ON sysobj.id= syscol.id
WHERE syscol.name = 'COLUMN_NAME_FOR_SEARCH'



-------------------------------------------

Get all columns and table names for a 'like column_name' query

SELECT syscol.[name] as Column_Name,
sysobj.name as Table_Name
FROM sysobjects sysobj
INNER JOIN syscolumns syscol
ON sysobj.id=syscol.id
WHERE syscol.name like '%COLUMN_NAME%'
kick it on DotNetKicks.com
 

Thursday, January 17, 2008

Example & Tutorial of Rhino Mocks

In object-oriented programming, mock objects are simulated objects that mimic the behavior of real objects in controlled ways. A computer programmer typically creates a mock object to test the behavior of some other object, in much the same way that a car designer uses a crash test dummy to test the behavior of a car during an accident.

 Wikipedia 

To full guide in code examples about Rhino Mocks Click Here

Full guide how to configuring VS 2008 for debugging .NET Framework Source Code

Click here to read a article.

Thursday, January 10, 2008

SQL Server 2005, Clean your Database Records & reset Identity Columns, all in 6 lines

Well, I had a small issue regarding writing a script to clean a database we have and reset its identity columns in all tables. Although the database wasn't huge one (less than 100 tables) I had to trace relations to be able to delete child table's records before parent's ones because of the foreign key constraints. The solution is disable the foreign keys and delete records with no fear of any errors then enables the constraints again.
Well, I found a solution to disable all constraints without the need to go on each table and disable it manually. and I was happy to know that I can use this solution in deleting all records from all tables. Not only this I was able to use the same solution to reset identity columns in all tables.
The solution was to use this built in stored procedure sp_MSforeachtable. For help about this proc search for it in Books online or use this sp_helptext sp_MSForeachtable.
Now back to my 6 lines, bellow is how I re-zeroed my Database:

/*Disable Constraints & Triggers*/
exec sp_MSforeachtable
'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
exec sp_MSforeachtable
'ALTER TABLE ? DISABLE TRIGGER ALL'

/*Perform delete operation on all table for cleanup*/
exec sp_MSforeachtable 'DELETE ?'

/*Enable Constraints & Triggers again*/
exec sp_MSforeachtable
'ALTER TABLE ? CHECK CONSTRAINT ALL'
exec sp_MSforeachtable
'ALTER TABLE ? ENABLE TRIGGER ALL'

/*Reset Identity on tables with identity column*/
exec sp_MSforeachtable
'IF OBJECTPROPERTY(OBJECT_ID(''?''),
'
'TableHasIdentity'') = 1
BEGIN DBCC CHECKIDENT ('
'?'',RESEED,0) END'




 


Via Moses on DotNetSlackers

Wednesday, January 09, 2008

How to check email works with no SMTP

<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory
pickupDirectoryLocation="c:\Test\" />
</smtp>
</mailSettings>
</system.net>


 
Via .Net Tip of The Day

Monday, January 07, 2008

How to extract URLs (href property) from HTML

protected ArrayList GetUrl(string text)
{
ArrayList listURL = new ArrayList();
Regex r =
new Regex("href\\s*=\\s*(?:(?:\\\
"
(?<url>[^\\\"]*)\\\")|
(?<url>[^\\s]* ))"
);
MatchCollection mathColl = r.Matches(text);

foreach (Match math in mathColl)
{
foreach (Group gr in math.Groups)
{
listURL.Add(gr.Value);
}
}
return listURL;
}

Sunday, December 23, 2007

What is the difference between URL and URI?

A URL is the address of some resource on the web, which means that normally you type the address into a browser and you get something back. There are other type of resources than web pages, but that's the easiest conceptually. The browser goes out somewhere on the internet and accesses something.

A URI is just a unique string that uniquely identifies something, commonly a namespace. Sometimes they look like a URL that you could type into the address bar of your web browser, but it doesn't have to point to any physical resource on the web.

URI is the more generic term, and a URL is a particular type of URI in that a URL has to uniquely identify some resource on the web.

Via .Net Tip of The Day

Thursday, November 22, 2007

Ajax control toolkit updated for Visual Studio 2008

Ajax control toolkit has been updated and released to version version 3.5.11119.0

AjaxControlToolkit-Framework3.5.zip is the full release package with complete source code to all controls, the test framework, VSI, and more.

AjaxControlToolkit-Framework3.5-NoSource.zip contains only the sample web site and VSI and is for people who don't need or want the source code for the controls.

Download link

kick it on DotNetKicks.com

Wednesday, November 21, 2007

Visual Studio 2008 and .NET Framework 3.5 Training Kit

The Visual Studio 2008 and .NET Framework 3.5 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2008 features and a variety of framework technologies including: LINQ, C# 3.0, Visual Basic 9, WCF, WF, WPF, ASP.NET AJAX, VSTO, CardSpace, SilverLight, Mobile and Application Lifecycle Management.

Download Page

kick it on DotNetKicks.com

Monday, November 19, 2007

Visual C# 2008 Keyboard Shortcuts Reference Poster

Microsoft present keybinding reference poster for Visual C# in Visual Studio 2008 

Download page

kick it on DotNetKicks.com

Thursday, November 15, 2007

Add automatic updates to your application

This article explain  step-by-step how to add automatic update capabilities to application quickly and easily.

Click here

kick it on DotNetKicks.com

Wednesday, November 14, 2007

How to add ComboBox to PropertyGrid

Create new class which inherit StringCoverter, and 3 methods:

internal class List2PropertyConverter : StringConverter
{
public override bool
GetStandardValuesSupported(
ITypeDescriptorContext context)
{
//True - means show a Combobox
//and False for show a Modal
return true;
}

public override bool
GetStandardValuesExclusive(
ITypeDescriptorContext context)
{
//False - a option to edit values
//and True - set values to state readonly
return true;
}

public override StandardValuesCollection
GetStandardValues(
ITypeDescriptorContext context)
{
return new StandardValuesCollection(
new string[] {"test1", "test2", "..."});
}
}




Add variable and encapsulate it:
 private string testValue;
[Browsable(true)]
[Category("Category name")]
[TypeConverter(typeof(List2PropertyConverter))]
public string TestValues
{
get { return testValue; }
set { testValue = value; }
}




PropertyGrid has 4 attributes for a manage properties:


[Browsable(bool)] - Visible/Hide property

[ReadOnly(bool)] - Editing (true/false)

[Category(string)] - Group of properties

[Description(string)] - Description of the property

kick it on DotNetKicks.com

Regards,

Sunday, November 11, 2007

CAPTCHA Kinda Spam Prevention in ASP.NET

Spammers really bug me.

I've been working on this on-going sports related portal project (that probably will NEVER go live :)

I love of hobby community sites degrade quickly because they lack the moderation resources to keep the user submitted content quality high and I've been thinking about this problem.

I thought I would share some interesting links that I found on the subject.

 

by Joe Stagner

kick it on DotNetKicks.com

Template Method Design Pattern vs. Functional Programming

Simple and obvious example how to realize Design Patterns. A example based on Hot Drinks and presented design of the application with explanations.

Click here

kick it on DotNetKicks.com

Thursday, November 08, 2007

ADInsight - new utility by Microsoft

ADInsight is an LDAP (Light-weight Directory Access Protocol) real-time monitoring tool aimed at troubleshooting Active Directory client applications. Use its detailed tracing of Active Directory client-server communications to solve Windows authentication, Exchange, DNS, and other problems.

Homepage

Download (720kb)

kick it on DotNetKicks.com

BGInfo - display PC information on the desktop

How many times have you walked up to a system in your office and needed to click through several diagnostic windows to remind yourself of important aspects of its configuration, such as its name, IP address, or operating system version If you manage multiple computers you probably need BGInfo. It automatically displays relevant information about a Windows computer on the desktop's background, such as the computer name, IP address, service pack version, and more. You can edit any field as well as the font and background colors, and can place it in your startup folder so that it runs every boot, or even configure it to display as the background for the logon screen.

HomePage

Download

kick it on DotNetKicks.com

Calling delegates using BeginInvoke, Invoke, DynamicInvoke and delegate

I wanted to write about delegates this month. There are different ways in which you can invoke delegates to get either a synchronous or an asynchronous behavior. But from what I noticed, the delegate model provides you very less control when you invoke it asynchronously. The caller cannot easily abort or terminate the operation.

If you want to execute a delegate asynchronously and still want to have good control from the caller then invoke it explicitly from a thread. The sample below demonstrates multiple ways you can invoke a delegate and each has its own features with it. Till I wrote this, I didn’t realize that there are 6 ways to invoke a delegate and I am sure there are a few more that I am missing here. It was also interesting that when you execute a delegate on a thread then it cannot return a value as the caller of the thread is gone when the thread returns. If you want to pass parameters to the delegate in the thread you can use the ParameterizedThread option which is very useful.

 

Click here to continue...

kick it on DotNetKicks.com

Sunday, October 28, 2007

Care about Event Memory Leaks with Delegate.GetInvocationList()

Subscribed events are one of the most common reasons of memory leaks in .Net. This means that if you have an object that has an event

and there are other object that are subscribed to that event, the original object won't be properly disposed until all events are unsubscribed since

an event is a strong reference.

 ....

public partial class MyForm : Form
{
public event EventHandler OnDoMyFormThing;

public MyForm()
{
InitializeComponent();
}

private void button1_OnClick
{
MessageBox.Show(
"Test of OnDoMyFormThing event"
);
OnDoMyFormThing(this, new EventArgs());
}

protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
foreach (EventHandler eventDelegate
in
OnDoMyFormThing.GetInvocationList())
OnDoMyFormThing -= eventDelegate;
components.Dispose();
}
base.Dispose(disposing);
}
}



 


To full  article click here

Tuesday, October 23, 2007

Convert UTF-8 to Unicode

private static string Utf8ToUnicode(string utf8)
{
    return Encoding.Unicode.GetString(
        Encoding.Convert(
        Encoding.UTF8,
        Encoding.Unicode,
        Encoding.UTF8.GetBytes(utf8)));
 }

LINQ solution:
private static string Utf8ToUnicode(string utf8)
{
  return   Encoding.UTF8.
       GetString(input.Select(item => (byte)item).ToArray()); 
}

Strategy Pattern in C# 2.0

Strategy pattern can very handy when a system designer or architect wants to separate algorithms from the system implementation. Also with strategy pattern approach it is very easy to select between different algorithms on the fly. With the introduction of generics in .NET 2.0 implementing strategy pattern is even more easy.

Click Here

 

 

via DotNetKicks.com

Sunday, October 21, 2007

Full guide to create Installer class in VS.Net 2005

6 pages of amazing guide by devCity.net explains all point of deployment project and include follow parts:

  • Requirements 
  • Terminology
  • How to create an Installer Class
  • Un-written rules
  • Unpleasent features
  • Using these events (about Installer Class events)
  • Using the Commit event to change the target directory permissions.
  • Using the Uninstall event to clean the target directory
  • Where is the "NT AUTHORITY\SERVICE" account coming from?
  • Exceptions and Exception handling in your installer class.
  • Adding user interfaces (forms) to your installer class.
  • Launching your application after installation.
  • Conclusions.
  • References.

To read "Visual Studio 2005 Setup and Deployment Installer Classes and Custom Actions" CLICK HERE

kick it on DotNetKicks.com

Listas - new feature from Microsoft

At Live Labs, we are always experimenting with new ideas that we think will be useful.  Today we are releasing our latest technology preview:

Listas (http://listas.labs.live.com)

Listas is a tool for the creation, management and sharing of lists, notes, favorites, and more. It allows you to quickly and easily edit lists, share them with others for reading or wiki-style editing, and discover the public lists of other users.  We encourage you to try using it for meeting notes, bookmarks, shopping lists, to plan a night out, or whatever other creative ways you can think of....

kick it on DotNetKicks.com

Sunday, October 14, 2007

Sharp Cache Session Manager

The SharpCacheSessionManager is a HttpHandler that allows to display the entries stored in the Cache, Session and Application object. You can view the data stored inside the objects and you can also remove the objects from the corresponding storage. To download the SharpCacheSessionManager click HERE

via Christopher Steen

 kick it on DotNetKicks.com

Wednesday, October 10, 2007

Monday, October 08, 2007

Find and get list of controls on page

If you want to find list of controls on Page you can use this method:
private List<T> GetControls<T>() where T:Control
{
List<T> list = new List<T>();
foreach (Control rootControl in Controls)
{
foreach (Control control in rootControl.Controls)
{
if (control as T != null)
{
list.Add(control as T);
}
}
}
return list;
}
And a using is very simple. In example you can see how to change background to all labels:
List<Label> list = 
GetControls<Label>();
list.ForEach(
delegate (Label lab)
{
lab.BackColor =
System.Drawing.Color.Pink;
}
);

 


kick it on DotNetKicks.com

Sunday, October 07, 2007

A Visual Guide to Version Control

A beautiful, "highly visual" overview of Version Control, (a.k.a. Source Control). It also references Subversion command line examples, but the overview applies to most version control systems by BetterExplained.

To read a full article click HERE.