Mahdi Taghizadeh I'm who I'm!

16Jun/100

Help The First Persian IT and Computer Q&A Website

Everybody in the community has seen StackOverflow website at least once and many developers use this great QA website on a daily basis in order to ask their technical questions or help other developers resolve their programming issues. StackOverflow is built using a platform called StackExchange. StackExchange is (now a free) platform that let one build a powerful QA website on a subdomain on StackExchange.com or a dedicated domain name. To ensure that they can keep their service quality at a reasonable level, there are some qualification stages to be eligible to use their great service and support.

A few days ago my friend, Hamed Saeedifard, started a big work and prepared a proposal and sent it over to StackExchange as the first step toward the first professional QA website for Persian language developers (covering many in Iran, Kurdistan, Afghanistan, Tajikistan, etc.) and fortunately StackExchange response was hopeful and also many Iranian developers started to contribute to this project by sending some questions to evaluate potential of this proposal and request. That was the first stage and by the help of all members, Danatarin is now qualified for commitment stage and we should encourage more and more developers to commit and support it. Oh! I said Danatarin! It is a temporary name that Hamed has chosen for this QA website and it may change after we complete the mission! Personally I love this name ;-) By the way, Danatarin means "The Wisest" in Persian.

At this stage, it's very important to invite more developers (even non-Persian speaking guys whose commits can be very effective) to commit and help us be qualified for beta program. So I would be appreciated if you take a little of your time commiting to our Danatarin: http://j.mp/helpdanatarin.

If you want to know more about Danatarin you can

It's good to know that Danatarin is now among the first five websites which are qualified for second level and we're really proud of this!

I would like to thank Hamed for his great idea and all his efforts to start this project and also all the people who are trying to gather and share their knowledge; thank you guys :-)

UPDATE: StackExchange behavior on commitment stage was disappointing. So my friend, Hamed, started a clone of StackOverflow (powered by python/django) on http://beta.danatarin.com. Go there, sign up and start to contribute to Danatarin right now!

3Jun/101

Updated feed address

If you're an old reader of my blog you know that my blog was previously on SharpLife.NET domain name and its feed was http://feeds.feedburner.com/SharpLife, after I migrated it to mahdi.mp domain name, I changed this feed's target to mahdi.mp too but I have been seeing many readers are still subscribing to old address instead of new http://mahdi.mp/feed or http://feeds.feedburner.com/MahdiTaghizadeh.

To resolve this issue, I deleted SharpLife feed from my FeedBurner account and now all its traffic is redirecting to http://mahdi.mp/feed; I would be appreciated if you check your reader and update address to http://mahdi.mp/feed if it's pointed to old SharpLife.NET address.

Thank you guys :-)

Tagged as: , 1 Comment
2Jun/105

EAV and the .NET Framework

Recently I've been working on a web application's database model in which I had different types of products and services that my client is going to offer in his eShop. The problem was different nature of attributes each type had and I should have defined a relationship between them and my online order pipleline. Using the common relational database approach I finished up with an OrderDetail table which had multiple foreign keys related to tables which was representing different kinds of products. Anyway, I'm not going to explain my project details here. That was a preface to explain a concept that Farid Arzpeyma introduced to me: Entity-Attribute-Value (EAV) Model, an approach that is widely used in enterprise eCommerce platforms like Magento.

There are many documents and articles out there describing EAV, its concept, principals and usages and I'm not going to talk about it here but quoting this which describes it shortly:

Entity-Attribute-Value model (EAV), also known as object-attribute-value model and open schema is a data model that is used in circumstances where the number of attributes (properties, parameters) that can be used to describe a thing (an "entity" or "object") is potentially vast, but the number that will actually apply to a given entity is relatively modest. In mathematics, this model is known as a sparse matrix.

What I came up with in my mind was possible existing frameworks for .NET developers to implement this model in their applications. Because EAV breaks the rule in which we're urged to use a vertical data representation (using columns) - by introducing another method of collecting data records and their types in table rows - it's necessary to adopt our OOP code to smoothly interact with this new structure. By the time Microsoft hadn't released SQL Server 2005, storing hierarchical data structures was a painful handy job for database developers but at the time Microsoft introduced XML datatype with SQL Server 2005 it became easier for them to natively store such structures right inside a column in a database. EAV is a similar concept and its main goal is to enable developers store attribute/value information in a table in a hierarchical manner.

Unfortunately it seems that there have been very few interests in the .NET community to work on open source frameworks in order to work with EAV database models. My searches shows a disappointing number of articles, blog posts and tools for this purpose.

The first article I found was Entity-Attribute-Value (EAV) model with SQL Server 2005 xml datatype that is talking about how to implement an EAV-like model using the new XML datatype in SQL Server 2005 and later. Mladen Prajdić has also referenced to another article explaining EAV in SQL Server more generally.

The second was a newer talking about a solution with Entity Framwork: Generic Entity Attribute Value Model – A POCO Implementation. This is closer to what I had in my mind because it's talking about EAV in general and how to implement our data layer, built on EAV pattern, using EF.

And finally the third was an open source project on CodePlex but unfortunately it seems that it's no longer active and there isn't even a public release out.

My conclusion is, the .NET community hasn't done much efforts on EAV concept and in my opinion it is because Microsoft policy - since creation of .NET Framework - has been just to spread this technology and best practices have rarely gone further on advanced and enterprise topics.

Tagged as: , 5 Comments
25May/106

How to use Google Data API in ASP.NET MVC. Part 2 – YouTube

YouTube Data APIPreviously on this series, I had talked about  How to use Google Data API in ASP.NET MVC to interact with Google Analytics. In this second part I'm going to show you how to store and retrieve videos on/from YouTube using Google Data API and YouTube API.

YouTube is the largest and most popular video sharing website and since Google has acquired it and integrated its API into GData it's been an ultimate choice for developers to choose it as a safe and powerful backend for their videos.

I should mention that there are two types of YouTube APIs for developers:

  1. The Data API which lets you incorporate YouTube functionality into your own application or website. You can perform searches, upload videos, create playlists, and more.
  2. The Player APIs which give you control over YouTube video playback on your website. Configure basic settings, drive the player interface, or even build your own player controls.

One may add the third Custom Player to the list above but indeed it's not an API.

In our tutorial we will go through the first item: Data API; the second is left for JS and AS developers and maybe Pedram would write about it!

Well, let's go!

I'll divide my blog post main content into two seperate topics: Storing Videos and Retrieving Video.

Storing Videos on YouTube

First of all your have to prepare required tools to interact with YouTube Data API. Here's what you would do:

  1. Sign up for a developer key. You will also need your Google account username and password.
  2. Download YouTube SDK.

After installing YouTube SDK, reference the following assemblies in your project:

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.YouTube;

Whenever you want to send/receive data to/from YouTube you should authenticate yourself (your application) against it. The following helper method first checks if there is already an authenticated request object in Session and use it for the current request as well, otherwise it will create a new YouTubeRequest using the YouTubeRequestSettings which we provide:

public static YouTubeRequest GetRequest()
{

    var request = HttpContext.Current.Session["YTRequest"] as YouTubeRequest;

    if (request == null)

    {

        var settings = new YouTubeRequestSettings("SampleWebApp", "NA",
                              ConfigurationManager.AppSettings["YouTubeAPIDeveloperKey"],
                              ConfigurationManager.AppSettings["YouTubeUsername"],
                              ConfigurationManager.AppSettings["YouTubePassword"]);

        request = new YouTubeRequest(settings);

        HttpContext.Current.Session["YTRequest"] = request;

    }

    return request;

}

Now we are ready to create a view to let the end user browse his video file and upload it to YouTube:

<%
    var youTubeRequest = GetRequest();
    var newVideo = new Video { "VideoTitle", Description = "VideoDescription" };

    newVideo.Media.Categories.Add(new MediaCategory("All")); // You can assign any category here.

    newVideo.Keywords = "samplekeyword";
    newVideo.YouTubeEntry.Private = false;

    var token = youTubeRequest.CreateFormUploadToken(newVideo);
    var postUrl = token.Url;
    var tokenValue = token.Token;
%>

<% if ((bool)ViewData["UploadError"])
{%>
    <%= "Error uploading the video!" %>
<%} %>

<form action="<%= postUrl %>?nexturl=http://localhost/upload/success" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="hidden" name="token" value="<%= tokenValue %>" />
    <input type="submit" value="Upload!" />
</form>

The code above consisted of two parts; first we create a YouTubeRequest object (using the helper method which we built before) and then we prepare the required YouTube Video object which contains our video meta data information. One thing I've experienced using this Video object is that you MUST specify a MediaCategory and also some Keywords; otherwise you will receive a bad request error.  After assigning the required properties to our Video object, we need to request a token value. A token is used by YouTube API to recognize your request and prevent duplicate requests. This token provide us with a Url property that would be used to post uploaded file to. We've also implemented a simple error handling section to show a friendly error message if uploading process failed. The second part of the code shows an HTML <form> tag that lets you upload a video file. Action value is our "postUrl" variable which we created before plus a nextUrl query string value - the page which you want to return back to when the upload process is completed.

When you uploaded a video successfully you would be automatically redirected to the page which you specified in nextUrl query string value. YouTube API sends back some information along with this nextURL. You will receive Video ID (something like "mLw7ySQFuV4") and an integer Status Code. If Status Code doesn't equal 200 it means something went wrong and you should return a friendly error message and ask your user try again; otherwise, upload process has been successful. The action method behind "/success" URL is shown below:

public ActionResult Success(int status, string id)

{

    if (status != 200) // Upload was not successful. Checking the status code.

    {

        ViewData["UploadError"] = true;

        return RedirectToAction("Upload");

    }

    // Now you should store uploaded video information using your Data Access layer / Repository.
    // This is the place in which you should set Video ID returned back to this action from YouTube API.
    // This ID (in form of XXXXXXXXXXX) will be used to retrieve a video to edit or play.

   return RedirectToAction("Manage");

}

Learn more about different status codes here.

I recommend you split your upload operation into two steps: first let the end user enter video meta data like title, description, tags, etc. and store them in your database then ask him to upload and attach the video file to this record. This way it's easy to track video properties state when an error accures and you have to show back the upload view again.

Congratulations! You uploaded and stored your first video onYouTube from inside your application using YouTube API.

Retrieving a Video from YouTube

Now you have a real video under the account that you have used to authenticate against YouTube. Two other common scenarios you may want to implement are editing an existing video (either changing meta data information or replacing the video file with a new one) and the second is playing that video.

In both scenarios we should retreive the video object first. Logic behind this, is similar to what we've implemented to create a new video entry with a some minor differences:

var youTubeRequest = YouTubeHelper.GetRequest();

var videoEntryUrl = new Uri(string.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads/{1}",

        ConfigurationManager.AppSettings["YouTubeUserId"], youTubeId));

var youTubeVideo = youTubeRequest.Retrieve<Google.YouTube.Video>(videoEntryUrl);

Now you have the existing Video object ready and can change its meta data information or create a new token value to upload a new video file.

Playing the video (using YouTube pre-built player) is very easy as well. Just pass Video ID to Play action method and retrieve it from YouTube as shown in the code above; then pass it to the respected view:

public ActionResult Play(string youTubeId)

{

    var youTubeRequest = YouTubeHelper.GetRequest();

    var videoEntryUrl = new Uri(string.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads/{1}",

            ConfigurationManager.AppSettings["YouTubeUserId"], youTubeId));

    var youTubeVideo = youTubeRequest.Retrieve<Google.YouTube.Video>(videoEntryUrl);

    return View(youTubeVideo);

}

Final step is using the model in a view page. I have used popular SWFObject to ebmed YouTube player in my view:

<script type="text/javascript">

    var params = { allowScriptAccess: "always" };

    var atts = { id: "myytplayer" };

    swfobject.embedSWF("http://www.youtube.com/v/<%= Model.VideoId %>?enablejsapi=1&playerapiid=ytplayer",

        "ytapiplayer", "625", "556", "8", null, null, params, atts);

</script>

You're done!

Please note that I have tried to simplify all steps and customize everything for an ASP.NET MVC app scenario and in real world scenarios your should provide your end user with more features and customization options.

20May/104

Create a Twitter API proxy for your own!

As you may know I live in Iran and many websites are blocked here due to governmental censorship policies. Therefor, to access websites like Facebook or Twitter we have to use proxies or VPNs. Proxies and VPNs have their own problems here and are not reliable solutions indeed. The issue becomes more complicated when it comes to mobile phone world; for example to access Twitter on my iPhone I have to connect to my VPN first and then open my Twitter client and it's really exhausting and painful!

Yesterday, that Twitter announced official "Twitter for iPhone", I received an update on my iPhone that replaced Tweetie 2 with the new official app and as soon as I opened the new app it asked for my Twitter username and password; one interesting point which I noticed was a proxy setting section that let users use a different proxy API other than Twitter official API. Soon after this, Pedram came up with a solution in his mind! His suggesting solution was twip. twip stands for Twitter + Proxy + PHP and is a free Twitter API proxy in PHP that let you create your very own proxy API on your desired domain name and use it instead of Twitter original API. In my case it was great because I could use it in on my iPhone and now I'm able to read tweets and update it without a VPN!

All you need to setup your proxy API on your domain are

  1. apache with mod_rewrite enabled
  2. >=PHP-5.2.4 with curl enabled (it may work with <5.2.4, but I only tested it on 5.2.4 :-) )
  3. zlib support if you want the gzip compression work

Then you should download twip and extract it in a folder on your web server (even root) and define it as your proxy API in Twitter for iPhone (or any other application which supports proxy API settings). At least you get rid of Twitter censorship in countries like Iran! I wish same solutions for Facebook, etc. ;-)

After setting this up successfully, I was thinking if there is any desktop Twitter client with the same functionality (to let the end user set his own proxy API) but unfortunately didn't find anything. So, do you know any? Tell me in the comments!

UPDATE: Thanks (!) to our friends at Google Code which have blocked all Iranian IPs, you have to use a proxy or VPN to download Twip from Iran! So I uploaded both available versions of Twip here. Go get it!

Tagged as: , , 4 Comments
Get Adobe Flash playerPlugin by wpburn.com wordpress themes