Thursday, June 2, 2016

fullcalendar for your web application

Google does it with no cost. But what if you need to have your own calendar control to manage your appointments in your own web application or one that you work on.

fullcalendar is a good plugin that you can download and implement.

The following simple integration works fine as a starter.

The HTML Part
 <div id="calendar"></div>  
 <div id="createEventModal" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">  
   <div class="modal-header">  
     <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>  
     <h3 id="myModalLabel1">Create Appointment</h3>  
   </div>  
   <div class="modal-body">  
   <form id="createAppointmentForm" class="form-horizontal">  
     <div class="control-group">  
       <label class="control-label" for="inputPatient">Patient:</label>  
       <div class="controls">  
         <input type="text" name="patientName" id="patientName" tyle="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source="[&quot;Value 1&quot;,&quot;Value 2&quot;,&quot;Value 3&quot;]">  
          <input type="hidden" id="apptStartTime"/>  
          <input type="hidden" id="apptEndTime"/>  
          <input type="hidden" id="apptAllDay" />  
       </div>  
     </div>  
     <div class="control-group">  
       <label class="control-label" for="when">When:</label>  
       <div class="controls controls-row" id="when" style="margin-top:5px;">  
       </div>  
     </div>  
   </form>  
   </div>  
   <div class="modal-footer">  
     <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>  
     <button type="submit" class="btn btn-primary" id="submitButton">Save</button>  
   </div>  
 </div>  

The Javascript Part
 $(document).ready(function() {  
    var calendar = $('#calendar').fullCalendar({  
    defaultView: 'agendaWeek',  
    editable: true,  
     selectable: true,  
    //header and other values  
    select: function(start, end, allDay) {  
      endtime = $.fullCalendar.formatDate(end,'h:mm tt');  
      starttime = $.fullCalendar.formatDate(start,'ddd, MMM d, h:mm tt');  
      var mywhen = starttime + ' - ' + endtime;  
      $('#createEventModal #apptStartTime').val(start);  
      $('#createEventModal #apptEndTime').val(end);  
      $('#createEventModal #apptAllDay').val(allDay);  
      $('#createEventModal #when').text(mywhen);  
      $('#createEventModal').modal('show');  
     }  
   });  
  $('#submitButton').on('click', function(e){  
   // We don't want this to act as a link so cancel the link action  
   e.preventDefault();  
   doSubmit();  
  });  
  function doSubmit(){  
   $("#createEventModal").modal('hide');  
   console.log($('#apptStartTime').val());  
   console.log($('#apptEndTime').val());  
   console.log($('#apptAllDay').val());  
   alert("form submitted");  
   $("#calendar").fullCalendar('renderEvent',  
     {  
       title: $('#patientName').val(),  
       start: new Date($('#apptStartTime').val()),  
       end: new Date($('#apptEndTime').val()),  
       allDay: ($('#apptAllDay').val() == "true"),  
     },  
     true);  
   }  
 });  


We will discuss how to merge this control into our own web application in next posts. Until that try this.
http://jsfiddle.net/mccannf/azmjv/16/

Happy Coding...


Tuesday, May 3, 2016

Look for a file inside a directory in C#

We have seen how EnumerateFiles worked in our previous post and the differences between GetFiles too. So we will extend that method to find a file inside a directory with or without its extension. See the below method,
  private static string GetFileNameFromDirectory(string path, string fileName)  
   {  
     DirectoryInfo di = new DirectoryInfo(path);  
     if (di.Exists == false)  
       return string.Empty;  
     IEnumerable<string> dirs = (from file in di.EnumerateFiles(fileName)  
                   orderby file.LastWriteTime descending  
                   select file.Name).Distinct();  
     foreach (string Name in dirs)  
     {  
       if (Path.GetFileNameWithoutExtension(Name).ToLower() == (fileName).ToLower())  
         return Name;  
     }  
     dirs = (from file in di.EnumerateFiles(fileName + ".*")  
         orderby file.LastWriteTime descending  
         select file.Name).Distinct();  
     foreach (string Name in dirs)  
     {  
       if (Path.GetFileNameWithoutExtension(Name).ToLower() == (fileName).ToLower())  
         return Name;  
     }  
     int idx = fileName.LastIndexOf('.');  
     var flName = fileName.Substring(0, idx);  
     dirs = (from file in di.EnumerateFiles(flName + ".*")  
         orderby file.LastWriteTime descending  
         select file.Name).Distinct();  
     foreach (string Name in dirs)  
     {  
       if (Path.GetFileNameWithoutExtension(Name).ToLower() == (flName).ToLower())  
         return Name;  
     }  
     return string.Empty;  
   }  


Suppose you need to find whether the file exists on a particular directory or you need to find a file irrespective of it's extension, you can use this method.

"GetFileNameFromDirectory" expects two parameters.
Path : is the physical path to the folder
FileName : the name of the file you are looking for. Ex:  myImage.jpg or myImage.png or even you can just send myImage (without extension)

If a perfect match found, it will return the name of the file.
If there is no matching file with the extension you sent (myImage.jpg) it will look for a file similar to that name (myImage) without extension and return the matching file. (myImage.png)

Suppose you have more than one file with same name but different extensions, then it sorts the file based on LastWriteTime descending and pick the most recently added file to the directory. (Based on file attributes such as Last Modified Date.

Try this method and see how nice it works.

Happy Coding... :)

Thursday, April 7, 2016

EnumerateFiles in DirectoryInfo vs GetFiles in c#

When a folder need to be read for the content of files, the GetFiles() method is widely used. But it has some negative impacts as well for loading a folder content that has lot of files. To overcome this issue, EnumerateFiles can be used. Look at the following method,

 private static string GetFilePathFromDirectory(string path, string fileName)  
     {  
       DirectoryInfo di = new DirectoryInfo(path);         
       foreach (FileInfo fi in di.EnumerateFiles(fileName))  
       {  
         if (Path.GetFileNameWithoutExtension(fi.Name).ToLower() == (fileName).ToLower())  
           fi.Name;  
       }  
       foreach (FileInfo fi in di.EnumerateFiles(fileName + ".*"))  //if the extension doesn't match, find another with same name
       {  
         if (Path.GetFileNameWithoutExtension(fi.Name).ToLower() == (fileName).ToLower())  
           fi.Name;  
       }        
       return string.Empty;  
     }  

And see why we shouldn't use GetFiles when it comes to large number of files.

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

Read it here on MSDN

Happy coding... :)

Wednesday, April 6, 2016

Converting dd/mm/yyyy formatted string to Datetime in C#

A localized string of Date can based to a DateTime object in C# as below;

 DateTime dtBorn = DateTime.ParseExact(dtBorn, "dd/MM/yyyy", CultureInfo.InvariantCulture)  

It's a french format to C# DateTime object.

Happy Coding...

Tuesday, April 5, 2016

Custom file extension in Visual Studio

Sometimes, we use custom file extensions to make our work easy. For example, we may use .prc for stored procedures and .tbl for table scripts. And many more. But when it opens through visual studio, those files are treated as normal text files.

But what if we need to make them look like some known file format, which for example in the above case, the content of the file should be visible as real sql files.

It is easy,

Go to Tools > Options >  Text Editor > File Extensions and add the extensions that matches with relevant type of editing experiences.


So here is how those files look like now,


It just like it was on SQL Server Management Studio with file format of .sql but it really is a .prc file.




GetFileNameWithoutExtension in C#

No matter the extension, what if you need to find whether there is a file matching to a certain name in that particular directory? Look at the below peace of code,

 private static string GetFilePathFromDirectory(string path, string fileName)  
   {  
     DirectoryInfo di = new DirectoryInfo(path);  
     FileInfo[] smFiles = di.GetFiles();  
     foreach (FileInfo fi in di.GetFiles())  
     {  
       if (Path.GetFileNameWithoutExtension(fi.Name).ToLower() == (fileName).ToLower())  
         return fi.FullName;  
     }  
     return string.Empty;  
   }  

You can pass the folder path, and the file name without extension, if there is a matching file, it will return with the extension.

Copy it and try yourself,

Happy Coding...



Thursday, March 17, 2016

Javascript - Remove URL Parameter with relevant value without redirecting / reloading

If you think you don't need to show the URL parameters all the time but need to keep then by the time the page is loaded, this is the better way.

 var strKey = "strName";  
   var flKeyFound = false;  
   var url = "";  
   var query = window.location.search.substring(1);  
   var vars = query.split('&');  
   for (var i = 0; i < vars.length; i++) {  
     var pair = vars[i].split('=');  
     if (decodeURIComponent(pair[0]) != strKey) {  
       url = url + decodeURIComponent(pair[0]) + "=" + decodeURIComponent(pair[1]) + "&";  
     }  
   }  
   url = window.location.href.split('?')[0] + "?" + url.substring(0, url.length - 1);  
      if (history.pushState) {      
       window.history.pushState({ path: url }, '', url);  
     }  

Paste this peace of JavaScript code will remove the parameter ("strName") and it's value from the query string once the page is loaded.

Make sure you execute this code after the page load is finished.

strName is the key here. Change it to any name as needed.

Read more about History API on JavaScript here.
Happy coding...