Foursquare–part 2 of 4

After successfully connecting to Foursquare with an Web application, the problem is what to don with a Desktop application. The most simple desktop application is a Console . The first idea that I have had is to start a browser, let the user pass his credentials and retrieve data from browser.

Something like this

string urlAuth = this.sharpSquare.GetAuthenticateUrl(urlSOA + "home/redirect4sq/" + this.thisRequest);
Process p = new Process();
p.StartInfo.FileName = getDefaultBrowser();
p.StartInfo.Arguments = urlAuth;
p.Start();


However, I have been not capable of taking data from the WebBrowser process. So the solution is this one:

The Console program open a web browser to the Foursquare web site with a redirect to http://fsq.apphb.com/ and GUID. The user enters his credentials to FourSquare site. Then Foursquare is redirecting to the http://fsq.apphb.com/  -and the http://fsq.apphb.com/ memorizes a GUID and his token. Then the Console reads from http://fsq.apphb.com/ the token ( has the GUID) and it is set.

 

 

The code looks like this:

public void AuthenticateNewWebBrowser()
        {
            string urlAuth = this.sharpSquare.GetAuthenticateUrl(urlSOA + "home/redirect4sq/" + this.thisRequest);
            Process p = new Process();
            p.StartInfo.FileName = getDefaultBrowser();
            p.StartInfo.Arguments = urlAuth;
            p.Start();
            Thread.Sleep(5000);
            AuthenticateToken();
        }
//retrieving from website
        public void AuthenticateToken()
        {
            var newUrl = urlSOA + "api/Values/ClientToken/" + this.thisRequest;
            var code = new WebClient().DownloadString(newUrl).Replace("\"", "");
            SetAccessCode(code);

        }

Next time I will do code for solving same problem – but from inside the program( without needing to launch a new Process)

Friday links 55

  1. Microsoft’s Free Security Tools – A Deeper Look at XSS Attacks and Microsoft’s free Anti-Cross-Site Scripting Library – Microsoft Security Blog – Site Home – TechNet Blogs
  2. Writing debugger type visualizers for C++ using .natvis files in C#, XML for Visual Studio 2012
  3. TouchDevelop – learn
  4. The Real Problem With BioShock Infinite’s Box Art: Poor Trigger Finger Discipline
  5. QuitSmoking.com – Kill the Habit on Vimeo
  6. 6 Simple Rituals To Reach Your Potential Every Day | Fast Company
  7. Providers of Free MOOC’s Now Charge Employers for Access to Student Data – Technology – The Chronicle of Higher Education
  8. Keeping Multiple IIS 7 Servers in Sync with Shared Configuration : Rick Barber’s Blog : The Official Microsoft IIS Site
  9. Random Acts of Coding: LINQing to MEF Imports
  10. Configuring IIS methods for ASP.NET Web API on Windows Azure Websites and elsewhere
  11. Gamasutra – Features – Free-to-Play: The Lost Generation
  12. Entity Framework: Be vigilant with Include method! – Matthieu MEZIL
  13. BBC News – Viewpoint: How happiness changes with age
  14. Wolfpack 104 –Jungle Man Art vs. GI Science
  15. Conditional validation | Hobbscene.com
  16. ASP.NET MVC Conditional validation – Stack Overflow
  17. You’re not anonymous. I know your name, email, and company.
  18. Machine Learning, Big Data, Deep Learning, Data Mining, Statistics, Decision & Risk Analysis, Probability, Fuzzy Logic FAQ | William M. Briggs
  19. The Best Full Size Tablet
  20. I’m Chris Anderson, and This Is How I Work

Solving “No parameterless constructor defined for type of ‘System.String’.”

TL;DR

If you have the problem

No parameterless constructor defined for type of ‘System.String’!

just add the DeserializeObject and InterceptError functions , add this 2 lines:

var obj = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json); //json parameter is the string content of the api
<your object> = DeserializeObject(obj, typeof(<your object type>)) as <your object type>; 

watch the debug window and you will see the problems marked with !!!
( See also video at http://youtu.be/7oZ37pnSNtM)

Long story:

I wanted to do a tutorial for obtaining data from foursquare from Web , Desktop and mobile applications. I have made some research first and I have discovered the API and a library for obtaining data.

Unfortunately, foursquare changed his API and , when deserializing, the application was giving  

“No parameterless constructor defined for type of ‘System.String’.

 

at this line

fourSquareResponse = new JavaScriptSerializer().Deserialize<FourSquareSingleResponse<T>>(json);

I have made a custom code to see where the errors are. 

I do not want to explain the code, just look at it and then I will show how to use:

/// <summary>
        /// TODO: make this add to global errors to return to the caller
/// </summary>
        /// <param name="message"></param>
        private void InterceptError(string message)
        {
            var cc = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(message);
            Console.ForegroundColor = cc;
            Debug.WriteLine(message);
        }
        private object DeserializeObject(Dictionary<string, object> dictItem, Type tip)
        {
            
            var newInstance = Activator.CreateInstance(tip);
            var isDictionary = (tip.GetInterface("IDictionary") != null);
            PropertyInfo p = null;
            foreach (var k in dictItem.Keys)
            {
                var ser=  new JavaScriptSerializer().Serialize(dictItem[k]);

                
                Type tipP = null;
                if (isDictionary)
                {
                    tipP = tip.GetGenericArguments()[1];
                }
                else
                {
                    
                    try
                    {
                        p = tip.GetProperty(k);
                        if (p == null)
                            throw new ArgumentNullException(k);
                    }
                    catch (Exception)
                    {
                        //Console.WriteLine(ex.Message);                        
                        InterceptError("missing property:" + k + " to class" + tip.FullName + " value:" + ser);
                        continue;
                    }
                    tipP = p.PropertyType;
                }
                
                
                if (tipP.IsClass && tipP.FullName != typeof(string).FullName)
                {
                    
                    dynamic val = null;
                    try
                    {
                        val = new JavaScriptSerializer().Deserialize(ser, tipP);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("error for class:" + k + ex.Message);
                        IList arr = dictItem[k] as object[];
                        if (arr == null)
                        {
                            arr = dictItem[k] as ArrayList;
                        }
                        if (arr == null)
                        {                            
                            var t1 = dictItem[k] as Dictionary<string, object>;
                            if (t1 == null)
                            {
                                InterceptError("Not a dictionary, not an array - please contact ignatandrei@yahoo.com for " + k);
                            }

                            val = DeserializeObject(dictItem[k] as Dictionary<string, object>, tipP);
                            
                        }
                        else
                        {
                            val = Activator.CreateInstance(tipP);
                            var tipGen=tipP.GetGenericArguments()[0];
                            foreach (var obj in arr)
                            {
                                val.Add((dynamic)DeserializeObject(obj as Dictionary<string, object>, tipGen));
                            }
                        }
                        

                    }

                    if (isDictionary)
                    {
                        ((IDictionary)newInstance).Add(k, Convert.ChangeType(val, tipP));
                    }
                    else
                    {
                        p.SetValue(newInstance, Convert.ChangeType(val, tipP), null);

                    }
                }
                else//simple int , string, 
                {
                    try
                    {
                        if (isDictionary)
                        {
                            ((IDictionary)newInstance).Add(k, Convert.ChangeType(dictItem[k], tipP));
                        }
                        else
                        {
                            p.SetValue(newInstance, Convert.ChangeType(dictItem[k], tipP), null);
                        }
                    }
                    catch (Exception ex)
                    {
                        InterceptError("!!!not a simple property " + k + " from " + tip + " value:" + ser);
                    }
                }
            }
            return newInstance;
        }

Now the original code that throws the error looks this way:

try
            {
                fourSquareResponse = new JavaScriptSerializer().Deserialize<FourSquareSingleResponse<T>>(json);  //json parameter is the string content of the api
            }
            catch (Exception ex)
            {
                var obj = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);  //json parameter is the string content of the api
                fourSquareResponse = DeserializeObject(obj, typeof(FourSquareSingleResponse<T>)) as FourSquareSingleResponse<T>; 
            }

When looking to the debug window, you will see:

!!!not a simple property icon from FourSquare.SharpSquare.Entities.Category value:{"prefix":"https://ss1.4sqi.net/img/categories_v2/building/home_","suffix":".png"}

 

If looking to the source code, you will see

public string icon
        {
            get;
            set;
        }

And in the foursquare api you will see

 

    • icon: {
      • prefix: "https://ss1.4sqi.net/img/categories_v2/travel/trainstation_"
      • suffix: ".png"

      }

  •  

    Now it is clear : icon is not a string, is a class!
    So just add a class with required properties , modify the property from string to this class and it is all solved!
    ( for me, the class is:

       public class Icon
       {
           public string prefix { get; set; }
           public string suffix { get; set; }
    
        }
    

    and the definition will be:

    public Icon icon
            {
                get;
                set;
            }
    

    Moral of the story:

    When obtaining data via HTTP API, just be sure that you can handle modifications!

    Foursquare–part 1 of 4

    I have decided to log my daily routine from FourSquare .  I decided to make a Web application and a desktop application ( console, to be easiear) .

    As a good application, 4Sq have an API at https://developer.foursquare.com/ . I suggest you to start with conecting to 4Sq, https://developer.foursquare.com/overview/auth .

    For WebServers , you will redirect the user to  an URL from 4Sq.

    https://foursquare.com/oauth2/authenticate
        ?client_id=YOUR_CLIENT_ID
        &response_type=code
        &redirect_uri=YOUR_REGISTERED_REDIRECT_URI

    The user gives his accept to use your application and 4Sq redirects the browser back to YOUR_REGISTERED_REDIRECT_URI

    Then , with the code, you can ask for an access token and then you can search 4Sq API.

    I have searched also a 4Sq application in .NET   – and I found this one : https://github.com/ignatandrei/SharpSquare

    Ok, so for implementing with ASP.NET MVC it is relatively simple – I must make an action that can answer to YOUR_REGISTERED_REDIRECT_URI and then ask for user checklist for the previous day – rather simple:

     public ActionResult oldWay(string id)
            {
                var c = new conect4Sq();
                c.SetAccessCode(id);
                var data = c.CheckinsYesterday();
                return View("~/Views/Home/ShowCheckins.cshtml",data);//TODO: use T4MVC
    
            }
    

    You can see the application in work at http://fsq.apphb.com/  – just press the first “learn more” from the left.

    You will find  the source code at https://github.com/ignatandrei/4SqDayHistory

    Problem solved !

    Now the real problem is to do the same thing from a DESKTOP application ( or Console, to be easier) – but this will be in the second part next week!

    Friday links 51

    1. Sticky Menus Are Quicker To Navigate | Smashing UX Design
    2. 9 Common Usability Mistakes In Web Design | Smashing UX Design
    3. The Toolbox: a directory of useful single-page sites and apps
    4. Top 10 free Nokia Lumia 800 games for Windows Phone (AUGUST UPDATE) | NokNok.tv
    5. Gamasutra – News – Opinion: Negative developers and team stability
    6. INCIDENTAL COMICS: We Are the Introverts
    7. The Next Twenty Years
    8. SSW Rules to Better …
    9. Templated Razor Delegates
    10. The Limits of Communication by Jodi Dean – Guernica / A Magazine of Art & Politics
    11. How to Self Publish a Book: 2 Methods – wikiHow
    12. TimeSnapper Lets You Play Back Your Time On The PC Like A Movie [Windows]
    13. .NET Design Patterns in C# and VB.NET – Gang of Four (GOF) – DoFactory
    14. learn.knockoutjs.com
    15. 8 Signs You’ve Found Your Life’s Work | Fast Company
    16. Software Engineering: What are the best examples of software bugs that became features? – Quora
    17. Q*bert – Wikipedia, the free encyclopedia
    18. Unlock the 007 in you. You have 70 seconds! – YouTube
    19. Blog: The stolen bytes: Visual Studio, virtual methods and data alignment – Lol Engine
    20. Whitney Hess » Pleasure and Pain » What’s Your Problem? Putting Purpose Back into Your Projects
    21. TED | Talks | List
    22. Securing RESTful Web Services with OAuth2 | CloudFoundry.org Blog
    23. Free Online Course Materials | Audio/Video Courses | MIT OpenCourseWare
    24. Video Listing
    25. SpecFlow extension
    26. What’s new in v1.9 | SpecFlow
    27. BBC – Future – Health – Does life speed up as you get older?
    28. How to Hack It in a Hackathon | Seven Days
    29. Creating Powershell pre-build and post-build events for Visual Studio projects « David Frette’s Blog

    Minimize Json

    TL;DR:

    Minimize Json Answer by minimizing the names of the properties transmitted. As a practical example, see http://jsonminimize.apphb.com/ ( although is gzipped , the answers are 3862 versus 3089 bytes – an 20% gain . Your results will vary – because of how I obtain the random obtaining of data )

     

    Prerequisites:

    Ajax / Json   – http://msprogrammer.serviciipeweb.ro/2011/12/05/jquery-ajax-request-and-mvcdetailed/

    AutoMapper – for automating transformation on server code of an object to another : http://automapper.org/

    Mandatory for source code: Knockout – just because I needed a templating engine for javascript

     

    Introduction

     

    Let’s say you have an application that shows a report of something( for my example, departments and employees). Let’s say that you have optimized database for speed , the network connection, the data you load, everything.

    However, because the end user wants to retrieve entire data, the page loads in 3 seconds. And this is not acceptable.

    Looking to the source, you see that thepage makes one Json request that retrieves all data. You can not minimize this data. You tell the user that you can make several JSon request – but he will experience some delays. The user does not want to do this.

    You look deeper into JSon answer and see that response from JSon:

    {"ok":true,"departments":[{"IdDepartment":0,"NameDepartment":"Department 0","Employees":[{"FirstName":"Andrei","LastName":"Ignat","Login":"Andrei.Ignat","DateOfBirth":"\/Date(-62135596800000)\/","ManagerName":"Knowledge"},{"FirstName":"0 JkerzEZgv","LastName":"0 DjYFekyLF","Login":"0 JkerzEZgv.0 DjYFekyLF","DateOfBirth":"\/Date(24019200000)\/","ManagerName":"manager 0"},{"FirstName":"0 SlBKASBb","LastName":"0 rYGQXWQ","Login":"0 SlBKASBb.0 rYGQXWQ","DateOfBirth":"\/Date(21686400000)\/","ManagerName":"manager 1"}]},{"IdDepartment":1,"NameDepartment":"Department 1","Employees":[{"FirstName":"1 JkerzEZgv","LastName":"1 DjYFekyLF","Login":"1 JkerzEZgv.1 DjYFekyLF","DateOfBirth":"\/Date(24019200000)\/","ManagerName":"manager 0"},{"FirstName":"1 SlBKASBb","LastName":"1 rYGQXWQ","Login":"1 SlBKASBb.1 rYGQXWQ","DateOfBirth":"\/Date(21686400000)\/","ManagerName":"manager 1"}]},{"

    What if , instead of “IDDepartment” the server transmits just “I” ? And if , instead of “NameDepartment” just “N” ? The response will be minimized! However, you do not want to affect the page source, so this article is about.

     

    Original Application

    The original application is displaying the departments and theirs employees. It is made with Knockout for templating and have this code ( oversimplified for convenience) :

    $.ajax({
    //code
                success: function (returndata) {
                        if (returndata.ok) {
                            window.alert("Departments transferred: " + returndata.departments.length);
                            ko.applyBindings(returndata);
    //code
    

    and the knockout templating engine will interpret the templating

    <div data-bind=”foreach: departments”>
    <h3 data-bind=”text: NameDepartment”><h3>

    The steps:

    1. Create 2 new classes , DSmall  and ESmall with properties names smaller.

    2.Map the properties with a Dictionary from Department to DSmall  and from Employee to ESmall

    3. Map the list of Department to list of DSmall and list of Employees to ESmall (using AutoMapper and the dictionaries from 2)

    4. Verify with an console example

    5. Transmit over JSon the DSmall and ESmall. 

    6. In javascript recreate the Department and Employees from DSmall and ESmall.

     

    7.Results

     

    8.Homework

     

    Create 2 new classes , DSmall  and ESmall with properties names smaller.

    The Departmen have a property named IDDepartment. DSmall will have a property named I. And so on – see below:

    
    public class Department{
            public Department()
            {
                Employees = new List<Employee>();
            }
            public int IdDepartment { get; set; }
            public string NameDepartment { get; set; }
            public List<Employee> Employees { get; set; }
    
    
    
        }
    
    public class DSmall
        {
            public int I { get; set; }
            public string D { get; set; }
    
            public List<ESmall> E{ get; set; }
        }
    
    
    public class Employee
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Login
            {
                get
                {
                    return FirstName + "." + LastName;
                }
            }
            public DateTime DateOfBirth { get; set; }
    
            public string ManagerName { get; set; }
    
    
        }
    
    public class ESmall
        {
            public string F { get; set; }
            public string L { get; set; }
            public string Lo { get; set; }
            public DateTime D{ get; set; }
    
            public string M{ get; set; }
        }

     

     

     

    Map the properties with a Dictionary from Department to DSmall  and from Employee to ESmall

    As I said,the Departmen have a property named IDDepartment. DSmall will have a property named I. And so on. So I came up with this for department:

      dDep = new Dictionary<string, string>();
                dDep.Add("I", "IdDepartment");
                dDep.Add("D", "NameDepartment");
                dDep.Add("E", "Employees");
    

    and for converting Employees to ESmall

    dEmp = new Dictionary<string, string>(); 
                dEmp.Add("F", "FirstName");
                dEmp.Add("L", "LastName");
                dEmp.Add("Lo", "Login");
                dEmp.Add("D", "DateOfBirth");
                dEmp.Add("M", "ManagerName");
    

    The dictionaries will be good also for transmitting to javascript the names in order to not change the names of the properties in templating.

     

     

     

    Map the list of Department to list of DSmall and list of Employees to ESmall (using AutoMapper and the dictionaries from 2)

    This is the easiest line:

    Utils<Employee, ESmall>.CreateMap(dEmp);
    Utils<Department, DSmall>.CreateMap(dDep);
    
    I invite you to read the code on utils class. It involves some lambda programming. I will not detail here - just grab the source from https://github.com/ignatandrei/MVCMinimizeJson/ 
    
    
    
    <p>&#160;</p>  <p>&#160;</p>  <h3> Verify with an console example </h3>  <p>&#160;</p> 
    I have made an console example to show the difference of serializing DSmall and Department. The code does not involve database - just loads some random data.
    I have serialized with XMLSerializer and Javascript serializer 99 Department with random employees and then transforming to DSmall and ESmall
    
    
               #region xml
                var ser = new XmlSerializer(typeof(List<Department>));            
                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                {
                    ser.Serialize(sw, d);
                }
     //           Console.WriteLine(sb.ToString());
                var nrXML = sb.Length;
                #endregion
    
                #region javascript
                var jss = new JavaScriptSerializer();
                int nrJss = jss.Serialize(d).Length;
                #endregion
    

    For javascript the result is impressive: 30%. ( as I say, because of the random, your result may vary a little . Do your research)

    image

    Transmit over JSon the DSmall and ESmall. 

     

     

    This was the easiest part. I just put the random data into appliaction( I know, I know... but it was easier). And I have created 2 actions

    public JsonResult RequestEmployees()
            {
                //usually this will be loading from database
                //but to compare same data when minimizing, 
                //I have to put somewhere            
                List<Department> d = this.HttpContext.Application["data"] as List<Department>;
                return Json(new { ok = true, departments = d });
            }
    
            public JsonResult RequestEmployeesMinimizing()
            {
                //usually this will be loading from database
                //but to compare same data when minimizing, 
                //I have to put somewhere                        
                List<Department> d = this.HttpContext.Application["data"] as List<Department>;
                var min = LoadData.Minimize(d);
                return Json(new { ok = true, departmentsMin = min, LoadData.dDep, LoadData.dEmp }); 
    
            }
    

    As you see, when transmitting the minimizing version of data, we will send also the dDep ( dictionary department) and dEmp( dictionary employees) of mapped properties to the View - in order to re-instantiate the original Employee and Department from javascript

     

    In javascript recreate the Department and Employees from DSmall and ESmall.

     

     

     

    We must do this in order to not modify the template that we already have.So I have created a simple mapping function in Javascript:

     function createObjectMapped(minObject, dictProp) {
                var obj = new Object();
                
                for (var prop in dictProp) {
    
                    obj[dictProp[prop]] = minObject[prop];
    
                }
                return obj;
            }
    

    and use like this:

    returndata.departments = [];
                            $.each(returndata.departmentsMin,function(index, departmentMin)
                            {
                                var dep = createObjectMapped(departmentMin, returndata.dDep);
                                //mapping employees of the department
                                dep.Employees = [];
                                $.each(departmentMin.E, function (index, employeeMin) {
                                    dep.Employees.push(createObjectMapped(employeeMin, returndata.dEmp));
                                });
                                returndata.departments.push(dep);
    
                            });
    
    

    7.Results

    In Fiddler, for 99 departments with random employees, the original data is 77.765 bytes . The minimized data is 55.796 bytes. My gaining was 28%

    8.Homework

    Do the same when sending json bulk data - see http://msprogrammer.serviciipeweb.ro/2014/01/05/javascript-mvvm-and-asp-net-mvc/

    Source code at https://github.com/ignatandrei/MVCMinimizeJson/
    View online at http://jsonminimize.apphb.com/

    The original problem and idea was coming from Adrian Petcu Thank you !

    Andrei Ignat weekly software news(mostly .NET)

    * indicates required

    Please select all the ways you would like to hear from me:

    You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

    We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.