Pages

Affichage des articles dont le libellé est c#. Afficher tous les articles
Affichage des articles dont le libellé est c#. Afficher tous les articles

mercredi 22 mai 2013

A simple .Net Wrapper of Yammer API

Introduction

In ScrumPilot, I plan to replace my native news feed by a Yammer news feed; additionally, I want to allow people who don't have Team Foundation Server accounts the possibility view this news feed.
I wrote this API wrapper to interact easily with Yammer.

Codes sources

@ CodePlex : Yammer.SimpleAPI
or just use it 
@nuget : Yammer.SimpleAPI package

First Step

In order to use Yammer API, you must setup your app in "My Apps" in Yammer.
Below is screen shot of my own app setup: ScrumPilot.
Note at the bottom of the form, the URL redirection to a local address, if you want to interact with your dev environment.

Example

In VS Solution, I added an MVC project for this example.

First Screen

First screen shot, when you run the MVC site, you will see a form where you should type your Yammer Client ID and Client Secret given to you by Yammer when you setup your app.

Yammer API first screen

Post in Controller

It's a very classic Post. it prepares an object with all of the information and it redirects to Yammer with some of the information (see source code below for details).
It retains connection information in Session in case of success (when it comes back from Yammer).

[HttpPost]
public ActionResult Index(IndexViewModel model)
{
    if (ModelState.IsValid)
    {
        // prepare info for Yammer
        var myConfig = new ClientConfigurationContainer
                     {
                        ClientCode = null,
                        ClientId = model.ClientId,
                        ClientSecret = model.ClientSecret,
                        // especially where it should return
                        // after auth 
                        RedirectUri = Request.Url.AbsoluteUri 
                                + Url.Action("AuthCode") 
                      };
        // Create a new Rest Client
        var myYammer = new YammerClient(myConfig);
        // Make the right Yammer Url
        var url = myYammer.GetLoginLinkUri();
        // Save data in Session
        this.TempData["YammerConfig"] = myConfig;
        // go to Yammer
        return Redirect(url);
    }
    return View(model);
}

If everything is correct, you should see the screen shot below; it asks you to authorize Yammer to share information with your app (in my case: ScrumPilot).


When you have clicked on "Allow", Yammer returns to your app, and provides it an authorization code.
To better understand this workflow, read the oauth2 website.


Result and Interactions

// Call back by Yammer when you allow your app
// interact with it
public ActionResult AuthCode(String code)
{
    // I receive auth code from Yammer
    if (!String.IsNullOrWhiteSpace(code))
    {
       var myConfig = this.TempData["YammerConfig"]
                          as ClientConfigurationContainer;
        myConfig.ClientCode = code;
        var myYammer = new YammerClient(myConfig);

        // Some examples
        // var yammerToken = myYammer.GetToken();
        // var l = myYammer .GetUsers();
        // var t = myYammer .GetImpersonateTokens();
        // var i = myYammer .SendInvitation("test@test.fr");
        // var m = myYammer .PostMessage("A test from here", 
        //                                    0, "Event" topic);
        return View(myYammer.GetUserInfo());
     }
     return null;
}

Once your app has the authorization code, it can interact with Yammer (read, write...).
A result example: 




mardi 14 mai 2013

Un "Wrapper" .NET de L'API Yammer

Introduction

Dans le but de remplacer le feed natif de ScrumPilot par le feed de Yammer, et aussi d’informer des gens affiliés à Yammer, mais qui n'ont pas de compte ScrumPilot ou Team Foundation Server, j'ai fabriqué une librairie pour accéder facilement à Yammer et interagir avec lui.

Codes sources

sur CodePlex : Yammer.SimpleAPI

Préalable

Pour dialoguer avec Yammer au travers de son API, il faut préalablement configurer une "Apps" dans Yammer.
Le didacticiel est bien fait, et ci-dessous, des copies d'écran de ma propre inscription.
Notez l'adresse de redirection en bas du formulaire qui pointe vers une adresse locale.

Exemple d'utilisation

Dans ma solution, j'ai ajouté une application MVC qui illustre l'utilisation de la librairie.

Connexion

Le but de l'écran ci-dessous est de saisir les renseignements fournis par l'inscription, le Client ID et de Client Secret fourni par Yammer.

Yammer API first screen

Post dans le Controller

Le post dans le Controller est des plus classiques, il prépare les informations à envoyer, il redirige vers Yammer qui demande si l'application est autorisée. Je stocke les informations de connections pour les sauvegarder au retour.

[HttpPost]
public ActionResult Index(IndexViewModel model)
{
    if (ModelState.IsValid)
    {
        // prepare info for Yammer
        var myConfig = new ClientConfigurationContainer
                     {
                        ClientCode = null,
                        ClientId = model.ClientId,
                        ClientSecret = model.ClientSecret,
                        // especially where it should return
                        // after auth 
                        RedirectUri = Request.Url.AbsoluteUri 
                                + Url.Action("AuthCode") 
                      };
        // Create a new Rest Client
        var myYammer = new YammerClient(myConfig);
        // Make the right Yammer Url
        var url = myYammer.GetLoginLinkUri();
        // Save data in Session
        this.TempData["YammerConfig"] = myConfig;
        // go to Yammer
        return Redirect(url);
    }
    return View(model);
}

Si tout se passe bien, vous devriez arriver sur un écran comme celui-ci, il vous demande l'autorisation de partager vos informations avec votre application (celle que vous avez déclarée dans le préambule, pour ma part ScrumPilot)


En cliquant sur "Allow", Yammer retourne vers votre application en lui fournissant un code d’authentification.
Pour une meilleure compréhension de la mécanique générale de cette authentification, je vous renvoie vers
OAuth 2.

Résultat et interactions

public ActionResult AuthCode(String code)
{
    if (!String.IsNullOrWhiteSpace(code))
    {
        var myConfig = this.TempData["YammerConfig"]
                          as ClientConfigurationContainer;
        myConfig.ClientCode = code;
        var myYammer = new YammerClient(myConfig);

        // Some examples
        // var yammerToken = myYammer.GetToken();
        // var l = myYammer .GetUsers();
        // var t = myYammer .GetImpersonateTokens();
        // var i = myYammer .SendInvitation("test@test.fr");
        // var m = myYammer .PostMessage("A test from here", 
        //                                    0, "Event" topic);
        return View(myYammer.GetUserInfo());
     }
     return null;
}

Une fois que vous êtes autorisés à interagir avec Yammer, vous pouvez lire et écrire depuis et dans Yammer.
Un petit exemple : 




vendredi 4 mars 2011

Create an asp.net mvc3 mobile app with jQuery Mobile

A 7 minutes video to show how to create an asp.net mvc3 mobile app with jQuery Mobile from the scratch

Complete sources is here



Links :
Using 51Degrees.Mobi Foundation for accurate mobile browser detection on ASP.NET MVC 3 by  Steve Sanderson
A Better ASP.NET MVC Mobile Device Capabilities ViewEngine by Scott Hanselan

mardi 1 mars 2011

Debug tip for ASP.NET MVC 3 in mobile context

For manage Mobile page, I'm inspired from this excellent post "A Better ASP.NET MVC Mobile Device Capabilities ViewEngine" by Scott Hanselmann
But, when I want inspect some html parts or if I want trace a javascript behavior, I want and I prefer use Firefox and FireBug.
So, I create a fake mobile engine which use Firefoxe+firebug

First, I have added my new engine in globlal.asax.cs 
In "Global.asax.cs" (full source here)
protected void Application_Start()
{
  AjaxHelper.GlobalizationScriptPath =
  "http://ajax.microsoft.com/ajax/4.0/1/globalization/";
  AreaRegistration.RegisterAllAreas();
  RegisterGlobalFilters(GlobalFilters.Filters);
  RegisterRoutes(RouteTable.Routes);

  // Add the auto mobile detection & redirection
  ViewEngines.Engines.Clear();
  ViewEngines.Engines.AddIPhone<RazorViewEngine>();
  ViewEngines.Engines.AddWindowsMobile<RazorViewEngine>();
  ViewEngines.Engines.AddGenericMobile<RazorViewEngine>();
#if DEBUG
// Just use it for debug JS in firebug & inspect HTML
  ViewEngines.Engines.AddFireBug<RazorViewEngine>();
#endif
  // Std engine
  ViewEngines.Engines.Add(new RazorViewEngine());} 

Second, I had in my custom mobile engine my new "Firefox+firebug" fake mobile engine

in CustomMobileViewEngine cs (full source here)

public static class MobileHelpers
{
    ...
    //Add firefox + firebug for help to debug
    public static void AddFireBug(this ViewEngineCollection ves) 
                  where T : IViewEngine, new()
    {
        ves.Add(new CustomMobileViewEngine(c =>
                c.UserAgentContains("firefox"), "Mobile",
                new T()));
    }
} 
You could do the same thing with "F12" on IE if you are used it.

lundi 28 février 2011

Une astuce pour Asp.net MVC 3 avec jQuery Mobile et HTML 5

Si vous utilisez HtmlHelper dans Asp.net MVC 3, vous pourriez avoir quelques difficultés à définir des propriétés personnalisées.
Par exemple, en utilisant jQuery Mobile,et j'ai eu besoin d'initialiser «data-theme» ou «data-transition» sur un ActionLink
Si vous l'écrivez avec le séparateur '-' , vous obtenez une erreur de syntaxe. Les gars de Redmond nous ont mijotés une petite surprise, il faut remplacer le '-' par des '_'comme ceci :

@Html.ActionLink("My team", "UsersList", "Home", null,
 new { data_theme = "b", data_transition = "fade",
 data_icon = "star" })

et, automatiquement, les '_' sont remplacés par des '-'
<a data-icon="star" data-theme="b" data-transition="fade"
 href="/Home/UsersList">My team</a>

Je pense que cela marche aussi pour propriétés spécifiques à Html 5

A tip about dashes for Asp.net MVC 3 in jQuery Mobile and HTML 5 context

if you use HTMLhelper in Asp.net MVC 3, you could have some difficulties to set custom properties.
For example, I'm using jQuery Mobile, and I need to set 'data-theme' or 'data-transition' on an ActionLink.
If you write it with '-' separator, you have a syntax error. The Redmond guys have cooked a small surprise for us, you should replace the '-' by '_' like this
@Html.ActionLink("My team", "UsersList", "Home", null,
 new { data_theme = "b", data_transition = "fade",
 data_icon = "star" })
and automaticly, they replace '_' by '-' in Hmtl code
<a data-icon="star" data-theme="b" data-transition="fade"
 href="/Home/UsersList">My team</a>
I think we can do the same thing for HTML 5 properties

jeudi 17 février 2011

How to use Telerik Report in asp.net MVC 3 page

I made a small video to illustrate how to use Telerik report web viewer in a asp.net MVC 3 page



You can find the sources here

Enjoy