Thursday, January 26, 2023

Cache or Not to Cache LambdaExpression.Compile

As per below statement from Microsoft, don't need to create a cache mechanism to avoid LambdaExpression.Compile() calls.

I will caution you against trying to create any more sophisticated caching mechanisms to increase performance by avoiding unnecessary compile calls. Comparing two arbitrary expression trees to determine if they represent the same algorithm will also be time consuming to execute. You'll likely find that the compute time you save avoiding any extra calls to LambdaExpression.Compile() will be more than consumed by the time executing code that determines of two different expression trees result in the same executable code.

However, still not sure if again and again compiling of an expression tree is memory friendly or not.

Source: https://learn.microsoft.com/en-us/dotnet/csharp/expression-trees-execution

A guy here is claiming that there seems to be no memory problem. I guess we'll see in production :P.

Monday, September 26, 2022

JavaScript Kendo Window as Dialog (async/await)

	
	// This function will add following methods in kendo Window
	//		openAsync()		opens the window asynchronously, true = OK, false = Cancel
	//		closeOk()		call this method on "OK" button click
	//		closeCancel()		call this method on "Cancel" button click
	//	IMPORTANT: kendoWindow paramter must be a kendow window
	//				e.g. addOpenAsyncInKendoWindow($("#popup").data("kendowWindow"));
    
	function addOpenAsyncInKendoWindow(kendoWindow) {
  		if (!kendoWindow.openAsync) {
			kendoWindow.bind("deactivate", () => {
      				if (kendoWindow.dispatchClosePopupCall)
        				kendoWindow.dispatchClosePopupCall(kendoWindow.asyncDialogResult);
			});
    			kendoWindow.getResponseAsync = async () => {
      				return (new Promise(resolve => kendowWindow.dispatchClosePopupCall = resolve)).then((data) => { kendowWindow.dispatchClosePopupCall = null; return data; });
			};  
    			kendoWindow.openAsync = async () => {
      				kendoWindow.center();
      				kendoWindow.open();
      				return await kendowWindow.getResponseAsync();
			};
    			kendoWindow.closeOk = () => {
      				kendoWindow.asyncDialogResult = true;
      				kendoWindow.close();
			};
    			kendoWindow.closeCancel = () => {
      				kendoWindow.asyncDialogResult = false;
      				kendoWindow.close();
			};
		}
	}
    
	// Example Usage
	$("#btnOpenPopup").on("click", async e => {
		e.preventDefault();
		const kp = $("#popup").data("kendoWindow");
		addOpenAsyncInKendowWindow(kp);
		const dialogResult = await kp.openAsync();
		if (dialogResult)
			alert("Ok was clicked");
		else
			alert("Cancel was clicked");
	});
    
	$("#btnOk").on("click", e => {
		e.preventDefault();
		const kp = $("#popup").data("kendoWindow");
		kp.closeOk();
	});
	$("#btnCancel").on("click", e => {
		e.preventDefault();
		const kp = $("#popup").data("kendoWindow");
		kp.closeCancel();
	});
JsFiddle Demo

Saturday, March 30, 2019

Generic Insert/Update/Delete Permission Checking Using Reflection

Summary:

A good number of developers spend their time in working with LOB (business) applications wether Desktop or Web. Most of the business applications revolve around CRUD operations on several entities and each CRUD method usually requires Permission Checking routine. In this post we shall see how we can utilize the Reflection to create a generic Permission Checking method in order to minimize the code writing.

Download: Visual Studio C# Project GenericPermission_Reflection.zip

Level: Expert

Knowledge Required:
  • Reflection
  • Application Architecture
  • Some ORM e.g. Entity Framework
Description

For this post, I have created a sample business application which just keeps track of customer sales orders. To make project simple, I haven’t implemented any Data Access code. Usually in business applications we have 3 layers, UI / Presentation Layer, Data Access Layer and Business Layer. Since this post only focuses on business layer functionality therefore, we’ll not have any UI or Data Access Layer implementation.

In this application I have created 4 entities

As you can notice that other than 4 entity classes, we have RecordState enum and EntityBase class. All the 4 POCO entity classes are inhertied from the EntityBase class.

As shown in above image, the EntityBase class has RecordState property which tells the current state of the object that we are about to manipulate. I am assuming that you are already familiar with different ORMs like Entity Framework, which uses similar approach to check what DB operation (insert/update or delete) needs to be performed on the data. A quick recap of this approach is that, each entity is loaded from database with RecordState = Unchanged, then it is passed to user interface, later user makes changes on the user interface which changes the RecordState = Updated, then this object with RecordState = Updated is sent back to the Business Layer and finally business layer performs DB Update using Data Access Layer. Similarly, RecordState property can be used to create a new record or to delete a record by setting appropriate value in RecordState property.

And we also have defined the RecordState enum

Now assume that we are about to create methods in our business layer to manipulate Item entity.

First method that we defined is Item_Get method. It’s pretty straight forward and just loads 1 record from database and return it to the caller which can be a presentation layer.

Next method we will define is Item_Save method.

As you can see, we haven’t implemented the method much and only defined the basic structure of this method. The Item class that we are using in this method has already been inherited from EntityBase class so it will automatically have the RecordState property.

We are about to implement the permission checking in this method, but for this we have created a separate class for permissions.

It’s a good approach to keep the constants aside. Although, we could define these constants within our business layer, but it’s better to keep them like this in separate class. This will also help us in implementing the generic permission checking method.

To check whether the currently logged-in user has certain permission or not I’ve created a separate method in our business layer as well.

Again, here we are not implementing actual permission checking code because it’s beyond the scope of this article.

Now we are good to go to implement the permission checking in our Item_Save method

As you can see above, we are checking the current RecordState property of Item and then we are validating if the current user has respective permission.

Now this is for 1 entity only i.e. Item entity, imagine if you have 50 entities and you have to write 50 Save methods. It would be easier if there is some generic method which we could use to avoid writing the same repeated code again and again. This is what we are going to achieve using Reflection.

First, we’ll create an Attribute class to create a link between different permissions constants and respective entity.

Next, we’ll add this Attribute class with each permission

We are actually linking the permission with the entity and also, we are telling for which RecordState this permission should be used.

Finally, we can define our generic permission testing method

In above method we are using Reflection to extract all the permissions where our special attribute is set, then we are trying to extract the exact permission which is matching with the given entity’s Type and RecordState, once we found the correct permission constant we pass it in our HasPermission method, if it returns false (does not have permission). Then we through exception as per the RecordState.

After this, we can implement this generic save permission checking method in our Item_Save method

Thursday, January 29, 2015

Export System.Data.DataTable to PDF using AT.PDFReportCreator

I was engaged in a big web-application which has lots of inquiry pages. As we all know, each inquiry page has filtering options and a grid which displays the data. With each inquiry page we need to show export buttons, in PDF and Excel. Exporting data in excel was simple, we just need to create a sheet and put all the data in there. But export of PDF was difficult, client was asking to have a good formatted PDF file, with company logo, total number of pages, heading and with inquiry parameters.

Features:

  • Provide your own Logo and Watermark files, yes AT logo and watermark is NOT hard-coded you can change it :-)
  • Page X of Y in the footer
  • Date and Time of printing in the footer
  • Custome Report Heading
  • Provide Page Layout, for example custom page width, height, margins and orientation
  • Define which columns should be included in PDF from DataTable, in-case if you don't want all columns to be printed
  • Define widths for each column
  • Provide Parameters which will be displayed in the report header

iTextSharp is a very powerful library for creating PDF files in .net Applications. So I decided to create a generic API using iTextSharp library, which can be used to create PDF for every inquiry screen. We just need to pass the Data to the utility and it will create the PDF File. Usually I don't have time, so I did a quick work and created a DLL, which can be used with .net Applications, like ASP.net or Desktop. Also I tried my best to keep the usage as simple as possible.

Below is the Export PDF code written for a ASP.net Web Application using my wrapper library around iTextSharp.

protected void btnCreatePDF_Click(object sender, EventArgs e)
{
    try
    {
        using (System.Data.DataTable dt = this.GetData())
        {
            var reportParam = new AT.PDFReportCreator.PDFReportParam()
            {
                ReportData = dt
            };

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Customers.pdf");
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.ContentType = "application/pdf";

            AT.PDFReportCreator.PDFReportCreator.CreatePDF(HttpContext.Current.Response.OutputStream, reportParam);

            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    }
    catch (Exception ex)
    {
        Trace.Write("Export PDF", ex.Message, ex);
    }
}
Due to time limit, I only came up with DataTable export, while we have other possibilities as well, such as,
  • Export ASP.net GridView Control to PDF
  • Export Entity Framework's List of Entity to PDF
  • Export Desktop Application's DataGridView Control to PDF
For above scenarios we can convert them into DataTable, for example iterate each GridView control row and add the content in DataTable and then pass that DataTable to Export utility.
Downloads:
PDFExportTest.zip Download this file, it contains a Web Application project which shows the export option. Also contains the AT.PDFReportCreator.dll and iTextSharp.dll files. If you want to quickly start testing and don't want to go in complex details, then just download this zip file, extract the DLLs and use in your project.
AT.PDFReportCreator.zip Source code of export API, which is actually a wrapper around iTextSharp