Sunday, March 15, 2015

Of Nullable Type in C#

Nullable Types (they are used for value types) are very useful when dealing with database tables that has a column with NULLABLE value type. Allowing the default value to go through in the ORM or data layer could be misleading becuase NULL could default to the 0 value say for an int type property/column.

So use int? to assign the value of the NULLABLE int column type from the database when mapping to your POCO objects. Since we use a nullable type, we can use HasValue method while mapping the property to try to get to the value.

Nullable types DONT work for reference types like strings or your reference type POCO objects, because they are already NULLABLE (default value is NULL) and the compiler does not allow it. It makes sense, because there is no reason to add NULLABLE type to reference types which are already NULL by default.

So these are not allowed
Player? nullablePlayer;
string? nullableString;


while this is allowed
int? nullableInt; //The default value then is NULL and not 0.

Sunday, November 9, 2014

SQL Coalesce Example

What does this SQL do?

SELECT COALESCE(FirstName + ' ' + MiddleName, FirstName) + ' ' + LastName FROM Customer

If MiddleName is NULL, then FirstName + '' + MiddleName would be NULL, and so would return FirstName + ' ' + LastName.

If MiddleName is not NULL, it would return FirstName + ' ' +MiddleName + ' ' + LastName

Wednesday, October 22, 2014

Calling a WCF client proxy properly


There is a lot of discussion on how to use the WCF client proxy correctly. This is one use case where you do NOT want to use the elegant using statement, whether you are instantiating the client proxy directly or creating a service factory to create the WCF channel. In other words, don't do either of these:

using ( var client = new WcfClientProxy())
{
    .........
    .........
}

Or

using (var factory = new ChannelFactory<ISomeService>())
{
     var channel = factory.CreateChannel()
     ..........
     ..........
}


This is because the channel could have faulted ( a timeout, a connection fault etc) before dispose can be called with the using statement (the last } is where dispose is called).

The accepted best practice is to

  • wrap the call to the WCF Service using a try catch block
  • call close on the proxy at the end of the call in the try block
  • call abort (immediately calls close) at the end of each catch statement

Not doing so could leave a lot of open and non-usable channels and connections on your Server serving the WCF requests, thereby degrading performance significantly.

SO Reference
http://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue

MSDN article
http://msdn.microsoft.com/en-us/library/aa355056.aspx

And here's an interesting blog on it
http://adamprescott.net/2013/07/18/wcf-client-closal-disposal/

Sunday, September 28, 2014

Did you know - AngularJS custom Service and Promise trivia

If you are writing a custom Angular service that says goes out and

  • does a $http.get() and
  • uses  .then() promise


the .then() promise will actually end up returning another promise that you can wire up to in your controller(where you are using this custom service). Also, note that in this scenario you are likely to use the revealing module pattern - like using a factory to return an object that you need instantiate, in order to use the custom service. This is different from the regular service singleton you get when using the built-in angular services.

Sunday, September 21, 2014

Sql Update Stats Tip

Auto Update Stats only works with the default sampling which are changes that affect 20% of the total number of rows. For very large tables or even for smaller tables with a highly jagged distribution of data, we often need to manually update the stats using the FULLSCAN option. Otherwise the stats will remain highly skewed and the cardinality estimates that the Sql Optimizer depends on will be unreliable.

Note that FULLSCAN is not the panacea of all skewed data and if the data distribution is very jagged, it may not help much in updating the stats. That's where creating filtered stats comes handy, but that's another topic.

Command to check the histogram of the stats for an index, run
DBCC SHOW_STATISTICS('tablename', 'indexname')

Another option (Sql2008 and higher) to automatically trigger updating the stats (rather than the 20% default threshold) on say large tables is by turning on the trace 2371 like so

DBCC TRACEON(2371, -1)  -- the -1 is for all sessions
GO

DBCC TRACESTATUS
GO

The downside of turning on this trace is it results in recompilation of all queries accessing the table.


From SQL2008 onwars, the DMV sys.dm_db_stats_properties is useful in determining how much changes have taken place in the table before the update stats would be triggered. Of particular interest is the modification_counter column using the query

--Examine stats of a table
SELECT
     s.name,
     p.object_id,
     p.stats_id,
     p.last_updated,
     p.rows,
     p.rows_sampled,
     p.steps,
     p.unfiltered_rows,
     p.modification_counter
FROM sys.stats AS s
CROSS APPLY sys.dm_db_stats_properties
  (s.object_id, s.stats_id) AS p
WHERE s.object_id = OBJECT_ID('tablename')


References:
http://msdn.microsoft.com/en-us/library/dd535534(SQL.100).aspx
http://support.microsoft.com/kb/2754171

Friday, September 12, 2014

Plan Cache Pollution

Sql Server will cache plans for "safe" statements but not in the way you might expect. For example, if we pass different integer values for a parameter in a safe statement, Sql Server may cache tinyint, smallint, int and bigint plans, thereby leading to Plan Cache pollution.

If Sql Server deems a set of ad hoc identical statements to be unsafe, then it will not parameterize them and end up creating a separate plan for each of the statement. For instance WHERE predicates with = and LIKE may throw up different plans, depending on the data selectivity. So Sql Server may use a non-clustered index that is available or decide to go for a full table scan, even for the same LIKE - depending on what parameter value has been used.

Now compiling the identical queries each time and having the separate plans may be good too as it will be optimized for each statement. The downside is the plan bloat and non-reuse of already compiled plans.

Likewise, when using variables as the predicate parameters, SQL Server deems them to be unsafe, so even if we pass in a highly selective value for the parameter, the optimizer will not use the non- clustered index available and will treat the variable value as "Unknown", and choose an index scan plan. This is because the variable value is not known until runtime to Sql Server.

So using a variable in an sd hoc sql statement fundamentally changes the way Sql Server uses the optimizer!

--------------------------------------------------------------------------------------
Plan Cache pollution with Dynamic String Execution

Even though it is a safe statement, with string concatenation and no strongly type parameter, this will lead to plan cache pollution.

declare @sql nvarchar(4000), @memberId INT = 12345;
select @sql = N'Select * from member where memberId="
                           + CONVERT(nvarchar(10), @memberId);

Exec (@sql);

To make it strongly typed, convert the INT variable back to its data type after the string concatenation within the string like so:

declare @sql nvarchar(4000), @memberId INT = 12345;
select @sql = N'Select * from member where memberId= CONVERT(INT,'
                           + CONVERT(nvarchar(10), @memberId) + N')';

Exec (@sql);

This will result in just one plan, no matter how many times you execute it with different values for the INT parameter. So this is a good way to right dynamic sql with strongly typed parameters.

Avoiding Sql Injection


  1. Use QUOTENAME to wrap user supplied parameters to prevent Sql Injection y delimiting it. Only works with sys objects - table names, column names etc with nvarchar 128. 
  2. REPLACE all single quotes with double quotes for simple string parameters and delimit the parameters.
  3. Make sure that all parameters passed in are validated at the client application layer
  4. For Dynamic String Executions in Stored procedure, you can even create a login-less user with very low privileges to execute that DSE within the stored procedure. This is done by restricting the execution context with EXECUTE AS