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