October 26, 2014

Entity Framework: DBContext ExecuteSqlCommand and Stored-procedure does not return value

I have stored-procedures for CRUD and I expect all of my insert, update and delete stored-procedures would return an integer value after it is executed but the Entity Framework's DBContext ExecuteSqlCommand does not get the value that I use the command return in my stored-procedure.

Solution for now, I use an output parameter in my stored-procedures and I get the value that I return.
Ex:

My stored-procedure:

PROCEDURE [dbo].[TestReturnScalarValue]
    @par1 int,

    @ReturnValue INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    SET @ReturnValue = @par1
END
My C# code:

public virtual int ExecuteStoredProcedureInt(string query, SqlParameter Output, params SqlParameter[] parameters)
        {
            DbContext.Database.ExecuteSqlCommand(query, parameters);
            return (int)Output.Value;
        }


To execute the above behavior in C#:

var par1= new SqlParameter("par1", 11);

var ReturnValue = new SqlParameter("ReturnValue", System.Data.SqlDbType.Int)
            {
                Direction = System.Data.ParameterDirection.Output
            };

var returnValue = ExecuteStoredProcedureInt(";EXEC [dbo].[TestReturnScalarValue] @ReturnValue, @par1", ReturnValue, par1); 

October 10, 2014

One Algorithm per day (C#): Merge two sorted Arrays and keep duplicate values


int[] Arr= {1, 5, 6, 8, 10, 15, 20, 23, 27, 29, 30, 32};
int[] Arr2 = {5};

int i = 0;
int j = 0;
int k = 0;
int m = Arr.Count() + Arr2.Count();
int[] Arr3 = new int[m];

while(k < m){
if(i < Arr.Count() && j < Arr2.Count()){
 if(Arr[i] < Arr2[j]){
  Arr3[k] = Arr[i];
  i++;
 }else if(Arr[i] < Arr2[j]){
  Arr3[k] = Arr2[j];
  j++;
 }else{
  Arr3[k] = Arr2[j];
  Arr3[k+1] = Arr[i];
  i++;
  j++;
  k++;
 }
}else if(i < Arr.Count()){
 Arr3[k] = Arr[i];
 i++;
}else{
 Arr3[k] = Arr2[j];
 j++;
}
k++;
}

foreach (int num in Arr3)
 Console.WriteLine(num);

One Algorithm per day (C#): Find the first repeating element in an array of integers

int[] Arr= {1, 2, 3, 7, 8, 9, 10, 11, 3, 7, 13};

int i = 0;
while(i < Arr.Count()){
 for(int j = i + 1; j < Arr.Count(); j++){
  if(Arr[i] == Arr[j]){
   Console.WriteLine(Arr[i]);
   i = Arr.Count();
   break;
  }
 }
 i++;
}

One Algorithm per day (C#): Create a new array which the started index Num = array.Count() - n

//Ex: int[10] array1;
// n = 2;
// => Num = 8;
// if n = 12;
// => Num = 8;

List<int> Nums = new List<int>();
List<int> result = new List<int>();

int num = 10;
int n = 12;

for(int i = 0; i < num; i++)
 Nums.Add(i+1);

int m = num;
int j = num - (n % num);

while( m > 0)
{
 result.Add(Nums[j]);
 m--;
 j++;
 j = j % num;
}

foreach(int i in result)
 Console.WriteLine(i);

One Algorithm per day (C#): What would be the last element of index n=3 in a List of integer numbers

List elements = new List();
int m = 10;
int n = 3;
for(int i = 0; i < m; i++){
 elements.Add(i + 1);
}

int k = 0;
int elementsLeft = m;
int j = 0;

while (elementsLeft > 1){
 k++;
 j++;
 j = j % elementsLeft;
 
 if(k % n == 0){
  elements.Remove(elements[j]);
  k = 0;
  elementsLeft--;
 }
}

Console.WriteLine(elements[0]);

October 08, 2014

Context Database SqlQuery executes Stored Procedure and get Return Values

The method you are trying to use only works for results of a query. It can't put the values of the output parameters into a new object for you automatically.
You have to create the parameters explicitly and read their values after the stored procedure has been run.
So if you have a stored prodcudure like this:
CREATE PROCEDURE dbo.insertemployee
(
    @iName varchar(500),
    @OEmployeeId int OUTPUT,  
    @OSalary Money OUTPUT
)
AS
BEGIN
    SELECT @OEmployeeId = 1337;
    SELECT @OSalary = 1000;
END
... you can execute it and get the results of the parameters like this:
using (var ctx = new Context())
{
    var nameParam = new SqlParameter("iName", "TestName");

    var employeeIdParam = new SqlParameter("OEmployeeId", SqlDbType.Int) 
    { 
        Direction = System.Data.ParameterDirection.Output 
    };

    var salaryParam = new SqlParameter("OSalary", SqlDbType.Money) 
    { 
        Direction = System.Data.ParameterDirection.Output 
    };

    ctx.Database.ExecuteSqlCommand(
        "insertemployee @iName, @OEmployeeId out, @OSalary out", 
        nameParam, employeeIdParam, salaryParam);

    var employeeId = (int)employeeIdParam.Value;
    var salary = (decimal)salaryParam.Value;
}

“this” in function parameter

This is the syntax for declaring extension methods, a new feature of C# 3.0.
An extension method is part code, part compiler "magic", where the compiler with the help of intellisense in Visual Studio make it appear that your extension method is actually available as an instance method on the object in question.
Let me give an example.
There's no method on the String class that is named GobbleGobble, so let's create an extension method:
public static class StringExtensions
{
    public static void GobbleGobble(this string s)
    {
        Console.Out.WriteLine("Gobble Gobble, " + s);
    }
}
The class name is just my naming convention, it isn't necessary to name it like that, but it has to be static, as do the method.

Reference: http://stackoverflow.com/questions/846766/use-of-this-keyword-in-formal-parameters-for-static-methods-in-c-sharp

October 05, 2014

Bootstrap 3 Navigation bar with Search


MS SQL: Create Stored-Procedure to get Data as pagination

CREATE PROCEDURE GetProductLimit 
 @PageNum INT,   -- Ex: 1, 2, 3, 4
 @PageSize INT   -- Ex: 10 per page
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

    DECLARE
  @fromNum int,
  @toNum int

  SET @fromNum = (@PageSize * (@pageNum - 1)) + 1
  SET @toNum = @pageSize * @pageNum

 ;WITH Product AS
 (
  SELECT ID, ProductName, [Description], Price, Qty,
  ROW_NUMBER() OVER (ORDER BY ID) AS RowNumber
  FROM dbo.Products 
 ) 
 SELECT ID, ProductName, [Description], Price, Qty  
 FROM Product 
 WHERE RowNumber BETWEEN @fromNum AND @toNum;
 END
GO

Grant Execute Permission on Stored Procedure in MSSQL

GRANT EXECUTE ON [dbo].[StoredProcedure] TO [Public]

September 29, 2014

Asp.Net MVC application SignalR: Access denied

While I'm trying my first app on SignalR, I got HTTP status 401, Access denied. In order to fix it, we just change the property of the project, Windows Authentication, to be Enabled.

Web Service Vs WCF Vs Web API

Web Service

  1. It is based on SOAP and return data in XML form.
  2. It support only HTTP protocol.
  3. It is not open source but can be consumed by any client that understands xml.
  4. It can be hosted only on IIS.

WCF

  1. It is also based on SOAP and return data in XML form.
  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  3. The main issue with WCF is, its tedious and extensive configuration.
  4. It is not open source but can be consumed by any client that understands xml.
  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

  1. To use WCF as WCF Rest service you have to enable webHttpBindings.
  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  5. It support XML, JSON and ATOM data format.

Web API

  1. This is the new framework for building HTTP services with easy and simple way.
  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  5. It can be hosted with in the application or on IIS.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API

  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.


    Reference:
    http://www.dotnet-tricks.com/Tutorial/webapi/JI2X050413-Difference-between-WCF-and-Web-API-and-WCF-REST-and-Web-Service.html

November 06, 2013

CRUD Generated

-- =============================================

-- Author:        FirstName LastName 

-- Create date:   10/11/2007

-- Description:   

-- Revisions:     

-- =============================================

Create Procedure [dbo].[SafetyIncident_Create]
      @WeekId int,
      @Description varchar (2047),
      @SafetyIncidentId int OUTPUT
AS
Begin
      SET NOCOUNT ON
      insert into SafetyIncident
            ( WeekId, Description)
      values
            (@WeekId,@Description)
 
      select @SafetyIncidentId = SCOPE_IDENTITY()
End
 
-- =============================================

-- Author:        FirstName LastName 

-- Create date:   10/11/2007

-- Description:   

-- Revisions:     

-- =============================================

Create Procedure [dbo].[SafetyIncident_Delete]
      @SafetyIncidentId int
AS
Begin
      SET NOCOUNT ON
      delete from SafetyIncident
      where
            SafetyIncidentId = @SafetyIncidentId
End
 
-- =============================================

-- Author:        FirstName LastName 

-- Create date:   10/11/2007

-- Description:   

-- Revisions:     

-- =============================================

Create Procedure [dbo].[SafetyIncident_ReadAll]
 
AS
Begin
      SET NOCOUNT ON
      select
       SafetyIncidentId, WeekId, Description
      from SafetyIncident
End
 
-- =============================================

-- Author:        FirstName LastName 

-- Create date:   10/11/2007

-- Description:   

-- Revisions:     

-- =============================================

Create Procedure [dbo].[SafetyIncident_ReadById]
      @SafetyIncidentId int
AS
Begin
      SET NOCOUNT ON
      select
       SafetyIncidentId, WeekId, Description
      from SafetyIncident
      where
            SafetyIncidentId = @SafetyIncidentId
End
 
-- =============================================

-- Author:        FirstName LastName 

-- Create date:   10/11/2007

-- Description:   

-- Revisions:     

-- =============================================

Create Procedure [dbo].[SafetyIncident_Update]
      @SafetyIncidentId int,
      @WeekId int,
      @Description varchar (2047)
AS
Begin
      SET NOCOUNT ON
      update SafetyIncident
      set
            WeekId = @WeekId,
            Description = @Description
      where
            SafetyIncidentId = @SafetyIncidentId
End

August 06, 2013

Sort Number Strings Naturally

Scenario/Problem:When you sort strings that contain numbers (such as the digits from 1 to 10), they are “computer sorted” (that is, 10 comes before 2), but you need them “naturally” sorted such that 10 comes in order after 9.
Solution:You must write your own string comparer to do the comparison correctly. You can either write a class that implements IComparer or a method that conforms to the delegate Comparison (see Chapter 15, “Delegates, Events, and Anonymous Methods,” which discusses delegates). Listing 7.3 provides an example of the first option.

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace NaturalSort
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] originals = new string[]
            {
                "Part 1", "Part 2", "Part 3", "Part 4", "Part 5",
                "Part 6", "Part 7", "Part 8", "Part 9", "Part 10",
                "Part 11", "Part 12", "Part 13", "Part 14", "Part 15",
                "Part 16", "Part 17", "Part 18", "Part 19", "Part 20"
            };

            Console.WriteLine("Naive sort:");
            List copy = new List(originals);
            copy.Sort();
            foreach (string s in copy)
            {
                Console.WriteLine("\t{0}", s);
            }

            Console.WriteLine();
            Console.WriteLine("Natural Sort:");
            copy = new List(originals);
            copy.Sort(new NaturalSorter());
            foreach (string s in copy)
            {
                Console.WriteLine("\t{0}", s);
            }
        }
    }

    class NaturalSorter : IComparer
    {
        //use a buffer for performance since we expect
        //the Compare method to be called a lot
        private char[] _splitBuffer = new char[256];

        public int Compare(string x, string y)
        {
            //first split each string into segments
            //of non-numbers and numbers
            IList a = SplitByNumbers(x);
            IList b = SplitByNumbers(y);

            int aInt, bInt;
            int numToCompare = (a.Count < b.Count) ? a.Count : b.Count;
            for (int i = 0; i < numToCompare; i++)
            {
                if (a[i].Equals(b[i]))
                    continue;

                bool aIsNumber = Int32.TryParse(a[i], out aInt);
                bool bIsNumber = Int32.TryParse(b[i], out bInt);
                bool bothNumbers = aIsNumber && bIsNumber;
                bool bothNotNumbers = !aIsNumber && !bIsNumber;
                //do an integer compare
                if (bothNumbers) return aInt.CompareTo(bInt);
                //do a string compare
                if (bothNotNumbers) return a[i].CompareTo(b[i]);
                //only one is a number, which are
                //by definition less than non-numbers
                if (aIsNumber) return -1;
                return 1;
            }
            //only get here if one string is empty
            return a.Count.CompareTo(b.Count);
        }

        private IList  SplitByNumbers(string val)
        {
            System.Diagnostics.Debug.Assert(val.Length <= 256);
            List list = new List();
            int current = 0;
            int dest = 0;
            while (current < val.Length)
            {
                //accumulate non-numbers
                while (current < val.Length &&
                       !char.IsDigit(val[current]))
                {
                    _splitBuffer[dest++] = val[current++];
                }
                if (dest > 0)
                {
                    list.Add(new string(_splitBuffer, 0, dest));
                    dest = 0;
                }
                //accumulate numbers
                while (current < val.Length &&
                       char.IsDigit(val[current]))
                {
                    _splitBuffer[dest++] = val[current++];
                }
                if (dest > 0)
                {
                    list.Add(new string(_splitBuffer, 0, dest));
                    dest = 0;
                }
            }
            return list;
        }
    }
}


References: http://my.safaribooksonline.com/book/programming/csharp/9780672331985/strings/ch07lev1sec12

December 07, 2012

Clear selected values and text from Telerik RadCombobox

function clearItemInRadCombobox(item) {
        item.clearSelection();
        item.Text = "";
        item.trackChanges();
        for (var i = 0; i < item.get_items().get_count(); i++) {
            item.get_items().getItem(i).set_checked(false);
        }
        item.commitChanges();
    }

ASP.net Controls on Client Side

var county2 = document.getElementById("<%= pCounty.ClientID %≶");
console.log(county2);
county2.style.visibility = "hidden";