Wednesday, July 13, 2016

SQL Server 2012 Auto Identity Column Value Jump bug!

I am working on a database using SQL Server 2012. There is a table named Order has an auto Identity Column named OrderId datatype is int .

I noticed that the sequence of the identity is just not right. It has jumped with 1000.
After research about this issue, I found that this is an issue with SQL Server 2012 version.

From SQL Server 2012 version, when SQL Server instance is restarted then its auto Identity column value is jumped based on identity column datatype.

If it is an integer data type, then jump value is 1000 and if  it is a big integer, then jump value is 10000.

So now how can we solve this issue?
We can work around by 2 ways:

1- Using Sequence

We will have to remove Identity column from the table.
Create a sequence without cache feature and insert number from that sequence.
Please find below code sample:
CREATE SEQUENCE OrderId_Sequence AS INT
START WITH 1
INCREMENT BY 1
MINVALUE 0
NO MAXVALUE
NO CACHE
This is how you can use that Sequence:
INSERT INTO Order VALUES(NEXT VALUE FOR OrderId_Sequence, 'OrderName', 'OrderDescription');

2- Register -t272 to SQL Server Startup Parameter

Go to SQLServer configuration manager.
Select SQL Server 2012 instance then select Properties Menu.
You should find a tabbed dialog window.
Now you select start up parameters tab from there and register -t272.
Finally restart SQL Server 2012 instance.

Source: https://www.nilebits.com/blog/2014/02/sql-server-2012-auto-identity-column-value-jump-bug/

Thursday, January 1, 2015

How to migrate a domain without losing your SEO

1. Map All Old Domain URLs To Their New Domain Versions 

This basically required mapping all of the dynamic and static old domain URLs to new domain URLs so they could all be 301 redirected at launch.

2. Understand How Any UI Changes Might Affect SEO 

Changing UI while changing domains should be avoided whenever possible to eliminate yet another thing that could go wrong. That said, if you are going to change the UI, you need to make sure that the links, text, images and other elements are considered for their SEO impact.

3. Reduce Or Eliminate 404 (Not Found) Errors 

You’ll want to do this regardless of whether or not you are changing domains, but when you make the switch, you’ll want Googlebot to be able to crawl the site quickly and effectively. URL errors can slow down Google’s ability to find all of the URLs on both the old and new sites, so you’ll want them gone before you do anything. Typical fixes included: Identifying patterns that were causing 404s and deploying fixes. Where it made sense, changing 404s to 200s and using rel=canonical tags to canonicalize them to active, relevant pages. Removing broken links from the UI. 301 redirecting outdated URLs to active pages when there was a high degree of relevance. The majority of “Not Found” errors were identified by using the following tools: Reviewing Google Search Console’s Crawl Errors Report. Crawling the site with text browsers such as Screaming Frog and Xenu. Using the broken inbound link reports in backlink analysis tools like Majestic.

4. Figure Out Your Subdomains

We identified all existing subdomains and tagged each as “kill” or “keep.” Subdomains that were worthy of making the leap to the new domain were redirected. Those that didn’t make the cut were deprecated with a 301 redirect to a new, relevant page or area of the site.

5. Clean Up Your XML Sitemaps 

Once XML sitemaps on sites with millions of URLs are deployed, they typically get ignored by developers who often have better things to do than worry about a huge file that often was built by someone else three years ago with god knows what kind of logic. As with the subdomains, the migration finally gave us a good justification to go in and figure out how to map sitemaps to the new domain while getting rid of superfluous files.

6. Figure Out Your Canonical Links

The decision was made to canonicalize as many corresponding similar pages as we could identify to try to tighten up the site against potential Panda issues. All canonical links that had been previously implemented on old domain were identified and mapped to the new domain and relevant pages. All of this data was shared with the team via a Google Spreadsheet that could be easily updated and disseminated quickly.

7. “Warm Up” The New Domain

In my experience, migrations to new domains that either have never been indexed by Google or have few or no backlinks are the ones that typically get hit the worst when they are launched. With that in mind, old domain set up new domain several weeks before launch and posted new content to the site once a week to help get a jump on being indexed by search engines. The content was general and not connected to the old domain brand, so it wouldn’t be associated with old domain before the big reveal.

Saturday, February 1, 2014

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack ASP.NET

While I was debugging an ASP.NET Application, I wanted to get an object values I got this error message instead:

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

This problem occurs when using Response.Redirect or Server.Transfer method, because the Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

There are 3 Solutions for this problem use just one of them:
  • For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest() method instead of Response.End to bypass the code execution to the Application_EndRequest event.
  • For Server.Transfer, use the Server.Execute method instead.
  • For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End.

Friday, August 23, 2013

Adding the specified count to the semaphore would cause it to exceed its maximum count

I got this unusual exception while working on an ASP.NET project:
"Adding the specified count to the semaphore would cause it to exceed its maximum count error".

I thought it is something related to SQL Server Database Connection String.
After using Query Profiler I was able to run SQL queries directly without any problems.
So this means that the issue in ASP.NET Application not with the SQL Server Database.
I did a research about this issue to figure out a solution and I discovered that this issue related to ADO.NET Connection Pool manager.

The Connection Pool Manager is enabled by default in the connection string.
It will attempt to find a free connection, but if it didn't find a free connection it would threw the exception we are talking about.

To fix this issue all you have to do is to disable the Connection Pool Manager as shown below:
<add name="contest" connectionString="Data Source=Server1Test;Initial Catalog=DBTest;User ID=UserTest;
Password=PasswordTest;Pooling=False;" providerName="System.Data.SqlClient" />

Thursday, July 11, 2013

How to disable some context menu items on Telerik TreeView

There is an event named "OnClientContextMenuShowing" for Rad Treeview that calls javascipt function and passes 2 arguments "sender, args".
The Args parameter contains The current selected TreeNode and Context Menu Items.
You can enable or disable any Context menu item based on any attributes for the Current Selected Tree Node.

Here is a code snippet for the javascript function that demonstrate how can you get the current select Tree Node and the Context menu Items and how can you disable the items.
function onClientContextMenuShowing(sender, args) {
            var treeNode = args.get_node();
            if (treeNode._attributes != undefined) {
                if (treeNode._attributes._keys[0] == 'BoolFlag') {
                    // 0 refer to the Context Menu item index
                    args.get_menu().get_items().getItem(0).set_enabled(false);
                    args.get_menu().get_items().getItem(1).set_enabled(false);
                    args.get_menu().get_items().getItem(3).set_enabled(false);
                }
            }
        }

Wednesday, May 1, 2013

How to Select from Data Table in C#

DataTable Object has a Select Method which acts like Where in SQL Server. So if you want to write filter query you write the column name directly without Where and the filter expression you want.

I made a simple example that creates a DataTable and fill it with some data and use Select method:

DataTable dt = new DataTable("MyDataTable");
dt.Columns.Add(new DataColumn("ID", typeof(int)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));

for (int i = 0; i < 10; i++)
{
    DataRow dr = dt.NewRow();
    dr["ID"] = i + 1;
    dr["Name"] = "Name " + (i + 1).ToString();

    dt.Rows.Add(dr);
}

DataRow[] rows = dt.Select("ID = 3");

Friday, March 1, 2013

How to get Year, Month and Day out of SQL Date in SQL Server

Let is say that we have the following Date 2007-04-05 10:13:14.109 and we want to get Year, Month and Day out of this date.

There is a function named DATEPART() that can be used to archive this.
DECLARE @MyDate AS DATETIME 
SET @MyDate = '2007-04-05 10:13:14.109'
SELECT DATEPART(DAY, @MyDate) AS MyDay, DATEPART(MONTH, @MyDate) AS MyMonth, DATEPART(YEAR, @MyDate) AS MyYear

The result would be:

MyYearMyMonthMyDay
20070405

Friday, February 1, 2013

How to know if a Date is in range between two Dates in C#

Let's say that we have a DateTime = Jan 1, 2012 and we want to check if this date is between 2 other dates.
The following code example Implements IRange interface that can be used with Integers too.
public interface IRange
    {
        T Start { get; }
        T End { get; }
        bool WithInRange(T value);
        bool WithInRange(IRange range);
    }

    public class DateRange : IRange
    {
        public DateTime Start { get; set; }
        public DateTime End { get; set; }

        public DateRange(DateTime start, DateTime end)
        {
            Start = start;
            End = end;
        }

        public bool WithInRange(DateTime value)
        {
            return (Start <= value) && (value <= End);
        }

        public bool WithInRange(IRange range)
        {
            return (Start <= range.Start) && (range.End <= End);
        }
    }

This is how to use this class function:
DateTime startDate = new DateTime(2011, 1, 1);
        DateTime endDate = new DateTime(2013, 1, 1);
        DateTime inRange = new DateTime(2012, 1, 1);
        DateTime outRange = new DateTime(2010, 1, 1);
        DateRange range = new DateRange(startDate, endDate);
        bool yes = range.WithInRange(inRange);
        bool no = range.WithInRange(outRange);

Tuesday, January 1, 2013

How to avoid Uncaught ReferenceError: $ is not defined in jQuery

Sometimes while developing an existing Web Application, I wanted to use jQuery function and I get this error "Uncaught ReferenceError: $ is not defined".

There are some reasons causing it and ways to avoid them:
  • Make sure the references to the jQuery scripts is loading first, but them in the head of master page or the page you are using.
  • Sometimes the references to the jQuery scripts is loading twice, make sure it loads only once.
  • If you have external js files with your function, which depend on other jQuery libraries, you have to load that library first, and then dependent JS file with your functions.
Example:

This will not work:
<script src="customlib.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
But this will work:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="customlib.js"></script>

Friday, June 1, 2012

How to Replace the First Instance of a String in C#

Assume that you have a string and you expect that this string might have some duplicated instances.

String.Replace() is very good Function, but it will replace all the instances of the string. So to accomplish this you need to replace the first instance you find.

The next code example can be used as a helper method in your project if you are dealing with strings frequently:

public static string ReplaceFirst(string str, string term, string replace)
{
    int position = str.IndexOf(term);

    if (position < 0)
    {
        return str;
    }

    str = str.Substring(0, position) + replace + str.Substring(position + term.Length);

    return str;
}

Tuesday, May 1, 2012

How to Programmatically create iFrame in ASP.NET

Sometimes we may need to create iFrames and use it within GridView or Repeater, and we want to pass some values to it.
This example will show you how to create iFrame Programmatically and add it to a PlaceHolder.

HtmlGenericControl myFrame = new HtmlGenericControl();

myFrame.TagName = "IFRAME";
myFrame.Attributes["src"] = "MyPagePath";
myFrame.Attributes["id"] = "myFrame1";
myFrame.Attributes["name"] = "myFrame1";
myFrame.Attributes["width"] = "500";
myFrame.Attributes["height"] = "500";
myFrame.Attributes["class"] = "frames";

myPlaceHolder.Controls.Add(myFrame);

Monday, April 23, 2012

Operation is not valid due to the current state of the object, Exception in ASP.NET

I got this error when I tried to save a Page with lots of form fields to SQL Server Database.
The default max number of form fields that can be post is 1000.
In order to solve this error add this Line to your Web.Config File:

<appSettings>
  <add key="aspnet:MaxHttpCollectionKeys" value="10000" />
</appSettings>

Thursday, March 1, 2012

How to Convert SqlDataSource to DataTable and DataView in C#

Sometimes I want to use SqlDataSource  returned data programmatically and here is how you can do this,

In this example I will assume that SqlDataSource  ID is SqlDataSource1 which is the default ID:
DataSourceSelectArguments args = new DataSourceSelectArguments();
DataView view = SqlDataSource1.Select(args) as DataView; 
DataTable dt = view.ToTable();

Wednesday, February 15, 2012

How to Submit a Form Using JavaScript

Any form is submitted when the user click on the submit button.
But you may need to submit the form programmatically using JavaScript.
JavaScript has the form object that contains the submit() method.
Use the "ID" of the form to get the form object.
Example:
If the name of the form is "Form1", JavaScript code for the submit method is:
document.forms["Form1"].submit();

Sunday, January 1, 2012

Javascript Regular Expression to match a comma delimited list

This method uses the JavaScript String's match() method to parse a comma delimited list and show its content in a Panel control.

You can try it here http://jsfiddle.net/38tXU/
function parseList(list) {
    var reg = list.match(/\w+(,\w+)*/g);
    document.getElementById('pnl').innerHTML = 'Total length:' + reg.length + '<br />';
    for (var i = 0; i < reg.length; i++) {
        document.getElementById('pnl').innerHTML += 'Token:\'' + reg[i] + '\'<br />';
    }
}
//Call parseList function
parseList('item1, item2, item3');

Wednesday, November 9, 2011

How to Completely Disable Viewstate in ASP.NET

I tried to disable Viewstate of a website by set EnableViewState Page directive to false.
But when I get the Page HTML Source I found the following line:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
 value="/wEPDwUKMTY1NDU2MTA1MmRk7eWz8DBE7zF7MW8sS4wNndKCr5gBJPZZ/LOS1KIbBo4=" /> 

protected override void SavePageStateToPersistenceMedium(object viewState)
{

}

protected override object LoadPageStateFromPersistenceMedium()
{
  return null;
}

Tuesday, November 1, 2011

Difference between Inner and Outer Join in SQL

Joins are used to combine the data from two tables, with the result being a new, temporary table.
The temporary table is created based on column(s) that the two tables share, which represent meaningful column(s) of comparison.
The goal is to extract meaningful data from the resulting temporary table.
Joins are performed based on something called a predicate, which specifies the condition to use in order to perform a join.
A join can be either an inner join or an outer join, depending on how one wants the resulting table to look.

Example:
Suppose you have two Tables, with a single column and data as follows:

Table1: ID1                        Table2: ID2
            A                                        C 
            B                                        D
            C                                        E
            D                                        F

Inner Join Query would look like:

select * from Table1 INNER JOIN Table2 ON Table1.ID1 = Table2.ID2

You would get the following result:

ID1    ID2
C       C  
D       D

Left Outer Join Query would look like:

select * from Table1 LEFT OUTER JOIN Table2 ON Table1.ID1 = Table2.ID2

You would get the following result:

ID1    ID2
A       null 
B       null
C        C
D        D

Full Outer Join Query would look like:

select * from Table1 FULL OUTER JOIN Table2 ON Table1.ID1 = Table2.ID2

You would get the following result:

 ID1    ID2
 A       null 
 B       null
 C        C
 D        D
null      E
null      F

Wednesday, October 19, 2011

How to Copy some rows from a GridView to another in ASP.NET

A junior developer asked me can I select some rows from a GridView and copy them to another GridView?
I told him sure all you have to do is to create a DataTable and the columns that will be added to it.
Now you will loop for each row in the first GridView then add the selected rows to the DataTable.
Set the DataSource of the other GirdView to DataTable.
Here is the code that would do the trick:
DataTable dt = new DataTable();
DataRow dr;
       
dt.Columns.Add(new DataColumn("FirstName"));
dt.Columns.Add(new DataColumn("LastName"));
      
foreach (GridViewRow row in GridViewEmployees.Rows)
 {            
  if(((CheckBox)row.Cells[3].FindControl("CheckBox")).Checked == true)
   {
    dr = dt.NewRow();
    dr["ColumnName1"] = ((Label)row.Cells[0].FindControl("Label")).Text;
    dr["ColumnName2"] = ((Label)row.Cells[1].FindControl("Label")).Text;
    dt.Rows.Add(dr);
   }
 }
 
GridViewManagers.DataSource = dt;
GridViewManagers.DataBind();

Monday, October 3, 2011

Two Databound Fields in Gridview column

Boundfields are great in the Gridview, but they do have their limitations.
One is that it only has room for one bound field. So, what do you do when you want two or data fields.
For example, First and Last names returned to the same column.
Turn the BoundField into a TemplateField, with a label in it:

<asp:templatefield>
 <itemtemplate>               
  <asp:label id="lblname" runat="server" text="<%# Eval("Fname") + ", " + Eval("Lname") %>" />            
 </itemtemplate>
</asp:templatefield>

Thursday, September 1, 2011

Select Drop Down List Item After Declarative Databinding

The new declarative controls of ASP.NET 2.0 are really great. However, there are some times, when it may not seem so.
Let's say you have a DropDownList which is bound by a DataSource control. Also, you have other pages hitting this page, with querystrings, and based on the item in the querystring, you'd like the to select that item.
In ASP.NET 1.1, you'd just code it, and select it after the code, or in the Pre-render event.
DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText(Request.Querystring("YourQuerystring"));