Tuesday, September 20, 2016

Using Google MAPs to show your store locations - Part 1

If you have a commerce website that needs to show the store locations, Google Maps is the best tool to use and its free too.
You may need to follow few steps first to get a key to use for your code.

Click Here to get the key.

Create a project and get a key. Keep it saved because it's what you are going to use.



You can always use the documentation here.

Basically you can show  a static location as below;

 <!DOCTYPE html>  
 <html>  
  <head>  
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
   <meta charset="utf-8">  
   <title>Simple markers</title>  
   <style>  
    html, body {  
     height: 100%;  
     margin: 0;  
     padding: 0;  
    }  
    #map {  
     height: 100%;  
    }  
   </style>  
  </head>  
  <body>  
   <div id="map"></div>  
   <script>  
    function initMap() {  
     var myLatLng = {lat: -25.363, lng: 131.044};  
     var map = new google.maps.Map(document.getElementById('map'), {  
      zoom: 4,  
      center: myLatLng  
     });  
     var marker = new google.maps.Marker({  
      position: myLatLng,  
      map: map,  
      title: 'Hello World!'  
     });  
    }  
   </script>  
   <script async defer  
   src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">  
   </script>  
  </body>  
 </html>  

This is a sample you can follow as per Google Map Documentation. But What if we need more. Different locations, and more dynamics.

It will be our next post. So, wait for it. :)

Happy Coding...!






Friday, August 12, 2016

Classic ASP - Create Folder Structure

It is common that we have almost forgotten classic asp but what if you got some modification to do. Here is how we can create a folder structure if not exists...
   Set FS = Server.CreateObject("Scripting.FileSystemObject")       
   'Create folder if not exists  
   dim pathCounter  
   dim arrUploadPath
   dim newPath  
   newPath = ""  
   pathCounter=0  
   arrUploadPath = Split(uploadPath,"\")  
   For Each item in arrUploadPath  
     If Trim(item) <> "" Then  
       newPath = newPath + item + "\"  
       If pathCounter <> 0 Then          
         If Not FS.FolderExists(newPath) Then              
          FS.CreateFolder(newPath)            
         End If  
       End If  
       pathCounter = pathCounter + 1    
     End If         
   Next   



Monday, July 25, 2016

summernote editor for email editor

I found this amazing editor at http://summernote.org that accepts copy paste of images. I was looking for such editor to avoid re-inventing the wheel so that it can be used for an email application. This fits well and it is easy to use too. First, you may download the summernote editor here.

Lets implement summernote editor first.

1. link the js and css file.

 <link href="/script/summernote/summernote.css" rel="stylesheet" type="text/css" />  
 <script src="/script/summernote/summernote.js" type="text/javascript"></script>  

2. Add the editor textarea tag.
 <textarea id="txtSNBody" name="txtDescriptionIE9" runat="server" rows="15" cols="80" clientidmode="Static" style="width: 100%"></textarea>  

3. Convert it to Summernote Editor
 var f = jQuery.noConflict(); // To avoid JQuery conflict  
        f(document).ready(function () {  
             f('#txtSNBody').summernote({  
                  height: 300,         // set editor height  
                  minHeight: null,       // set minimum height of editor  
                  maxHeight: null,  
                  width: 150, // set width  
                  toolbar: [  
               // [groupName, [list of button]]  
               ['Insert', ['picture', 'link', 'video', 'table', 'hr', 'style', 'ol', 'ul', 'paragraph', 'height', 'fullscreen', 'codeview', 'undo', 'redo', 'help']],  
               ['style', ['fontname', 'fontsize', 'color', 'bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear']]                
                  ],  
                  defaultFontName: 'Arial',  
                  callbacks: {  
                       onKeyup: function (e) {  
                            DrafttxtSNBody(f('#txtSNBody').summernote('code')); // This function saves the email as a draft asynchronously using jquery ajax  
                       }  
                  }  
             });  
             f('.note-toolbar').css('font-size', '11px'); // Set toolbar font size  
        });  

4. Now the editor will looks like this;
(The content is blurred using a photo editor)

5. Now you can use this as a standard email editor page that support HTML for the body. Even this editor support copy paste of images. But it uses Base64 encoding that is not understood by most browsers and email clients as valid inline images. So you will notice the red cross marks that says no valid images attached to the body.





6. To avoid this, We can write an email handler class. We discussed one here and lets modify it to cater the Base64 Encoded images. The following is a public class that you can use to send emails.

 public class EmailHelper  
   {  
     private MailMessage Message = null;  
     private SmtpClient smtpClient = null;  
     public MailAddress FromAddress { get; set; }  
     public string Subject { get; set; }  
     public string Body { get; set; }  
     public bool has64BaseImages { get; set; }  
     public EmailHelper()  
     {  
       smtpClient = new SmtpClient();  
       smtpClient.Host = ConfigurationManager.AppSettings["smtpHost"];  
       smtpClient.UseDefaultCredentials = false;  
       //smtpClient.EnableSsl = true;  // Enable this if SSL is needed 
       smtpClient.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["userName"], ConfigurationManager.AppSettings["password"]);  
       smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);  
       Message = new MailMessage();  
     }  
     public EmailHelper(string host, int port, string userName, string password, bool ssl)  
       : this()  
     {  
       smtpClient.Host = host;  
       smtpClient.Port = port;  
       smtpClient.EnableSsl = ssl;  
       smtpClient.Credentials = new NetworkCredential(userName, password);  
     }  
     public void AddToAddress(string email, string name = null)  
     {  
       if (!string.IsNullOrEmpty(email))  
       {  
         email = email.Replace(",", ";");  
         string[] emailList = email.Split(';');  
         for (int i = 0; i < emailList.Length; i++)  
         {  
           if (!string.IsNullOrEmpty(emailList[i]))  
             Message.To.Add(new MailAddress(emailList[i].Trim(), name));  
         }  
       }  
     }  
     public void AddCcAddress(string email, string name = null)  
     {  
       if (!string.IsNullOrEmpty(email))  
       {  
         email = email.Replace(",", ";");  
         string[] emailList = email.Split(';');  
         for (int i = 0; i < emailList.Length; i++)  
         {  
           if (!string.IsNullOrEmpty(emailList[i]))  
             Message.CC.Add(new MailAddress(emailList[i].Trim(), name));  
         }  
       }  
     }  
     public void AddBccAddress(string email, string name = null)  
     {  
       if (!string.IsNullOrEmpty(email))  
       {  
         email = email.Replace(",", ";");  
         string[] emailList = email.Split(';');  
         for (int i = 0; i < emailList.Length; i++)  
         {  
           if (!string.IsNullOrEmpty(emailList[i]))  
             Message.Bcc.Add(new MailAddress(emailList[i].Trim(), name));  
         }  
       }  
     }  
     public void AddAttachment(string file, string mimeType)  
     {  
       Attachment attachment = new Attachment(file, mimeType);  
       Message.Attachments.Add(attachment);  
     }  
     public void AddAttachment(Attachment objAttachment)  
     {  
       Message.Attachments.Add(objAttachment);  
     }  
     public void SendMail()  
     {  
       try  
       {  
         string imgTempFolder = new Random().Next().ToString();  
         string imgSavePath = HttpContext.Current.Server.MapPath(@"~\App_Code\GBL\EmailHelper\" + imgTempFolder + @"\"); // You can have your own path  
         string msg = "<html><body>" + Body + "</html></body>";  
         foreach (Match m in Regex.Matches(msg, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))  
         {  
           string src = m.Groups[1].Value;  
           if (src.StartsWith("data:image/png;base64"))  
           {  
             has64BaseImages = true;  
             break;  
           }  
         }  
         if (has64BaseImages)  // If Base64 found let them attach as LinkedResources 
         {  
           if (!Directory.Exists(imgSavePath))  
             Directory.CreateDirectory(imgSavePath);  
           Dictionary<int, string> dicImgs = new Dictionary<int, string>();  
           Dictionary<int, LinkedResource> dicImgLR = new Dictionary<int, LinkedResource>();  
           int c = 1;  
           foreach (Match m in Regex.Matches(msg, "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase | RegexOptions.Multiline))  
           {  
             string src = m.Groups[1].Value;  
             if (!src.StartsWith("data:image/png;base64"))  
               continue;  
             int i = new Random().Next();  
             byte[] bytes = Convert.FromBase64String(src.Split(',')[1]);  
             Image image;  
             using (MemoryStream ms = new MemoryStream(bytes))  
             {  
               image = Image.FromStream(ms);  
             }  
             image.Save(imgSavePath + i.ToString() + ".png");  
             dicImgs.Add(c, imgSavePath + i.ToString() + ".png");  
             string mediaType = MediaTypeNames.Image.Jpeg;  
             LinkedResource ilImg = new LinkedResource(imgSavePath + i.ToString() + ".png");  
             ilImg.ContentId = c.ToString();  
             ilImg.ContentType.MediaType = mediaType;  
             ilImg.TransferEncoding = TransferEncoding.Base64;  
             ilImg.ContentType.Name = ilImg.ContentId;  
             ilImg.ContentLink = new Uri("cid:" + ilImg.ContentId);  
             dicImgLR.Add(c, ilImg);  
             src = src.Replace(src, "cid:" + c);  
             c++;  
           }  
           AlternateView htmlView = AlternateView.CreateAlternateViewFromString(msg, Encoding.UTF8, MediaTypeNames.Text.Html);  
           foreach (var item in dicImgLR)  
           {  
             htmlView.LinkedResources.Add(item.Value);  
           }  
           Message.AlternateViews.Add(htmlView);  
         }  
         if (FromAddress == null || (FromAddress != null && FromAddress.Address.Equals("")))  
         {  
           throw new Exception("From address not defined");  
         }  
         else  
         {  
           if (string.IsNullOrEmpty(FromAddress.DisplayName))  
             FromAddress = new MailAddress(FromAddress.Address, string.Empty);  
           Message.From = FromAddress;  
         }  
         if (Message.To.Count <= 0)  
         { throw new Exception("To address not defined"); }  
         Message.Subject = Subject;  
         Message.IsBodyHtml = true;  
         if (!has64BaseImages)  
           Message.Body = Body;  
         Message.BodyEncoding = Encoding.UTF8;  
         Message.SubjectEncoding = Encoding.UTF8;  
         smtpClient.Send(Message);  
       }  
       catch (Exception)  
       {  
         throw new Exception("Email failed to send");  
       }  
     }  
     public static string GetFileMimeType(string fileName)  
     {  
       string fileExt = Path.GetExtension(fileName.ToLower());  
       string mimeType = string.Empty;  
       switch (fileExt)  
       {  
         case ".htm":  
         case ".html":  
           mimeType = "text/html";  
           break;  
         case ".xml":  
           mimeType = "text/xml";  
           break;  
         case ".jpg":  
         case ".jpeg":  
           mimeType = "image/jpeg";  
           break;  
         case ".gif":  
           mimeType = "image/gif";  
           break;  
         case ".png":  
           mimeType = "image/png";  
           break;  
         case ".bmp":  
           mimeType = "image/bmp";  
           break;  
         case ".pdf":  
           mimeType = "application/pdf";  
           break;  
         case ".doc":  
           mimeType = "application/msword";  
           break;  
         case ".docx":  
           mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";  
           break;  
         case ".xls":  
           mimeType = "application/x-msexcel";  
           break;  
         case ".xlsx":  
           mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";  
           break;  
         case ".csv":  
           mimeType = "application/csv";  
           break;  
         case ".ppt":  
           mimeType = "application/vnd.ms-powerpoint";  
           break;  
         case ".pptx":  
           mimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";  
           break;  
         case ".rar":  
           mimeType = "application/x-rar-compressed";  
           break;  
         case ".zip":  
           mimeType = "application/x-zip-compressed";  
           break;  
         default:  
           mimeType = "text/plain";  
           break;  
       }  
       return mimeType;  
     }  
   }  

7. Call this class as below to send email.
 EmailHelper emailHelper = new EmailHelper();  
 emailHelper.FromAddress = new System.Net.Mail.MailAddress("From@domain.com");  
 emailHelper.AddToAddress("To@domain.com");  
 emailHelper.AddCcAddress("Cc@domain.com");  
 emailHelper.AddCcAddress("Bcc@domain.com");  
 emailHelper.AddBccAddress(txtEmailBcc.Text.Trim());  
 emailHelper.AddAttachment("FilePath", EmailHelper.GetFileMimeType(item.Value.Value));  
 emailHelper.Subject = "Subject";  
 msgBody = txtEmailBody.InnerText.Trim();  // The summernote editor
 emailHelper.Body = msgBody;  
 emailHelper.SendMail();  

8. There is no 8th step. This is it. Try it in your application and copy paste the images to body as you wish and send as inline attachments.

Happy coding... And if any issue, just comment.












Thursday, June 2, 2016

JQuery Animation - Rotate your html control

Until the next fullcalendar article comes, here is a nice thing that you can try. Rotating html element is easy with jquery. Of course we use this for the fullcalendar. But lets see how it goes below.

 $(this).animate({ borderSpacing: 360 }, {  
         step: function (now, fx) {  
           $(this).css('-webkit-transform', 'rotate(' + now + 'deg)');  
           $(this).css('-moz-transform', 'rotate(' + now + 'deg)');  
           $(this).css('transform', 'rotate(' + now + 'deg)');  
         },  
         duration: 'slow'  
       }, 'linear');  

try it and lets see how we apply it for the fullcalendar in coming articles.

Happy coding...


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... :)