Crosstab Query (3)

DECLARE @Names VARCHAR(8000)  
SELECT @Names = COALESCE(@Names + ', ', '') + Name FROM People
SELECT @Names

Or this post about FOR XML PATH

http://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string
Posted in SQL | Leave a comment

Southern California .NET user groups

Orange County

Master Calendar of many developer user groups in the OC and in San Diego – http://www.socaldotnet.org/

V_Next Orange County – http://www.meetup.com/vNext-OrangeCounty/
XPSoCal (Agile) – http://tech.groups.yahoo.com/group/xpsocal/
Orange County .NET User Group — http://www.ocdotnet.org
Orange County Android UG – http://www.meetup.com/OCAndroid/
SoCal .Net Architecture Users Group –http://www.SoCalDotNetArchitecture.org
Orange County SQL User Group – http://sqloc.com/sqloc/Default.aspx

Amazon Web Services AWS OC – http://www.meetup.com/NBALLSTAR/
OC-HUG (Hadoop) – http://www.meetup.com/OC-HUG/
MongoDB OC – http://www.meetup.com/Orange-County-MongoDB-User-Group/

LA

San Gabriel Valley (Pasadena) .NET Developers Group — http://www.sgvdotnet.org/
LA C# Developers Group — http://www.lacsharp.org/
Los Angeles .NET Developers Group — http://www.ladotnet.org/
Los Angeles SQL Server Professionals Group — http://www.sql.la/
South Bay .NET User Group — http://southbaynet.org/
LA Ruby – http://www.meetup.com/laruby/

MongoDB LA — http://www.meetup.com/Los-Angeles-MongoDB-User-Group/AWS AWS (Amazon Web Services) LA – http://www.meetup.com/Los-Angeles-AWS-Users-Group/
R (Data Science Language) LA – http://www.meetup.com/LAarea-R-usergroup/
LA Coding Dojo (Live coding practices) – http://www.meetup.com/The-Los-Angeles-Coding-Dojo/
Educelerate LA (LA technical education meetup) — http://www.meetup.com/Educelerate-LA/

Riverside

Inland Empire .NET User’s Group – http://www.iedotnetug.org/

San Diego and South

San Diego .NET Developers Group – http://sddotnetdg.org/
San Diego .NET User Group — http://www.sandiegodotnet.com/
San Diego SQL Server Users Group (also San Diego SQL BI) – http://sdsqlug.org/
Agile San Diego – http://www.agilesandiego.org/
SD JUG (Java) – http://www.sdjug.org/
San Diego Tech Immersion (Study) Group – https://sites.google.com/site/sandiegotig/
SD Ruby – http://sdruby.org/
San Diego GTUG (Google Developer User Group) – http://www.gtugs.org/chapter.jsp?id=1037

Posted in Uncategorized | Leave a comment

Injecting Values for Default MVC Model Binding

In a recent project, due to security concerns, we want to encrypt all QueryString values into a single encrypted value before placing the link in web pages, then decrypt it back to individual name/value pairs and pass them to default MVC model binder to bind (to both simple types and complex types).
Default MVC model binder reads from form data, query string, route data etc. Among those, only route data is editable. So the natural choice is to inject these decrypted values to route data collection:

HttpContext.Current.Request.RequestContext.RouteData.Values["AccountId"] = 1234;

But the key is where do we do that? It must be before the model binder kicks in.
I tried Application_BegineRequest and found it is too early. Any RouteData I set there will be wiped out in MVC’s routing set up process, where MVC initializes the route data with controller, action, and other values.
After some research I found I can implement a custom model binder (by inheriting the DefaultModelBinder) and register it in glabal.asax to replace the default one. I will have the opportunity to populate the route data before I pass the control to the default/base implementation:

public class CalvinModelBinder : DefaultModelBinder
{
 public override object BindModel(ControllerContext controllerContext, 
 ModelBindingContext bindingContext)
 {
 if( encryptionKeyFoundInQueryString )
 { 
 controllerContext.RouteData.Values["accountId"] = myDecryptedValue;
 }
 return base.BindModel(controllerContext, bindingContext);
 }
}

And register it in global.asax:

ModelBinders.Binders.DefaultBinder = new CalvinModelBinder();

However, this didn’t work. The controllerContext DID have my route data inserted, but bindingContext’s ValueProvider property didn’t have it, and this very bindingContext is what MVC’s default model binding uses to get values. I dived into the ValueProvider property (a ValueProvider collection consists of FormDataValueProvider, QueryStringDataValueProvider, JsonDataValueProvider etc.) and found that the RouteDataValueProvider keeps a local copy of the route data and doesn’t query controllerContext.RouteDate.Values.
After checking MVC source code, I found that RouteDataValueProvider constructs it’s local value list from controllerContext at a very early stage, before the model binding is even being called. Any changes to controllerContext.RouteData after that will not affect the internal list in RouteDataValueProvider.
Here is the final solution. First in global.asax, I registered a custom ValueProviderFactory:

ValueProviderFactories.Factories.Insert(0, new CalvinValueProviderFactory());

It’s very important that my own factory is registered at the first place, so that my object will be constructed before all other ValueProviders. Here is my value provider and its factory:

public class CalvinValueProviderFactory : ValueProviderFactory
{
 // this will be called when controllerContext first initialize ValueProvider property, 
 // which will call all registered factories. Make sure ours is the first one
	public override IValueProvider GetValueProvider(ControllerContext controllerContext)
	{
		return new CalvinValueProvider();
	}
}
public class CalvinValueProvider : IValueProvider
{
	public CalvinValueProvider()
	{
		if (!String.IsNullOrEmpty(HttpContext.Current.Request["calvinKey"]))
		{
			var values = HttpContext.Current.Request.RequestContext.RouteData.Values;
			values["AccountId"] = "4";
			values["page"] = 1;
			values["GroupName"] = "testgroup";
 //...
		}
	}
	   
 // still have to implement these method of this interface but we don't provide any values.
 // the whole purpose of this class to inject to route data before RouteDataValueProvider is being constructed
 // and we leave the binding to MVC's default mechanism
	public bool ContainsPrefix(string prefix)
	{
		return false;
	} 
	public ValueProviderResult GetValue(string key)
	{
		return null;
	}
}

The binding works for both simple types and complex types.
Initially I was trying to implement a complete customized value provider but the logic in ContainsPrefix() became very tricky. Injecting values to route data and having default MVC mechanism to handle it is much easier.

Posted in ASP.NET, MVC | Tagged , | Leave a comment

SET NUMERIC_ROUNDABORT ON and others

A good link: http://sqlservercode.blogspot.com/2006/11/use-sessionproperty-to-check-if.html

Useful commands:

DBCC USEROPTIONS
SELECT SESSIONPROPERTY(‘numeric_roundabort’)

NUMERIC_ROUNDABORT seems is a server level (or user session level) setting. Because when I change it on one DB, all other DBs are changed too.

If use Visual Studio Database project, make sure to check the database settings in project properties. Otherwise the changes in DB may be overwritten by next publish.

 

Posted in SQL | Tagged | Leave a comment

Why the view doesn’t display the new values set in the post back method

In MVC, when you post back any changes, it’s recommended that you follow the PRG (Post-Redirect-Get) pattern to the View page. However, if you want to display the same model data back in the same request, there might be something you have to do.

Say if you have Edit method handles both Create and Update request, and you have a @Html.HiddenFor(m=>m.Id) in your view so that the update method knows which record to update:

 if( model.Id == 0 )
{
    int newId = InsertNewToDataBase( model );
   model.Id = newId; // <= this will not work
}
else
   UpdateDataBase(model);

return View(model);

After a new record is created, you want to set the new Id to the model so that the view will pick it up for the following edit request to work. No, this doesn’t work, @Html.HiddenFor(m=>m.Id) will still give you a zero.

Why is that?

MVC maintains a ModelState collection which holds the posted back data along with validation result. When you display the same view back with the posted back model, MVC will display the original value user enters on the browser with possible validation errors. For data integrity reasons, MVC ignores your direct change on the view model data when it binds the data using the Html helper method. So your model.Id = newId will NOT work.

The workaround is either use pure HTML control

<input type=’hidden’ value=’@Model.Id’ />

or remove the individual entry in the ModelState collection

ModelState.Remove(“Id”)

ModelState.Clear() works too. It will remove everything including the validation messages.

Posted in MVC | Tagged | Leave a comment

TFS – “The path … is already mapped in workspace …”

After installing some power too, my VS 2010 now always run under another admin account of me. So my previous mapping of the projects are lost and I can’t check out files to the original local path. The above error occurs if I try to remap the project to the same location. After some googling these tips helps:

In VS command line, use

  • c:\>tf workspaces /owner:*  (to show all workspace)
  • c:\>tf workspace /delete COMPUTER_NAME;USER_NAME (to remove the workspace)
  • c:\>tf workspace COMPUTER;USERNAME (this will open a GUI dialog to edit the workspace. The BEST option!)

I change my workspace to public so that any user can work on it (in case my VS switches back to my own account).

Posted in Tools | Tagged | Leave a comment

SQL command always times out after 30 seconds

One of my query takes more than 30 seconds to run. Even I set the “Connection Timeout=120″ in my connection string, it still throwing timed out exception. It turned out that the time out setting in the connection string is only for setting up the connection (as the name implies). To change the default 30 seconds time out for each individual database call, I need to set it on the SqlCommand object:

sqlCmd.CommandTimeout = 120; // 2 minutes

Posted in .NET, SQL | Tagged | Leave a comment