Wednesday, December 5, 2012

"Add Web Reference" missing in Visual Studio 2010/2012 - Solution

Where is the Add Web Reference option in Visual Studio 2010 and 2012.

Did microsoft remove the option to add web service and retained option only to use WCF references (Service Reference) ?

Everytime Microsoft comes up with a new version of a product, some of the options are either renamed or rearranged.

The same happened with Visual Studio 2010.
The option to add web reference is still available but is misplaced.

To access the option follow the steps below:

1) Right Click the Project -> Select "Add Service Reference". You get the "Add Service Reference" window.
2) On its left bottom there is an "Advanced..." button. It will take you to the "Service Reference Settings" window.
3) Bottom left of this window there is the old "Add Web Reference..." button dumped in a corner.
Click to get the "Add Web Reference window".


Monday, December 3, 2012

How to declare local variable in ASP.NET MVC Razor?

How to declare local variable in ASP.NET MVC Razor?
This is a very common scenario that newbies in ASP.NET MVC Razor view comes across.
It would be confusing when even with the "@" sign before the declaration it doesn't work.

The solution as simple as placing the whole declation statement inside curly braces.
Even multiple declarations can be placed inside a curly braces block.
The declaration and usage would be as below.

@{int count = 1;}
@foreach (var step in level.steps)
        <span class="title">@step.Name</span>
        <span class="meaning">@step.Description</span>

Sunday, November 18, 2012

How to add text to beginning or end of each line using notepad++

Get your text to modify in notepad++.

Step 1) Bring up the Find/Replace Dialog box by going to menu Search->Replace; or using shortcut CTRL+H.
Step 2) Select the "Regular expression" option in the "Search Mode" section of the dialog box.
Step 3) Enter "^" into the "Find what" textbox. ("^" denotes (matches) beginning of a line in Regular Expression syntax)
Step 4) In this example we will add "http://" to the beginning of each line. So enter "http://" (without double quotes) in the "Replace with" textbox.
Step 5) Press "Replace All" and your text will have "http://" at the beginning of each line.

Similar steps can be followed to add texts to the end of each line. Just use "$" instead of "^". In Regular Expression syntax, "$" matches the end of a line.

Tuesday, November 6, 2012

ASP.NET 4.0 A potentially dangerous Request.Form value was detected from the client.

"A potentially dangerous Request.Form value was detected from the client".

This error happens in ASP.NET when you try to submit text to server which contain HTML Tags. This is a mechanism in ASP.NET environment to safagaurd from cross sire scripting attack.

The error can be suppressed by setting a property to your page directive. The property and its value is as follows:
validateRequest="false" .
So the part of the Page Directive will look like below:
<pages validateRequest="false" />

But with .NET Framework 4.0 and above, the error started showing up again even with the validateRequest property set to "false".
To overcome this error in .NET Framework 4.0 you will need one more step.
You will need to set the "requestValidationMode" property  to "2.0" to the httpRuntime configuration section of the web.config file. The resulting tag will look like:
<httpRuntime requestValidationMode="2.0"/>

If your web.config file does not have a httpRuntime section already, then add it inside the
<system.web> section.

If you want to turn off request validation for users globally, the following line in the web.config file within <system.web> section will help:
<pages validateRequest="false" />

Wednesday, October 24, 2012

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.


While programming with Microsoft Entity Framework, you might have come across this error. The error occurs when calling the SaveChanges() method of the entity framework db context object. The original problem is not known unless you dig deeper into some of the property values of Entity Framework Exception classes.
Usually the exception raised is as below:

Server Error in '/' Application.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

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.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

You need to catch the exception (DbEntityValidationException ) and get into its properties to find the issue. Here is the catch block that will bring out the real issue:

C# Version:
catch (DbEntityValidationException dbEx)
    foreach (var validationErrors in dbEx.EntityValidationErrors)
        foreach (var validationError in validationErrors.ValidationErrors)
            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);

Wednesday, October 17, 2012

ATTACH DATABASE encountered operating system error 5 Access is denied Error

While trying to attach an .MDF SQL Server Express Database to my current SQL Server Instance, I encountered with the below error. This was the error message received.

Attach database failed for Server 'HABEEB-HP\SQLEXPRESS'.  (Microsoft.SqlServer.Smo)
For help, click:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
Unable to open the physical file "C:\testApp\App_Data\MyDB.mdf". Operating system error 5: "5(Access is denied.)". (Microsoft SQL Server, Error: 5120)
For help, click:

Googling quiet a bit mis led me to some version conflict reasons and file system security access issues. I tried to give full access to Network Service to the file. I tried to run SQL Server Service with Administrator Privilege from some suggestions online and nothing worked. Fiddling on it after a break I could figure out that its an SQL Server Management Studio (SSMS) privilege issue. I opened SSMS as Administrator and everything worked as a breeze.

Tuesday, October 9, 2012

When to use .First and .FirstOrDefault with LINQ?

When to use .First() and when to use .FirstOrDefault() with LINQ?

This is a frequent question among .NET developers who use LINQ.
Many of the developers keep coding with this doubt being uncleared in the back of their mind.
This is a very simple and straight forward question and solution.

Use .First() when you are pretty use that the LINQ query will definitely return at least one element in a sequence. In this case First() works pretty well and it will return the top 1 element from the resulting enumeration. But the sad part is when there is nothing returned executing the LINQ expression. In which case it will throw and exception. Practicing to catch the exception and always using only .First() is a very bad practice as it will affect the performance.

Use .FirstOrDefault() in the case where you cannot guarantee a result when executing a LINQ statement. In this case it gracefully returns the default value depending on the type. That is Null for reference types and the default values for primitive types. For example the default value for int is 0;

Transpose Columns into Rows (UNPIVOT)

How to Transpose (PIVOT (actually UNPIVOT ) / Transform) Columns into Rows
Sometimes you want to transpose Columns into Rows in SQL Server.

The below T-SQL will transpose or transform Columns into Rows. It uses the reverse of PIVOT which is UNPIVOT.

DECLARE @Table Table
(NameCol1 varchar(10),
NameCol2 varchar(10),
NameCol3 varchar(10))
INSERT INTO @TABLE VALUES ('Name 1', 'Name 2', 'Name 3')
--INSERT INTO @TABLE VALUES ('Name 4', 'Name 5', 'Name 6')
--INSERT INTO @TABLE VALUES ('Name 7', 'Name 8', 'Name 9')

SELECT Name, Nameval
(SELECT NameCol1, NameCol2, NameCol3
(NameVal FOR Name IN
(NameCol1, NameCol2, NameCol3)
)AS unpvt

Name             Nameval
-------------     ----------
NameCol1      Name 1
NameCol2      Name 2
NameCol3      Name 3

Tuesday, September 18, 2012

Problem in mapping fragments starting at line (xxx):All the key properties (____) of the EntitySet ____ must be mapped to all the key properties

Error 3003: Problem in mapping fragments starting at line xxx:All the key properties (table.column) of the EntitySet table must be mapped to all the key properties (table.column, table.column) of table table.

The most common cause of this issue is when there are some key constrain changes in the database and these changes are not properly reflected in the Entity Model. Usually the change is reflected in the Database mapping in the Entity but not in the Entity classes. In this case, "Update Model from Database" option also doesn't work quiet well.

1) Goto the Properties Window of the column that has the issue. (On the Entity Diagram Design View, right click -> Mapping Details -> Select the table with the issue column -> In Mapping Details window select the column and press F4 for its properties). In the properties window change Nullable property value from (None) to False.
2) If the Nullable property is already False, then the best option is to remove the table from the Entity Model. Then selection option "Update Model from Database". Select the removed table and click on Finish. Now the issue should be fixed.

Thursday, September 13, 2012

SQL Server "Saving changes is not permitted" Management Studio (SSMS)

"Saving changes is not permitted" - Error from SSMS when saving Table in Design View

"Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created."

This error happens from SQL Server Management Studio, when trying to save (edit/update) Table structure in Design View. Actually this is a SQL Server Management Studio (SSMS).

Tools -> Options -> Designers-> Uncheck "Prevent saving changes that require table re-creation"

Sunday, July 22, 2012

C# - Convert String to DateTime using ParseExact() method of DateTime

It is a common requirement to convert a Date/Time you have as a string to .NET native DateTime type.
The point to note here is to convey to the .NET Framework regarding the Date Format you provide as the input string. ParseExact() method of DateTime Type comes handy here.
Below is the solution to these

Convert String to DateTime in C# .NET
// String to DateTime
String dateText;
dateText = "1999-09-01 21:34 PM"; // Provide this according to your computer personal settings

DateTime myDate;
myDate = new DateTime();
myDate = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);

Convert DateTime to String in C# .NET
//DateTime to String
myDate = new DateTime(1999, 09, 01, 21, 34, 00);
String dateText = myDate.ToString("yyyy-MM-dd HH:mm tt");

Tuesday, July 10, 2012

C# - Linq - Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'int'

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'

In Linq queries sometimes you get the exception "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'int'". A scenario where you find this exception is as illustrated below:

int domainId = from p in pages
               where p.Value.aspxFile == pageFileName
               select p.Value.domain;

Logically I know there will only be one value being returned from this Linq Query statement, so it should work for me. But by syntax, this Linq statement returns type IEnumerable Collection.


int domainId = (from p in pages
        where p.Value.aspxFile == pageFileName
        select p.Value.domain).First();

This solves my issue and it will return only one object and not a collection. The object type is determined by the compiler at compile time which will be int in my case.

You can use .First() or FirstOrDefault() or Single(). But for Single() make sure that there is exactly only one element in the list.

Monday, April 2, 2012

ASP.NET AJAX not working on Google Chrome and Safari - Update panel/Popup Extender.

Recently i faced this issue when working with ASP.NET Ajax Updatepanel and Popup extender. The Popup was always visible and took a fixed space on the page like a normal div.

Added the below javascript code to a .js file.
Sys.Browser.WebKit = {}; //Safari 3 is considered WebKit
if( navigator.userAgent.indexOf( 'WebKit/' ) > -1 )
  Sys.Browser.agent = Sys.Browser.WebKit;
  Sys.Browser.version = parseFloat( navigator.userAgent.match(/WebKit\/(\d+(\.\d+)?)/)[1]); = 'WebKit';

Refer the .js file in the ScriptManager.
<ajax:ToolkitScriptManager ID="scripts" runat="server" ScriptMode="Release" EnableHistory="true"
EnableSecureHistoryState="false" EnablePageMethods="True" CombineScripts="true"
OnAsyncPostBackError="Page_OnAsyncError" OnNavigate="OnHistoryNavigate">
        <asp:ScriptReference Path="~/js/webkit.js" />

Sunday, April 1, 2012

JAVASCRIPT - How to remove last character from string

A common requirement, I have been approached is to have a javascript function to remove last character of a string. This is usually for some delimited string like a comma separated string.

var yourStr = "1, 2, 3, 4,"    
var yourstrLen =  yourStr.length;
yourStr =  yourStr.slice(0,yourstrLen-1);
alert (yourStr);

Instead of 
    yourStr.slice(0, 1); is also equally acceptable, because negative value sets offset from the end of the string.

Monday, March 26, 2012

SQL SERVER – Find First Day / Last Day of any month - Current - Previous - Next

Use the below queries as a sample to find the First day and Last Day of any month.
The sample below shows the First and Last days for previous and next months.

SELECT @today = GETDATE();
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@today)),@today),101) ,
'Last Day of Previous Month'
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(@today)-1),@today),101) AS Date_Value,
'First Day of Current Month' AS Date_Type
SELECT CONVERT(VARCHAR(25),@today,101) AS Date_Value, 'Today' AS Date_Type
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@today))),DATEADD(mm,1,@today)),101) ,
'Last Day of Current Month'
SELECT CONVERT(VARCHAR(25),DATEADD(dd,-(DAY(DATEADD(mm,1,@today))-1),DATEADD(mm,1,@today)),101) ,
'First Day of Next Month'
SELECT CONVERT(VARCHAR(25),DATEADD(dd,1-day((DATEADD(mm,-1,@today))),DATEADD(mm,-1,@today)),101) AS Date_Value,
'First Day of Previous Month' AS Date_Type

Alternatively you can also use the below code, this gives time precision also:

----Last Day of Previous Month
----Last Day of Current Month
----Last Day of Next Month

Sunday, March 25, 2012

SQL SERVER - How to use TRANSACTION in Stored Procedure | COMMIT, ROLLBACK

A SQL Server Transaction in a Stored procedure can be used to do a batch of queries especially INSERT / UPDATE / DELETE. The changes made to data in a transaction will persist only once COMMITTED. Hope the sample below helps you to get a practical idea about its usage.


INSERT INTO Person(Name, Age, Phone, Address)
VALUES ('Gates',50, '800-MSFT', 'Redmond, Washington, U.S')

IF @@ERROR <> 0

ASP.NET - Adding AjaxToolkit Accordion Pane Dynamically in C#

How to add AjaxToolkit Accordion Pane Dynamically in C#

In the below code, it iterate thought a List/Dictionary of custom object BannerList and creates Accordion Panes dynamically. The code is part of a sample I was working on. But it will help you understand the idea.

foreach (KeyValuePair<int, List<Banner>> entry in BannerList)
    AccordionPane ap1 = new AccordionPane();
    ap1.HeaderContainer.Controls.Add(new LiteralControl(Countries[entry.Key].ToUpper()));
    CheckBoxList chkLst = new CheckBoxList();
    chkLst.ID = "chkBoxLst" + Countries[entry.Key];
    chkLst.RepeatColumns = 5;
    foreach(Banner b in entry.Value)
        chkLst.Items.Add(new ListItem(b.BannerName, b.BannerID.ToString()));
    Button btnSave = new Button();
    btnSave.ID = "btnSave" + Countries[entry.Key];
    btnSave.Text = "Save";
    Button btnCancel = new Button();
    btnCancel.ID = "btnCancel" + Countries[entry.Key];
    btnCancel.Text = "Cancel";

Thursday, March 22, 2012

C#/VB.NET - Iterate through a Dictionary - Generic Collection

The cleanest and most straight forward way to iterate through a Dictionary is as follows:

foreach(KeyValuePair<int,String> valuePair in dict)  
    int i = entry.Key;  
    string s = entry.Value;  

SQL SERVER - How to split a comma separated string / delimited text

Use this SQL Server Function to split any string delimited text and get back items as a recordset.

    @string2split VARCHAR(8000) -- String to Split
  , @delimiter VARCHAR(8000) = ',' -- delimiter that separates string items
) RETURNS @List TABLE (item VARCHAR(8000))

WHILE CHARINDEX(@delimiter,@string2split,0) <> 0

 IF LEN(@sItem) > 0

IF LEN(@string2split) > 0
 INSERT INTO @List SELECT @string2split -- Put the last item in

SELECT * FROM dbo.fnSplit('Sudan, Congo DRC, Kenya, Uganda, Bahrain',',')


Congo DRC

ASP.NET - Method 'get_EnableCdn' in type 'System.Web.UI.ScriptManager' from assembly 'System.Web.Extensions' does not have an implementation

Error: "Method 'get_EnableCdn' in type 'System.Web.UI.ScriptManager' from assembly 'System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation."

This error is frequent in ASP.NET projects which are migrated from an older version of .NET Framework to a new version of Framework. So mostly in projected build in Visual Studio 2005/2008 when build in Visual Studio 2010, this error might occur. This is because of the web application referring to an older version of "System.Web.Extensions" Assembly.

You will have to explicitly reference to the latest version of the "System.Web.Extensions" Assembly. You can do it in web.config of your website/web application as below.

  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
      <bindingRedirect oldVersion="" newVersion=""/>
      <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
      <bindingRedirect oldVersion="" newVersion=""/>

Wednesday, March 21, 2012

SQL SERVER – Add Column With Default Column Constraint to Table

Setting a default value to a column in case a row in inserted with a no value provided for the column. Please find the below code to set a default value for a column. The example below adds a new column and applies the default constraint and default value of 'Hello' and the column doesn't allow null.

ADD YourNewColumn VARCHAR(50)

Constraint name is not mandatory as SQL Server will take a default constraint name in case if you don't provide one.

SQL SERVER – Convert Text to Numbers (Integer) – CAST and CONVERT

Using  CAST
SELECT CAST(YourVarcharColumn AS INT) FROM YourTable

SELECT CONVERT(INT, YourVarcharColumn) FROM YourTable

Here  YourVarcharColumn is of SQL type Varchar in table YourTable.

Exception happens when using  CAST or CONVERT is applied on alpha-numeric and casted/converted to numeric.

Tuesday, March 20, 2012

C#/VB.NET - Object cannot be cast from DBNull to other types | .NET Exception | Error

"Object cannot be cast from DBNull to other types" - Error / Exception in .NET / ASP.NET / ADO.NET

While executing the below code it throws and exception "Object cannot be cast from DBNull to other types".

while (reader.Read())  
   age = Convert.ToInt32(reader[0]);  

This is a common mistake from novice .net developers.

The error occurs because the field fetched by the DataReader has a database value null. This null value is attempted to convert to type int and thus the error "Object cannot be cast from DBNull to other types". If "Allow Null" is enabled for this field in the database and it contains null, then there is a possibility for this error.

Do a check for null before trying to access the value from the DataReader. Both solution 1) and solution 2) should work.

Solution 1)
 while (dr.Read())  
     age = reader.GetInt32(0);  

Solution 2)
 while (dr.Read())  
 if (reader[0] != DBNull.Value)  
 age = Convert.ToInt32(reader[0]);  

Wednesday, January 18, 2012

ASP.NET - Validation control not preventing postback

Issue: ASP.NET RequiredFieldValidator and other validation controls doesn't work the way it used to be all these time. I have a textbox and a RequiredFieldValidator Validation control attached to it. But when i submit the button it postback the page and then displays the validator message. This is not as we would expect. There could be a number of reasons for this. We will analyze different steps to solve it one by one.

1) If you had upgraded the solution from a previous version (1.1 usually) of .NET then in the web.config file, this tag is added and it can cause the issue.
Remove the line and the Validator issue must be fixed.
2) Try explicitly setting "EnableClientScript" property to true for the Validator control. Also make sure you have javascript enabled on the browser.
3) Set "EnableEventValidation" property to true on page level (<%@ Page EnableEventValidation="true" .... %>) or application level in web.config (<pages enableEventValidation="true"/>).
4) If you are using nested virtual directory, then test moving the page to the root directory.
5) Try in Visual Studio command prompt : aspnet_regiis – c . This will copy the folder aspnet_client to all the sub virtual directories.

As general prequation, check if javascript is enabled on client browser. Also always check "Page.IsValid" property in code behind because who knows what happens on client side.