Sunday, June 5, 2016

Azure Search #1

 

I will be writing a series of post on azure search step by step. Each post I will be explaining different areas in azure search.

As this is the first post I will be explaining what azure search is and what are the applications of azure search.

What is Azure Search ?

A search-as-a-service solution allowing developers to incorporate great search experiences into applications without managing infrastructure or needing to become search experts.

If I elaborate the definition bit more,Azure search provides lot of services, which allows developer to add high search experience to their end users, without been a search expert. In other words developer has to call some API calls to azure search all the search algorithms will be executed by azure search service and result will be returned. this makes developer life easier and giving end user a high search experience.

Why we need search?

Search box in an application has been the main entry point of most of the applications. If we unable to provide good search results it tends users to leave our application.

Ex:- If users makes a typo on searching an item in a shopping cart and if no results came, user might think this cart doesn't have the tem he searched for, user might leave and go and try on another shopping cart. To avoid such situations we need to have a search service which detects users type and send the search results with best match.

What are the Search Options?

Before we jump in to azure search first we will see what are the search capabilities we need to provide for our end users. Following are some examples of an shopping cart.

1. Type Ahead

When user comes and type in the search box, we should be provide them some type heads with suggestions so user can click on them and complete search without typing the whole search text.

image

2. Facets

Facets are filters given to users to filter out the search results based on different criteria's.

image

3. Hit Highlighting

On the search results the search text which user has entered should be highlighted in search item title or description so user can see the relevance of the search items.

image

4. Spelling Mistakes

As you can see when searching “mountain” user has made a typo and entered “Mountan” still the user is getting search results which best match

image

5. Geo-Spatial Search

In case user wants to search items near his location, then geo- spatial search is needed to be added to the application

image

6. Paging

image

7. Sorting & Scoring

User should be able to sort the results on different options. Also Best Match sorting should be also available.

Ex:- if the search text is found in product title should come top of the results than the products which contains the search text in the product description. For that search results should contain a score best on the relevance to the search text.

image

Azure Search service provides services to add these capabilities in your search using minimum code and time.

When We should Use it?

Basically Microsoft pointed 3 main areas where this search service could add real value. It does not mean this can be used only in these areas, it could be used in many areas other than this.

1. E-Commerce Application.

2. User Generated Content Applications Ex:- Recipe sites

3. Business Application

Hope you had a basic understanding of what azure search provides as a service and why and when we should use it. In my next article I will be discussing concepts behind azure search then how to enable your data to be searched by azure search.

 

Hope this helps

Thursday, April 7, 2016

Saving Base64 String as image to Azure Blob Storage

 

Recently I started working on a API which supports mobile backend. I got the following requirement

1. When user uploads a image to their profile API will get the base64 string of the image

2. When viewing the User profile to increase the performance of service calls have to send an image URL rather base64 string

 

Solution : Save the base 64 string in the azure storage & save it in DB

  
  public class AzureBlogService
    {
        private static string _connectionString = "DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****";
        public static string UploadImage(string imageData, ImageType imageType, int cardId)
        {
            string filename = GetFileName(imageType, cardId);
            CloudBlobContainer container = GetContainer("userimages");
            byte[] imageBytes = Convert.FromBase64String(imageData);
            CloudBlockBlob blob = container.GetBlockBlobReference(filename);
            blob.Properties.ContentType = "Jpeg";
            blob.UploadFromByteArray(imageBytes, 0, imageBytes.Length);
            return blob.StorageUri.PrimaryUri.AbsoluteUri;
        }

        private static CloudStorageAccount GetConnection()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);
            return storageAccount;
        }

        private static string GetFileName(ImageType imageType, int cardId)
        {
            switch (imageType)
            {
                case ImageType.Cover:
                    return string.Format("Cover-{0}.jpeg", cardId);
                case ImageType.Profile:
                    return string.Format("Profile-{0}.jpeg", cardId);
                default:
                    return null;
            }


        }
        private static CloudBlobContainer GetContainer(string containerName)
        {
            CloudStorageAccount storageAccount = GetConnection();
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            // Create the container if it doesn't already exist.
            container.CreateIfNotExists();

            return container;
        }


    }

Hope this is helpful.

Happy Coding !!!

Wednesday, April 6, 2016

Group By First Letter of word with Linq

 

This is sample code which you can used to group some list of objects based on first letter of the object name or any string property.

In the following example I get list of contacts in an application and after getting those from DB , I group them with the First letter of the Contact name and order them in alphabetical order.

Following is my Contact Class.

  
 public class CardContactModel
    {
        public int CardId { get; set; }
        public string CardName { get; set; }
        public int? ContactId { get; set; }
        public JObject Information { get; set; }
        public string ProfileImage { get; set; }
        public string SharedTo { get; set; }
        public string RecievedFrom { get; set; }

    }

Then I group it and add it to a dictionary with the following line of code.

  
Dictionary> Contacts  = contacts.GroupBy(x => x.CardName.Substring(0, 1).ToUpper(), (Letter, Contacts) => new { Alphabet = Letter, SubList = Contacts.OrderBy(x => x.CardName).ToList() })
                .OrderBy(x => x.Alphabet).ToDictionary(x => x.Alphabet, x => x.SubList);
            return searchContactsResponse;

Hope this is helpful.

 

Happy Coding !!!

Tuesday, January 26, 2016

RSS reader in c#

 

What is RSS?

RSS (Rich Site Summary) is a format for delivering regularly changing web content. Many news-related sites, weblogs and other online publishers syndicate their content as an RSS Feed to whoever wants it.

Recently I got a requirement of reading rss feeds of blogger and other few sites and load posts in to db.

I followed the following steps.

1. Create Domain Classes

public class Post:Entity
  {
      public Post()
      {
      }

      public Post(long id)
      {
          Id = id;
      }
      public DateTime DatePublished { get; set; }
      public Blogger Blogger { get; set; }
      public string PostGUID { get; set; }
      public string Title { get; set; }
      public string PostURL { get; set; }
      public string Description { get; set; }
      public string ThumbnailURL { get; set; }
      public string PostCategories { get; set; }
      public decimal RankGiven { get; set; }

      public int  RecordCount { get; set; }

  }

2. Create Console App

A console app will first read all the blogger urls in the db then pass it to the rss feed parser.

Following is the code I used to read the RSS feed and load the content in to the Post class which I have defined previously.

    public class RSSFeedParser
       {

           public static List<Post> Parse(List<Blogger> bloggerList)
           {
               List<Post> posts = new List<Post>();
               foreach (Blogger blogger in bloggerList)
               {
                 
                   if (!string.IsNullOrEmpty(blogger.RSSFeedURL))
                   {
                       Console.WriteLine(string.Format("Started reading feeds for : {0}", blogger.BlogURL));
                       try
                       {
                           var rssFeed = XDocument.Load(blogger.RSSFeedURL);
                           XNamespace media = XNamespace.Get("http://search.yahoo.com/mrss/");
                           foreach (var item in rssFeed.Descendants("item"))
                           {
                               var elements = item.Elements();
                               Post post = new Post();
                               post.Blogger = blogger;
                               post.Title = item.Element("title").Value;
                               post.Description = GetTruncakedDescription(item.Element("description").Value);
                               post.DatePublished = Convert.ToDateTime(item.Element("pubDate").Value);
                               post.PostGUID = item.Element("guid").Value;
                               post.PostURL = item.Element("link").Value;
                               post.ThumbnailURL = item.Element(media + "thumbnail") != null ? item.Element(media + "thumbnail").Attribute("url").Value : null;
                               post.PostCategories = string.Join(",", item.Elements("category").Select(x => x.Value).ToList());
                               posts.Add(post);
                           }

                           Console.WriteLine(string.Format("Successfully parsed posts for  : {0}", blogger.BlogURL));
                       }

                       catch (Exception ex)
                       {
                           Console.WriteLine(string.Format("Error occured while parsing posts for  : {0}", blogger.BlogURL));
                       }
                   }
               }

               return posts;

           }

           private static string GetTruncakedDescription(string description)
           {
               string plainTextDesciption = Regex.Replace(description, @"<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;", string.Empty).Trim();
               string trucatedDescription = plainTextDesciption.Substring(0, plainTextDesciption.Length>400?400 : plainTextDesciption.Length);
               return trucatedDescription;
           }
       }

RSS feed is an XML document with set of defined nodes. You can see the full list of nodes which RSS standard has defined in the following site.

https://validator.w3.org/feed/docs/rss2.html

Here I have read the post name, url, thumbnail, categories and some relevant data I need for my app.

I have used a different method to parse the description field. It is to solve two issues.

1. Description field contains full post content which it too long. So I sub string the content get got the content length as required for my site requirement

2. In some RSS feeds description field contains the HTML file content. But I need to have the plain text. So I used regex to remove html tags from the field content to get the plain text.

Hope this helps.

Happy Coding

Thursday, December 31, 2015

Integrate your GIT repository with Visual Studio 2015

 

You can now easily use visual studio with your solution in GIT. You can Commi, pull, push ans run all source control commands with in your favourite IDE visual studio. You dont need to use any third party tools for that. Integration in so much easy just new steps.

1. Visual Studio-> Team-> Manage Connections

2. Then you can see team explorer

image

3. Under Local GIT repositories Click on clone

image

in there on first text box enter your GIT repository URL and the the second one add the local path and then click clone then It will promted to enter your credentails/

It will download the source code from GIT with source control binding. After that you can see all source control commands related GIT available in your visual studio.

I .Commit your changes locally

after you done with the changes when you right click on a file , project or solution you can find the Commit option as follows. This will commit your changes to local repository.

image

II .Sync your code with server code

Before pushing your code to online GIt repositor you need sync your local repository with server. For that you can use the option sync then pull.

image

III .push your changes to server

Then you can push your changes to server using push option

If you are someone familiar with TFS this is very smiliar to use.Even command names are bit different it does almst the same function

Get rid of usafe tag on angular url

 

Issue :

I recently wanted to use html sms tag in my mobile web site. In the site I have used angual binding to dynamically bind the sms url as follows

<a id="lnk_sms" href="{{sms_Link}}"  class="sms-button social-media-button" alt="SMS" style="display:none">SMS</a>
 
href value is something like :- 'sms:?body=bodyText’

when I run the application agular keep adding a unsafe prefix infront of the url and sms functionality wasn’t working.

<a id="lnk_sms" href="'unsafe:sms:?body=bodyText’"  class="sms-button social-media-button" alt="SMS" style="display:none">SMS</a>

After spending hours I was able to find the problem and soltion

Problem :

Only http, https, ftp and mailto are enabled by default. Angular will prefix a non-whitelisted URL with unsafe:

Solution :

You need to explicitly add URL protocols to Angular's whitelist using a regular expression. A good place to whitelist the sms: protocol would be in your module's config block:

var app = angular.module( 'myApp', [] )
.config( [
    '$compileProvider',
    function( $compileProvider )
    {   
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
        // Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
    }
]);

The same procedure also applies when you need to use protocols such as file: and tel:.

Please see the AngularJS $compileProvider API documentation for more info.

Hope this Helps!!!

Monday, December 28, 2015

Share you link in Social Media

Technorati Tags: ,

If you want to a share a link in you web app there are plenty of options available.

Recently I got a requirement to share a link , which is browsed through mobile. We have provided the following options to the users.

1. SMS

2. Twitter

3. LinkedIn

4. FaceBook

5. Viber

Following points gives you how to add the functionality to your site easily.

 

1. SMS

For this you have to just put the following HTML tag in to you application which is accessed via mobile. This will open the sms app in user’s mobile pre populated with the content which you have stated.

<a href="sms:/* phone number here */?body=/* body text here */">Link</a>

If you want it to work on iOS, you need this:

<a href="sms:/* phone number here */;body=/* body text here */">Link</a>

Apparently iOS8 had to go and change things on us, so thanks to some of the other commenters/responders, there's a new style for iOS:

<a href="sms:/* phone number here */&body=/* body text here */">Link</a>

(phone number is optional)

You can see a live demo here http://bradorego.com/test/sms.html (note the "Phone and ?body" and "Phone and ;body" should autofill both the to: field and the body text. View the source for more info)

 

2. Twitter

Twitter is really easy. All what you have to do is go to following link and twitter will generate the code to be pasted in you app.

https://about.twitter.com/resources/buttons#tweet

image

You will get something like this finally. Here I am sharing the current page URL.

<a href="https://twitter.com/share" class="twitter-share-button"{count}>Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>

Rather sharing a link this page gives you generating code for buttons for follow,hashtag and mention.

 

3. LinkedIn

LinkedIn also provides you a button generation in the following link.

https://developer.linkedin.com/plugins/share

image

Here URL is optional. If you keep it blank and generate the button it will be default to current page, In case if you want to share a different URL then you can set it in the URL text box and generate the button. They have different options of buttons with number of shares as well.

finally you will get a code as follows.

<script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/Share" data-counter="right"></script>

 

4. FaceBook

Following link provided you step by step on how to add a share button for facebook

https://developers.facebook.com/docs/plugins/share-button#configurator

image

same as the above once this also have a button generator where you just have to copy and paste it.

5. Viber

Viber provided the following link for you to integrate your web app with there viber app.

https://www.viber.com/en/developers/share_on_viber

Just going through two simple steps you can add share via viber options in you web app.

As you can see adding these functionalities are really easy and takes less time. But these functionality will increase traffic in you web app.

Hope this is helpful