Tuesday, December 31, 2013

Firebug Net panel - HTTP Traffic Monitoring

Needed to collect info around request URL, request header, response status, and response value of REST service calls, I utilized Net panel of Firebug which provided me a lot of details to verify the service calls processes in the web application.

The goal of using the Net panel was monitoring the HTTP traffic initiated by a web page which simply revealed all the collected and computed information in a graphical and intuitive interface.





introduction of Firebug by Rob Campbell


Share/Bookmark

IIS 7.5 Advanced Logging

To be able to capture all requests URLs and status of them in a real-time manner during a load test I added IIS Advanced Logging and customized it by defining the log, setting, and activating it.

It helped to monitor the sequence of requests and status of service responses during a load test.




Share/Bookmark

Trace listener and logging trace in a file

Possible to create and use a trace listener in code or by using a configuration file, as it’s easier to change configuration file without touching the code I tried to add it for a WebApi REST service by the following code for Telerik reports:

<system.diagnostics> <trace autoflush="false" indentsize="4"> <listeners> <add name="WebApiRESTListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="Services.Reporting.REST.Tracing.log" /> <remove name="Default" /> </listeners> </trace> </system.diagnostics>

Share/Bookmark

Friday, December 20, 2013

{System.Data.EntityException: The underlying provider failed on Open.

Entity Framework 5.0 with DbContext in the code tried to have access data as data Access layer code of a WCF service, the following error happened:

{System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Connection Timeout Expired. The time out period elapsed during the post-login phase. The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=50; handshake=1215; [Login] initialization=0; authentication=14; [Post-Login] complete=13022; ---> System.ComponentModel.Win32Exception: The wait operation timed out

It didn't have Transaction around the code, if I had a TransactionScope around the code then it treat connections as multiple ones using a distributed transaction which force open/close connections with each call. But without the transaction I needed to add opening connection code.

using (MyEntities ctx = new MyEntities()) { #region Added to work when Transaction is not around ctx.Database.Connection.Open(); #endregion courseList = ctx.MyMethod(MyParam).ToList(); }

Share/Bookmark

Friday, December 6, 2013

jQuery - replace html element by .remove()

.remove()
Remove the set of matched elements from the DOM.

You could remove an element from DOM but it doesn't get eliminated from wrapper set and this feature allows you remove an element, operate on that element, and then place that element back into the DOM, all within a single jQuery chain.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title></title> </head> <body> <div id="ItemToBeRelaced">remove it!</div>
<script> (function ($) { $('#ItemToBeRelaced') .remove() .html('<a href="http://greyknots.com/">GreyKnots</a>') .appendTo('body'); })(jQuery); </script>
</body> </html>

Share/Bookmark

jQuery - difference between closest() and parents()

closest() stops traversing once it finds a match.
closest() can only return a maximum of one element.
closest() will actually include the currently selected element in its filtering.
parents() gets all parents and then filters on your optional selector.

Try the following example:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title></title> </head> <body> <!-- Nested Div(s) --> <div id="parent3"> <div id="parent2"> <div id="parent1"> <div id="parent0"> <div id="LastInChain"></div> </div> </div> </div> </div>
<script> (function ($) { alert($('#LastInChain').parents().length); alert($('#LastInChain').parent().attr('id')); alert($('#LastInChain').parents('#parent0').attr('id')); alert($('#LastInChain').parents()[0].id);
alert($('#LastInChain').closest('#parent1').length); alert($('#LastInChain').closest('#parent1').length); alert($('#LastInChain').closest('#parent1').attr('id')); })(jQuery); </script>
</body> </html>

Share/Bookmark

Friday, November 29, 2013

Automating package restore in Visual Studio, don’t keep NuGet Packages in source control

When developers install NuGet packages and set references to those assemblies then it would be necessary to keep them available during build. On the other side down the road maybe the NuGet packages in your projects need to be upgraded and also keeping more and more binaries in repositories will just consume more space in your local disk and in repository especially for Git or Distributed version control systems (DCVS) which include every version of every file within the repository.

The best way is to enable package restore during build, the feature added since NuGet 2.0 and improved as of NuGet 2.7.

By automating package restore in Visual Studio the build events can handle installing the missing packages which eliminate the necessity of keeping them in repository.

There are two levels which should be set, simply go for ToolsOptions and then try to choose Package Manager 1. Visual Studio is configured to 'Allow NuGet to download missing packages' 2. Visual Studio is configured to 'Automatically check for missing packages during build in Visual Studio'



It’s done, but there is other options too like [MSBuild-Integrated Package Restore] which I’ll point to that in next blog entry.

Share/Bookmark

Friday, November 22, 2013

Adding external assemblies to load with Visual Studio at startup

Needed to add user defined methods for Telerik Reporting to be able to call the methods in expression builder of report, then it was necessary that Visual Studio loads the assembly at startup to make it ready for Telerik Report designer in VS.

Looked into VS configuration file:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe.config

Found the probing tag points to PublicAssemblies & PrivateAssemblies:
<probing privatePath="PublicAssemblies;PrivateAssemblies;..."/>

The above paths allows to have access to assemblies other than GAC, in this case, I needed to drop the custom coded assembly in a path which is known for VS.

Also assemblies deployed in PublicAssemblies path appear in the Add Reference dialog box, if you don't like to make them available in the Add Reference list but be known for VS, it should be deployed in PrivateAssemblies path.

Simply found the paths as following:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PublicAssemblies
C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\PrivateAssemblies

in this special case, I added the following parts in devenv.exe.config

<configSections> ... <section name="Telerik.Reporting" type="Telerik.Reporting.Configuration.ReportingConfigurationSection , Telerik.Reporting , Version=7.2.13.1016 , Culture=neutral , PublicKeyToken=a9d7983dfcc261be" allowLocation="true" allowDefinition="Everywhere"/> </configSections>

and then added the following part in devenv.exe.config to introduce the external methods functionality to Telerik.Reporting designer.
<Telerik.Reporting> <AssemblyReferences> <add name="MyAssembly" version="1.0.0.0" /> </AssemblyReferences> </Telerik.Reporting>

Now VS loads the assembly and it gets available for Telerik.Reporting as extended methods inside designer.
Share/Bookmark

Friday, October 4, 2013

Disable strong name validation in registry or skipping registered assemblies for verification

Tried to install a assembly .exe file as a windows service through installUtil.exe tool then I got the following error:



Then I tried to verify the assembly and it shows the assembly is delay-signed which figured out the reason of previous error:
sn -v assemblyName.exe

To drop the assembly from verification I could run the following command: sn -Vr *,c3692091f38d16a2

Alternative solution is to disable strong name validation by changing registry by adding a new key as "*,*" under the following one:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\StrongName\Verification



Caution: (Check here) "Use this option only during development. Adding an assembly to the skip verification list creates a security vulnerability. A malicious assembly could use the fully specified assembly name (assembly name, version, culture, and public key token) of the assembly added to the skip verification list to fake its identity. This would allow the malicious assembly to also skip verification."

Share/Bookmark

Monday, September 30, 2013

How to find the login security type for MS SQL Server

xp_loginconfig Reports the login security configuration of an instance of SQL Server.

exec master.sys.xp_loginconfig 'login mode'


xp_loginconfig (Transact-SQL)

Share/Bookmark

WCF Load Balancing – basicHttpBinding

To enable WCF service to take advantage of Load balancing with basicHttpBinding easily it needs to set keepAliveEnabled property of binding to false when there is connection reuse. When this property is enabled, will lead a client to maintain a persistent connection with the service which helps for performance side of view as the connection reuses with multiple messages. Ideally in a load balanced cluster the purpose is to avoid having sticky sessions and strongly associated a client with a server, a simple solution is utilizing the following configuration for custom binding:

<customBinding> <binding name="CustomHttpBindingConfig" closeTimeout="00:10:00" openTimeout="00:10:00" sendTimeout="00:10:00"> <textMessageEncoding /> <httpTransport keepAliveEnabled="false" /> </binding> </customBinding>


Another approach to apply necessary changes through the code discussed before in “WCF service under Network Load Balancing (NLB)” blog entry.

Share/Bookmark

Tuesday, September 24, 2013

Add SSRS (SQL Reporting Services) to an existing SQL Server Clustered Instance

To add a SSRS feature to already installed SQL server cluster it's necessary to bypass checking HasClusteredOrPreparedInstance rule before running setup file otherwise the unstallation will encounter with error during "Installaation Rules" check with some popup message like following:



To avoid above mentioned error it's possible to run setup as following:
Setup.exe /SkipRules=StandaloneInstall_HasClusteredOrPreparedInstanceCheck /Action=Install


Share/Bookmark

SSRS (Reporting Services), Scale Out, Clusters, or NLB, ...

The question around installing Reporting Services as part of a SQL Cluster install with attention to the fact that SSRS is not cluster aware and utilizing NLB if you want to do it (even though it's not recommended) ended up in the following URL which I would like to share here.

Share/Bookmark

Monday, September 23, 2013

How to find out installed features on SQL server instance

The SQL Server Setup Discovery Report helps to view installed features on a local SQL server instance,

Start menu --> All Programs --> Microsoft SQL Server --> Configuration Tools --> SQL Server Installation Center --> Click the "Tools" --> "Installed SQL Server features discovery report"



The command line version would be like the folowing:
setup.exe /ACTION=RUNDISCOVERY /Q

The setup.exe is located somewhere like (for MS SQL Server 2012):
C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\SQLServer2012

The report will be located in log folder under "Setup Bootstrap" in a unique subfolder which will be named as YYYYMMDD_HHmmSS, but the location can be vary depend on installation location:
C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\Log\YYYYMMDD_HHmmSS

Share/Bookmark

Thursday, September 19, 2013

SSRS Line Spacing

LineHeight property of Textbox control works just when the report renders in HTML format, to control line spacing in a Multi line textbox which carries a long text who handles auto text wrap up doesn't functions correctly.

Vote up for the following item in Microsoft Connect:
https://connect.microsoft.com/SQLServer/feedback/details/557661/line
Share/Bookmark

Friday, September 13, 2013

JavaScript - Calling function "statements" before definition

function statements get interpreted and will be added to the execution stack before code execution then that's the reason but have attention that it doesn't happen to neither function expressions nor functions which define by Function constructor.

<!DOCTYPE html><html lang="en"><body><script> // logs 11 console.log(aFunc(1, 2, 3)); function aFunc(x, y, z) { return x*y + arguments[0]*arguments[1]*arguments[2] };
// logs "Uncaught TypeError: ..." console.log(iFunc(1, 2, 3)); var iFunc = function (x, y, z) { return x*y + arguments[0]*arguments[1]*arguments[2] };
// logs "Uncaught TypeError: Property 'bFunc' of object [object Object] is not a function" console.log(bFunc(1, 2, 3)) var bFunc = function (x, y, z) { return x*y + arguments[0]*arguments[1]*arguments[2] }; </script></body></html>

Share/Bookmark

Thursday, September 12, 2013

Non-primitive [false] Boolean object is actually [true]

A Boolean object with false parameter (not the primitive false value) which generated from the Boolean() constructor, the object value will be true to check you may use it in an "if" condition.

If a value is false, undefined, null, NaN, 0, -0, or an empty string(""), it is false! but any other value in JavaScript will be converted to true if used in a Boolean context.

<!DOCTYPE html> <html lang="en"> <body> <script> var myBoolean = new Boolean(false); console.log( myBoolean ); console.log( myBoolean.toString() ); console.log( myBoolean.valueOf() ); if( myBoolean ) console.log( typeof myBoolean ); </script> </body> </html>

Share/Bookmark

Wednesday, September 11, 2013

JavaScript - references to object properties

if the property of an object which you try to access is not available, JavaScript will try searching the prototype chain. At first steps it goes after the constructor function that created the object to check its prototype (e.g., Array.prototype) and if that's not available there it keeps searching up the chain at the constructor behind the initial constructor.

As all those prototype properties are objects, the final step would be Object.prototype because there is no other constructor prototype property upper than Object level to be examined.

Anyway if finally JavaScript can't find the property it would have produced an error stating that the property was undefined.

<!DOCTYPE html><html lang="en"> <body> <script> var myArray = ['element1', 'element2']; console.log(myArray.hasOwnProperty('join')); console.log(myArray.join());
console.log(myArray.hasOwnProperty('toLocaleString')); console.log('toLocaleString' in myArray); console.log(myArray.toLocaleString());
</script> </body> </html>

Share/Bookmark

Javascript console.log for web browsers

Javascript console.log for web browsers by console.log you may view any output message, other debugging tools or plugins can be utilized too for this purpose which are generally better as they provide rich features for debugging (e.g Firebug, ...).

To open the console window the following keywords work depend on the web browser:

console window
<b>Internet Explorer<\b> F12 to open the developer tools, then
Ctrl+3 to open the console window
<b>Chrome<\b> Ctrl+Shift+J
<b>Firefox<\b> Ctrl+Shift+K
<b>Safari<\b> Ctrl+Alt+I

Share/Bookmark

Tuesday, September 10, 2013

Enable/Disable - SSRS Export Types

SSRS supports exporting to different formats when you view the report through a drop-down list. Report services server configuration file which is available in the following path allows to control the list:
C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer\rsreportserver.config

Inside the <Render> tag elements, the Extension names have Visible attribute which changing them to true will make the Extension visible in the Export list.
Example:


Share/Bookmark

Thursday, September 5, 2013

TSQL - Count number of lines in string

Counting \r\n in a TSQL string and determine the number of new lines.
DECLARE @str VARCHAR(128) SET @str = RTRIM(LTRIM( 'Line 1' + CHAR(13)+CHAR(10) + 'Line 2' + CHAR(13)+CHAR(10) + 'Line 3' + CHAR(13)+CHAR(10) + 'Line 4' )) SELECT @str , (LEN(@str) - LEN(REPLACE(@str, CHAR(13)+CHAR(10), ''))) / 2 + IIF( CHARINDEX(CHAR(10)+CHAR(13), REVERSE(@str), 0) = 1, 0, 1) AS strNoOfLines

Share/Bookmark

Thursday, August 29, 2013

SQL Server Data Tools - Update to open Database Project

When tried to open a SQL database project in Visual Studio 2012 Update 2, I encountered with the following error message.



My search ended up with updating SQL Server Data Tools for Visual Studio 2012 which I used this MSDN link to load and set it up, the problem solved.

Share/Bookmark

Clustered SQL server - Get the current node name of running instance

One way to get the current node name of running instance of clustered SQL server would be to execute the following scripts:

--Check SQL Server instance name SELECT @@SERVERNAME --Check the name of the node on which the clustered -- SQL Server instance is running on SELECT SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [CurrentNodeName]


Alternatively, you may run Server manager (right click on "Computer" in start menu and choose "Manage"), then
Features -> Failover Cluster Manager -> [The cluster name] -> Services and applications -> SQL server

It shows details and the "Current Owner" shows the node which SQL server is running on that node.
Share/Bookmark

Wednesday, August 28, 2013

Query all SSRS Reports, shared and embeded Datasources, and locations

As the SSRS reports details are available in ReportServer DB, sometime that's a good idea to take a look into reports' detail such as data sources which in some point may help to make a better decision to keep them embedded or utilize a shared one.

By customizing the folllowing script easily more information can be queried.

Use ReportServer GO ;WITH SSRS_Rprt_DtaSrc AS ( SELECT Catalog.Name AS [Report Name] , Catalog.path AS [Report Location] , DataSource.Name AS [Data Source Name] , DataSource.Link AS Link FROM [Catalog] INNER JOIN DataSource ON Catalog.ItemID = DataSource.ItemID ) SELECT [Report Name] , [Report Location] , [Data Source Name] , Ctlg.Name AS [Data Source Item] FROM SSRS_Rprt_DtaSrc INNER JOIN [Catalog] AS Ctlg ON SSRS_Rprt_DtaSrc.Link = Ctlg.[ItemID] ORDER BY [Report Location]

Share/Bookmark

Friday, August 23, 2013

Microsoft iSCSI Software Target 3.3 (MS Windows Server 2008 R2)

Needed to install SQL server clusters, then it needs shared data to be used as centralized disk subsystem by SQL nodes in the cluster, the feature is build in by MS Windows Server 2012 but for MS Windows Server 2008 R2 it’s available as a download in Download Center if you search for “iSCSI Target” which is free.



By clicking on “iSCSI Software Target” it downloads a .msi and install it. After running, right click on device and choose “Create Virtual Disk”.



Choose a file name for the Virtual disk which has .vhd extension and click on Next.



Set the Virtual disk size and click on Next.



Possible to write a description too (optional) and click on Next.



Now bypass adding iSCSI targets by clicking on Next as targets are not defined yet and after that click on Finish.



The Virtual disk is ready:



Right click, on “iSCSI Target” and then “Create iSCSI Target”



Then choose a name:



Better to address the target by IP, then click on Advanced, choose “Add”, and now choose “IP Address” and enter the IP and click to finish this part



Now the target is available:



Then assign the Target to Device by right clicking on the Virtual Disk and choose “Assign/Remove Target”



Click on Add in Target Access tab:



Choose the Target and click on Ok and close the window. It’s done now you can use it in the Target side.
Connect to remote system, choose “Administrative Tools” and choose “iSCSI Initiator” Enter IP address of target In Target text box and click on Quick Connect



Quick connect window discovers target, now click on Done.



Now choose “Volumes and Devices” tab



The device adds in Volume list:



Click on OK and close the window



now right click on the disk and click on Online then right click again and choose “Initialize Disk”, right after right click on new disk and choose “New Simple Volume” to set a letter and format the volume which make it available immediately.


Share/Bookmark

Wednesday, August 14, 2013

ASP.NET MVC and SQL Server Reporting Services

ASP.NET MVC and SQL Server Reporting Services If you need to view a SSRS type report in ASP.NET MVC application one way would be to have a Controller action method to launch report and an ASP.NET Web Form to host the Report Viewer control. Then the action method redirects to the .aspx page which contains the report viewer control and passes necessary parameters for report's query filter. The sample code is as following:

".ASPX web form page who contains ReportViewer control"
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="8pt" Height="768px" ProcessingMode="Remote" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Width="1024px"> <ServerReport ReportPath="/REPORTS_FOLDER/REPORT_NAME" ReportServerUrl="http://YOUR_SSRS_SERVER/reportserver" /> </rsweb:ReportViewer> </form> </body> </html>

using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.Reporting.WebForms; ... protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { var rprtPrms = (Dictionary) Session["reportParameters"]; foreach (var item in rprtPrms) { ReportViewer1.ServerReport.SetParameters( new List() { new ReportParameter(item.Key, item.Value.ToString()) } ); } } }

"The action in the controller"
public ActionResult Index() { var rprtPrms = new Dictionary(); rprtPrms.Add("MyReportParameter", 6); Session["reportParameters"] = rprtPrms; return Redirect("/RprtViewer.aspx"); }

Share/Bookmark

Tuesday, August 13, 2013

SSRS Report - Showing Header objects only on First Page

To hide the header objects (textboxes, images) that hold the header information on pages other than first one it's possible to control visibility of objects by a conditional expression lok like the following one:
=iif(Globals!PageNumber = 1, FALSE, TRUE)

The expression property will be accessible with below steps:
right-click on the header object (Image, text box) -> choose properties -> visibility -> select "Show or hide based on expression" -> insert expression above


Share/Bookmark

Adding a Page Break after a Sub-report (SSRS report)

I needed to break the page after a sub-report to force the next sub report to be shown in next page.

One way which was fit for my case comes simply as following:

- Added a rectangle onto my report and position it just below the sub-report.
- Resized the rectangle to only one pixel tall.
- In properties windows of the Rectangle object, set the PageBreak->BreakLocation property to Start.


Share/Bookmark

Tuesday, August 6, 2013

WCF service under Network Load Balancing (NLB)

To use WCF services on multi servers under Network Load Balancing one solution would be utilizing BasicHttpBinding as WCF channels that use this binding are inherently stateless, and terminate their connections when the channel closes.

In message Http header of BasicHttpBinding the Keep-Alive value is true by default which helps to keep persistent connections into services to reuse by sending messages to the same server that improves performance of services. The side effect is the cause of associating clients to specific server which reduces the effectiveness of load balancing. Setting KeepAliveEnabled value to false within a CustomBinding allows NLB functions correctly without sticky session and server affinity.

using (var srv = new SrvClient("BasicHttpLB")) { #region Custom binding to disable [Keep Alive] property of transport Element var wcfsrvCstmBndng = new CustomBinding(svcBinding); var bindingTransportElement = wcfsrvCstmBndng.Elements.Find< HttpTransportBindingElement>(); bindingTransportElement.KeepAliveEnabled = false; // Disable [Keep Alive] property of Transport Element #endregion srv.Endpoint.Binding = wcfsrvCstmBndng; .... //Calling service operations and do what's necessary }

Share/Bookmark

Thursday, August 1, 2013

.NET Framework Version (including 4.0+)

As the .NET Framework 4.5 is an in place update then it updates assemblies if .NET 4.0 is already installed, the best way to find out available .NET framework versions in the system would be checking it in registry.

The following code is executable directly in LinqPad too, you can get the perfect LinqPad tool (free) by (Joseph Albahari) here.

// Microsoft.Win32 // System void Main() { RegistryKey ndpKey = RegistryKey.OpenBaseKey( RegistryHive.LocalMachine , RegistryView.Registry32).OpenSubKey( @"SOFTWARE\Microsoft\NET Framework Setup\NDP\"); foreach (string verKeyName in ndpKey.GetSubKeyNames()) { if (verKeyName.StartsWith("v")) { RegistryKey verKey = ndpKey.OpenSubKey(verKeyName); string name = (string)verKey.GetValue("Version", ""); string sp = verKey.GetValue("SP", "").ToString(); string install = verKey.GetValue("Install", "").ToString(); if (install == "") Console.WriteLine( verKeyName + " " + name); else if (sp != "" && install == "1") Console.WriteLine( verKeyName + " " + name + " SP" + sp); if (name != "") continue; foreach (string subKeyName in verKey.GetSubKeyNames()) { RegistryKey subKey = verKey.OpenSubKey(subKeyName); name = (string)subKey.GetValue("Version", ""); if (name != "") sp = subKey.GetValue("SP", "").ToString(); install = subKey.GetValue("Install", "").ToString(); if (install == "") Console.WriteLine(verKeyName + " " + name); else if (sp != "" && install == "1") Console.WriteLine( " " + subKeyName + " " + name + " SP" + sp); else if (install == "1") Console.WriteLine( " " + subKeyName + " " + name); } } } }

Share/Bookmark

Monday, July 29, 2013

DbEntityValidationException - Entity framework validation error handling

A sample code to catch part of an error handling when dealing with Entity Framework.
try { ... } catch (DbEntityValidationException dbEx) { #region LINQ query to get EF DB entity validation errors /* var errMsgs = dbEx.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage).ToArray(); var exceptionFullErrMsg = string.Concat( dbEx.Message, " Validation errors (DbEntityValidationException): " + UtilityHelper.ErrMsgBuilder(errMsgs)); log.Error(exceptionFullErrMsg); */ #endregion #region Loop to find Entity Framework DB entity validation errors foreach (var validationErrors in dbEx.EntityValidationErrors) foreach (var validationError in validationErrors.ValidationErrors) log.Error(UtilityHelper.ErrMsgBuilder(new string[] { "DbEntityValidationException" , validationError.ErrorMessage } )); #endregion } catch (Exception ex) { #region Exception logging log.Error(UtilityHelper.ErrMsgBuilder( new string[] { ex.GetType().Name } ), ex); #endregion } finally { ... } ... #region Utility Helper class public class UtilityHelper { public static string ErrMsgBuilder(String[] msgArray) { StringBuilder sbErr = new StringBuilder(); foreach (string msg in msgArray) sbErr.AppendLine(msg); return sbErr.ToString(); } } #endregion

Share/Bookmark

Friday, July 26, 2013

Unable to update the EntitySet 'EntityName' because it has a DefiningQuery and no element exists in the element to support the current operation.

Tied to debug my unit [TestMethod] in a unit test project through Test Explorer in Visual Studio 2012, then it tried to save the entity changes in database through a DbContext and it throw the folowing error message: 'Unable to update the EntitySet 'EntityName' because it has a DefiningQuery and no element exists in the element to support the current operation.'

In my case the problem was incorrect Entity Key setting on my entity in EF Model plus forgetting to set primary key in DB table. After setting primary key for the table which entity pointing too, I needed to update the model and open the EF model and manualy set Entity Key for primary key related member in the entity and clearing Entity Key setting for unnecessary entity members. Then rebuild, it worked. The reason was EF created a compound key made of all non nullable entity members which I had to reset them all.

It was my case but there are other possibilities for this error which already discussed if you search on Internet (Google or bing it)
Share/Bookmark

Wednesday, July 17, 2013

SQL - Record count for all tables in a DB

I needed to count the number of records after a DB backup and restore then the following script helped to do that.
USE [Database_Name] GO CREATE TABLE #tblRecCount ( tblName varchar(255), tblRowCount int ) EXEC sp_MSForEachTable @command1='INSERT #tblRecCount (tblName, tblRowCount) SELECT ''?'', COUNT(*) FROM ?' SELECT tblName, tblRowCount FROM #tblRecCount ORDER BY tblName, tblRowCount DESC SELECT SUM(tblRowCount) AS totalDbRowCount FROM #tblRecCount DROP Table #tblRecCount
The original post is available here.
Share/Bookmark

Tuesday, July 16, 2013

How to add a digital ID to adobe reader (.pfx exported certificate file)

When you see a PDF document after opening with a message that it’s signed but not valid, you need to import the necessary .pfx certificate file, if you have the .pfx file simply add it as following: Adobe reader :: Edit –> Protection –> Security Settings -> Windows Digital IDs then now click on “Add ID” and follow the wizard to impost the certificate.
Share/Bookmark

Sunday, April 14, 2013

Microsoft Security Essentials - a must have security pieces to protect your system

Get Microsoft Security Essentials for the low, low price of free. http://windows.microsoft.com/en-US/windows/security-essentials-download

Saved me from Sirefef.gen!C which is a computer virus that intercepts secure web connections and can steal passwords and other sensitive data. Chrome recognises this virus, but it affects all software on the computer. Other browsers and software may continue to work but they are also affected and rendered insecure.

Microsoft Security Essentials can reportedly remove this virus. When the virus is removed, the warnings in Chrome will stop.
Share/Bookmark