Monday 21 October 2013

Writing Text on Images Using Custom Fonts in ASP.NET C#

Introduction

Sometimes you may want to use third party or custom fonts to write texts over an image within your ASP.NET applications.

This is how you do it.


Create a new website or project

Create an empty Asp.Net project in visual studio.

Add Images and Fonts folders to your project. Then put an image file in the Images and a font file to Fonts folders.

Add Test.aspx page and put the code shown below in the page behind.


The Code

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Text;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string fontName = "YourFont.ttf";
        PrivateFontCollection pfcoll = new PrivateFontCollection();
        //put a font file under a Fonts directory within your application root
        pfcoll.AddFontFile(Server.MapPath("~/Fonts/" + fontName));
        FontFamily ff = pfcoll.Families[0];
        string firstText = "Hello";
        string secondText = "Friend!";

        PointF firstLocation = new PointF(10f, 10f);
        PointF secondLocation = new PointF(10f, 50f);
        //put an image file under a Images directory within your application root
        string imageFilePath = Server.MapPath("~/Images/YourImage.jpg");
        Bitmap bitmap = (Bitmap)System.Drawing.Image.FromFile(imageFilePath);//load the image file

        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            using (Font f = new Font(ff, 14, FontStyle.Bold))
            {
                graphics.DrawString(firstText, f, Brushes.Blue, firstLocation);
                graphics.DrawString(secondText, f, Brushes.Red, secondLocation);
            }
        }
        //save the new image file within Images directory
        bitmap.Save(Server.MapPath("~/Images/" + System.Guid.NewGuid() + ".jpg"));
        Response.Write("A new image has been created!");
    }

}

Finally

Go back to your project Images folder and see the new image with your new fonts on it.


Sunday 20 October 2013

Working with Twitter's REST API V1.1 Using LinqToTwitter

Introduction

This article explains how quickly and easily it is possible to post a status or a status with media to Twitter via LINQ to Twitter. At the time of this article, LINQ to Twitter version 2.1.9 was the latest.

Let's kick off and see some practical examples.

Step 1: Creating Twitter App

If you have done this before and if you are confident about application configurations, you can jump to Step 2.

Creating the app

Go to http://dev.twitter.com/apps and sign in.
Once you signed in, click on "Create a new application" button.
create a new application

Fill the application's details and click on "Create your Twitter Application" button right at the bottom of the page.
application detail
If you've created your twitter app successfully, you should see a page like below. The two important values that we need for our project development, Consumer Key and Consumer Secret values, can be found under Details tab oAuth Settings section.


Click on the Settings tab, and make sure that you filled the Callback URL(can be any link to start with), select Read and write Application Type and tick Allow this application to be used to sign in with Twitter and save (Update this Twitter application's settings) from the settings section.
settings
update settings

Step 2: Creating the Project (Visual Studio)

  1. Create an AsplNet Empty Web Application or Empty Web Site whichever is convenient for you.
  2. If you are on VS 2012, go to Tool > Library Package Manager > Package Manager Console and type Install-Package linqtotwitter in the opening window otherwise go here and download LinqToTwitter.dll file. Add a reference of this file to your project. If you are working on web sites instead, drag the downloaded .dll file to your site's bin folder. At this stage, you should have the following reference within your application bin.
    • LinqToTwitter.dll

Step 3: Adding a Test Page and an Image

  1. Add a new page and name it "Test.aspx"
  2. Add an image to your application root and name it test.jpg
  3. Go to the code behind page (Test.aspx.cs) and modify the code as follows.

    Code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Globalization;
    using LinqToTwitter;
    namespace TwitterRestAPITest
    {
        public partial class Test : System.Web.UI.Page
        {
            private WebAuthorizer auth;
            private TwitterContext twitterCtx;
            protected void Page_Load(object sender, EventArgs e)
            {           
                IOAuthCredentials credentials = new SessionStateCredentials();
    
                if (credentials.ConsumerKey == null || credentials.ConsumerSecret == null)
                {
                    credentials.ConsumerKey = "your consumer key";
                    credentials.ConsumerSecret = "your consumer secret";
                }
                if (Request.QueryString["oauth_token"] != null)
                {
                        string requestToken = Request["oauth_token"].ToString();
                        string pin = Request["oauth_verifier"].ToString();
                    
                }
                
                auth = new WebAuthorizer
                {                 
                    Credentials = credentials,
                    PerformRedirect = authUrl => Response.Redirect(authUrl),
                    
    
                };
                if (!Page.IsPostBack)
                {
                    auth.CompleteAuthorization(Request.Url);
                }
    
                if (Request.QueryString["oauth_token"] == null)
                {
                    auth.BeginAuthorization(Request.Url);
                }
                var twitterCtx = new TwitterContext(auth);
                string status = "Testing TweetWithMedia #Linq2Twitter " +
                DateTime.Now.ToString(CultureInfo.InvariantCulture);
                const bool PossiblySensitive = false;
                const decimal Latitude = StatusExtensions.NoCoordinate; 
                const decimal Longitude = StatusExtensions.NoCoordinate; 
                const bool DisplayCoordinates = false;
    
                string ReplaceThisWithYourImageLocation = Server.MapPath("~/test.jpg");
    
                var mediaItems =
                    new List
                    {
                        new Media
                        {
                            Data = Utilities.GetFileBytes(ReplaceThisWithYourImageLocation),
                            FileName = "test.jpg",
                            ContentType = MediaContentType.Jpeg
                        }
                    };
    
                Status tweet = twitterCtx.TweetWithMedia(
                    status, PossiblySensitive, Latitude, Longitude,
                    null, DisplayCoordinates, mediaItems, null);
    
                Response.Write("Your tweet has been published successfully: " + tweet.Text);
            }
           
        }
    }
    
    
  4. That is it! Run your page and see what happens. Don’t forget LinqToTwitter requires .net Framework 4
  5. Downlaod the Solution

Issues

If you encounter a problem or an error, go back to http://dev.twitter.com/apps and check whether your Twitter application settings are exactly as stated as step 1.


Thursday 17 October 2013

Working with Twitter's REST API V1.1 Using TweetSharp

Introduction

This article explains how quickly and easily it is possible to post a status or a status with media to Twitter via TweetSharp. At the time of this article, TweetSharp version 2.3.1 was the latest. Make sure that you have the full package added to your project. TweetSharp has a dependancy on Newtonsoft.Json and it also works with Hammock Client Profile.

If you would like to know how to use NuGet libraries in your projects, please refer NuGet Overview.
Let's kick off and see some practical examples.

Step 1: Creating Twitter App

If you have done this before and if you are confident about application configurations, you can jump to Step 2.

Creating the app

Go to http://dev.twitter.com/apps and sign in.
Once you signed in, click on "Create a new application" button.
create a new application

Fill the application's details and click on "Create your Twitter Application" button right at the bottom of the page.
application detail
If you've created your twitter app successfully, you should see a page like below. The two important values that we need for our project development, Consumer Key and Consumer Secret values, can be found under Details tab oAuth Settings section.


Click on the Settings tab, and make sure that you filled the Callback URL(can be any link to start with), select Read and write Application Type and tick Allow this application to be used to sign in with Twitter and save (Update this Twitter application's settings) from the settings section.
settings
update settings

Step 2: Creating the Project (Visual Studio)

  1. Create an AsplNet Empty Web Application or Empty Web Site whichever is convenient for you.
  2. If you are on VS 2012, go to Tool > Library Package Manager > Package Manager Console and type Install-Package TweetSharp in the opening window otherwise go here and download the .dll files explained in the introduction above. Add references of these files to your project. If you are working on web sites instead, drag the downloaded .dll files to your site's bin folder. At this stage you should have the following three references within your application bin.
    • Hammock.ClientProfile
    • Newtornsoft.Json
    • TweetSharp

Step 3: Adding a Test Page and an Image

  1. Add a new page and name it "Test.aspx"
  2. Add an image to your application root and name it test.jpg
  3. Go to the code behind page (Test.aspx.cs) and modify the code as follows.

    Code

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.IO;
    using System.Drawing;
    using TweetSharp;
    
    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var oauth_consumer_key = "replace this with your twitter application consumer key";
            var oauth_consumer_secret = "replace this with your twitter application consumer key";
    
            string dbToken = string.Empty;
            string dbSecret = string.Empty;
    
            //the assumption here is your application has members
            //check whether an authenticated member has twitter access token and secret within our local database; 
            //for now let's say there is no in db ==> hasTokensInDb = false
            bool hasTokensInDb = false; //GetMembersTwitterTokenFromDb(ref string dbToken, ref string dbSecret);
            var service = new TwitterService(oauth_consumer_key, oauth_consumer_secret);
    
            if (hasTokensInDb)
            {
                service.AuthenticateWith(dbToken, dbSecret);
                DoWhatThisAppNeedToDo(ref service); 
            }
            else
            {
                //if oauth_token is null (i.e. if we haven't sent a token request to twitter yet, 
                //then send a get token request by addressing the this page as a callback (Request.Url.AbsoluteUri)
    
                if (Request["oauth_token"] == null)
                {               
                    OAuthRequestToken requestToken = service.GetRequestToken(Request.Url.AbsoluteUri);
                    Response.Redirect(string.Format("http://twitter.com/oauth/authorize?oauth_token={0}", requestToken.Token));
                   
                }
                else
                {
                    string requestToken = Request["oauth_token"].ToString();
                    string pin = Request["oauth_verifier"].ToString();
                    // Using the values Twitter sent back, get an access token from Twitter
                    var accessToken = service.GetAccessToken(new OAuthRequestToken { Token = requestToken }, pin);
                    // Use that access token and send a tweet on the user's behalf
                    if (accessToken != null && !string.IsNullOrEmpty(accessToken.Token) && !string.IsNullOrEmpty(accessToken.TokenSecret))
                    {
                        service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);
                        UpdateDatabase(accessToken.Token, accessToken.TokenSecret);
                        DoWhatThisAppNeedToDo(ref service);                                             
                    }
                }
            }
        }
    
        private void UpdateDatabase(string token, string secret)
        { 
            //do database updates
        }
        private void DoWhatThisAppNeedToDo(ref TwitterService tService)
        {
            //if you want status update only uncomment the below line of code instead
            //var result = tService.SendTweet(new SendTweetOptions { Status = Guid.NewGuid().ToString() });
            Bitmap img = new Bitmap(Server.MapPath("~/test.jpg"));
            if (img != null)
            {
                MemoryStream ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                ms.Seek(0, SeekOrigin.Begin);
                Dictionary<string, Stream> images = new Dictionary<string, Stream>{{"mypicture", ms}};
                //Twitter compares status contents and rejects dublicated status messages. 
                //Therefore in order to create a unique message dynamically, a generic guid has been used
    
                var result = tService.SendTweetWithMedia(new SendTweetWithMediaOptions { Status = Guid.NewGuid().ToString(), Images = images });
                if (result != null && result.Id > 0)
                {
                    Response.Redirect("https://twitter.com");
                }
                else
                {
                    Response.Write("fails to update status");
                }
            }
        }
    
    }
    
  4. That is it! Run your page and see what happens. Don’t forget TweetSharp requires .net Framework 4
  5. Download the Solution

Issues

If you encounter a problem or an error, go back to http://dev.twitter.com/apps and check whether your Twitter application settings are exactly as stated as step 1.