Skip to main content

Posts

Showing posts from 2014

SQL SERVER – Query to Find First and Last Day of Current Month

Following query will run respective to today’s date. It will return Last Day of Previous Month, First Day of Current Month, Today, Last Day of Previous Month and First Day of Next Month respective to current month. DECLARE  @mydate  DATETIME SELECT  @mydate  =  GETDATE () SELECT  CONVERT ( VARCHAR ( 25 ), DATEADD ( dd ,-( DAY ( @mydate )), @mydate ), 101 ) , 'Last Day of Previous Month' UNION SELECT  CONVERT ( VARCHAR ( 25 ), DATEADD ( dd ,-( DAY ( @mydate )- 1 ), @mydate ), 101 ) AS  Date_Value , 'First Day of Current Month'  AS  Date_Type UNION SELECT  CONVERT ( VARCHAR ( 25 ), @mydate , 101 )  AS  Date_Value ,  'Today'  AS Date_Type UNION SELECT  CONVERT ( VARCHAR ( 25 ), DATEADD ( dd ,-( DAY ( DATEADD ( mm , 1 , @mydate ))), DATEADD ( mm , 1 , @mydate )), 101 ) , 'Last Day of Current Month' UNION SELECT  CONVERT ( VARCHAR ( 25 ), DATEADD ( dd ,-( DAY ( DATEADD ( mm , 1 , @mydate ))- 1 ), DATEADD ( mm , 1 , @mydate )), 101 ) , 'First Day of

Using try catch in SQL Server stored procedures

Overview A great new option that was added in SQL Server 2005 was the ability to use the Try..Catch paradigm that exists in other development languages.  Doing error handling in SQL Server has not always been the easiest thing, so this option definitely makes it much easier to code for and handle errors. Explanation If you are not familiar with the Try...Catch paradigm it is basically two blocks of code with your stored procedures that lets you execute some code, this is the Try section and if there are errors they are handled in the Catch section.  Let's take a look at an example of how this can be done.  As you can see we are using a basic SELECT statement that is contained within the TRY section, but for some reason if this fails it will run the code in the CATCH section and return the error information. CREATE PROCEDURE uspTryCatchTest AS BEGIN TRY     SELECT 1/0 END TRY BEGIN CATCH     SELECT ERROR_NUMBER() AS ErrorNumber      ,ERROR_SEVERITY() AS ErrorSeverity      

BCrypt.net - Strong Password Hashing for .NET and Mono

Using raw hash functions to authenticate passwords is as naive as using unsalted hash functions. Don’t. Thomas Ptacek BCrypt.net is an implementation of OpenBSD's Blowfish-based password hashing code, described in " A Future-Adaptable Password Scheme " by  Niels Provos  and  David Mazières . It is a direct port of  jBCrypt  by  Damien Miller , and is thus released under the same BSD-style license. The code is fully managed and should work with any little-endian CLI implementation -- it has been tested with Microsoft .NET and Mono. Why BCrypt? Most popular password storage schemes are based on fast hashing algorithms such as MD5 and SHA-1. BCrypt is a computationally expensive adaptive hashing scheme which utilizes the Blowfish block cipher. It is ideally suited for password storage, as its slow initialization time severely limits the effectiveness of brute force password cracking attempts. How much overhead it adds is configurable (that's the  adaptive  part

Cast Object to Generic List

Lots of trial and error gave me this on SL 5 but it should also work on a regular C#. You also need to add LINQ to your using list for the last half to work. List <object> myAnythingList = ( value as IEnumerable <object> ). Cast <object> (). ToList () Ref :  http://stackoverflow.com/questions/2837063/cast-object-to-generic-list

DotNetOpenAuth.Asp Couldnt Load Assembly or one of its dependencies in MVC4 App Unit Tests

Error: Could not load file or assembly 'DotNetOpenAuth.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) Solution <configuration> <runtime> < assemblyBinding xmlns = "urn:schemas-microsoft-com:asm.v1" > <dependentAssembly> < assemblyIdentity name = "DotNetOpenAuth.AspNet" publicKeyToken = "2780ccd10d57b246" culture = "neutral" /> < bindingRedirect oldVersion = "0.0.0.0-4.3.0.0" newVersion = "4.3.0.0" /> </ dependentAssembly > <dependentAssembly> < assemblyIdentity name = "DotNetOpenAuth.Core" publicKeyToken = "2780ccd10d57b246" culture = "neutral" />

Object to xml and write in text file using C# code

 public static void ObjectToXml(object obj, string path_to_xml)         {             //serialize and persist it to it's file             try             {                 System.Xml.Serialization.XmlSerializer writer =                 new System.Xml.Serialization.XmlSerializer(obj.GetType());                 System.IO.StreamWriter file =                 new System.IO.StreamWriter(path_to_xml);                 writer.Serialize(file, obj);                 file.Close();                 //XmlSerializer ser = new XmlSerializer(obj.GetType());                 //FileStream fs = File.Open(                 // path_to_xml,                 // FileMode.OpenOrCreate,                 // FileAccess.Write,                 // FileShare.ReadWrite);                 //ser.Serialize(fs, obj);             }             catch (Exception ex)             {                 throw new Exception(                 "Could Not Serialize object to " + path_to_xml,              

SQL SERVER – Comma Separated Values (CSV) from Table Column

I use following script very often and I realized that I have never shared this script on this blog before. Creating Comma Separated Values (CSV) from Table Column is a very common task, and we all do this many times a day. Let us see the example that I use frequently and its output. USE  AdventureWorks GO -- Check Table Column SELECT  Name FROM  HumanResources.Shift GO -- Get CSV values SELECT  SUBSTRING ( ( SELECT  ','  +  s.Name FROM  HumanResources.Shift s ORDER BY  s.Name FOR  XML PATH ( '' )), 2 , 200000 )  AS  CSV GO I consider XML as the best solution in terms of code and performance. Further, as I totally prefer this option, I am not even including the linka to my other articles, where I have described other options. Do you use any other method to resolve this issue? Can you find any significant difference in performance between these options? Please leave your comment here. Ref :  http://blog.sqlauthority.com/2009/11/25/sql-server-comma-separated-va

Kendo UI :How do you make a kendo datepicker do date validation for a minimum date?

<!DOCTYPE html> <html> <head> <link href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.common.min.css" rel="stylesheet" type="text/css" /> <link href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.rtl.min.css" rel="stylesheet" type="text/css" /> <link href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.default.min.css" rel="stylesheet" type="text/css" /> <link href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.dataviz.min.css" rel="stylesheet" type="text/css" /> <link href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.dataviz.default.min.css" rel="stylesheet" type="text/css" /> <link href="http://cdn.kendostatic.com/2013.3.1119/styles/kendo.mobile.all.min.css" rel="stylesheet" type="text/css" /> <script src=&qu

MVC: Fix: The version of SQL Server in use does not support datatype 'datetime2'.

This message appeared today after posting a new build to our ASP.NET 4 web app: The version of SQL Server in use does not support datatype 'datetime2'. The DBA doesn’t use datetime2 because it’s new in SQL Server 2008 and the site runs on 2005.  It turns out that Entity Framework 4 somehow got the idea to use  SQL Server 2008. The fix was to edit the .edmx file in an XML editor and set the   ProviderManifestToken="2005 " instead of 2008. (You need to rebuild.) Here’s how the line should look against SQL Server 2005: <Schema Namespace="OfficeBookDBModel.Store" Alias="Self" Provider="System.Data.SqlClient" ProviderManifestToken="2005" xmlns:store=http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">    I’m not sure where EF got the notion to ‘upgrade’ to SQL Server 2008. Perhaps it detected something locally.  I’ve jus

MVC: Exact string Custom Validation

Model Property [Display(Name = "SchoolName CustomValidator(ValidName='MySchool')")] [ExactString(ValidName = "MySchool", ErrorMessage = "The Input Name must exactly equal by Valid Name")] public string SchoolName { get; set; } Custom Validation class public class ExactStringAttribute : ValidationAttribute ,IClientValidatable     {         public string ValidName { get; set; }         public override bool IsValid(object value)         {             if (value != null)                 if (value.ToString() == ValidName)                     return true;             return false;         }         public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)         {             var rule = new ModelClientValidationRule();             rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());             rule.ValidationParameters.Add("validname",

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Could not load type ‘System.ServiceModel.Activation.HttpModule’ from assembly ‘System.ServiceModel, Version=3. 0 . 0 . 0 , Culture=neutral, PublicKeyToken=b77a5c561934e089′. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.TypeLoadException: Could not load type ‘System.ServiceModel.Activation.HttpModule’ from assembly ‘System.ServiceModel, Version=3. 0 . 0 . 0 , Culture=neutral, PublicKeyToken=b77a5c561934e089′. Solution : You need to run aspnet_regiis.exe for both .NET Framework v2 and v4. This can be accomplished by using the –iru parameters when running aspnet_regiis.exe as follows: aspnet_regiis.exe -iru start-> Run--> c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -iru

Kendo UI File Uploading Client Side Validation

In Kendo UI async file uploading there is no option to make some client side validation like: No of files you can upload at a time Size of the file Extension of your uploading file               So, how we can achieve this ? So, to know that see the javascript code snippet below. I am going to explain that. $ ( '#selectedFiles-edit-win' ). kendoUpload ({ multiple : true , localization : { select : 'Select File(s)' }, async : { saveUrl : "/CFCS/AjaxFactory.cfc?method=uploadFile" , removeUrl : "/CFCS/AjaxFactory.cfc?method=cancelUploadedFile" , autoUpload : true }, select : function ( e ) { var files = e . files ; if ( files . length > 10 ) { alert ( "Maximum 10 files can be uploaded at a time." ); e . preventDefault (); return false ; }   for ( var fileCntr = 0 ; fileCntr < files . length ; fileCntr ++ ) { if ( files [ fileCntr ]. s