Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Tuesday, September 3, 2013

Sending email from your app

Let’s say that your app needs to have the ability to send an email, “New order has arrived” kind of email.
Let me introduce you “Fluent Email” – a nice library for making your life easy when sending emails for your app.
Fluent Email is available in the nearest nugget server so go ahead and install this package.
Before we send the email we need to configure our email smpt server in our configuration file:
  <system.net>
  <mailSettings>
    <smtp>
      <network enableSsl="true" host="smtp.gmail.com" port="587" userName="nerush.dennis@gmail.com" password="*****" defaultCredentials="false" />
    </smtp>
  </mailSettings>
  </system.net>
All the above values are different when using different smpt servers. If you want gmail to be your email server then you have to specify the port as 587 and set enableSsl to true.

The API

Email.From (myEmail)
     .To(sendToEmail)
     .Subject("New order has arrived!")
     .Body("The order details are…")  
     .Send();

Pretty straight forward.

If you are not willing to wait until the email is being sent you can use the Sendsync method:
Email.From (myEmail)
     .To(sendToEmail)
     .Subject("New order has arrived!")
     .Body("The order details are…")  
     .Sendsync(MailDeliveredCallback);
  
You can specify the “from” email value in the config file:
<system.net>
  <mailSettings>
    <smtp from=”Nerush.dennis@gmail.com”>

And then you can use the “FromDefault” method:
Email.FromDefault()
     .To(sendToEmail)
     .Subject("New order has arrived!")
     .Body("The order details are…")  
     .Send();

Templates

Another cool feature is the templates. Let’s say that you want to send a nice email to your users which has not only simple text but a table, a picture and some more stuff. You can create an HTML template and use it for your mail:

Template.cshtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body dir="rtl">
    <h1>New user has signed in for the website!</h1>
    <p>New user’s name:<b>@Model.Name</b>
        <br/>
        The new user email: <b>@Model.Email</b>
        <br/>
        <u>
The message text:
        </u>
        @Model.Text
    </p>
    <br/>
    <p>Have a great day!</p>
</body>
</html>

Notice the @Model? Those are parameters that you can pass for the template from the API:

Email.FromDefault()
     .To(sendToEmail)
     .Subject("New user has signed in!")
     .UsingTemplate(tempalte, new {Name = message.Name,
       Email = message.Email,
       Text = message.Text})

     .Send();

Culture support

In the last commits of the project Eyal Luxenburg added another cool feature for the library – the ability to use a template based on the current culture. The method is calledUsingCultureTemplateFromFile. This is the methods signature:
UsingCultureTemplateFromFile<T>(string filename, T model, CultureInfo culture = null, bool isHtml = true)

If you specify a culture it will try to load the template file which has the matching culture extension (same way as with the resource files). Specifying the He-IL culture will force fluent email to look for a template file that has the culture extension: template.he-IL.cshtml. This way you can create email templates for all the languages that your app supports.

Email.FromDefault()
     .To(sendToEmail)
     .Subject("See you in the next post")
           .UsingCultureTemplateFromFile(template, emailModel, hebrewCulture)
     .Send();





Friday, February 15, 2013

Always having the latest version of jQuery

When you develop your website you'll have to use the latest version of jQuery . So you'll download the latest version from http://jquery.com/ or some other site and add it to your project.

So far so good but what happens when jQuery will release a new version?
You'll re download it and update your site every time?
Perhaps. Or you can add this line to your master page/layout:
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
This way you reference the google hosted jquery.js file of the latest version, which is regularly updated.

You can also add the latest jQuery-ui.js file:
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
What about the jQuery-ui.css?You got it!
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/pepper-grinder/jquery-ui.css" type="text/css" />

Stay updated.

Tuesday, January 15, 2013

Data Annotations Extensions

You are probably familiar with the MVC Data Annotations, those attributes that define validations on your model properties.
   1: [MaxLength(20)]

   2: [Required]

   3: public string FirstName { get; set; }

   4:  

   5: [MaxLength(20)]

   6: [Required]

   7: public string LastName { get; set; }

   8:  

   9: [Required]

  10: [Date(ErrorMessage = "You have to be at legal age")]

  11: [DataTypeAttribute(DataType.Date)]

  12: public DateTime BirthDate { get; set; }

  13:  

  14: [Required]

  15: [EnumDataType(typeof(Sex))]

  16: public Sex Sex { get; set; }

  17:  

  18: [Required]

  19: [DataType(DataType.EmailAddress)]

  20: [Display(Name = "Email address")]

  21: public string Email { get; set; }

  22:  

  23: [Phone]

  24: public string Phone { get; set; }

You can define which properties are required, input max length, custom error messages, custom types and built in regular expressions (like email or phone).

However there not enough data annotations in the framework: you can’t define a property that will be only numeric, or credit card number and more. Yes you can define a custom regular expression but who likes to define them?

Let me introduce the “DataAnnotationsExtensions” – an open source library that gives you more attributes like “Digits” or “CraditCard” and more.

Enjoy.

Monday, October 8, 2012

FQL - Getting all your friends


In my last post I showed you how to get and display your facebook details, in this post I'll show you how to display the details of all your friends.

Same as last time we need to understand what are the relevant tables and which columns interest us. We'll go to http://developers.facebook.com/docs/reference/fql/friend/and take a look at the FRIEND table:


Its a really simple table with just two columns: the logged in user id and the friend's id.
SELECT uid1, uid2 FROM friend WHERE uid1 = me() AND uid2 = 220439

Using this query you can easily determine if two users are friends
The me() method returns the id of the logged in user and the second id is the other user id, if the query returns an answer then the two users are connected – friends.

Let's return to other main topic: Displaying all my friend's details. Every friendis eventually a user; the FRIEND table holds only the users ids but not their details. In order to get their details we'll have first to get all the friends ids and then query the USER table with those ids.

This query gets all my friends:

SELECT uid2 FROM friend WHERE uid1 = me()


We'll create a sub-select to retrieve all the details off all my friends:

SELECT first_name, last_name, pic_square FROM user WHERE uid in 
(SELECT uid2 FROM friend WHERE uid1 = me())

Now after we know how to get the friends details let's code!


Since eventually we'll retrieve a list of users we'll use the same model from last time – FacebookUserModel, this name will suite more: FacebookUsersModel.



Same as before the model holds a list of FacebookUser that represents the wanted fields from the USER table.

Now let's create the controller:



Connect to facebook servers and run the query then get the data from the dynamic object,  desirialize the Json and send the model to the view.

The view needs to be strongly-typed viewso we'll have access to the model's properties that we want to display: pic_square, first_name and last_name:



(I love MVC- using .net features and html tags together)

F5 the SLN and navigate to the Friends controller








There you have it!

All your friends on one page. If you want to split them for pages stay tuned for my next post–"Paging and FQL"





Monday, October 1, 2012

Getting Facebook data using FQL


After we managed to log into facebook in my previous post now it's time to get some data from facebook.
Facebook allows us to query its data using 3 ways:
1.       Legacy REST API – allows you to send requests and receive data via HTTP requests. Facebook are now in the process of deprecating this feature.
2.       Graph API
3.       FQL – Facebook Query Language
All facebook data is stored in huge tables (e.g. album, user, photo...), both Graph API and FQL allow you to query that data. Graph API makes you send http requests with the suitable parameters to get what you want as oppose to FQL that allows you to write some sort of SQL kind of language to query the facebook data.

Graph API example

Try them!  You'll receive a JSON response (which by the way you can switch to XML if you change the header of your request) with all your friends and all your albums details.


FQL

In my opinion it is a better way to query data from facebook because it reminds me SQL that is simple and obvious. It allows me to filter my queries adding a "where clause" that is used on indexed fields to increase performance and it "looks" better (readable and clear) when using it from .net class.

Let's see how we can retrieve personal details from facebook to our website

The first thing you need to do is go to http://developers.facebook.com/docs/reference/fql/ and scroll to the bottom where you'll see all the tables that can be queried. The tables have pretty obvious names (I admit that I still haven't understood why particular tables exist but I'm working on it) so as their columns. You can see the columns and their description in every table (e.g. user table - http://developers.facebook.com/docs/reference/fql/user/ ).
 Similar to SQL, FQL allows you to retrieve only the data that you want using the SELECT statement.  Opposed to SQL, FQL requires you to use the WHERE clause not only in every query you run but you can query only fields that are indexed (makes sense…you don't want to wait for a query that gets all the facebook users).

We want to receive some basic details about the user that is logged in our website. Mmm let's say we want his/her first name, last name, gender, profile picture and friend count. That means we need the following fields (according to the user table): first_name,  last_name, sex, pic_square and friend_count.
FQL is built like a basic SQL query: SELECT field1, field2 FROM tableName WHERE
Our query is: SELECT first_name,  last_name, sex, pic_square, friend_count FROM user WHERE uid=me()
Me() is a special facebook function that retrieves the logged in user id.

Now let's run it from our website!

First we create a new controller "UserDetailsController"






In order to present the user details in the View we'll need a model: "FacebookUserModel". The query retrieves JSON result so in order to desirialize the JSON to an object we'll have to create an object with the exact identical fields as the JSON response. One more thing: even though the query will retrieve just a single user the response is built like the query is supposed to retrieve an array of users so that our model will hold a list of "FacebookUser" which will hold our 4 properties (no .net standards =\)











Alright now we have our model, let's add some logic to the controller. First we need to connect to the facebook servers using the access token we received when we logged in, then we need to send our FQL and receive the JSON response. To receive a response from facebook we'll use the "Get" method that takes 2 arguments: path and object. Path tells facebook that is the second argument type – in our case it's "fql". The second argument will hold the query itself.
Facebook return JSON result that the best way to "hold it" is using dynamic object. If you'll open your debugger you will see that response starts with the word "data" and the whole response is surrounded with "[ ]" brackets" because the response is an array.
After we hold our JSON response all we have to do is desirialize it to an actual object (To use the JsonConvert nugget "json" and add it to your project – it's helpful). Remember! We don't  deserialze the response to the "FacebookUserModel" but to a list of "FacebookUser".

The last thing we have to do is send the "FacebookUser" object to our view. Oh right, we need to create a view…Right click inside our method and choose "AddView". In the settings window choose "Create a strongly-typed view" and choose the "FacebookUser" model class.


Doing so we enable our view to access the model properties that the controller sent it.

Simple html table with all the user's fields:


F5 the solution and login. Now add to your address the controller name.


 


Cool right?

Sunday, September 30, 2012

Log into your MVC4 website using facebook API


As a software developer I think that you have to watch "The Social Network" movie once a month.
If you haven’t invented facebook yet then you should always try to create something that will change the world.
A few days ago I watch it again and suddenly I had an idea to create a website that in my opinion many people will use it (I hope). The website will have to integrate with facebook. I decided to post some tutorials for using Facebook API with mvc4.
If your website will use facebook info the first thing you have to do is log into facebook. I tried to use different helpers (Facebook helper, Microsoft helper) but after a while I decided that the best way is to write your own code (the helpers didn’t really help).

This post I'll talk about login into facebook from your site.

We will login into facebook in 10 simple steps:
1. Create an asp.net mvc4 web application using basic tamplate:


2. Create Home controller and the Index view:
3. Create a "FacebookLoginModel":

    public class FacebookLoginModel
    {
        public string Uid { get; set; }

        public string AccessToken { get; set; }
    }

4. Create the "AcountController" and the "FacebookLoginMethod". This method will be called after a successful login so that we store the access token and the user id in order to use them whenever we would like to connect to facebook servers from our site:

 public class AccountController : Controller
    {
        [HttpPost]
        public JsonResult FacebookLogin(FacebookLoginModel model)
        {
            Session["uid"] = model.Uid;
            Session["accessToken"] = model.AccessToken;

            return Json(new { success = true });
         }
}


5. Go to https://developers.facebook.com/ and create a new facebook app. Even though you create your own website you have to create a facebook application so that all the facebook services would work.



Make sure that all the app's urls point to your website url

6.  Save the AppId and the AppSecret in your web.config:
       <add key ="FacebookAppId" value="11111111"/>
    <add key ="FacebookAppSecret" value="2222222222"/>

7. Create Facebook.js file and paste there this script:
function InitialiseFacebook(appId) {

    window.fbAsyncInit = function () {
        FB.init({
            appId: appId,
            status: true,
            cookie: true,
            xfbml: true
        });

        FB.Event.subscribe('auth.login', function (response) {
            var credentials = { uid: response.authResponse.userID, accessToken: response.authResponse.accessToken };
            SubmitLogin(credentials);
        });

        FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                alert("user is logged into fb");
            }
            else if (response.status === 'not_authorized') { alert("user is not authorised"); }
            else { alert("user is not conntected to facebook");  }

        });

        function SubmitLogin(credentials) {
            $.ajax({
                url: "/account/facebooklogin",
                type: "POST",
                data: credentials,
                error: function () {
                    alert("error logging in to your facebook account.");
                },
                success: function () {
                    window.location.reload();
                }
            });
        }

    };

    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    } (document));

}


This java script will subscribe us to the login event on which we'll receive our access token and save it in the Session object. Besides that the js will alert every time the user logs in and logs out.


8.   Add the initialization method for the facebook services in your _Layout.cshtml:

<div id="fb-root"></div>
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/Facebook.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            InitialiseFacebook(@System.Configuration.ConfigurationManager.AppSettings["FacebookAppId"]);
            });
    </script>

9.  Now we'll add the facebook button html to our view
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>
<fb:login-button autologoutlink="true" perms="read_friendlists, create_event, email, publish_stream"></fb:login-button>


Now your session holds the access token which helps you to connect to facebook from your site.

 10. F5 the solution and observe!


Hitting the pretty login button opens formal facebook login page that after submitting stores the access token in the Session object.



In the next post I'll show you have to get your facebook details and how to use the FQL – Facebook Query Language.