Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Wednesday, 15 August 2018

VB.NET Extending the MailMessage to have the ability to save the mail message

Problem:

The System.Net.Mail.MailMessage is badly missing the option of saving the Message as a file. Though there is a workaournd by using the SpecifiedPickupDirectory option of the SmtpClient to write the mail message ot the specific folder. This option however doesn't have flexibility in naming the files. In a multi-threaded parallel execution environment, it is difficult to identify and rename the specific files post writing to disk. There ought to be a better solution to handle this problem.

Solution:

You can extend the MailMessage class and add a Save method yourself. The Send method of the SmtpClient creates and uses MailWriter object to write out the mail message and it uses fileMailWriter when the SpecificPickupDirectory is specified as the DeliveryMethod. Create your own MailWriter object using FileStream and invoke the internal Send method, passing your MailWriter object. Check out this Code Project Article for more details. The code samples given there are for the C# language. Just in case you need, given below the same code for the Extension in VB.NET.


Imports System
Imports System.Net.Mail
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.IO
Imports System.Reflection
Imports System.Runtime.CompilerServices

Module MailMessageExtension
    <Extension()>
    Public Sub Save(ByVal msg As MailMessage, FileName As String)

        Dim asm As Assembly = New SmtpClient().GetType().Assembly
        Dim _mailWriterType As Type = asm.GetType("System.Net.Mail.MailWriter")


        Using _fileStream As FileStream = New FileStream(FileName, FileMode.Create)


            ' Get reflection info for MailWriter contructor
            Dim _mailWriterContructor As ConstructorInfo = _mailWriterType.GetConstructor(BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, New Type() {GetType(Stream)}, Nothing)

            ' Construct MailWriter object with our FileStream
            Dim _mailWriter As Object = _mailWriterContructor.Invoke(New Object() {_fileStream})

            ' Get reflection info for Send() method on MailMessage
            Dim _sendMethod As MethodInfo = New MailMessage().GetType().GetMethod("Send", BindingFlags.Instance Or BindingFlags.NonPublic)


            ' Call method passing in MailWriter

            _sendMethod.Invoke(msg, BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, New Object() {_mailWriter, True, True}, Nothing)

            ' Finally get reflection info for Close() method on our MailWriter
            Dim _closeMethod As MethodInfo = _mailWriter.GetType().GetMethod("Close", BindingFlags.Instance Or BindingFlags.NonPublic)

            ' Call close method
            _closeMethod.Invoke(_mailWriter, BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, New Object() {}, Nothing)
        End Using

    End Sub
End Module


You may observe that you need to create extensions as a module.

Sunday, 12 March 2017

MS Excel - Copy Sum of Selected Cells

Problem:


Mirosoft Excel is a wonderful office product and is an essential tool in our work life for most of us. But still many would have not discovered its capabilities to the fullest. Here is a problem that I wanted to solve. Typically, techies don't like to do same thing repeatedly and would look for a possible shortcut for that. I have been working through multiple excel sheets, where in have to find totals for a group of cells, without any specific parameters to determine the qualifying cells. If there is a shortcut to accomplish this it would be of help to many.


Solution:


Given that there are no parameters that determine the qualifying cells, it is difficult to come up with a an algorithm to automate the selection and totalling. But it would be possible to leave the selection to the users and then facilitate the summing part. We can leverage the clipboard to achieve this. Let the users select the desired cells and then invoke the macro using the assigned short cut key combination and the total is copied into the clipboard and available for pasting any where.

Here is the macro that does the work:

Sub mySum()   
 Dim MyDataObj As New DataObject   MyDataObj.SetText Application.Sum(Selection)   MyDataObj.PutInClipboard 
End Sub

I am sure every one knows how to create a macro and assign a short cut key for it. You may find a lot of resources on creating a macro in excel.

Saturday, 10 September 2016

ASP.NET - Setting HTML Meta tags in content pages

Problem:


Though the @Page directive in a content page allows one to specify the Description and Keywords attrubutes, the same is ignored when the page is rendered. Instead the Description and Keywords as specified in the master page is what gets rendered as part of the final html output. Is this the intended design and is there a solution to work around this issue?


Solution:


By design, the HTML Meta tags specified in the content page is ignored when the page is rendered. In this context it is important to understand the following:

  • The Master page contains the <head> tag of the page and not the content page. As such the meta tags specified in the master page will prevail.
  • The Content page derives the System.Web.UI.Page class, which though recognizes the Title attribute provided as part of the @Page directive, it does not recognize the other meta tags like description and keywords.
  • The master page and content page are dendered in teh following order:
    • Content Page PreInit event
    • Master Page Init event
    • Content Page Init event
    • Content Page Load event
    • Master Page Load event

As you may observe, while the Load event of Master page happens after that of the Content Page, the Init event of the Master page happens ahead that of the content page.  Given that the Master page loads after the content page, you can manage to use the Title attribute specified in the content page using the script tag within the <title> element, as below:

<title><%: Page.Title %></title>


You cannot however handle the Meta tags in the same way. One solution to handle the Meta tags specified in the Content page is to use a custom Page class, which extends the System.Web.UI.Page class, wherein add support to handling the Description and Keywords as input in the @Page directive. This can be accomplished by adding appropriately overriding the OnLoadComplete event of the Page class, wherein the needed Meta tags are constructed using the values specified in the @Page directive and the same are added to the Page Header.

Check out this codepage link for a sample solution.

Saturday, 9 July 2016

SSRS - Custom Period Filters

Problem:

Just wondering if the reports published on SQL Server Reporting Services can be customized to have a predefined period filters like Last Week, Last Month, Last Quarter, etc.

By: Anonymous

Solution:

You have few options to work around this, which are given below:

1. Dynamic Parameter

Basically, your underlying query or stored procedure needs the values for the From and To paramteres to apply in the where clause of the query. You can do this by first creating a mutli valued Period parameter, with values like, Last Week, Last Month, etc specified as available values. The From and To parameters can then be set up in such a way that it fetches the default value from a query, which takes the value from the Period parameter and then return the corresponding From and To values respectively. In these, the Period Parameter shall be positioned above the From and To parameters. The query can be as simple as

SELECT 
CASE 
WHEN @Period = 'LW' THEN DATEADD(D,((DATEPART(dw, GETDATE())-1)*-1)-7,GETDATE())
WHEN @PEriod = 'LM' THEN DATEADD(M,-1,DATEADD(D,(DAY(GETDATE())-1)*-1, GETDATE()))
END AS FROM_DATE

for the default values of the From parameter. You may extend this idea and use it different ways to make a parameter dynamically derive a value based on a previous parameter. Note that the order of the parameter is important as the parameters are constructed sequentially and there is nothing like an onChange event that you can think of.

2. Let the SQL Query / Procedure do the work

The second alternative is to put in a logic similar to the above within the Report Query or Stored Procedure, so that the user just selects the period filter and the SQL Server interprets it appropriately and returns the appropriate results. The only difference with this option is that the From and To Filters need not be designed in the report and the user won't see it on screen.

3. Wrap the report within an Application

Just in case, you are rendering the reports within an Application, like a ASP.NET application or a Windows Forms Application, then you can have the complete control on the Filters in the presentation layer of your application. For instance in this case, you accept a Period Filter from the user in your front end application and then transform it to an appropriate From and To dates to the ReportViewer component and get the report rendered accordingly.





Sunday, 3 July 2016

Issues in Signing a .NET Assembly using .pfx file

Problem:

I have procured a code signing certificate with a view to ensure that one of application that we intend to distribute to external users is signed so that the same can be trusted by the end users. I imported the certificate into the certificate store and used it successfully to sign the Click Once Manifest using the Signing tab in the Projec Properties dialog in Visual Studio 2013. But I could not have the assembly signed. I exported the certificate from the store as a .pfx file and tried using it for signing the assembly, but am getting issues like "Private Key not Found", while the Private key is very much present in the .pfx file.

By: Rajkumar David

Solution:

Visual Studio 2013 has known issues in handling PKCS# 12 certificate files as it cannot handle files with multilpe certificates in the CA certificate chain. Visual studio may not still consider such certificates for signing the assembly because of the KeySpec Parameter, which is usually set as AT_KEYEXCHANGE(1), whereas Visual Studio expects this to be AT_SIGNATURE(2). It is possible that while requesting the certificate, the KeySpec is set as 1 and as such the certificate is generated with the value as 1. You may verify CSR that you have submitted to the CA to check this.

OK, now what do you with that certificate? You have option to import such certificates with KeySpec set as AT_SIGNATUR. The Windows Servers from 2003 onwards have a commandline certificate import utility - certutil.exe. This command allows you to import the certificate with the right KeySpec parameter. Use the following command to do this:

certutil -importPFX -user <pfxfilename> AT_SIGNATURE

After importing the certificate using the above command into the certificate store and then export it back as .pfx file from the store for assembly signing within Visual Studio. This should resolve the given problem.

More on the CertUtil command can be found here.

Sunday, 26 January 2014

Continuous Integration in Agile Software Development

Question:

I am a fresher and have recently joined an IT firm as a .NET developer. After 15 days of orientation and training I am not part of a project team. I have been hearing a lot about Continuous Integration. Can you help me understand what it is and how does it help the project execution?

By: Rajesh Narayanan

Answer:

One of the important reason behind the software project failure was that the defects or issues discovered in the later phases proving to be too expensive to address and thus adding to the time and cost of the project. The industry has come up with different methodologies to address such issues and thus Agile Methodology has gained much adoption and recognition. As you may be aware, one of the key principles of Agile is to put in processes and techniques, so that the defects or issues are detected early on and thus giving opportunity to address sooner. Practices like SCRUM, Pair Programming, Test Driven Development are all expected to address this issue of catching the defects early on. On the same lines Continuous Integration and Deployment also contributes towards offering an opportunity to discover issues early on by offering the customer a working software product every now and then.

Traditionally, developers work on building components or modules independently and there will be a phase which will be fairly closer to UAT for integrating these modules together. No wonder, the development teams will discover many inconsistencies leading to the modules not working in tandem as intended. This calls for rework on one or more of the already built modules.

Continuous Integration addresses this problem by ensuring that every time the developer checks-in the code changes, the code modules are integrated with other related modules and deployed as well. This activity is best achieved by automating the build and deployment process. That means, the developer as he checks in code changes, will see the build and deployment errors and or warnings, which are expected to be resolved then and there, so that every code change that is checkedin does not break the working product. Thus the end customer will be able to see a working product always and able to validate the change as it is implemented.

The following are some of the key practices that makes the Continuous Integration workable and useful as well:


  • Maintain a Single Code Repository - Continuous Integration won't work if developers maintain isolated code repositories for different component or modules. There are plenty of open source and commercial source code control tools that offers robust conflict resolution techniques and facilitates usage of single code repository.
  • Build Automation - The Continuous build and deployment activity is best accomplished by automating the same. Most of the programming languages support this requirement and tools like CruiseControl are also very useful to accomplish this.
  • Test Automation - The automation process shall also execute the basic tests by itself. this where Test Drivent Development is in use. The developers, as they write code are also expected to create test scripts, so that these will also be executed during the automated build process.
  • Frequent Code Commits - The developers should commit the code more frequently and at the least every day. They should commit the code after every logical completion of a code change, so that the build does not break. This where, the Agile principles revolves around braking the coding tasks into smaller units, so that such tasks typically take 8 or 16 hours to complete.
  • Automated Deployment - Coupled with build automation, the code should also be deployed on to the test environment, so those involved in testing see the latest changes as soon as they are committed into the repository.


Hope the above explains the purpose and the principles of Continuous Integration. You can look up Martin Fowler's article on the subject to know more.

Wednesday, 25 December 2013

TWAIN vs WIA

Question:

I have taken up an academic project to work with the imaging devices, like video and still image capture. I have read about TWAIN and WIA as the popular toolkits or APIs available for the purpose. I need help in deciding as to which API is good to go with and guidance on any other tools or SDKs would also be of help.

By: Matt Charles

Answer:

You are right that TWAIN and WIA are the widely used APIs for applications around image acquisition. The choice of the toolkit can be made by looking at the following criteria:


  • OS Support: Microsoft's Windows Image Acquisition apparently works only on Windows platform. But TWAIN works on Windows, Linux and Mac. If your project requires cross platform solutions, then look at TWAIN or else WIA is preferred for its other advantages. While TWAIN is an offering of TWAIN Working Group having leading device vendors as its members, WIA is Microsoft's offering which builds on top of low-level hardware abstraction STI and is available with Windows Me or later.
  • Programming Support: Working with TWAIN API require C/C++ skills. There are commercial high level libraries which expose various programming language specific APIs for ease of use. WIA, though primarily designed for C/C++ development, it offers ease of use with .NET programming languages as well.
  • Device Support: Most of the windows compatible imaging devices including digital cameras, webcams, video cameras and scanners are WIA compatible. But not all devices come with TWAIN support. The list of devices supported by the TWAIN specification 2.3.0 can be found here


TWAIN though originally developed in 1992, it is a sophisticated API and its portability across various platforms. TWAIN also offers a 'native' (Device Independent Bitmap) transfer mode in addition to the modes 'memory' and 'file' offered by WIA. WIA provides a TWAIN compatibility layer that allows TWAIN-aware applications to communicate with WIA devices, though such applications will not have full access to WIA functionality.

Here are some cool references or code samples for image acquisition using WIA

ADF Scanner Library
OpenNETCF WIA Library

Some of the commercial APIs that make building TWAIN aware applications a lot easier are:

EZTwain Pro 4.0
csXImage - ActiveX Image edit and Twain control

You may also want to explore JS-Feat a javascript library.

Assuming that your project is of academic nature and that you would be looking at a windows specific solution, I would recommend you to explore WIA.

Saturday, 15 June 2013

Image Drag, Drop and Zoom using HTML5 Canvas

Question:

How can I perform drag and drop of images and the zoom in and out of images using HTML5 Canvas element?

By Iyappan Ranganathan

Response:

There are many free Javascript libraries out there to accomplish many drag and drop and other image manipulation features. The one that I have used and satisfied with is KineticJS library. KineticJS exposes events and methods to manage multiple layers, shapes, images, grouping which in combination would help achieve your needs. Specifically the dragstart and dragend events will be the ones you would be interested to implement the drag and drop feature. For zoom in and out you should be using the setScale method.

Check out these links demonstrating the needed features:

HTML5 Canvas KineticJS Scale Animation Tutorial
HTML5 Canvas Drag and Drop an Image

As I said, there are many Javascript libraries and you may pick the one that best suits your needs.

Sunday, 14 April 2013

How to Integrate a POS device in a .NET Windows Forms Application

Question:

One of our recent project requires integrating our Windows Forms application with point of sale devices like barcode scanner, check reader etc. I could find out that there is a POS.NET library that can be used for the purpose, but it seems to have been built for .NET 1.12 and no updates after that. Can you suggest me if there is any other .NET libraries that can be used for the purpose. You may also help me by sharing your thoughts and ideas.

Question by Selvamurugan N.

Answer:

Answering your first part of the question - Why there are n't any updates to this library? - I can only guess the answer for this and that I feel is due to the fact the device manufacturers lag behind in updating the communication protocols, which is more so because typically these devices are built for a low cost specific purpose operating environments. For instance, the POS terminals don't have to be on a Windows 7, it would just be enough for them to be on Windows XP or even older operating system. That probably is the reason, why the Library continues to be based on COM components and does not need an update.

On using the POS.NET library, yes, you can still use it in the later frameworks of .NET, but be aware of some of the constraints or issues as described in this blog post. The blog author calls out issues with 64 bit environment and also with .NET Framework 4.0. Don't miss out the comments, as there are some valid opinions and observations in the form of comments. You may also want to check out the Microsoft's publication on using the POS.NET titled as Creating a Proof of Concept POS Application.

If that does not suit you, then go ahead and learn to access and work with USB devices using HID (Human Interface Device), but you need to know the communication protocols and the data structures as specified by the device manufacturer. This will for sure will give you a better control over your integration, but you would be re-inventing the wheel. Here is a nice introduction to working with USB devices in .NET.

My recommendation is that check out if the device vendor provides you a .NET or a COM Library and if yes, using that will be the best option as some device manufacturers may have built certain proprietary protocols, which would work best with their own drivers. If that is not the case, then evaluate POS.NET whether it fits your use cases. Most of the times it should be fine, unless you meet up with some of the constraints when using with later versions of .NET Framework. If left with no choice, use HID interface to have your requirements met. You may also want to check out this msdn article on using Alternate Input Devices.