29 December 2010

HTML : white space nowrap

In the gold days to avoid a white space wrap we could use the nobr tag. Now since the tag is deprecated we must use css:

.nobr { white-space:nowrap; }

This class can be applied to a span with the text we need to avoid the wrap.

16 December 2010

Immediate Window is missing in Visual Studio 2010 Menu

When the Immediate Window is missing in Visual Studio Menu, just do the following steps:
1) In the menu, select View -> Other Windows -> Command Window
2) Type immed in the command window and the It will bring the Immediate Window
3) Type cmd inside the Immediate Window and it will bring the Command Window back again

15 December 2010

Fix the MaxItemsInObjectGraph quota error

When there is a great amount of data to send to a WCF service, the following error occurs:

Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota.

To fix the error the MaxItemsInObjectGraph must be defined on the wcf service server and the client.

On the server:

<system.serviceModel>   
    <services>
        <service behaviorConfiguration="Service1Behavior" name="Service1">
           <endpoint address="" binding="basicHttpBinding" contract="IService1"></endpoint>
        </service>
    </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="Service1Behavior">          
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceDebug includeExceptionDetailInFaults="true"/>
                    <dataContractSerializer maxItemsInObjectGraph="2147483647"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

On the client:

<system.serviceModel>
    <client>
        <endpoint address="http://localhost/Service1.svc" behaviorConfiguration="Service1Behavior" binding="basicHttpBinding" contract="IService1Event" name="Service1">
      </endpoint>
    </client>
    <behaviors>
        <endpointBehaviors>
            <behavior name="Service1Behavior">
              <dataContractSerializer maxItemsInObjectGraph="2147483647"/>    
            </behavior>
        </endpointBehaviors>
</behaviors>
</system.serviceModel>

14 December 2010

Optimize tempdb Performance

To optimize tempdb Performance in a production environment:
1) Set the recovery model of tempdb to SIMPLE.
2) Allow for tempdb files to automatically grow as required.
3) Set the file growth increment to a reasonable size. Set it to 10% of the file size, with a minimnum of 10MB
4) create one data file for each CPU on the server, note that a dual-core CPU is considered to be two CPUs.
5) Make each data file the same size; this allows for optimal proportional-fill performance.
6) Put the tempdb database on a fast I/O subsystem. Use disk striping if there are many directly attached disks.
7) Put the tempdb database on dedicated disks.

For more information: MSDN Optimizing tempdb Performance

15 November 2010

LINQ To Objects: Left Join

Linq to Objects is a powerfull technology. One of the many features it has it the power to perform a left join between objects. The syntax for a left join is not like in SQL.

A left outer join is a join in which each element of the first collection is returned, regardless of whether it has any correlated elements in the second collection. Calling DefaultIfEmpty on the results of a group join returns the result of a left join.

Example:


   1:  class User
   2:  {
   3:       public int UserID { get; set; }
   4:       public string Name{ get; set; }
   5:  }
   6:   
   7:  class Order
   8:  {
   9:       public int OrderID { get; set; }
  10:       public int UserID { get; set; }
  11:       public int ProductID { get; set; }
  12:  }
  13:   
  14:  List<User> users = UserService.List();
  15:  List<Order> orders = OrderService.ListByUser(userID);
  16:   
  17:  var q = from o in orders 
  18:          join u in users on o.UserID = u.UserID into joinedUsers
  19:          from UserOrders in joinedUsers.DefaultIfEmpty()
  20:          select new UserOrder()
  21:          {
  22:              OrderID = o.OrderID,
  23:              ProductID = o.ProductID,
  24:              Name = UserOrders.Name
  25:          }
  26:  var result = q.ToList();

11 November 2010

How to use ASP.Net validators with a User Control?

ASP.Net validators and user controls (ascx) are great. They save us a lot of time.
But when we mix a User Control and a ASP.Net validator the following error occurs:

Control 'UserSelector' referenced by the ControlToValidate property of 'rvUserSelector' cannot be validated.

The solution to this problem is to use the attribute ValidationProperty on the User Control:

[ValidationProperty("UserID")]
public partial class UserSelector : UserControl

In this example the UserID property of the User Control is used by the validators to perform the validation.

To end, I would like to thank you Alexandre Simões for his help in solving this issue.

21 October 2010

KBxxxxxxx does not apply, or is blocked by another condition on your computer

When installing a visual studio 2010 hotfix I got the error:

KBxxxxxxx does not apply, or is blocked by another condition on your computer

To fix it i had to goto Programs and Features in the control panel, selected Microsoft Visual Studio 2010 and selected Unistall/Change. Then I made a repair.
When the repair finished I executed the hotfix and it installed.

20 October 2010

Missing Edit WCF Configuration menu option in Visual Studio

Normally the context menu option Edit WCF Configuration for a app.config or web.config is not shown.
To fix this issue open up the Tools menu in Visual Studio and choose Wcf Service Configuration Editor.
The tool will open, close it straight away and then right-click in your config file.
The Edit WCF Configuration context menu is now visible.

18 October 2010

Hotfixes available for ‘scrolling context menu’ problem

Finally, the hotfix for ‘scrolling context menu’ problem in visual 2010. The context menus had scrollbars even when there is sufficient screen real estate to show the menu without one.

For more information and installation:
http://blogs.msdn.com/b/visualstudio/archive/2010/10/14/hotfixes-available-for-scrolling-context-menu-problem.aspx

12 October 2010

Get only the Date Part of a DateTime

To get only the Date Part of a DateTime in an efficient way, use the following code:


SELECT CAST(FLOOR( CAST( GETDATE() AS FLOAT )) AS DATETIME)

How to Convert a String to Title Case

To convert a string Title Case, simply use the TextInfo class:


using System.Globalization;
using System.Threading;

CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;

string result = textInfo.ToTitleCase("this is test");

If the string is in uppercase first convert it to lowercase using the ToLower() method.

03 September 2010

Fix error :Unable to generate a temporary class (result=1). error CS2001: Source file ‘C:\WINDOWS\TEMP\file.cs’ could not be found error CS2008: No inputs specified

When a service in ASP.Net is executed the error:

Unable to generate a temporary class (result=1). error CS2001: Source file ‘C:\WINDOWS\TEMP\filename.cs’ could not be found error CS2008: No inputs specified

can occur.

The problem are the permissions on the C:\WINDOWS\TEMP folder.
To fix it, give the user of the Application Pool full control on that folder.

20 August 2010

How to change the identity value of a table

To change the identity value of a table use the statement:

DBCC CHECKIDENT (myTable, reseed, value)


Where
- myTable is the table to change the identity value
- reseed specifies that the identity value should be changed
- value is the new value to use for the identity column

Example:
DBCC CHECKIDENT (Products, reseed, 12)

After this command executed, the next identity value of the Products table will be 13

This command is useful if you delete records at the end of a table and want to keep the identity values sequential.

06 July 2010

Speed up development of ASP.Net

ASP.Net by default compiles all the pages of the same folder and the bin on every call.
In a development environment this can slow down the tests of the code and sometimes the slow startup of the ASP.Net site is very annoying.
To try to improve this issue, there are two configuration options for the web.config or machine.config.

<system.web>
     <compilation batch="false" optimizeCompilations="true"></compilation>
</system.web>

To use the optimizeCompilations in any version of ASP.Net you have install a Microsoft patch located here.
The path is not needed for ASP.Net 4.0

Note: As side effect, the HTML changes may not take effect between compilations. In this case the Temporary ASP.NET Files folder for the site must be manually deleted.

Change Temporary ASP.NET Files location

To change the Temporary ASP.NET Files location, simply define the tempDirectory attribute of the compilation element of the web.config or machine.config.

Example:

<system.web>
   <compilation tempDirectory="d:\TempASPNetFiles\"></compilation>
</system.web>

14 June 2010

Data Contract Serializer

The DataContractSerializer class serializes and deserializes an instance of a type stream or document using a supplied data contract.
The class to be serialized must be marked with the DataContractAttribute attribute.
Properties and fields of the class that are to be serialized must be marked with the DataMemberAttribute.

The DataContractSerializer WriteObject and ReadObject can then be used for serialization / deserialization.

Example:
1) Serialization

MyType myType = new MyType();
DataContractSerializer dcs = new DataContractSerializer(typeof(MyType));
MemoryStream ms = new MemoryStream();
dcs.WriteObject(ms, myType);

string result = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position);

2) Deserialization


MyType myType = null;

DataContractSerializer dcs = new DataContractSerializer(typeof(MyType));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(EncodedString));
myType = (MyType)dcs.ReadObject(ms);


Where the EncodedString is the encoded string to decode (result from step 1)

30 April 2010

How to create custom configuration section

To create custom configuration section on a web.config or app.config file the attribute ConfigurationCollectionAttribute must be used.

In my example let us create a custom section named mails. It has the mails collection to send messages.


<configuration>
<configSections>
<section name="Mails" type="Samples.XProg.MailsSection, ConfigurationCollectionAttribute" />
</configSections>
<Mails>
<sendlist>
<clear />
<add name="mail1" mail="mail1@noip.com" />
<add name="mail2" mail="mail2@noip.com" />
</sendlist>
</Mails>
</configuration>


using System;
using System.Configuration;
 
namespace Samples.XProg
{
class TestMailConfigurationSection
{
static void Main(string[] args)
{
MailsSection mails = ConfigurationManager.GetSection("MailsSection") as MailsSection;
 
Console.WriteLine("Mails list:");
for (int i = 0; i < mails.SendList.Count; i++)
{
Console.WriteLine("Name={0} Mail{1}", mails.SendList[i].Name, mails.SendList[i].Mail);
}
 
Console.ReadLine();
}
}
 
public class MailsSection : ConfigurationSection
{
[ConfigurationProperty("sendlist", IsDefaultCollection = false)]
[ConfigurationCollection(typeof(SendListCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")]
public SendListCollection SendList
{
get
{                    
return (SendListCollection)base["sendlist"];;
}
}
 
}
 
 
public class SendListCollection : ConfigurationElementCollection
{
public UrlsCollection()
{
}
 
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.AddRemoveClearMap;
}
}
 
protected override ConfigurationElement CreateNewElement()
{
return new UrlConfigElement();
}
 
protected override Object GetElementKey(ConfigurationElement element)
{
return ((UrlConfigElement)element).Name;
}
 
public MailElement this[int index]
{
get
{
return (MailElement)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
 
new public MailElement this[string Name]
{
get
{
return (MailElement)BaseGet(Name);
}
}
 
public int IndexOf(MailElement mail)
{
return BaseIndexOf(mail);
}
 
public void Add(MailElement mail)
{
BaseAdd(mail);
}
protected override void BaseAdd(ConfigurationElement element)
{
BaseAdd(element, false);
}
 
public void Remove(MailElement mail)
{
if (BaseIndexOf(mail) >= 0)
BaseRemove(mail.Name);
}
 
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
 
public void Remove(string name)
{
BaseRemove(name);
}
 
public void Clear()
{
BaseClear();
}
}
 
 
public class MailElement : ConfigurationElement
{
public MailElement(String name, String mail)
{
this.Name = name;
this.Mail = mail;
}
 
public MailElement ()
{
}
 
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get
{
return (string)this["name"];
}
set
{
this["name"] = value;
}
}
 
[ConfigurationProperty("mail", DefaultValue = "http://www.microsoft.com", IsRequired = true)]
public string Mail
{
get
{
return (string)this["mail"];
}
set
{
this["mail"] = value;
}
}
 
}
}

23 April 2010

Get only the date part of a DATETIME

To get only the date part of a DATETIME on an efficient manner use the following code:


CAST(FLOOR( CAST( GETDATE() AS FLOAT )) AS DATETIME)

15 April 2010

Fastest Storage for SQL Server please

A SQL Server database server with large data files, low main memory and slow data storage (disks) can compromise the performance of an application.
The solution is to add more main memory or get a fastest storage. If the data files are too large then the fastest storage is the only option.
There are solutions that really can do miracles...but at a price.
One of those solutions is the RamSan-440.
The main specifications are:

- 256GB or 512GB DDR RAM primary storage backed up by fast flash secondary storage
- Over 600,000 random I/Os per second
- 4500 MB/s random sustained external throughput
- Full array of hardware redundancy to ensure availability
- Exclusive Active Backup® software constantly backs up data without any performance degradation. Other SSDs only begin to backup data after power is lost.
- Patented IO2 (Instant-On Input Output) software allows data to be accessed during a recovery. Customers no longer have to wait for a restore to be completed before accessing their data.

With this hardware the problems are over...but when you talk to a CEO or an Administrator about the solution and the price, in most of the situations he doesn't mid to wait!!! :))

For more information press here.

You can also take a look at The Fastest Solid State Disks (SSDs)

30 March 2010

How to add a forms authentication cookie to the request

A common problem is how to add an forms authentication cookie to the request.
The solution is to add the forms authentication cookie when performing a HttpWebRequest.


Uri uri = new Uri("http://services.mysite.com/document/documentservice.svc");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);       
 
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
Cookie authenticationCookie = new Cookie(FormsAuthentication.FormsCookieName, cookie.Value, cookie.Path, HttpContext.Current.Request.Url.Authority);
webRequest.CookieContainer = new CookieContainer();
webRequest.CookieContainer.Add(authenticationCookie);
WebResponse myResponse = webRequest.GetResponse();
Stream stream = myResponse.GetResponseStream();

04 March 2010

Patterns Parallel Programming

In the .NET Framework 4.0 there is a Parallel Programming model that is worth understanding.
I recommend the reading of
Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4

Good reading.

28 January 2010

How to enumerate enum values?

To enumerate an enum use the GetValues of the Enum class.

For example:

foreach (int carColorValue in Enum.GetValues(typeof(CarColorEnum))
{
string carColorName = Enum.GetName(typeof(CarColorEnum), carColorValue);
}