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);
    }