Thursday, 3 September 2015

Error during serialization or deserialization using the JSON JavaScriptSerializer

Re: Error during serialization or deserialization using the JSON JavaScriptSerializer


You can configure the max length for json requests in your web.config file:
MaxJsonLength property is an integer so the max value you can set is: 2147483644
<configuration>
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="2147483644"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration>

Wednesday, 2 September 2015

Number to Roman convert

Number to Roman convert using Java Script
function convert(num) {

    var result = '';
    var rom = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
    var ara = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
    for (var x = 0; x < rom.length; x++) {
        while (num >= ara[x]) {
            result += rom[x];
            num -= ara[x];
        }
    }
    return result;
}

Number to Roman convert using C#
internal static string ToRoman(int number)
    {
        StringBuilder result = new StringBuilder();
        int[] digitsValues = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 };
        string[] romanDigits = { "I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M" };
        while (number > 0)
        {
            for (int i = digitsValues.Count() - 1; i >= 0; i--)
                if (number / digitsValues[i] >= 1)
                {
                    number -= digitsValues[i];
                    result.Append(romanDigits[i]);
                    break;
                }
        }
        return result.ToString();
    }

Tuesday, 4 August 2015

Get Month base on to date and from date

declare @StartDate date
declare @EndDate date
SELECT TOP 1 @StartDate=AcademicYearFrom,@EndDate=AcademicYearTo
FROM [LMS_Tbl_AcademicYear]

select distinct MonthNames,MonthNum from (
select DATENAME(month,AllDates) AS MonthNames,month(AllDates) AS MonthNum from (
SELECT DATEADD(MM, number, @StartDate) AS AllDates
FROM MASTER..spt_values main
WHERE TYPE = 'p'
)getDates
WHERE AllDates<=@EndDate
)mont
order by MonthNum

Wednesday, 29 July 2015

C# program that creates 2D array

using System;

class Program
{
    static void Main()
    {
 // Instantiate a new 2D string array.
 string[,] array = new string[2, 2];
 array[0, 0] = "top left";
 array[0, 1] = "top right";
 array[1, 0] = "bottom left";
 array[1, 1] = "bottom right";

 // Get upper bounds for the array
 int bound0 = array.GetUpperBound(0);
 int bound1 = array.GetUpperBound(1);

 // Use for-loops to iterate over the array elements
 for (int variable1 = 0; variable1 <= bound0; variable1++)
 {
     for (int variable2 = 0; variable2 <= bound1; variable2++)
     {
  string value = array[variable1, variable2];
  Console.WriteLine(value);
     }
     Console.WriteLine();
 }
 Console.ReadLine();
    }
}

Output

top left
top right

bottom left
bottom right
Nested loops. These are not always necessary. For example, if you are using a 2D array with only two elements in each row, you can index into positions 0 and 1 from a single for-loop.

Performance. GetUpperBound is slow. You may not want to call it often. I took a benchmark comparing one million repetitions. It shows the performance decrease with GetUpperBound.
Thus: Using the Length property for a loop boundary is faster than using GetUpperBound.
Benchmark
Memory: I have also tested the memory usage of jagged and 2D arrays. This helps us determine which one to use.
Jagged vs. 2D Array
2D array benchmark result

Looping with GetUpperBound: 142 ms
Looping with Length/2:       47 ms
Rank. Every array has a rank. This is the number of dimensions in the array. A one-dimensional array has a rank of 1. We access the Rank property from the Array base class.
Here: We design a method (Handle) that receives an array reference. It then tests the Rank of the parameter array.
And: It handles both 1D and 2D arrays in the same method. It uses GetValue to access the array elements.
C# that uses Rank

using System;

class Program
{
    static void Main()
    {
 // ... A one-dimensional array.
 int[] one = new int[2];
 one[0] = 1;
 one[1] = 2;
 Handle(one);

 // ... A two-dimensional array.
 int[,] two = new int[2, 2];
 two[0, 0] = 0;
 two[1, 0] = 1;
 two[0, 1] = 2;
 two[1, 1] = 3;
 Handle(two);
    }

    static void Handle(Array array)
    {
 Console.WriteLine("Rank: " + array.Rank);
 switch (array.Rank)
 {
     case 1:
  for (int i = 0; i < array.Length; i++)
  {
      Console.WriteLine(array.GetValue(i));
  }
  break;
     case 2:
  for (int i = 0; i < array.GetLength(0); i++)
  {
      for (int x = 0; x < array.GetLength(1); x++)
      {
   Console.Write(array.GetValue(i, x));
      }
      Console.WriteLine();
  }
  break;
 }
    }
}

Output

Rank: 1
1
2
Rank: 2
02
13
Arguments. We can use 2D arrays as arguments. The 2D array will be passed as a reference, which means changes to it will also affect the original version.
Thus: The reference itself will be copied, but not the data to which it points.

Dimensions. In C# we can also specify arrays with more than two dimensions. We can use another comma in the indexing syntax. It will work as expected.
Multidimensional Array
Lists. You can use the generic type List to simulate a jagged or 2D List that is dynamically resizable. The syntax for this nested type is somewhat more confusing.
Nested List
Tip: This can solve problems that would otherwise require confusing 2D array resizing and copying.

Jagged array. An array element can have any type. This includes other arrays. With an array of arrays, we construct a jagged array—this gives us great flexibility.
Jagged: Array of Arrays
Research. In the CLI standard, I found material about the types of arrays. The Framework determines the type of an array by its rank (dimension count) and its element type.
So: Both parts are considered in determining type. Arrays are not all the same type.
The rank of an array is the number of dimensions. The type of an array (other than a vector) shall be determined by the type of its elements and the number of dimensions.
The CLI Annotated Standard
2D arrays have many uses. And they can be used in many ways: we showed several indexing approaches. It is easiest to use Length, but GetUpperBound is sometimes needed.

A review. We created 2D arrays and looped over them. We mutated them. We benchmarked them. Before you use 2D arrays, research jagged arrays. These can improve the clarity and speed of code.

Difference between InvariantCulture and Ordinal string comparison

The "InvariantCulture" setting uses a "standard" set of character orderings (a,b,c, ... etc.). This is in contrast to some specific locales, which may sort characters in different orders ('a-with-acute' may be before or after 'a', depending on the locale, and so on).
"Ordinal" comparison, on the other hand, looks purely at the values of the raw byte(s) that represent the character. There's a great sample at http://msdn.microsoft.com/en-us/library/e6883c06.aspx that shows the results of the various StringComparison values. All the way at the end, it shows (excerpted):
StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
You can see that where InvariantCulture yields (U+0069, U+0049, U+00131), Ordinal yields (U+0049, U+0069, U+00131).

Tuesday, 28 July 2015

Find StartDate and EndDate using while loop in sql table and base on StartDate and EndDate Get sequence date


declare @Flag int=(select count(1) from [LMS_tbl_AcademicCalenderDetails])
while @Flag>0
begin
DECLARE @StartDate DATETIME,@EndDate DATETIME
SELECT @StartDate=MIN(EventStartDate),@EndDate=MAX(EventEndDate) FROM (
SELECT row_number() over(order by EventStartDate,EventSysId) as RN,EventStartDate,EventEndDate
FROM [LMS_tbl_AcademicCalenderDetails]
)t
WHERE RN=@Flag

IF (SELECT object_id('TempDB..#tmpDate')) IS NOT NULL
BEGIN
insert into #tmpDate (AllDates)
SELECT DATEADD(d, number, @StartDate) AS AllDates
FROM MASTER..spt_values main
WHERE TYPE = 'p'
AND number BETWEEN 0
AND DATEDIFF(dd, @StartDate, @EndDate)
END
ELSE
BEGIN
SELECT DATEADD(d, number, @StartDate) AS AllDates
into #tmpDate
FROM MASTER..spt_values main
WHERE TYPE = 'p'
AND number BETWEEN 0
AND DATEDIFF(dd, @StartDate, @EndDate)
END
set @Flag=@Flag-1
end
select * from #tmpDate
drop table #tmpDateD

Tuesday, 21 July 2015

Days difference between two dates duplicate

DateTime's can be subtracted to get a TimeSpan. The TimeSpan has a TotalDays which is the number of days (includes fractional days as well).
int DaysBetween(DateTime d1, DateTime d2) {
    TimeSpan span = d2.Subtract(d1);
    return (int)span.TotalDays;
}
NOTE Time spans are signed. If d1=1/9/11 and d2=1/11/11, then d1.subtract(d2)=timespan of -2 days. So if you want to use a time span to find out if dates are within X days of each other, you need to take the absolute value of the total days...
Math.Abs(span.TotalDays)

Monday, 20 July 2015

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

I think you are about this:
CONVERT(datetime, date_as_string, 103)
Notice, that datetime hasn't any format. You think about its presentation. To get the data of datetime in in appropriated format you can use
CONVERT(varchar, date_as_datetime, 103)

Friday, 17 July 2015

Convert Time DataType into AM PM Format:

Use following syntax to convert a time to AM PM format.
Replace the field name with the value in following query.
select CONVERT(varchar(15),CAST('17:30:00.0000000' AS TIME),100)

SELECT REPLACE(CONVERT(varchar(15),StartTime,22),':00','') AS StartTime,
     REPLACE(CONVERT(NVARCHAR(15),EndTime,22),':00','') AS EndTime
FROM LMS_tbl_TimeSlotDetails AS dtl

Tuesday, 7 July 2015

How to insert a data table into SQL Server database table?

Create a User-Defined TableType in your database:
CREATE TYPE [dbo].[MyTableType] AS TABLE(
    [Id] int NOT NULL,
    [Name] [nvarchar](128) NULL
)
Create a Table in your database:
CREATE TABLE[dbo].[Records](    [Id] int NOT NULL,
    [Name] [nvarchar](128) NULL
)
and define a parameter in your Stored Ptocedure:
CREATE PROCEDURE [dbo].[InsertTable]
    @myTableType MyTableType readonly
AS
BEGIN
    insert into [dbo].Records 
    select * from @myTableType 
END
and send your DataTable directly to sql server:
protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(getConString());
        using (var command = new SqlCommand("InsertTable") { CommandType = CommandType.StoredProcedure })
        {
            var dt = GetDataTable(); //create your own data table
            command.Parameters.Add(new SqlParameter("@myTableType", dt));            
            command.Connection = con;
            con.Open();
            command.ExecuteNonQuery();
            //SqlHelper.Exec(command);
        }
    }

    private DataTable GetDataTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Id");
        dt.Columns.Add("Name");
        dt.Rows.Add("1","Dharmendra");
        dt.Rows.Add("2", "Rakesh" );
        dt.Rows.Add("3", "Mukesh" );
        return dt;
    }

Getting name of Page being requested/was requested

public string GetPageName() 
{ 
    string path = System.Web.HttpContext.Current.Request.Url.AbsolutePath; 
    System.IO.FileInfo info = new System.IO.FileInfo(path); 
    return info.Name; 
}

Thursday, 2 July 2015

Convert DataTable to Generic List in C#

List<Cards> target = dt.AsEnumerable()
    .Select(row => new Cards
    {
        // assuming column 0's type is Nullable<long>
        CardID = row.Field<long?>(0).GetValueOrDefault(),
        CardName = String.IsNullOrEmpty(row.Field<string>(1))
            ? "not found"
            : row.Field<string>(1),
    }).ToList();

Wednesday, 17 June 2015

DownLoad file using C#

private void Download(string filePath, string fileName)
        {
            //string fileExtension = ".txt";
            // Set Response.ContentType
            Response.ContentType = msdnh.util.DownloadFile.GetContentType(fileName);

            // Append header
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);

            // Write the file to the Response
            Response.TransmitFile(Server.MapPath(filePath + Path.GetFileName(fileName)));
            Response.End();

        }

public static class DownloadFile
    {
        public static string GetContentType(string fName)
        {
            if (string.IsNullOrEmpty(fName))
                return string.Empty;

            string contentType = string.Empty;
            if (fName.EndsWith(".txt"))
            {
                contentType = "application/txt";
            }
            else if (fName.EndsWith(".pdf"))
            {
                contentType = "application/pdf";
            }
            else if (fName.EndsWith(".doc"))
            {
                contentType = "application/msword";
            }
            else if (fName.EndsWith(".docx"))
            {
                contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            }
            else if (fName.EndsWith(".xls"))
            {
                contentType = "application/vnd.ms-excel";
            }
            else if (fName.EndsWith(".xlsx"))
            {
                contentType = "application/vnd.xlsx";
            }
            else if (fName.EndsWith(".jpg"))
            {
                contentType = "image/jpg";
            }
            else if (fName.EndsWith(".gif"))
            {
                contentType = "image/GIF"; ;
            }
            else
            {
                contentType = "application/octet-stream";
            }

            return contentType;
            //switch (fileExtension)
            //{
            //    case ".htm":
            //    case ".html":
            //        contentType = "text/HTML";
            //        break;

            //    case ".txt":
            //        contentType = "text/plain";
            //        break;

            //    case ".doc":
            //    case ".rtf":
            //    case ".docx":
            //        contentType = "Application/msword";
            //        break;

            //    case ".xls":
            //    case ".xlsx":
            //        contentType = "Application/x-msexcel";
            //        break;

            //    case ".jpg":
            //    case ".jpeg":
            //        contentType = "image/jpeg";
            //        break;

            //    case ".gif":
            //        contentType = "image/GIF";
            //        break;

            //    case ".pdf":
            //        contentType = "application/pdf";
            //        break;
            //}

           
        }
    }

Saturday, 9 May 2015

Print html file using javascript

<script type = "text/javascript">
        function PrintPanel() {
            var panel = document.getElementById("<%=pnlMain.ClientID %>");
            var printWindow = window.open('', '', 'letf=0,top=0,width=1100,height=800,toolbar=0,scrollbars=1,status=0,resizable=yes');
            printWindow.document.write('<html><head><title>DIV Contents</title>');
            printWindow.document.write('</head><body >');
            printWindow.document.write(panel.innerHTML);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            setTimeout(function () {
                printWindow.print();
            }, 500);
            return false;
        }
    </script>

Thursday, 7 May 2015

SQL support date type

create table dbo.UserTable (ID int,DOB datetime,AddedDate datetime2,JoinDate datetimeoffset,upateDate date,lastdate smalldatetime)

Monday, 4 May 2015

How to use Rowspan in Gridview for 1st Column only




Use RowDataBound event instead:
void GridView31_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow )
    {
        if (e.Row.RowIndex % 4 == 0)
        {
            e.Row.Cells[0].Attributes.Add("rowspan", "4");
        }
        else
        {
            e.Row.Cells[0].Visible = false;
        }
    }
}