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()
 

16 January 2009

How To: Change the tempdb data files location

To change the tempdb data files location:
1) Determine the logical file names for the tempdb database.
The logical name for each file is contained in the NAME column.

USE tempdb
GO
EXEC sp_helpfile

2)Change the location of each file using ALTER DATABASE.
USE master
GO
ALTER DATABASE tempdb MODIFY FILE (NAME = tempdev, FILENAME = 'E:\DBData\tempdb.mdf')
GO
ALTER DATABASE tempdb MODIFY FILE (NAME = templog,FILENAME = 'E:\DBData\templog.ldf')
GO
3) Stop and restart SQL Server.

14 January 2009

Fix: Saving changed to a table not permitted on SQL Server 2008

An error message occurs when you try to save table chnages in SQL Server 2008 Management Studio:
Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created.

This problem occurs when the Prevent saving changes that require the table re-creation option is enabled.

To disable it:
1) Open SQL Server Management Studio (SSMS).
2) On the Tools menu, click Options.
3) Click Designers.
4) Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note that if you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

This is a bug from microsoft, more information here.

07 January 2009

How To: Drop a user that owns a schema

SQL Server returns the error

The database principal owns a schema in the database, and cannot be dropped

when a user is being dropped that owns a schema in the database.

The delete the user go to Sql Server Management Studio, expand your database -> Security and press on Schemas. In the Object Explorer Details (if not visible go to the View Menu e select Object Explorer Details) you can see a list of the schemas and the owners.

Now locate the schema(s) the user you want to delete is the owner, right click and select properties. In the General you can see the schema owner, change it to the new owner (dbo for example).

When the user you want to delete has no schemas owned you can delete it.

23 December 2008

How To: Turn on database statistics

Execute the following T-SQL:
ALTER DATABASE SET AUTO_UPDATE_STATISTICS ON

HOW TO: Get the database compability level

Execute the following query to get the compability level of all the databases.

SELECT name, compatibility_level FROM sys.databases

To change the compatibility level:

ALTER DATABASE SET COMPATIBILITY_LEVEL = 100