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;
}