Issue: How to set Startup / Default page in Windows Phone 7/8 app.
Solution:
Open WMAppManifest.xml file in Properties folder.
Set the proper Page name for the Tasks/DefaultTask/NavigationPage attribute as below:
<Tasks>
<DefaultTask Name ="_default" NavigationPage="Page1.xaml"/>
</Tasks>
Wednesday, May 1, 2013
Tuesday, February 19, 2013
How to get File Extension from File Name - C#,ASP.NET
Issue:
How to get File Extension from File Name - C#,ASP.NET
Solution:
System.IO.Path.GetExtension(filename);
Example:
string fileName = @"C:\temp\mypic.jpg";
extension = Path.GetExtension(fileName);
Console.WriteLine("Extension:"+extension);
How to get File Extension from File Name - C#,ASP.NET
Solution:
System.IO.Path.GetExtension(filename);
Example:
string fileName = @"C:\temp\mypic.jpg";
extension = Path.GetExtension(fileName);
Console.WriteLine("Extension:"+extension);
Saturday, January 19, 2013
Thursday, January 17, 2013
ASP.NET Session.Abandon() doesn't work - not Logged out
Issue:
Calling Session.Abandon() does not clear the full session and invalidate the login. User is not logged out by this.
Details:
Session.Abandon() Clears the current session of the user. This does not specifically ensures to clear all Session. For that you need to specifically call the Session.Clear() method. But many users expect to logout the user after these methods are called, which doesn't work well. Also this server side method doesn't clear the cached session on the client browser.
Solution:
If you want to invalidate the user login, the best solution is to use the ASP.NET LoginStatus control.
<asp:LoginStatus id="LoginStatus1" runat="server" LogoutAction="RedirectToLoginPage" />
Make sure to set the LogoutAction property to "RedirectToLoginPage". This will invalidate the user's session and Log him out.
Calling Session.Abandon() does not clear the full session and invalidate the login. User is not logged out by this.
Details:
Session.Abandon() Clears the current session of the user. This does not specifically ensures to clear all Session. For that you need to specifically call the Session.Clear() method. But many users expect to logout the user after these methods are called, which doesn't work well. Also this server side method doesn't clear the cached session on the client browser.
Solution:
If you want to invalidate the user login, the best solution is to use the ASP.NET LoginStatus control.
<asp:LoginStatus id="LoginStatus1" runat="server" LogoutAction="RedirectToLoginPage" />
Make sure to set the LogoutAction property to "RedirectToLoginPage". This will invalidate the user's session and Log him out.
Tuesday, January 8, 2013
Unable to update the EntitySet - because it has a DefiningQuery and no element exists in the element to support the current operation.
Error:
Unable to update the EntitySet 'Classroom' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
This error is raised while using Entity Framework.
While trying to save and persist db changes it raise this error. This error happens only in particular save and not every other places. The save operation raising this error is most probably an insert or a delete operation; like or example in my case:
db.Classrooms.Add(classroom);
db.SaveChanges();
Cause:
Eventhought the error message is a bit cryptic, the cause of the issue is simpler. The reason for this error is because the Primary key for the table is not set.
Solution:
Set the Primary key for the table and update the Entity Model (edmx file). This should clear the "Unable to update the EntitySet - because it has a DefiningQuery and no element exists in the element to support the current operation." exception.
Unable to update the EntitySet 'Classroom' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
This error is raised while using Entity Framework.
While trying to save and persist db changes it raise this error. This error happens only in particular save and not every other places. The save operation raising this error is most probably an insert or a delete operation; like or example in my case:
db.Classrooms.Add(classroom);
db.SaveChanges();
Cause:
Eventhought the error message is a bit cryptic, the cause of the issue is simpler. The reason for this error is because the Primary key for the table is not set.
Solution:
Set the Primary key for the table and update the Entity Model (edmx file). This should clear the "Unable to update the EntitySet - because it has a DefiningQuery and no element exists in the element to support the current operation." exception.
LINQ : How to check if a record exists in the database
Issue: How to check if a record exists in the database using LINQ
// Solution 1: Select . Don't use SingleOrDefault because if there are more than one record returned it throws exception.
var res = (from cls in db.Classrooms
where cls.Name == "10A"
select cls).SingleOrDefault();
if(res != null)
{
//record exists
}
// Solution 2: Select Count if you don't want to load the entity. This is an efficient method but not the most efficient. The LINQ expression translates to Count(*) in SQL.
int res = (from cls in db.Classrooms
where cls.Name == "10A"
select cls).count();
if(res > 0)
{
//record exists
}
// Solution 3:
Classroom cls = db.Classrooms.FirstOrDefault(cls => cls.Name == "10A");
if(cls != null) {
// record exists
}
else {
// record does not exist
}
// Solution 4: This is the most effective solution
// If you only want to know if such a Record exists:
// This is the most efficient as it generates an IF EXISTS SQL query
return db.Classrooms.Any(cls => cls.Name == "10A"); // true if exists
// Similar expression is:
return db.Classrooms.Where(cls => cls.Name == "10A").Any();
// Solution 5:
// If you want a count of how many such Record exists:
return db.Classrooms.Count(cls => cls.Name == "10A");
// Solution 6:
// If you want an enumeration (IEnumerable<Record>) of all such Record:
return db.Classrooms.Where(cls => cls.Name == "10A");
// Solution 1: Select . Don't use SingleOrDefault because if there are more than one record returned it throws exception.
where cls.Name == "10A"
select cls).SingleOrDefault();
if(res != null)
{
//record exists
}
// Solution 2: Select Count if you don't want to load the entity. This is an efficient method but not the most efficient. The LINQ expression translates to Count(*) in SQL.
int res = (from cls in db.Classrooms
where cls.Name == "10A"
select cls).count();
if(res > 0)
{
//record exists
}
// Solution 3:
Classroom cls = db.Classrooms.FirstOrDefault(cls => cls.Name == "10A");
if(cls != null) {
// record exists
}
else {
// record does not exist
}
// Solution 4: This is the most effective solution
// If you only want to know if such a Record exists:
// This is the most efficient as it generates an IF EXISTS SQL query
return db.Classrooms.Any(cls => cls.Name == "10A"); // true if exists
// Similar expression is:
return db.Classrooms.Where(cls => cls.Name == "10A").Any();
// Solution 5:
// If you want a count of how many such Record exists:
return db.Classrooms.Count(cls => cls.Name == "10A");
// Solution 6:
// If you want an enumeration (IEnumerable<Record>) of all such Record:
return db.Classrooms.Where(cls => cls.Name == "10A");
Tuesday, January 1, 2013
Open URL in Browser Programatically -IE/FF/Chrome [Windows Forms]
Problem:
I want to open a URL in desktop web browser programatically.
I want to open it in different browsers of my choice.
Solution:
Here are some code blocks to open a url in the browsers of our choice.
Below code will open a specific url in your default browser configured:
System.Diagnostics.Process.Start("http://www.habeeb.in");
To open the url in Internet Explorer, use the code:
System.Diagnostics.Process.Start("iexplore.exe", "http://www.habeeb.in");
To open the url in firefox, use the code:
System.Diagnostics.Process.Start("firefox.exe", "http://www.habeeb.in");
To open the url in Chrome, use the code:
System.Diagnostics.Process.Start("chrome.exe", "http://www.habeeb.in");
These solutions are based on Windows Desktops Winforms Applications.
I want to open a URL in desktop web browser programatically.
I want to open it in different browsers of my choice.
Solution:
Here are some code blocks to open a url in the browsers of our choice.
Below code will open a specific url in your default browser configured:
System.Diagnostics.Process.Start("http://www.habeeb.in");
To open the url in Internet Explorer, use the code:
System.Diagnostics.Process.Start("iexplore.exe", "http://www.habeeb.in");
To open the url in firefox, use the code:
System.Diagnostics.Process.Start("firefox.exe", "http://www.habeeb.in");
To open the url in Chrome, use the code:
System.Diagnostics.Process.Start("chrome.exe", "http://www.habeeb.in");
These solutions are based on Windows Desktops Winforms Applications.
Wednesday, December 5, 2012
"Add Web Reference" missing in Visual Studio 2010/2012 - Solution
Issue:
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.
Solution:
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".
Screenshots:
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.
Solution:
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".
Screenshots:
Monday, December 3, 2012
How to declare local variable in ASP.NET MVC Razor?
Issue:
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.
Solution:
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)
{
<div>
<span class="title">@step.Name</span>
<span class="meaning">@step.Description</span>
</div>
}
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.
Solution:
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)
{
<div>
<span class="title">@step.Name</span>
<span class="meaning">@step.Description</span>
</div>
}
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.
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.
Issue:
"A potentially dangerous Request.Form value was detected from the client".
Cause:
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.
Solution:
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" />
"A potentially dangerous Request.Form value was detected from the client".
Cause:
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.
Solution:
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.
Issue:
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.
Solution:
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);
}
}
}
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.
Solution:
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
Issue:
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: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=11.0.2100.60+((SQL11_RTM).120210-1917+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Attach+database+Server&LinkId=20476
------------------------------
ADDITIONAL INFORMATION:
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: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=10.00.5500&EvtSrc=MSSQLServer&EvtID=5120&LinkId=20476
------------------------------
Solution:
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.
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: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=11.0.2100.60+((SQL11_RTM).120210-1917+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Attach+database+Server&LinkId=20476
------------------------------
ADDITIONAL INFORMATION:
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: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=10.00.5500&EvtSrc=MSSQLServer&EvtID=5120&LinkId=20476
------------------------------
Solution:
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?
Issue:
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.
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;
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.
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)
Issue:
How to Transpose (PIVOT (actually UNPIVOT ) / Transform) Columns into Rows
Sometimes you want to transpose Columns into Rows in SQL Server.
Solution:
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
FROM
(SELECT NameCol1, NameCol2, NameCol3
FROM @TABLE) p
UNPIVOT
(NameVal FOR Name IN
(NameCol1, NameCol2, NameCol3)
)AS unpvt
-- OUTPUT
Name Nameval
------------- ----------
NameCol1 Name 1
NameCol2 Name 2
NameCol3 Name 3
How to Transpose (PIVOT (actually UNPIVOT ) / Transform) Columns into Rows
Sometimes you want to transpose Columns into Rows in SQL Server.
Solution:
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
FROM
(SELECT NameCol1, NameCol2, NameCol3
FROM @TABLE) p
UNPIVOT
(NameVal FOR Name IN
(NameCol1, NameCol2, NameCol3)
)AS unpvt
-- OUTPUT
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
Issue:
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.
Cause:
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.
Solution:
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.
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.
Cause:
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.
Solution:
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).
Resolution:
Tools -> Options -> Designers-> Uncheck "Prevent saving changes that require table re-creation"
"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).
Resolution:
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'
Issue:
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.
Solution:
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.
Issue:
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.
Solution:
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]);
Sys.Browser.name = '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">
<Scripts>
<asp:ScriptReference Path="~/js/webkit.js" />
</Scripts>
</ajax:ToolkitScriptManager>
Subscribe to:
Posts (Atom)

