Thursday, August 21, 2014

AzureSearch tutorial in ~100 lines of python

Here's a quick working sample of using AzureSearch with python. Please refer to readme in the comments for details on how to use it. It's pretty easy and basic stuff to get you started.



# Sample Python example to use AzureSearch
# **********************README***********************************
# Go to http://portal.azure.com and sign up for a search service.
# Get the service name and service key and plug it in below.
# This is NOT production level code. Please do not use it as such.
# You might have to install httplib2 if you're not already using it.
# ***************************************************************
import httplib2
import json

indexName = "adventurehotel"
serviceName = "azuresearch"
apiKey = '22CBC31568AAA84B243A63D36F555B85'

def getSampleDocumentObject():
    return {"value": [{
              "@search.action": "upload",
              "hotelId": "1",
              "baseRate": 199.0,
              "description": "Best hotel in town",
              "hotelName": "Fancy Stay",
              "category": "Luxury",
              "tags": ["pool", "view", "wifi", "concierge"],
              "parkingIncluded": False,
              "smokingAllowed": False,
              "lastRenovationDate": "2010-06-27T00:00:00Z",
              "rating": 5,
              "location": { "type": "Point", "coordinates": [-122.131577, 47.678581] }
            },
            {
              "@search.action": "upload",
              "hotelId": "2",
              "baseRate": 79.99,
              "description": "Cheapest hotel in town",
              "hotelName": "Roach Motel",
              "category": "Budget",
              "tags": ["motel", "budget"],
              "parkingIncluded": True,
              "smokingAllowed": True,
              "lastRenovationDate": "1982-04-28T00:00:00Z",
              "rating": 1,
              "location": { "type": "Point", "coordinates": [-122.131577, 49.678581] }
            },
            {
              "@search.action": "merge",
              "hotelId": "3",
              "baseRate": 279.99,
              "description": "Surprisingly expensive",
              "lastRenovationDate": None,
            },
            {
              "@search.action": "delete",
              "hotelId": "4"
            }]}

def getSampleIndexDefinition():
    return {
              "name": indexName,  
              "fields": [{"name": "hotelId", "type": "Edm.String", "key": True, "searchable": False},
                {"name": "baseRate", "type": "Edm.Double"},
                {"name": "description", "type": "Edm.String", "filterable": False, "sortable": False, "facetable": False, "suggestions": True},
                {"name": "hotelName", "type": "Edm.String", "suggestions": True},
                {"name": "category", "type": "Edm.String"},
                {"name": "tags", "type": "Collection(Edm.String)"},
                {"name": "parkingIncluded", "type": "Edm.Boolean"},
                {"name": "smokingAllowed", "type": "Edm.Boolean"},
                {"name": "lastRenovationDate", "type": "Edm.DateTimeOffset"},
                {"name": "rating", "type": "Edm.Int32"},
                {"name": "location", "type": "Edm.GeographyPoint"}] 
            }

def getServiceUrl():
    return 'https://' + serviceName + '.search.windows.net/indexes/'

def getIndexUrl():
    return 'https://' + serviceName + '.search.windows.net/indexes/' + indexName

def getMethod(url):
    http = httplib2.Http()
    headers = {'api-key': apiKey, 
               'Host': serviceName + '.search.windows.net', 
               'Accept': 'application/json'}

    response, content = http.request(url, 'GET', headers=headers)
    print response, content
    return response, content

def postMethod(url, body):
    http = httplib2.Http()
    headers = {'Content-type': 'application/json', 'api-key': apiKey, 'Host': serviceName + '.search.windows.net'}
    response, content = http.request(url, 'POST', headers=headers, body=body)
    print response, content

def deleteMethod(url):
    http = httplib2.Http()
    headers = {'api-key': apiKey, 'Host': serviceName + '.search.windows.net'}
    response, content = http.request(url, 'DELETE', headers=headers)
    print response, content

def createSampleIndex():
    indexDefinition = json.dumps(getSampleIndexDefinition())    
    url = getServiceUrl() + "?api-version=2014-07-31-Preview"
    postMethod(url, indexDefinition)

def getSampleIndex():
    url = getIndexUrl() + '?api-version=2014-07-31-Preview'   
    getMethod(url)

def uploadSampleDocument():
    documents = json.dumps(getSampleDocumentObject())
    url = getIndexUrl() + '/docs/index?api-version=2014-07-31-Preview'   
    postMethod(url, documents)

def printDocumentCount():
    url = getIndexUrl() + '/docs/$count?api-version=2014-07-31-Preview'   
    getMethod(url)

def sampleQuery():
    url = getIndexUrl() + "/docs?search=*&$orderby=lastRenovationDate%20desc&api-version=2014-07-31-Preview"
    response, content = getMethod(url)

def deleteIndex():
    url = getIndexUrl() + "?api-version=2014-07-31-Preview"
    deleteMethod(url)

createSampleIndex()
getSampleIndex()
uploadSampleDocument()
printDocumentCount()
sampleQuery()
#deleteIndex()

Wednesday, June 22, 2011

Persistent settings for your Silverlight based WP7 apps

While hacking around with Windows Phone 7 SDK, I realized that there is no easy way to read and write simple app settings with persistent storage. So I wrote a simple class that allows you to encapsulate that behavior and simply development. Hope you find it useful.

To use it follow these steps:
1. Instantiate an object



internal static AppSettings appsettings = new
AppSettings("app_foo_bar.settings");


2. To add key-value pairs


appsettings.settings["iseasy"] = "Easy";


3. To Write to persistant storage


appsettings.WriteSettings();


4. To Read settings on app load


appsettings.ReadSettings();


5. Fetch values


string difficultyLevelSettings = appsettings.settings["iseasy"];




public class AppSettings
{
internal string settingsFileName = "";
public Dictionary settings = new Dictionary();

public AppSettings(string filename)
{
this.settingsFileName = filename;
}

public void ReadSettings()
{
using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var file = appStorage.OpenFile(settingsFileName, FileMode.OpenOrCreate))
{
StreamReader sr = new StreamReader(file);
while (sr.Peek() != -1)
{
try
{
string streasy = sr.ReadLine();
string[] arr = streasy.Split(':');
settings.Add(arr[0], arr[1]);
}
catch
{
}
}
}
}

public void WriteSettings()
{
using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var file = appStorage.OpenFile(settingsFileName, FileMode.OpenOrCreate))
using (var writer = new StreamWriter(file))
{
foreach (var key in settings.Keys)
{
writer.WriteLine(string.Format("{0}:{1}", key, settings[key]));
}
}
}
}

Saturday, May 3, 2008

hiTech Finalists :)

Hi all,

It's been a long break from the blog. Have some good news to share. Our team at UCIrvine was declared amongst the top three in the Product Development Competition at ICS. Click here to read on.

It feels great to compete in a competition and finish successfully along with all the courses and other day to day activities. I want to thank all my team mates - Avi, Ala, Arjun, Tommy and our mentor - Sherman for the efforts which has resulted in this success.

Cheers guys. I had a great time. :)


Until later.


---Featured on OCRegister

Saturday, March 22, 2008

Thought provoking article.

I had all my thinking caps on when I read this article. It's really well written and gives a good plausible argument for working for small companies as opposed to large one. I still do not know how much I agree/ disagree with him, but I did do a lot of deliberation after reading this article.

Saturday, January 26, 2008

Disruptive Innovation!

Folks,

I had the pleasure of attending the "hiTech Competition" kickoff event a couple of days ago. hiTech is a software product competition organized by the Computer Science Department at the University of California, Irvine along with a few corporate partners. Find more information here.

The guest speaker at this event was Adam Mosam. He is a young entrepreneur who recently moved to Orange County from Toronto, Canada. He sold his first company here and as a true entrepreneur is thinking of a new venture, whilst working at the company that bought his first venture. Adam's story is very similar to stories of other entrepreneurs who start immediately out of school and struggle to the very core before reaping all the fruit. Among a lot of interesting things that Adam said I clearly recollect the phrase "Disruptive Innovation".

So I came home and thought about it. What is "Disruptive Innovation"? I guess in simple words it is something that challenges the dominating strategy in a particular market and completely changes the game by doing things differently using a new business model supported by a solid technological infrastructure advances. It is disruptive since all the "set up" businesses are at a risk of being challenged by some product and model that is better than theirs.

I wondered that, given the pace at which we see new technology thrown into the markets in all areas, how long will it be before the total landscape of the society changes? Right from the basic chores of shopping, communication, logging activities(photos, videos, journals) that every person performs to the way businesses operate and various disciplines merge. Everything is undergoing disruptive innovation as I see it. And what I also see in it is an opportunity. It is in application of technology to various fields like manufacturing, medicine, space etc that we can create new ways of doing things that were not possible before.

Exciting times lie ahead. Grab your seats for a fun ride is all I can say now. Don't have much vision or experience to predict things, but I can be sure that the things to come will be really really exciting and mind blogging!

Wednesday, January 23, 2008

Winning

Here is a quote from the best F1 racer that the world ever produced in my opinion.

"Of course there are moments that you wonder how long you should be doing it because there are other aspects which are not nice, of this lifestyle. But I just love winning."
-Ayrton Senna

Often I wonder what is it that makes certain individuals perform at their peak every single time. Is it their passion and desire to succeed, their perseverance, is it their skill, or is it simply their good luck. Well in most cases, after a little research I find that it is a bit of all of these. Almost all of the successful people I have known had all these qualities in plentiful that has seen them through thick and thin.

Passion and desire to succeed are key in defining what you it is that you seek to achieve. We need to ask ourselves what it is that we would give our life for? What is it that we badly want to do? It is certainly not easy to find this out. Very few people ever end up finding this out.

Once you figure out your passion in life, you need perseverance to see through all the odds and achieve a final goal. Uh Oh..... wait there is no final goal right? Since when you achieve a milestone you shift the goal to a higher level that requires even greater commitment, passion and desire.

Skill is something that a few people may be born with whilst a few acquire it on their way to success. Either way, you need this to enable you to fructify your dreams and desires. However, I feel it is a common misunderstanding that simply skill will get you what you ever wanted. It is the combination of skill with extreme desire that pushes you to achieve your dreams. Every person is skilled in some way or the other. Every one has strengths and weaknesses. We need to amplify our strengths to go out and achieve our goals.

Finally luck. Well I would just quote the very common saying now, "Fortune favors the brave".

So folks, take your time in figuring out where your passion lies. Then go for it as if there is no other thing left to be done. Here's wishing you good luck in this journey. It is difficult to change the way we think at first, however with practice it becomes a second nature and then you become addicted to "Winning" just like the great person I mentioned at the start of the post, Ayrton Senna.

This post is dedicated to Ayrton Senna, who was killed in an F1 crash in 1994, however even when he crashed out, he was leading the race! My humble salute to a great personality.