Monday, September 8, 2014

Unable to update the EntitySet ‘Table’ because it has a DefiningQuery and no element exists in the element to support the current operation

Entity Framework tried to add a record to a table which had Clustered Index but it didn't have Primary Key.

Simple solution was adding the Primary Key.

the reason is treating the table as View, then the EDMX file keep the table as a view in StorageModel\EntitySet\DefiningQuery element. When there is a DefiningQuery the Entity becomes readonly unless you add modification functions, the other solution can be adding modification functions like Stored Procedures for Inserting, Updating, and Deleting.

Share/Bookmark

Tuesday, August 19, 2014

VS :: Peek Definition

Everyday I enjoy the Peek definition in Visual Studio 2013 !

Share/Bookmark

Friday, June 27, 2014

SQL - Break execution of a SQL script

SET NOEXEC ON

SET NOEXEC ON skips the rest of the script but it does not terminate the connection.
To execute any other command you need to turn noexec off again.

OR

RAISERROR('Your error message', 20, -1) WITH log

This will terminate the connection, thereby stopping the rest of the script from running.
If you are logged in SQL as [admin] ('sysadmin' role), the RAISERROR will terminate the connection and stops the script from running the rest of code.
(If you are not logged in as [admin], otherwise the RAISEERROR() will fail and the script will continue executing.) Note that it requires both severity 20 (or higher) and "WITH LOG".

Share/Bookmark

Recursive SQL CTE to split CSV string to table rows

DECLARE @strCSV VARCHAR(8000) , @delimiter CHAR(1) SET @delimiter = ',' SET @strCSV = '001002330 ,001012657 ,001046228 ,001105047 ,001138189' DECLARE @TableVariable TABLE ( ID INT, Item VARCHAR(12) ) ;WITH RegNumStartEndIndexes AS( SELECT StartIndex = 0 , EndIndex = CHARINDEX(@delimiter,@strCSV) UNION ALL SELECT EndIndex+1 , CHARINDEX(@delimiter,@strCSV,EndIndex+1) FROM RegNumStartEndIndexes WHERE EndIndex>0 ) INSERT INTO @TableVariable (ID, Item) SELECT ROW_NUMBER() OVER(ORDER BY(SELECT 1)) AS ID , REPLACE( REPLACE( SUBSTRING(@strCSV, StartIndex, COALESCE(NULLIF(EndIndex,0), LEN(@strCSV)+1)-StartIndex), CHAR(13), ''), CHAR(10), '') AS Item FROM RegNumStartEndIndexes option (maxrecursion 0) -- [option (maxrecursion 0)] added To avoid following error when number of recursions gets high -- The maximum recursion 100 has been exhausted before statement completion SELECT * FROM @TableVariable

Originally grabbed the idea from here

Share/Bookmark

Monday, June 16, 2014

Query sp_Who2

sp_Who by MSDN - "Provides information about current users, sessions, and processes in an instance of the Microsoft SQL Server Database Engine. The information can be filtered to return only those processes that are not idle, that belong to a specific user, or that belong to a specific session."

DECLARE @Table TABLE( SPID smallint, Status nchar(30), LOGIN nchar(128), HostName nchar(128), BlkBy char(5), DBName nchar(128), Command nchar(16), CPUTime INT, DiskIO INT, LastBatch VARCHAR(MAX), ProgramName VARCHAR(MAX), SPID_1 INT, REQUESTID INT ) INSERT INTO @Table EXEC sp_who2 SELECT * FROM @Table WHERE DBName = 'DB_NAME'

Share/Bookmark

Friday, May 2, 2014

Global Assembly Cache Tool - Gacutil.exe

Gacutil.exe can help to view and manipulate the global assembly cache and download cache. Visual Studio installs the tool and it needs to run using the Developer Command Prompt.
gacutil [options] [assemblyName]


Share/Bookmark

Wednesday, April 30, 2014

Assembly Binding Log Viewer - fuslogvw.exe

When assembly binding fails, typically with an exception (usually, FileNotFoundException, FileLoadException, or BadImageFormatException).

At this point the Assembly Binding Log Viewer (fuslogvw.exe) which comes with .NET framework or The Microsoft .NET Framework SDK, I used it with .NET 4.5 the last time and through Developer Command Prompt for VS2013 which ran as Administrator.

When the binding happens, it looks like a Fusion, and "the Assembly Binding Log Viewer" will show you all assembly binds providing the HKLM\Software\Microsoft\Fusion\ForceLog registry value gets set to 1.

To force it to log I did the following setting in registery (by regedit.exe) HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion Add: DWORD ForceLog set value to 1 DWORD LogFailures set value to 1 DWORD LogResourceBinds set value to 1

My problem which caught me was about signing assemblies which were strongly named in addition to assembly versioning.

Sample log will be something like the following (but this one is a successful binding sample):
*** Assembly Binder Log Entry (4/28/2014 @ 2:30:11 PM) *** The operation was successful. Bind result: hr = 0x0. The operation completed successfully. Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll Running under executable C:\Program Files (x86)\IIS Express\iisexpress.exe --- A detailed error log follows. === Pre-bind state information === LOG: DisplayName = Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a (Fully-specified) LOG: Appbase = file:///D:/appBranch/DEV-R2/LT/Services/Authentication/Authentication/ LOG: Initial PrivatePath = D:\appBranch\DEV-R2\LT\Services\Authentication\Authentication\bin LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\f388dcb0 LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\f388dcb0 LOG: AppName = 90e27310 Calling assembly : (Unknown). === LOG: This bind starts in default load context. LOG: Using application configuration file: D:\LandTitles\DEV-R2\LT\Services\Authentication\Authentication\web.config LOG: Using host configuration file: C:\Users\Farhad.Bayanati\Documents\IISExpress\config\aspnet.config LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config. LOG: Post-policy reference: Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a LOG: Found assembly by looking in the GAC. LOG: Binding succeeds. Returns assembly from C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_4.0.0.0__b03f5f7f11d50a3a\Microsoft.CSharp.dll. LOG: Assembly is loaded in default load context.

Share/Bookmark

Monday, April 28, 2014

How to get Assembly full name(VersionNo, Culture, PublickeyToken)

In Visual Studio, Open a project, Debug Menu-->Windows-->Immediate
Shortcut: (Alt + Ctrl + i) or (Ctrl + D, I) open the Immediate Window

?System.Reflection.Assembly.LoadFile(@"C:\Path\YourAssemblyName.dll").FullName


P.S.
If you can't see the immediate window:
I am guessing that you picked a profile that hides this window.
Try: Tools->Import and Export settings->Reset all settings, and pick general development settings.

If you encoutered with following message:
"Design time expression evaluation for class libraries requires the Visual Studio hosting process which is unavailable in this debugging configuration."
Be sure in the project "Enable the Visual Studio hosting process" is checked, enabled.
Be sure in the project "Enable the Visual Studio hosting process" is checked, enabled.

The host process which is pointed to in above message refers to a feature of the CLR, Hosting allows one to configure the CLR before it gets started. One primary use of this is configuring the primary AppDomain and setting up custom security policies. Which is exactly what the hosting process is doing. in debug mode you are running with a customized version of the CLR, one that improves the debugging experience.


Share/Bookmark

Thursday, March 20, 2014

Physical DB and Log File location

A reminder!
USE [DB Name] GO SELECT * FROM sys.database_files

Share/Bookmark

Tuesday, February 25, 2014

C# - LINQ - Flatten nested Lists

Enumerable.SelectMany<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, IEnumerable<TResult>>)

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

IEnumerable group = new List(); // Select gets a list of lists of phone numbers IEnumerable> phoneLists = group.Select(g => g.Phones); // SelectMany flattens nested lists of phone numbers to a single list List phoneNumbers = group.SelectMany(g => g.Phones).ToList(); public class Phone { public string Number { get; set; } } public class Member { public IEnumerable Phones { get; set; } }

Share/Bookmark

Tuesday, January 21, 2014

A custom exception class with Log flag

A class to re-thrown Exception with property if the Exception is already logged.

[Serializable()] public class ExceptionLog : Exception { private bool isLogged; public bool IsLogged { get { return isLogged; } } protected ExceptionLog() : base() { } public ExceptionLog(bool value) : base() { isLogged = value; } public ExceptionLog(bool value, string message) : base(message) { isLogged = value; } public ExceptionLog(bool value , string message , Exception innerException) : base(message, innerException) { isLogged = value; } protected ExceptionLog(SerializationInfo info , StreamingContext context) : base(info, context) { } }

Share/Bookmark

Friday, January 3, 2014

Split Camel Case "string" To Human Readable

private string SplitCamelCaseToHumanReadable(string strCamelCase) { var rgx = new Regex( @"(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])" , RegexOptions.IgnorePatternWhitespace); return rgx.Replace(strCamelCase, " "); }

Share/Bookmark