July 26, 2017

AngularJS - ng-change is not working for input type file

In this post I will share the code how to detect the change event for HTML file input. We are supporting an old application written with AngularJS, and encountered this problem. If you are using default ng-change attribute, it will not work in AngularJS because of no binding support for file input control. I will show you I solved this problem in my case. I made a custom directive to listen for file input changes which enables us to invoke the custom event handler function. Lets start coding this solution:

Here is the custom directive fileOnChange definition:

 myApp.directive('fileOnChange', function () {
  return {
   restrict: 'A',
   link: function (scope, element, attrs) {
    var onChangeHandler = scope.$eval(attrs.fileOnChange);
    element.bind('change', onChangeHandler);
   }
  };
 });

Here is the HTML for file input showing how to bind this directive to listen for file changes.

 <input type="file" file-on-change="onFileChange"> </input>

Now the final part of this task, write the handler function to do the actual work required on file change. Within the target controller, I write this handler function, in this example it is only showing the selected file name in alert box.

 $scope.onFileChange = function (event) {
  var filename = event.target.files[0].name;
  alert('File name: ' + filename);
 };

July 6, 2017

How to remove all comment tags from XmlDocument

In this post I will share C# code to remove comments from XML string or file. I am using XMl file in this example: I found two possible ways to achieve this.

Lets say we need a function named RemoveCommentsFromXMLFile(string sourceFilePath, string destinationFilePath), which reads xml from source file and then save a copy of same xml content to destination file after removing comments.

  • Remove comments from XML content before loading from a source.

    public static void RemoveCommentsFromConfigFile(string sourceFilePath, string destinationFilePath)
    {
     XmlReaderSettings readerSettings = new XmlReaderSettings();
     readerSettings.IgnoreComments = true; //set this flag in readsettings to read xml without comments.
    
     XmlReader reader = XmlReader.Create(sourceFilePath, readerSettings);
    
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(reader);
     reader.Close();
     xmlDoc.Save(destinationFilePath);
    }
    
  • Remove comments from XML content after loading from a source.

    public static void RemoveCommentsFromConfigFile(string sourceFilePath, string destinationFilePath)
    {
     System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
     xmlDoc.Load(sourceFilePath);
    
     System.Xml.XmlNodeList list = xmlDoc.SelectNodes("//comment()");
    
     foreach (System.Xml.XmlNode node in list)
     {
      node.ParentNode.RemoveChild(node);
     }
    
     xmlDoc.Save(destinationFilePath);
    }
    

June 12, 2017

Open New Window (or Response.Redirect) from Server Side (Code Behind) in ASP.Net using C#

Here Is the question I received from one of my colleagues, how to open new page from server side in a new window. There could be two possible ways to get it work.

  • First option is to add javascript code to the button's OnClientClick handler. But this handler should be attached before the control is rendered, let's say in button's OnPreRender event.

    protected void MyButton_OnPreRender(object sender, EventArgs e)
    {
        string newPageUrl = "NewPage.aspx";
        MyButton.OnClientClick = "window.open('" + newPageUrl + "'); return false;";
    }
    

    This technique would not let the request post back to the server, so it could save this round-trip.

  • Second option could be use of Response.Write() method on regular button click event.

       Response.Write("<script>window.open('http://www.google.com.hk/','_blank');</script>"); 
    

    This would send a post back to the server, but the advantage to this method could be that it will allow you write code on button click you may want to execute before opening a new window.

June 5, 2017

C# - Delete files older than N number of Days/Months in a directory

In this post, I will share C# code to delete files from specific directory, with the condition that only files which are older than N number of Days or Month or any other time unit. Why I come to this code because recently we faced this problem because of not deleting the older files.

I was working on a small utility program to automate repeated tasks, one of which is to take daily backups for my project's database. This was done before, but after some time we faced this problem because we were running out of space, it happens for the reason that we have lot of backup files generated and no one is going to delete older files which are of no-use. The best solution come to my mind is to modify the program code to delete older files by it-self.

Here is the C# code for this task.

string[] files = Directory.GetFiles(directoryPath);

foreach (string file in files)
{
   FileInfo fi = new FileInfo(file);
   
   if (fi.LastAccessTime < DateTime.Now.AddMonths(-1))
   {
       fi.Delete();   
   }
}

Obviously you can change DateTime.Now.AddMonths method to AddDays, AddHours or other units according to your requirements.

May 25, 2017

How to generate script for multiple objects using SQL Server Management Studio

In this post, I will explain how to script multiple objects using SQL Server Management Studio. You may be aware of generating script by right clicking on specific object (Table / Stored Procedure / Function / View etc), or also you may generate scripts by right clicking on the database node, select Tasks, and then click on Generate Scripts... option. In this second option you can generate script for all objects or for some selected objects with advanced scripting options.

But in this post I will explain a short trick to generate script for multiple objects without going through the Generate Scripts... wizard. Obviously it will not provide other advanced options that we can have while using the Generate Script wizard, but it will let you create script for Create / Drop scenarios.

Following are the steps required to generate script for multiple objects, here I am considering generate Create script for selected tables.

  • Within SQL Server Management Studio, select your database.
  • Since I am going to generate script for tables, so I selected the Tables node, you may want to select Stored Procedures, Functions or Views etc.
  • On the right hand side you may see Object Explorer Details view, if not, you can make it visible from menu View > Object Explorer Details, or simply you can hit F7 shortcut key.
  • In details view, select the required objects.
  • Right click on the selected objects > Script Table as > Create To > New Query Editor Window (or other option)