Tuesday, March 03, 2009

Serialize and Deserialize objects in .NET

I'm not sure why XML standard doesn't allow certain characters to be encoded into XML... and it causes problems.

This C# code:

XmlSerializer xs = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(objString)))
{
obj = xs.Deserialize(memoryStream);
}

crashes with exception:
System.InvalidOperationException: There is an error in XML document (1, 50). ---> System.Xml.XmlException: ' ', hexadecimal value 0x0C, is an invalid character. Line 1, position 50.

Here's the fix and the fully working version (note that XmlTextReader is used in between MemoryStream and XmlSerializer:


[TestMethod()]
public void SerializeDeserializeObjectTest()
{
SerializeDeserializeObjectTest("test");
SerializeDeserializeObjectTest("\f");
}

private void SerializeDeserializeObjectTest(string input)
{
string serialized = Serializer.SerializeObject(input);
string deserialized = Serializer.DeserializeObject<string>(serialized);
Assert.AreEqual(input, deserialized, input);
}


public static class Serializer
{
public static string SerializeObject(Object obj)
{
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(obj.GetType());
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
return UTF8ByteArrayToString(memoryStream.ToArray());
}

public static T DeserializeObject<T>(string objString)
{
Object obj = null;
XmlSerializer xs = new XmlSerializer(typeof(T));
using (MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(objString)))
{
XmlTextReader xtr = new XmlTextReader(memoryStream);
obj = xs.Deserialize(xtr);
}
return (T)obj;
}

private static string UTF8ByteArrayToString(byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetString(characters);
}

private static byte[] StringToUTF8ByteArray(string xmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}

}



Thanks to Tom Goff for XML Serialization Sorrows article.

Thanks to Andrew Gunn for XML Serialization in C# article.

Friday, January 09, 2009

Troubleshooting SqlCacheDependency in SQL Server 2008 and SQL Server 2005

"Getting immediate notification from SQL Server when data changes" is a very attractive feature, but unfortunately it's not easy to implement.
(It took me full day to identify and fix all issues...).

SQL Server Query Notification framework is quite fragile and may not work for multiple reasons.
If you get error messages -- consider youself lucky. Sometimes there will be no error messages, but notifications simply would refuse to work.

There are two major steps in troubleshooting SqlCacheDependency notifications:
Step 1: Make SqlCacheDependency clean up ASP.NET Cache item.
Step 2: Prevent SqlCacheDependency from cleaning up ASP.NET Cache item when it's inapropriate.

Both steps are hard, but Step 1 is the hardest.

I strongly recommend iterative approach: implement the easiest possible solution first, and then make it more advanced one small step at a time. Test every little step.


Business context


In this example I use SqlCacheDependency in order to get list of blocked IP addresses on my web site PostJobFree.com.
From time to time I delete bad users and write their IP addresses into BlackListIpAddress table.

I can retrieve the list of recently blocked IP addresses like that:

CREATE Procedure spGetBlockedIpList
@cutDate datetime
AS

set nocount on
select IpAddress
from BlackListIpAddress with (nolock)
where (DecisionDate > @cutDate)
group by IpAddress
having count(1) > 1
GO

When anybody opens web page -- I check if current web page request came from that list of blocked IP addresses.
I created C# function that does that check:
public static bool IsBlackListed(string ipAddress)
{
bool cached;
if (GetBlockedIpAddresses(out cached).Contains(ipAddress)) return true;
return false;
}

Because I run IsBlackListed() on every page, I don't want to run spGetBlockedIpList without need.
So, I keep database results in ASP.NET Cache object and use SqlCacheDependency to clean up Cache object as soon as new IP address is blacklisted in BlackListIpAddress table.



Implementation

public static List GetBlockedIpAddresses(out bool cached)
{
HttpContext context = HttpContext.Current;
List blockedIPs = (List)context.Cache["BlockedIPAddresses"];
if (blockedIPs == null)
{
SqlCommand cmdDependency = new SqlCommand(@"select IpAddress from dbo.BlackListIpAddress where DecisionDate > @cutDate",
SqlUtilities.GetSqlConnection("PostJobFreeConnectionString"));
SqlUtilities.AddInputParameter(cmdDependency, "@cutDate", DateTime.UtcNow.AddMinutes(-1), SqlDbType.DateTime);
SqlCacheDependency dependency = new SqlCacheDependency(cmdDependency);
SqlUtilities.ExecuteNonQuery(cmdDependency, "PostJobFreeConnectionString");
blockedIPs = LoadBlockedIPsFromDatabase();
// Cache retrieved blockedIPs in ASP.NET Cache object:
context.Cache.Insert("BlockedIPAddresses", blockedIPs, dependency);
cached = false;
}
else
{
cached = true;
}
return blockedIPs;
}


Note, that almost always blockedIPs will be retrieved from ASP.NET Cache.
But if Cache["BlockedIPAddresses"] is empty -- I execute two SQL queries instead of one query.

I run simple query "select IpAddress from dbo.BlackListIpAddress where DecisionDate > @cutDate" in order to make SqlCacheDependency work.
I then run more complex query LoadBlockedIPsFromDatabase() (it runs spGetBlockedIpList) in order to get data I need.
spGetBlockedIpList is too complex to work with SqlCacheDependency.

Simple query is not smart enough to give me the data I need.

When you debug your own code -- dump more complex query and use only simple one.
Remember -- first step is to make SqlCacheDependency clean up ASP.NET Cache item.
If SqlCacheDependency cleans up your ASP.NET Cache -- you are about 70% done.

You may even start with even simpler SQL query. For example: "select IpAddress from dbo.BlackListIpAddress". You would polish it later.

Preparations


1) Make sure that when your Web Application start, you run SqlDependency.Start().
I do it this way:
public sealed class DenyIpAddressModule : IHttpModule
{
void IHttpModule.Init(HttpApplication application)
{
string connectionString = WebConfigurationManager.
ConnectionStrings["PostJobFreeConnectionString"].ConnectionString;
SqlDependency.Start(connectionString);
}
}
If you forget to do that, you would get "When using SqlDependency without providing an options value, SqlDependency.Start() must be called prior to execution of a command added to the SqlDependency instance." error message.

2) Enable Service Brocker on your database.
I do it like this in SQL Server Management Studio (SSMS):
use PostJobFree;
alter database PostJobFree set ENABLE_BROKER;

The trick here is to kill all existing connections prior to altering your database.
Use these SQL commands in SSMS:
sp_Who2
kill 52 -- or whatever SPID is


You may check your Service Broker setting like this:
use PostJobFree;
select is_broker_enabled from sys.databases where database_id=db_id()

1 - Enabled; 0 - Disabled (default).

3) Make sure that permissions in your database are not out of whack. SQL Server 2005 and SQL Server 2008 have unpleasant bug that [almost] silently kills Queue Notifications:
"You cannot run a statement or a module that includes the EXECUTE AS clause after you restore a database in SQL Server 2005" http://support.microsoft.com/kb/913423

I fixed it by running this command:
use PostJobFree
GO
sp_changedbowner [MyServerName\dennis]

You may check current database settings by this command:
sp_helpdb PostJobFree


Troubleshooting


1) If you are still unable to make SqlCacheDependency to invalidate your ASP.NET Cache, I recommend you great article "Using and Monitoring SQL 2005 Query Notification"
http://www.simple-talk.com/sql/sql-server-2005/using-and-monitoring-sql-2005-query-notification/
Sanchan explains how to use SQL Profiler to see what's going on with query notifications.
2) Using Profiler helped me to find the following errors in SQL Profiler:
- An exception occurred while enqueueing a message in the target queue. Error: 33009, State: 2. The database owner SID recorded in the master database differs from the database owner SID recorded in database 'PostJobFree'. You should correct this situation by resetting the owner of database 'PostJobFree' using the ALTER AUTHORIZATION statement.
- Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission.
That gave me an idea to run:
sp_changedbowner [MyServerName\dennis]


3) These couple of queries would let you take a look at what active Query Notification Subscriptions you currently have:
select * from sys.dm_qn_subscriptions
select * from sys.transmission_queue

4) I didn't need that step, but while troubleshooting I did it anyway.
Grant these permissions to the user account that runs your web application (it's usually either "aspnet" or "NT AUTHORITY\NETWORK SERVICE").
use PostJobFree
GRANT CREATE PROCEDURE TO [MyServerName\aspnet]
GRANT CREATE QUEUE TO [MyServerName\aspnet]
GRANT CREATE SERVICE TO [MyServerName\aspnet]
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO [MyServerName\aspnet]
GRANT SELECT ON OBJECT::dbo.BlackListIpAddress TO [MyServerName\aspnet]
GRANT SELECT ON OBJECT::dbo.T TO [MyServerName\aspnet]
GRANT RECEIVE ON QueryNotificationErrorsQueue TO [MyServerName\aspnet]
ALTER DATABASE PostJobFree SET TRUSTWORTHY ON


Clean up Cache only when needed


I assume that at this point you are done with the hardest part ("Make SqlCacheDependency object clean up Cache").
There is still some work ahead.
For example I noticed that my SqlCacheDependency code when I was playing with it -- always invalidated ASP.NET Cache. It didn't matter if I updated underlying BlackListIpAddress table or not.
By using trial & error approach I found that the problem was caused by using inapropriate version of SQL query.
I found that:
- "group by" doesn't work no matter what.
- "top 10" doesn't work.
- "with (nolock)" hint doesn't work.
- passing @cutDate parameter to the query _does_ work.

See documentation on SELECT statements that are supported by Query Notification: http://msdn.microsoft.com/en-us/library/ms181122(SQL.90).aspx


Other useful resources


1) More tips about SQL Server Query Notification:
http://rusanu.com/2006/06/17/the-mysterious-notification/

2) Troubleshooting Query Notifications
http://msdn.microsoft.com/en-us/library/ms177469.aspx

3) If you are lucky and expect everything to go smooth - use this articles:
SqlCacheDependency using ASP.NET 2.0 and SQL Server 2005
SQL 2005 and SQL2008 Enabling Notifications. SQL Chache Dependancy Part-I

Keywords:
ASP.NET 2.0, ASP.NET 3.5, C#

Wednesday, September 24, 2008

Cross Site Scripting and Cross Site Request Forgery

Jeff Atwood wrote a good article explaining the danger of XSRF and XSS

1) I want to confirm that checking UrlReferrer [hoping to prevent XSRF attack] is a waste of time. UrlReferrer can be spoofed by malicious user. Such spoofing can be done by combination of XSS and XSRF attack: injecting javascript into HTML output (XSS) on one web page and producing forged request (XSRF) pointing to another page of the same web site.
Jeff is also correct that legitimate users may have empty UrlReferrer. Rejecting such users is a mistake.

2) I agree that introducing parameters cuts off the most obvious XSRF attacks.
But if one of your pages is XSS vulnerable (allows javascript injection), then even if you have dynamic parameters to prevent XSRF (on another page), javascript can still read these dynamic parameters and re-submit them, so the request would succeed.
That's how Gmail was hacked -- the hacker used XSS vulnerability on some obscure Google's web site site in order to exploit XSRF vulnerability in Gmail).

Monday, August 25, 2008

Cure for "deadlocked!": learning to use proper SQL hints

Jeff Atwood's article Deadlocked! made me recall my painful experience with default locking settings in SQL Server.
Default select queries with (readcommitted) just don't work reliably in real life (because they cause deadlocks on regular basis).

It was hard to ignore scary stuff from SQL theoreticians about "dirty data", but eventually I've learned to use "with (nolock)" hint for most of my SELECT queries.
That doesn't mean that all queries should be written with nolock, but most of SQL queries should.
Especially if I'm writing web app.

In some situations I want to be sure that the data is consistent no matter what. In this case I use different locking hints. Which hints to use heavily depends on particular situation.

It's important to clearly understand what exactly locking does.
The locking model is relatively simple, however most of SQL Server locking tutorials are just terrible.

How-To learn SQL Server locking Tutorial

The best approach to learn about locking is to experiment:

1) Open three separate windows in SQL Management Studio.
Window One: for lock diagnostic sp_lock
Window Two: for pending transaction with Update/Delete/Insert query.
Window Three: for SELECT statements with different locking hints.

2) In Window One write and execute:
exec sp_lock
Take a look at the results.
Note what locks are there (these locks are generated by sp_lock itself).
Learn about what these locks mean (Google is your friend).

3) In Window Two (that's separate connection to SQL server) write and execute:
============
begin transaction
update MyTestTable set MyColumn = 1
-- rollback transaction
============
Note, that "rollback transaction" is commented out, so transaction won't complete.

4) Return back to Window One and execute sp_lock.
Note what additional locks you see in sp_lock results.

5) In Window Three execute:
select * from MyTestTable with (updlock)
The query won't complete, because it's locked by pending transaction in Window Two.

6) Switch to Window Two and cancel transaction by executing "rollback transaction"
Make sure that SELECT transaction in Window Three is completed now.

7) Try different combinations of locks (readcommitted), (nolock), (updlock), (repeatableread), (serializable), ... in Window Three.
Try other different update/insert/delete statements in Window Two.

8) Try to use "commit transaction" instead of "rollback transaction" in Window Two and see how it would affect SELECT results in Window Three.

9) Try to run:
begin transaction
select * from MyTestTable with (updlock)
in Window Two and:
select * from MyTestTable with (serializable)
in Window Three.

10) Keep monitoring locks using sp_Lock in Window One.

11) Do free-style experimenting and research problem on Google when you are getting unexpected results.

Saturday, August 02, 2008

RackSpace - are they really the best web hosting?

About a month ago I switched from Virtual Private Hosting on webhost4life to dedicated hosting on RackSpace.
It was definitely an improvement, but I'm still dissatisfied.


Here are painful parts of my experience with RackSpace:

1) RackSpace wanted me to sign paper contract (WebHost4Life didn't require that). That paperwork took almost a day (several hours of my efforts + some wait time). Sales guy couldn't open several versions of "Microsoft Office Image Writer" that I emailed to him, so I had to resend the document in different format.

2) It is a little unpleasant to deal with RackSpace sales guys. They forget (or "forget") to answer some of my questions; use some slightly unpleasant pushy sales techniques. Is it typical for any sales reps, not only RackSpace's sales?

3) After the contract was signed, it took RackSpace almost 4 days to install the server. I signed the contract Wednesday July 3rd 2008 and was hoping that on Saturday-Sunday night I'll be able to move my web site (www.postjobfree.com) to RackSpace. But RackSpace set up my server only on Monday - not convenient time for me and my users to do the move.

4) RackSpace promised me that they would help with the migration. They gave some tips, but not all of them were good. For example, they suggested me to shut down my web site for few hours while I will copy my database. Not a good approach for 24/7 service. So, basically I was mostly left on my own with the migration.
Fortunately, I used advise of Omar Al Zabir about smooth web hosting migration
Ironically -- it was Omar's recommendation to use RackSpace for web hosting that made me pick them.

5) Average response to my ticket requests is about few hours (2-3 may be?). Sometimes ticket response time is shorter; sometimes it's longer (up to a day or even more in some cases). It's an improvement in comparison with WebHost4Life, but is that really the best in hosting industry?

6) Most of the time responses are good, rarely great, and in some cases responses are incompetent :-(
For example, I asked RackSpace if it would be a good idea to run SMTP server on separate IP address (same physical machine). A RackSpace guy replied that it would be a good idea. So we did the switch. But it turned out that RackSpace cannot monitor ports on another IP addresses (only on primary IP address). So we updated SMTP server settings again to allow listen both IP addresses. That caused SMTP server to use primary IP address to send emails, but at this point smtp.postjobfree.com DNS record was pointing to second IP address, and this caused painful issues with spam filters on some servers. In the end we returned back to using primary IP for SMTP, but went through some pain because of incompetent advice.

7) RackSpace seems to be not really good in analyzing past problems. They simply ignored my request about digging into this incompetent SMTP advice. Nothing like "sorry, we screwed up and would do this and that to prevent it in the future". Nothing like "sorry, it was misunderstanding and you (me) should do this and that to avoid problems in the future". I would understand if cheap hosting provider would skip such "past failure analysis". But if hosting provider claims "fanatical support" - I expect to do a little better.
Well, may be it happenned because I still didn't have a chance to talk with my account manager. RackSpace doesn't have one for me yet (after being with RackSpace for a month):

8) Rackspace's ticketing system creates unneeded noise. For example, after I create a ticket on my.rackspace.com, it adds meaningless auto-response to the ticket and sends me notification email. If I update a ticket, I get notification email again. Why would I need notification about ticket updates I made myself? That's distracting.

9) Maintenance downtime. :-(
I mentioned already that RackSpace considered few hours web site downtime during migration as "ok" practice. That attitude goes toward other maintenance things too. Today they installed hardware firewall on my server. They brought down my server for almost an hour (!). Could anybody explain me why installation of hardware firewall should bring server down for almost an hour? It should be less than a minute downtime, or preferably zero downtime. That was disappointing. I managed to migrate web server from different hosting with no downtime (I copied 4 GB database between WebHost4Life and RackSpace and still managed to avoid downtime) and now trivial installation of hardware firewall caused almost an hour downtime:

10) The hardware firewall installation caused another issue as well -- my web site was not able to send out emails after the firewall installation. RackSpace didn't notice that, because their SMTP port monitoring didn't catch the issue. We noticed it few hours later and reported in a ticket. We got no reply for couple of hours, so I had to call RackSpace and remind that the issue is still there. They were not very good in pinpointing the issue. They were trying to re-test SMTP server and it worked. So we (at PostJobFree) had to find it out the problem ourselves. The problem was that smtp.postjobfree.com could be pinged from every computer, but not from my server itself, because hardware firewall didn't resolve the request from my server back to the server itself.
RackSpace techies couldn't grasp that for a while even after I pointed them into that direction. Eventually they recommended to update my application and made it use my new 192.168.x.x IP address for sending emails. Imagine that: update and redeploy my application web app to accommodate to hardware changes. And do it in the hurry after(!) hardware firewall is installed.
I suggested better solution: simply add one record to C:\WINDOWS\system32\drivers\etc\hosts:
127.0.0.1 smtp.postjobfree.com
RackSpace techies still cannot grasp that solution and comment on it. Fortunately my solution works so far.

11) There were few other minor issues, but I think my saga is getting too long already.

On the bright side:

1) When my server works (and it usually works) it works really fast. I'm happy with the speed so far. Though I'm not sure if I should attribute it to RackSpace or to dedicated server. With WebHost4Life SQL server was shared with 4 other clients and in the end I was getting 50+ timeouts/day.

2) Some RackSpace folks taught me some useful stuff, for example about DNS [re-]configuration.

3) RackSpace is expensive, but it's not THAT expensive. I got my server + SQL Server license + hardware firewall for a little over $600/mo (with 1 year contract)


So, what do you think, is it typical to have issues like these with any hosting provider, or there are better hosting providers out there?

Any other comments?


Update (2008 August 03):
Problems with RackSpace are getting worse.

RackSpace technician configured my SMTP server as open relay
:-(

That's how it sounded on the ticket:
"We did find a setting in your SMTP that was set incorrectly, and we corrected that."

In fact, SMTP server was configured properly and the problem was with DNS configuration. Instead of fixing DNS (after installing Hardware Firewall) RackSpace guys made the problems much worse by turning my SMTP server into spam-machine and enabling prompt access to all spammers through newly installed hardware firewall.

Crazy stuff.

Thursday, April 03, 2008

TechCrunch pushes Start-ups to fail

If you want to announce your start-up on TechCrunch50 the only thing you need to do is to sell your soul to the Devil deny your prospective customers access to your web site. Here's the quote:
Rules of participation in TechCrunch50
Until its presentation on stage at the conference, a company will keep its site password protected with limited private access to alpha or beta users for testing purposes.
That means that you have to decrease your popularity, get less testing and less feedback, get less word of mouth, and ultimately get less revenue.

On the other hand, your participation in TechCrunch50 would be free.

Free is good, isn't it?

Wednesday, March 26, 2008

Encrypt App.config

// Run "Encryption.EncryptConnectionStrings();" in the beginning of your winservice or winforms app.
// You need to add .NET reference to System.configuration.dll
using System.Configuration;
public static class Encryption
{
public static void EncryptConnectionStrings()
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection section = configuration.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
section.SectionInformation.ForceSave = true;
configuration.Save(ConfigurationSaveMode.Modified);
}
}

public static void DecryptConnectionStrings()
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationSection section = configuration.GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave = true;
configuration.Save(ConfigurationSaveMode.Modified);
}
}
}

Followers

About Me

My photo
Email me: blog@postjobfree.com