Avoiding “Cannot resolve the collation conflict exception in SQL Server”

31 12 2015

Avoiding “Cannot resolve the collation conflict exception in SQL Server”

This exception is usually thrown when a comparison between character data (‘strings’) is done and both the source have different collation. This can occur with temporary as well as permanent tables.

There are various ways to fix this but it purely depends on how and what kind of tables\query you are writing.

  • While comparing complex #Temp tables you can specify “COLLATE DATABASE_DEFAULT” with character based column
    E.g
create table #TempTable1 (ID int, Name varchar(100)COLLATE DATABASE_DEFAULT)
  • While dumping data into #Temp and then comparing you may like to utilize “into” clause. This would create the #Temp table with the collation of the database in which TestTable1 resides.
    E.g.
select * into #TempTable1 from TestTable1
  • While comparing permanent tables we dodnot have much choice of changing the declaration of character column and so we may like to use “COLLATE DATABASE_DEFAULT” directly within the query in where caluse.
    E.g.
select t1.*
from TestDatabase2.dbo.TestTable1 t1
inner join TestTable1 t2 on t1.Name COLLATE DATABASE_DEFAULT = t2.Name COLLATE DATABASE_DEFAULT

Note:
The rule behind the creation of #Temp table is that it gets created in System Databases >> tempdp database. Now this tempdb database can have a different collation than the database where stored procedure\another table to compare resides. You can use any of the above pattern to avoid this situation





Overriding Save Button Behavior in SharePoint

15 12 2015

Overriding Save Button Behavior in SharePoint

There are multiple ways to hookup a customized behavior with SharePoint “SaveButton”. Below are two options that can make your day.  

Option 1

Inherit from ListFieldIterator class and hookup OnSaveHandler with your custom method. Below is the simple code to customize SaveButton behavior while utilizing ListFieldIterator class.

public class CustomListFieldIterator : ListFieldIterator
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
SPContext.Current.FormContext.OnSaveHandler += new EventHandler(CustomOnSave);
}
protected void CustomOnSave(object sender, EventArgs e)
{
//custom code
// returns true if item saved else false
Boolean returnValue = SaveButton.SaveItem(SPContext.Current, false, "comments if any");
//custom code
}
}

Note:

For this approach static method SaveButton.SaveItem with parameters is available. Make sure to pass true for DocumentLibrary list and false for the normal list. It won’t have any issues saving the items but some stuff like “Check Out \ Check In” might not work as expected.

Option 2

Inherit from SaveButton class and override the virtual method SaveItem from base class.

public partial class CustomSaveButton : SaveButton
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
protected override bool SaveItem()
{
//custom code
bool result = base.SaveItem();
//custom code
return result;
}
}




My winning script for a play @my organization

15 12 2015

Topic: Teach & Protect

Pitch: A small IT company striving through recession period.

Play Members:

  • 1 Prospect Client (ABC)
  • 1 Manager (CEO) (Dhaval Upadhyaya🙂 )
  • 2 Leads (DEF & GHI)
  • 3 Developers (JKL, MNO & PQR)

Play:

It all began with a phone call of a new prospect customer attracted by a small yet powerful portfolio of our IT Company. A ray of hope to surpass the recession and continue our journey towards growth enlightened.

During the short conference call the customer briefed about the situation and gave a deadline of a month. The customer was also striving through the financial crises due to market conditions and technology wilderness. His business would almost crash if the existing system was not transferred to the new technology that would help to retain his customers and company alive.

It was all upto the company to decide whether to go for a shot or not. As a Manager the decision was taken to go for it considering the collapsing business and market condition. A milestone was kept at 15th day and final deliver after another 15 days.

Manger briefed the leads about the project and the achievable situations. One of the lead was domain expert and the other complimented with great technical knowledge. Developers were very smart but didn’t have expertise in domain nor the technology.

It all started with little skepticism and fear about failing but the moral of the entire team was up. Leads taught and protected developers when mistakes were made. Due to sharp learning curve and technical competency the schedule was running behind. The first milestone meeting came. The manager explains the client about the situation of being late by 5 days. Client with a short silence asked, Are you guys still going to make it? The manager with confidence and statistical data once again brings in the client’s hope. The last 10 days entire team work very smartly and collaboratively by teaching and protecting each other’s while making mistakes. On the final day the system was made live on time with reasonably acceptable gaps. Soon within a month client retained his end customers and also started accumulating new customers, because many other competitors went out of market.

It was a time to reward, relax and witness the accomplishment made.

There was a sign of prosperity each members felt when a prospect client was converted to permanent business partner. Money, even in recession started flowing. Both the customer and IT Company expanded.

 





Fostering development process in .Net

14 07 2014

Fostering development process in .Net

In this article I will explain how to speed up the development process using few fabulous features of Visual Studio IDE.

Code Snippets

What is it?

Have you ever tried writing try, foreach, while or any other keyword and than hitting tab after it. Do it and you will define what Code Snippet is and will realize what it can do.

Code Snippet is nothing but a predefined set of code that is plugged into the surface area by using a shortcut key defined for it.

When to use?

A set of code with a constant pattern but variable custom literals can be translated to code snippets. Example

for (int i = 0; i < length; i++)
{

}

The structure of for statement remains same but the variables used inside it needs to be changed. In the above code i and length would be replaced by the some other variable inline with your code. So whenever you have such kind of code that needs to be plugged in really quickly you can create a snippet for that.

How to use?

Snippets are basically and XML based files with .snippet extension. It contains two major sections Header and Snippet.

Header : This section includes the details regarding the snippet that is being used. Some details like Title of the snippet, Shortcut key for the snippet, author name and snippet type are defined in this section.

Snippet : This is the section where in the actual magic of creating the snippet is defined.

It includes other four subsections viz

  • Code Defines the language type for the snippet and the code to be plugged in.  is used for the actual code to be inserted when the snippet is used. Literals to be replaced are prefixed and suffixed by $ sign.
  • Declarations Defines the literals that need to be replaced. This appears green in color in the surface are. One can define the tooltip, default value etc pertaining to the literals in this section.
  • Import Defines the namespaces that will be automatically included if your snippet is used.
  • References Defines the dll to be included for the namespace added using Import statement

Below steps will drive you through the process of creating a sample snippet.

Step 1

Create file with .snippet extensions with below xml

Step 2

Open Visual Studio and click Ctrl+k b. This will open Code Snippet Manager window.

Step 3

Click Import and browse through the file created in step 1 and Click Ok

Step 4

Now Choose the location where in you want to categories your snippet and click ok.

If you choose Visual C# than the file would be copied to /%Visual Studio%/ VC#\Snippets\1033\Visual C# folder

Step 5

Go to the code are where in you want to use your code snippet and type replace and than hit tab key.

 

Code Block

What is it?

If you do not want to go by the approach of code snippets, than you can quickly achieve the same functionality by Code Blocks. Code Blocks are nothing but a predefined code that needs to be used with some refactoring.

How to use?

Creating the code blocks is simply a drag drop process.

Step 1

Select the code that you want to reuse.

Step 2

Drop it onto the toolbar. Visual Studio will create the toolbar item for the block you have copied. Rename the block to meaningful name.

Step 3

Now wherever you want to plug in the code just click on the block.

 

Enjoy and Speed up your development.





Printing in Silverlight

14 07 2014

Printing in Silverlight

Printing is a very basic requirement for business application now days. At the advent of Silverlight there was no direct support for printing. But in Silverlight version 4 Microsoft have provided Print Document assembly for achieving the printing functionality.

What if the application still uses Silverlight version 3.0 or earlier versions?

In this article I will discuss the alternate approach for printing in Silverlight version 3.0 and earlier and then move on to a more sophisticated approach using Print Document provided in Silverlight 4.0.

The alternative is bit simple but not that much mature. Here we will take the entire image of the control that needs to be printed and let the user to save it using the save dialog. But one major problem with this approach is related to scaling of the image. In a case that have a large number of records to be printed like 100 records in data grid than the height of the jpeg produce would be very high and when it would be printed then it would automatically scale down the size of the image to fit in one single print page. The clarity for the scaled down image would not be good enough for reading purpose. So to overcome this thing I developed an algorithm to split the big heighted image into fixed slices and then I have used PdfSharp library to send the each sliced images to separate pages in pdf file. Finally the user will be able to save the Pdf file from where he can print the document. But here the chances to cut down the data when the image is splitted would remain.

Due to such pain and alternate unorganized approaches Microsoft finally Gifted Silverlight 4.0 with Print Document class. This class provides printing capabilities in Silverlight Applications. Refer http://msdn.microsoft.com/en-us/library/system.windows.printing.printdocument(VS.95).aspx for more details.

I strived hard to develop one such common framework related to print document class till I found one fantastic article by Pete Brown in his blog Creating a Simple Report Writer in Silverlight 4 http://10rem.net/blog/2010/05/09/creating-a-simple-report-writer-in-silverlight-4

This framework allows printing for one item source with one data template. My requirement forced me to print multiple grids at the same time in one single print job. So I analyzed the framework and with some modifications finally achieved it. I have converted some of its properties to arrays which use combination of multiple Data Templates and Item Sources to print multiple grids in one single print job.

Thanks Peter for such a fabulous use of Print Document.





Understanding JavaScript Concepts for SharePoint App Development

10 05 2014

 

Understanding JavaScript Concepts for SharePoint App Development

JavaScript has been an important ingredient while developing things ranging from simple html/html5 pages, to .net web sites/web applications to SharePoint App’s. Though with the advent of JQuery a whole new era began for shortcuts but JavaScript still plays a major role in Client Side Programming.
Keeping this in mind I present a short series of few articles to help understand JavaScript and its programming techniques.

 

JavaScript Namespaces

As a developer you might have written JavaScript in web pages and thus you understand that JavaScript is comprised of functions. These functions can be written directly into web pages using script tags or separate referenced files. Simply writing functions places them into global namespace which resides within window’s object.
If you are cooking for a single page than this methodology which majority of developers follow doesn’t creates fuss, but for a web part or app based development it would simply lead to a messy error prone code.
So what to do?

That’s were Namespace comes to rescue. Using proper and appropriate custom namespaces helps to isolate your code from other JavaScript in the page. Custom namespaces should be defined within global namespace and most of the variables and functions should be defined within the custom namespace. Following a simple nomenclature one can write more managed and maintainable custom JavaScript libraries.

Sample custom namespace creation code

 

<script type="text/javascript">
	var myNamespace = window.myNamespace || {};
</script>

 

The above code simply declares a global variable named “myNamespace”. It would simply refer existing myNamespace object or will create a new one if it’s not already created.

 

JavaScript Variables

At little more granular level we have JavaScript variables. They can be declared either in a namespace or within a function. “var” keyword is used to define a variable.
It’s not compulsion but it’s a best practice to use “var” keyword as it has its own implications as depicted below

When “var” keyword is not used the variable is automatically defined within global namespace.

When “var” keyword is used outside of a function the variable is defined within global namespace.

When “var” keyword is used inside of a function the variable is scoped to function only.

 

<script type="text/javascript">
    var globalVariable = "Hi this is global variable";
    function globalFunction(){
    alert("Global function in Global namespace");
        for(var i=0;i<5;i++){
            alert("Local variable scoped at function " + i);
        }
    }
</script>

 

JavaScript does not have specific datatype keywords but variables do have a type based on the values they hold. One can check the type of value hold into the variable by using “typeof” keyword. Further “typeof” keyword can also be applied to function. “typeof” may return one of the following values depicted below when applied to variable or function

  • object
  • function
  • string
  • number
  • boolean
  • undefined

JavaScript is very flexible in terms of syntax and declarations and does not apply specific strict rules, which sometimes becomes bottleneck while managing huge amount of client side scripting which is common practice these days.

To stay away from mess and as a best practice one can use “use strict” at top of any custom library or function.

 

JavaScript Functions

As nothing new, function in JavaScript also consists of name, parameters and scope. A major difference from other programming languages is that, it’s not mandatory for the parameters to match the function signature as all parameters are passed using arguments array.

 

<script type="text/javascript">
    function myFunction(){
        for(var i=0;i<arguments.length;i++){
            alert(arguments[i]);
        }
    }
</script>

 

The above depicted “myFunction” does not include any parameters. Instead, it just alerts all argument from arguments array. All below mentioned call to “myFunction” will succeed.

 

<script type="text/javascript">
    myFunction();
    myFunction(1);
    myFunction('Hi');
    myFunction(1,2,3,4,5);
    myFunction('Hi','I','am',27,'year old');
</script>

 

Another beauty of javascript is that we can assign javascript functions to a variable and alter invoke the variable to call the function. Such type of declarations are known as “anonymous” functions.

 

<script type="text/javascript">
    var myFunctionPointerVariable = function(){
        alert("Hello observer I dont have name declared and so I am anonymous!");
    }
    myFunctionPointerVariable();
</script>

 

JavaScript Closures

At little complex level here comes one of the most important concept named “closure” which if not applied appropriately can make your, else your team members life a big hell. “closure” plays important role while developing encapsulated javascripts.

“anonymous” functions can be assigned to variables as well as they can be returned from other functions which is known as “closure”. Using “closure” one can develop libraries that are more maintainable and are friendly for object oriented developers.

 

<script type="text/javascript">
    function myFunction(name)
    {
        var display = function (){ alert("Hello " + name) }
        return {
            greet: display
        }
    }
    myFunction("Dhaval Upadhyaya").greet();
</script>

 

 

JavaScript Prototypes

JavaScript object is nothing but an unordered collection of key value pairs. Every “object” is based on “prototype” which is an object that supports inheritance. Though not fully object oriented but using “prototype” one can develop objects inheriting from others and so on.

 

Simple object

 

<script type="text/javascript">
    blogger = { Name: "Dhaval Upadhyaya", Age:30 };
    alert("Hello I am " + blogger["Name"]  + " and I turned " + blogger["Age"] + " year old!");
</script>

 

Complex Object using prototype and inheritance

 

<script type="text/javascript">
    var car = Object.create(null);
    Object.defineProperty(car,"Model",{value:"undefined",writable:true,enumerable:true,configurable:true});
    Object.defineProperty(car,"Bhp",{value:"undefined",writable:true,enumerable:true,configurable:true});
    Object.defineProperty(car,"Rpm",{value:"undefined",writable:true,enumerable:true,configurable:true});

    var lamborgini = Object.create(car);
    lamborgini["Model"]  = "Diablo"
    lamborgini["Bhp"] = "595"
    lamborgini["Rpm"] = "7300"

    alert(lamborgini["Model"]);
    alert(lamborgini["Bhp"]);
    alert(lamborgini["Rpm"]);

    lamborgini = Object.create(car);
    lamborgini["Model"]  = "Murcielago"
    lamborgini["Bhp"] = "640"
    lamborgini["Rpm"] = "8000"

    alert(lamborgini["Model"]);
    alert(lamborgini["Bhp"]);
    alert(lamborgini["Rpm"]);
</script>

 

With all of the above technicalities you can practice creating small custom libraries and I take a break for a while, to present patterns for “Creating Custom Libraries” in next session.

Enjoy!





Book Review SignalR Real Time Application Development

17 07 2013

SignalR Real Time Application Development

Few weeks back I got a chance to review “SignalR Real Time Application Development” a new book from Packt Publishing. It would be published in coming days.

It contains nice explanation about below mentioned topics, considering a chat sample as base.

Chapter 1: Revitalizing the Rich Client
Chapter 2: Persistent Connections
Chapter 3: Hubs
Chapter 4: Groups
Chapter 5: State
Chapter 6: Security
Chapter 7: Scaling out
Chapter 8: Monitoring
Chapter 9: Hosting a server using OWIN
Chapter 10: WinJS and Windows 8

You can go ahead and purchase the book at discounted price with steps I depicted below.

You can use discount code (“MRSR30”) to get discount.

– Visit Publisher website that is http://www.packtpub.com/
– Add the book to cart from the book-page.
– Next, open the cart/check-out page to find the book listed in the purchase items.
– Enter the code in the promotional code box, and update the cart page(MRSR30)
– Post updating, the cart-page would reflect the discounted price.
– Checkout and pay the bills

Enjoy Reading!








Follow

Get every new post delivered to your Inbox.