Back to Basics – Deleting Cookies using ASP.NET

You cannot instruct ASP.NET to physically remove cookies from the user’s computer so you have to tell the user’s browser to modify the cookie in order to trigger the browser to remove the cookie.

See code example:

1
2
3
4
5
6
7
8
9
HttpCookie aCookie;
string cookieName;
int limit = Request.Cookies.Count;
for (int i=0; i {
cookieName = Request.Cookies[i].Name;
aCookie = new HttpCookie(cookieName);
aCookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(aCookie);
}

 

References:

http://msdn.microsoft.com/en-us/library/ms178194.aspx#Y5776

You receive a “The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect” exception when using NVarchar parameters with Sqlclient

The problem

I got the following random error:

You receive a “The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect” exception when using NVarchar parameters with Sqlclient

The Solution

Its a known bug with the .Net SqlClient Data Provider.   If you have a field in the database of type nvarchar(max) or greater than 4000 characters and if the user enters data into the field greater than 4000 characters via the .Net SqlClient Data Provider you will receive an exception.

To get around this, reduce the field size to less that 4000 characters or change your type to ntext or set the Sqlparamter.size property to -1 to allow the entire data to be saved.

References




http://support.microsoft.com/kb/970519

Open XML – OLE Automation Date Issues

If you are exporting a date from C# to Excel using 2007, you probably will use the following:

1
Math.Round(DateTime.Now.ToOADate(), 12).ToString()

This exports the date as a OLE Automation date recognized by Excel 2007. How ever, in Excel 2010 this was causing issues, every time I exported to Excel 2010, it said that it has to repair my document and it never displayed the values correctly as dates.

Because I was using Open XML to generate the markup, Excel 2010 has been support for Open XML. I got around the problem of using:

1
DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffzzz");

This exports the date as a XML Date format.
Hope this helps anyone who has the same problem!

EF Strongly Typed ObjectQuery.Include

The problem that I faced was having to put up with “hard coded” strings in the ObjectQuery.Include function to load related objects through POCO objects in the Entity Framework. This faced challenges when I renamed columns in the Model which caused a run-time error when recompiling and re-starting the application. Thanks to David Kiff, we can now change the code from being strings:

1
2
3
4
using (CommuicationsEntities entities = new CommuicationsEntities())
{
entities.Order.Include("OrderDetails");
}

To a nice strongly typed includes using a IncludeBuilder class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class IncludeBuilder
{
private readonly List _propertiesToInclude;

public IncludeBuilder()
{
_propertiesToInclude = new List();
}

public void Add(Expression<Func<T, object>> propertySelector)
{
MemberExpression memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("Parameter propertySelector must be a MemberExpression");
_propertiesToInclude.Add(memberExpression.Member.Name);
}

public ObjectQuery Includes(ObjectQuery query)
{
foreach (string include in _propertiesToInclude)
{
query = query.Include(include);
}
return query;
}
}

the following code calls the include builder, includes the relationship and gets a simple list with no tracking on the POCO objects.

1
2
3
4
IncludeBuilder _include = new IncludeBuilder();
_include.Add(a => a.Orders);
ObjectQuery customers= DataContext.Servers;
return _include.Includes(customers).Execute(MergeOption.NoTracking).ToList();

References:

http://davidkiff.co.uk/post/2009/08/27/EF-Strongly-Typed-ObjectQuery3cT3eInclude%28e2809ce2809d%293b.aspx

Fixing the EF Tracing and Caching Provider Wrapper Issue

If you have been using the Tracing and Caching Provider Wrappers for the ADO.NET Entity Framework 4.0, you might of come across this error message when creating POCO objects, adding them to a Data Context and commiting them to the database using the Caching Wrapper:

[NotImplementedException: The method or operation is not implemented.]
   EFCachingProvider.EFCachingDataReaderCacheWriter.GetName(Int32 ordinal) in EFCachingProvider\EFCachingDataReaderCacheWriter.cs:109
   System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues) +8118458
   System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) +267

Line 107:        public override string GetName(int ordinal)
Line 108:        {
Line 109:            throw new NotImplementedException();
Line 110:        }
Line 111:

Basically, the author’s of the code have created a wrapper for the DBDataReader class and have not implement the override methods.   This can be fixed by calling the Wrapper DataReader object methods.  This is what I have modified in the EFCachignDataReaderCacheWriter.cs file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
using System;
using System.Data;
using System.Data.Common;
using EFCachingProvider.Caching;

namespace EFCachingProvider
{
///
/// Implementation of the  which reads the results of another data reader
/// and stores a copy in the cache.
///
internal class EFCachingDataReaderCacheWriter : EFCachingDataReaderBase
{
private DbQueryResults queryResults = new DbQueryResults();
private DbDataReader wrappedReader;
private int maxRows;
private Action addToCache;

///
/// Initializes a new instance of the EFCachingDataReaderCacheWriter class.
///
///
<span> </span>The wrapped reader.         ///
<span> </span>The maximum number of rows which can be cached.         ///
The delegate used to add the result to the cache when the reader finishes.         public EFCachingDataReaderCacheWriter(DbDataReader wrappedReader, int maxRows, Action addToCache)
{
this.wrappedReader = wrappedReader;
this.addToCache = addToCache;
this.maxRows = maxRows;
}

///
/// Gets a value that indicates whether this  contains one or more rows.
///
///
/// true if the  contains one or more rows; otherwise false.
///
public override bool HasRows
{
get { return this.wrappedReader.HasRows; }
}

///
/// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement.
///
///
///
/// The number of rows changed, inserted, or deleted. -1 for SELECT statements; 0 if no rows were affected or the statement failed.
///
public override int RecordsAffected
{
//get { throw new NotImplementedException(); }
get { return this.wrappedReader.RecordsAffected; }
}

///
/// Gets a value indicating whether the  is closed.
///
///
/// true if the  is closed; otherwise false.
///
public override bool IsClosed
{
//get { throw new NotImplementedException(); }
get { return this.wrappedReader.IsClosed; }
}

///
/// Gets a value indicating the depth of nesting for the current row.
///
///
///
/// The depth of nesting for the current row.
///
public override int Depth
{
//get { throw new NotImplementedException(); }
get { return this.wrappedReader.Depth; }
}

///
/// Gets name of the data type of the specified column.
///
///
The zero-based column ordinal.         ///
/// A string representing the name of the data type.
///
public override string GetDataTypeName(int ordinal)
{
//throw new NotImplementedException();
return this.wrappedReader.GetDataTypeName(ordinal);
}

///
/// Gets the data type of the specified column.
///
///
The zero-based column ordinal.         /// The data type of the specified column.
public override Type GetFieldType(int ordinal)
{
return this.wrappedReader.GetFieldType(ordinal);
}

///
/// Gets the name of the column, given the zero-based column ordinal.
///
///
The zero-based column ordinal.         /// The name of the specified column.
public override string GetName(int ordinal)
{
return this.wrappedReader.GetName(ordinal);
}

///
/// Gets the column ordinal given the name of the column.
///
///
The name of the column.         /// The zero-based column ordinal.
///
/// The name specified is not a valid column name.
///
public override int GetOrdinal(string name)
{
return this.wrappedReader.GetOrdinal(name);
}

///
/// Returns a  that describes the column metadata of the .
///
///
/// A  that describes the column metadata.
///
public override DataTable GetSchemaTable()
{
return this.wrappedReader.GetSchemaTable();
}

///
/// Advances the reader to the next result when reading the results of a batch of statements.
///
///
/// true if there are more result sets; otherwise false.
///
public override bool NextResult()
{
if (this.wrappedReader.NextResult())
{
this.queryResults = null;
return true;
}
else
{
return false;
}
}

///
/// Closes the  object.
///
public override void Close()
{
this.wrappedReader.Close();

if (this.queryResults != null)
{
this.addToCache(this.queryResults);
}
}

///
/// Advances the reader to the next record in a result set.
///
///
/// true if there are more rows; otherwise false.
///
public override bool Read()
{
if (this.wrappedReader.Read())
{
object[] values = new object[this.wrappedReader.FieldCount];

this.wrappedReader.GetValues(values);
SetValues(values);
if (this.queryResults != null)
{
this.queryResults.Rows.Add(values);
if (this.queryResults.Rows.Count &gt; this.maxRows)
{
this.queryResults = null;
}
}

return true;
}
else
{
return false;
}
}
}
}

Detect when a session has ended ASP.NET

A problem that I have had in the past is trying to find out when a session has expired within ASP.NET and how to deal with the expired session.   One solution is to add the following code into the Page_Init event.   You can add this event into a class that inherits the Page class so that you can reuse on more than one page or all pages if needed.

1
2
3
4
5
6
7
8
If Not Context.Session Is Nothing Then
If Session.IsNewSession Then
Dim szCookieHeader As String = Request.Headers("Cookie")
If Not String.IsNullOrEmpty(szCookieHeader) And szCookieHeader.IndexOf("ASP.NET_SessionId") &gt;= 0 Then
Response.Redirect("/sessiontimeoutpage.aspx")
End If
End If
End If

This code checks if a new session has been created and if the header has a ASP.NET Session id.   This makes sure that we are checking for a session that has just been created.

Random number of items from a Generic List extension method

Here is a code snippet  for returning N number of items from a generic list using a extension method.  This requires .NET 3.5.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public static class Extensions
    {
        /// <summary>
        /// method for returning N number of random items from a generic list
        /// </summary>
        /// <typeparam name="T">Item type</typeparam>
        /// <param name="list">Generic list we wish to retrieve from</param>
        /// <param name="count">number of items to return</param>
        /// <returns></returns>
        public static IEnumerable<T> Randomize<T>(this List<T> list, int count)
        {
            List<T> randomList = new List<T>();
            Random random = new Random();

            while (list.Count > 0)
            {
                //get the next random number between 0 and
                //the list count
                int idx = random.Next(0, list.Count);

                //get that index
                randomList.Add(list[idx]);

                //remove that item so it cant be added again
                list.RemoveAt(idx);
            }

            //return the specified number of items
            return randomList.Take(count);
        }

        /// <summary>
        /// method for returning 1 item from the generic list
        /// </summary>
        /// <typeparam name="T">Item type</typeparam>
        /// <param name="list">Generic list we wish to retrieve from</param>
        /// <param name="count">number of items to return</param>
        /// <returns></returns>
        public static T Randomize<T>(this List<T> list)
        {
            return Randomize(list, 1).FirstOrDefault();
        }
    }

used in code by calling the following: List<mytype> = myGenericList.Randomise(5) or mytype = myGenericList.Randomise();

Could not load file or assembly ‘NameOfAssemblyGoesHere’

Encounted the following error:

Could not load file or assembly ‘NameOfAssemblyGoesHere’ or one of its dependencies. An attempt was made to load a program with an incorrect format.

The problem happened when deploying a web application to a 64bit server where all the required DLL’s where marked as running only on a 32bit system.   You can change this by setting the target platform to AnyCPU which will solve this issue.   There is another workaround which is setting IIS compatability mode to 32bit, Open a command prompt and navigate to the %systemdrive%\Inetpub\AdminScripts directory.  Type in the command cscript.exe adsutil.vbs set W3SVC/AppPools/Enable32BitAppOnWin64 “true”.

Change username in ASP.NET Membership Provider

Found a great article here about the process of changing the username with the ASP.NET Membership Provider.

Here is a summary of the process that I found best useful which is one of the comments:

1. Make sure New UserName is Unique

2. Update the aspnet_Users table directly

3. Execute to following code to change the username/cookie/identity without leaving the webpage…

‘ Obtains the name of the FormsAuthentication Cookie, uses that name to request the Cookie and Decrypts the Cookies information into a AuthTicket

Dim AuthTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName).Value)

‘ Instantiates a new user identity authenticated using forms authentication based on the FormsAuthenticationTicket.

‘ The FormsAuthenticationTicket has been created using the exact same parameters of the user with the Old Username except the Old Username has been updated with the New Username.

Dim NewFormsIdentity As New FormsIdentity(New FormsAuthenticationTicket(AuthTicket.Version, NewUsername, AuthTicket.IssueDate, AuthTicket.Expiration, AuthTicket.IsPersistent, AuthTicket.UserData))

‘ Parse out the AuthTicket’s UserData into a string array of Roles

Dim Roles As String() = AuthTicket.UserData.Split(“|”.ToCharArray)

‘ Creates a new user that has the NewFormsIdentity and belongs to the array of Roles, if any, that was stored in the FormsAuthenticationTicket

Dim NewGenericPrincipal As New System.Security.Principal.GenericPrincipal(NewFormsIdentity, Roles)

‘ Sets the security information for the current HTTP request to the new user. The Username has now been changed (i.e. HttpContext.Current.User.Identity.Name = NewUsername, prior to this step is was the OldUsername)

HttpContext.Current.User = NewGenericPrincipal

‘ Removes the forms-authentication ticket from the browser

FormsAuthentication.SignOut()

‘ Cancels the current session

HttpContext.Current.Session.Abandon()

‘ Creates an authentication ticket for the supplied New Username and adds it to the cookies collection of the response or the URL

FormsAuthentication.SetAuthCookie(HttpContext.Current.User.Identity.Name, AuthTicket.IsPersistent)

4. Response.Redirect back to the same page if needed.

References:

http://omaralzabir.com/how_to_change_user_name_in_asp_net_2_0_membership_provider/

IIS Wont start error 13 data is invalid

I got the following error when trying to figure out why I couldn’t start IIS 7 on Windows Server 2008 R2.    I tried to start the World Wide Web Publishing Service but its dependency Windows Activation Service wouldn’t start.   I got the following error in the Event Log:

The Windows Process Activation Service service terminated with the following error:
The data is invalid.

After doing some research, I found a good article here.   But I still had the issue, it turned out that I had a valid applicationHost.config file but my C:\Windows\system32\inetsrv\config\schema\NetFx40_IIS_schema_update.xml file was corrupt and had invalid XML.   So I was able to recover the XML file from the C:\inetput\history\schema folder.  Fewl!   Run all the services again and had no problems.

References:

http://www.gringod.com/2008/08/15/when-iis-wont-start-error-13/

http://www.gringod.com/2008/08/15/when-iis-wont-start-error-13/”