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.


Sunday 1 July 2012

Cross Domain Calls to a Windows Communication Foundation (WCF) Services

Introduction

This blog focuses on calling a WCF service in a cross domain environment. To elaborate it, let us say the WCF service is hosted in a domain called http://wcf.com and the client application that requires to call the WCF service is hosted in a domain called http://client.com. Cross domain interaction between web resources has been a challenge as far as client scripting like Javascript, flush and others are concerned.

This blog provides a downloadable solution, links for further reading and a bit of explanation about some important web configuration sections and service properties.

JSON with Padding (JSONP)

JSONP is a complement to the JSON data format. The JSONP format enables a page to request data from a server in a different domain. See useful references.

The downloadable solution uses the JSONP format to make requests to the WCF service hosted in a different domain. The Jquery library supports the JSONP format requests in its $.ajax() and $.getJSON() methods. Later in this blog, there will be examples for both Jquery methods.

The WCF Service

The example WCF service is designed to return a list of customers when its GetCustomer method has been called. Key properties are highlighted.

.Net Framework 4 and Visual Studio 2010 are both required to compile the solution.


Service Designer (.svc)

<%@ServiceHost
    language="c#"
    Debug="true"
    Service="Microsoft.Samples.Jsonp.CustomerService"
    Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"
%>
 

Service Class (.cs)


using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Collections.Generic;
namespace Microsoft.Samples.Jsonp
{
    [DataContract]
    public class Customer
    {      
        [DataMember]
        public string FirstName;
       
        [DataMember]
        public string LastName;
    }


    [ServiceContract(Namespace="JsonpAjaxService")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CustomerService
    {
        [WebGet( BodyStyle=WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
        public List<Customer> GetCustomer()
        {
            List<Customer> list = new List<Customer>();
            list.Add(new Customer() { FirstName="Nathan", LastName="Abebe"});
            list.Add(new Customer() { FirstName = "Dawit", LastName = "Yitagesu" });
            return list;
        }
    }
}
 

Web.Config

<system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonP"
                 crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webHttpBehavior">
          <webHttp helpEnabled="true"/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
        multipleSiteBindingsEnabled="true" />
    <services>
      <service name="Microsoft.Samples.Jsonp.CustomerService">
        <endpoint address="" behaviorConfiguration="webHttpBehavior"
            binding="webHttpBinding"
                  bindingConfiguration="webHttpBindingWithJsonP"
            contract="Microsoft.Samples.Jsonp.CustomerService" />
      </service>
    </services>    
  </system.serviceModel>

The Client (Javascript)

       var Type;
        var Url;
        var Data;
        var ContentType;
        var DataType;
        var ProcessData;
        var method;
       
        //Call service static class
        function CallService() {
            $.ajax({
                type: Type, //GET or POST or PUT or DELETE verb
                url: Url, // Absolute location of the service
                data: Data, //Data sent to server (Example {APIKey: 'your api key'})
                contentType: ContentType, // content type sent to server
                dataType: DataType, //Expected data format from server
                processdata: ProcessData, //True or False
                success: function (msg) {//On Successful response
                    ServiceSucceeded(msg);
                },
                error: ServiceFailed// On Unsuccessful response
            });
        }
        function ServiceFailed(xhr) {
            alert(xhr.responseText);
            if (xhr.responseText) {
                var err = xhr.responseText;
                if (err)
                    error(err);
                else
                    error({ Message: "Unknown server error." })
            }
            return;
        }
        function ServiceSucceeded(data) {                    
            if (DataType == "jsonp") {
                    $.each(data, function () {
                    var string = this.FirstName + " \n " + this.LastName;
                    alert(string);
                });
            }
        }
        //Url is consisted of {domain}/{service file}/{method name}
        //assuming the serivce file is found in the application root folder

        function getCustomerByJqueryAjax() {            
            Type = "GET";
            Url = "http://localhost:33695/service.svc/GetCustomer";
            DataType = "jsonp";
            ProcessData = false;
            method = "GetCustomer";
            CallService();
        }
        //Url is consited of {domain}/{service file}/{mothod name}{?callback=?}
        //assuming the serivce file is found in the application root folder
        function ajaxJsonPost() {

            $.getJSON("http://localhost:33695/service.svc/GetCustomer?callback=?",
                function (data) {
                    $.each(data, function (index, item) {
                        alert(item.FirstName + ' ' + item.LastName);                        
                    });
                });
            }            
        $(document).ready(function () {
            getCustomerByJqueryAjax();
            getCustomerByJqueryGetJson();
        });

Useful References

Windows Communication Foundation Sample Solution Downloads

JSONP for cross-site Callbacks

What is JSONP

Tuesday 30 August 2011

ASP.NET with Jquery Autocomplete

Whilst researching on creating an auto search suggestion dropdown (i.e. kind of google or bing suggestions), I found a great jquery plugin called "autocomplete" that does the job amazingly.

In this blog I will show you how you can use this jquery plugin with an ASP.NET server side (*.aspx) page as a backend support.

autocomplete

View Demo   Download Sample