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

06 April 2009

jQuery Intellisense in VS 2008

I have been working with the jQuery in VS 2008 and I needed jQuery intellisense support.
Since the process in not straightforward, I decided to document it here:
1) Install VS 2008 SP1
2) Install VS 2008 Patch KB958502 to Support "-vsdoc.js" Intellisense Files
You can download it for here
3) Download the jQuery-vsdoc.js from the official download page here
Use the Documentation: Visual Studio link.
4) Save the jquery-vsdoc.js file in the same folder of the jquery.js file in your project and make sure its naming prefix matches the jquery file name
5) There is no intellisense support in user controls (ascx) unless the jQuery.js file is included. Since normally we don't want to include the jQuery file in the ascx there is a workaround:


<% if (false) {%>
<% script src="js/jquery.js" type="text/javascript"><% /script>
<% } %>


For more information:
jQuery Intellisense in VS 2008

12 March 2009

How to delete a temporary table in TSQL

When a TSQL script creates a temporary table, it is useful in developing mode to drop the table if it exists.

The following script does the job:

IF OBJECT_ID( N'tempdb..#MyTempTable') IS NOT NULL
DROP TABLE #MyTempTable

How to: Restore a SQL Server database with TSQL

The task of restoring a SQL Server database with a TSQL script is as simple as executing the following script:

RESTORE DATABASE [MyDatabase]
FROM DISK = N'C:\Backup\MyDatabase.bak'
WITH  FILE = 1,
MOVE N'MyDataLogicalName' TO N'D:\DatabasesData\MyDatabase.mdf', 
MOVE N'MyLogLogicalName' TO N'D:\DatabasesLog\MyDatabase_log.ldf', 

The only problem with the previous script is that if there are any open connections to the database the following error is generated:


Exclusive access could not be obtained because the database is in use.


To fix the issue one solution is to put the database in single user mode before the backup.

-- Put the database in single user Mode
ALTER DATABASE MyDatabase
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
-- Restore the Database
RESTORE DATABASE MyDatabase FROM DISK ...
-- Put the database back in multiuser mode
ALTER DATABASE MyDatabase SET MULTI_USER
GO

If this script fails, execute the last statement to put the data base back in multiuser mode.

To simply restore the database use:
-- Put the database in single user Mode
ALTER DATABASE MyDatabase
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
-- Restore the Database
RESTORE DATABASE MyDatabase FROM DISK = N'C:\Backup\MyDatabase .bak' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10
-- Put the database back in multiuser mode
ALTER DATABASE MyDatabase SET MULTI_USER
GO

29 January 2009

Render aspx page to a HTML string

To render a aspx page to a HTML simply execute the following code:

   1: StringWriter writer = new StringWriter();
   2: HttpContext.Current.Server.Execute("~/MyPage.aspx", writer);

To convert to a string:



   1: writer.ToString()