Skip to main content

Posts

Showing posts from May, 2014

Implementing OAuth2 consumer in C#

Recently I worked on a project that involved integrating with social networking and jobs websites like Elance. These days almost all major services that allow applications to access users' data, perform authorization/authentication using OAuth1.0 or OAuth2. OAuth2 compared to OAuth1 is very easy to implement. OAuth1 involves generating nonce,timestamp,signaturebase and signing the request with any algorithm like HMAC-SHA1 and appending data to query string of URL and passing in Authorization header of HTTP. OAuth2 removed all these requirements. Following is OAuth2 process in a nutshell 1) Redirect user to Authorization url passing client_id and redirect_url in query parameters 2) If user authenticates successfully through service provider it will redirect user to the redirect_url passed with authorization access code in query parameters. 3) After getting authorization access code you exchange this to receive access token. You make a POST HTTP request to a URL passing client_id

JEE File Upload - Handling Multipart requests in Servlets 3.0

Prior to Servlets 3.0 developers have to use 3rd party libraries to process complex multipart request that is sent when file is uploaded by user. Starting from Servlets 3.0 JEE provides a better way to handle file uploads (multipart requests) without using any 3rd party library. Making your Servlet ready to handle Multipart requests All you have to do is to add  @MultipartConfig annotation on your servlet class and it is ready to handle Multipart requests. @MultipartConfig   public class FileUploadServlet extends HttpServlet { Our example HTML form <form method="POST" enctype=" multipart/form-data "> <input type="file" name="ufile" /> <input type="submit" value="Submit" /> </form> Handling the POST in processRequest method of Servlet protected void processRequest (HttpServletRequest request,         HttpServletResponse response)         throws ServletException, IOException { Gettin

Truncate/Ignore time part of DateTime column in Entity Framework

There are times when you want to perform query on only date part of the column that has type DateTime in database. Entity framework does not support DateTime.Date property but provides a helper class EntityFunctions . EntityFunctions has a method TruncateTime that can be called in Linq2Entities query and truncates the time part from datetime. Here is how to use it using (AccountEntities dal = new AccountEntities ()) {               DateTime dtStart=DateTime.Now.AddDays(-20).Date;               DateTime dtEnd=DateTime.Now.Date;     transactions = (from t in dal.Transactions                             where                             EntityFunctions.TruncateTime (t.TransactionDate.Value)                             >= dtStart                             &&                             EntityFunctions.TruncateTime (t.TransactionDate.Value)                             <= dtEnd                            orderby t.TransactionDate descending                          

Android pull down to refresh implementation

There are many apps that allow you to refresh content by simply pulling down the list. I had a similar requirement in one of my projects. I decided to write a blog post that how easily I implemented this feature. For simplicity I will remove code of setting Adapter to ListView etc.I will only show code to detect pull down on ListView First lets see the layout of my screen <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >       <!-- this linear layout will contain our content which we will show -->     <!-- to user while refreshing -->     <LinearLayout android:id="@+id/layoutRefresh"         android:orientation="vertical"         android:layout_height="wrap_content"         andr

Multithreaded C# TCP server to handle multiple clients

I decided to write a minimal multithreaded TCP based server as a blog post. Following class can serve as a skeleton for any small or large scale multithreaded TCP socket server. It do not contain much error handling , it is only to give an idea that how multithreaded server works and how it can process multiple clients using threading. using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections.Generic; namespace RandomStuffMine { public class MTServer {     public int Port{get;set;}     public Socket ServerSocket{get;set;}     private List<Client> Clients=new List<Client>();     private bool runServer=true;     public MTServer(int port)     {         Port=port;         ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);     }     public void Start()     {         Thread thr=new Thread(new ThreadStart(StartServer));         thr.IsBackground=t

Playing with Date and Time in MySQL

Manipulating date and time in database is an important task in any database driven application. MySQL is the most popular open source database deployed widely. Here are some tasks that you can perform on date and time using MySQL built in functions. Adding interval to a date DATE_ADD function allows adding/subtracting(using - sign) any interval to date/datetime. The usage of this function is as follows DATE_ADD(date,INTERVAL  [expression] [unit] ) unit can be one of the following MICROSECOND,SECOND,MINUTE,HOUR,DAY,WEEK,MONTH,QUARTER,YEAR,SECOND_MICROSECOND,MINUTE_MICROSECOND,MINUTE_SECOND,HOUR_MICROSECOND,HOUR_SECOND,HOUR_MINUTE,DAY_MICROSECOND,DAY_SECOND,DAY_MINUTE,DAY_HOUR,YEAR_MONTH expression  depends upon the unit. We will explore some units and respected expressions in this post. Note: All example queries use column name "column_dt" for a column of type datetime. Adding SECOND(s) to DATETIME Following query will add 1 second to the value of column_dt

Cannot find RIMIDEWin32Util.dll in Eclipse for Blackberry development

I switched to Windows 7 64 bit few months back and I upgraded all my tools/SDKs to 64 bit versions including JDK. Suddenly after I updated JDK to 64bit my Eclipse plugin that I use to develop Blackberry applications started giving this error on every start Cannot find RIMIDEWin32Util.dll. This is a required component of the IDE.  Solution to this problem is that install both JDK and Eclipse 32bit versions. And set the following environment variables in Windows JAVAHOME=path to the folder where JDK(32bit) is installed PATH=add path to bin folder of your JDK(32bit)

Android - receiving result from another activity

Its a common operation in Android application to launch new activity all the time. There are times when you want to receive the result from new activity started. For example in one of my recent projects I have to launch settings activity ( SettingsActivity ) to set the mode of application and when this activity is closed it should return the selected mode to the caller activity ( MainActivity ). How child Activity returns result Activity class has a method setResult  which sets the result code to be returned to parent activity. Another overload of setResult  allows you to pass Intent also for any extra data to be sent. In my SettingsActivity I have code like this if (settingsSavedByUser()){     Intent i=new Intent();     i.putExtra("mode","selectedApplicationMode");     setResult(RESULT_OK,i); //RESULT_OK and Intent(i) will be returned to parent }else{     setResult(RESULT_CANCELLED); //RESULT_CANCELLED will be returned to parent } How parent Activity

HTTP POST request in Java

In one blog post I wrote about how we can make HTTP requests and receive response in Java. That post was only about sending GET request. This time we will learn how to make POST (submitting form etc) request in Java.  This post assumes that you are familiar with  HttpURLConnection  found in  java.net  package. If you are not please read this blog post http://random-stuff-mine.blogspot.com/2013/06/http-request-and-response-java.html HTTP POST request Lets say you entered username/password in a website and pressed "Login" button. Most probably the web browser makes a HTTP POST request containing your username/password. A simple POST request would look like this POST /path/to/script HTTP/1.1 User-Agent: RemzyHttpBot Content-Type: application/x-www-form-urlencoded Content-Length: 32   username=rameez&password=test In the above request you see that username and password are sent inside the request body and content-type of request is set to application/x-www-form-

Smart pointers in C++

Using pointers in a program increases the risk of memory and resource leaks. Programmers have to make sure that they always free memory (acquired by new operator) using delete operator. Bare pointers in C++ are not exception safe , they do not get destroyed (release memory) if there is an exception in your program. Smart pointers are helpful to avoid all the problems mentioned above. There are many kinds of smart pointers but in this blog post we will discuss 2 types of smart pointers: unique_ptr and  shared_ptr. What are smart pointers ? Smart pointers are wrapper over a normal C++ pointer. They are objects that store pointer to dynamically allocated objects. They conceptually own the object pointed to, they delete the object as soon as object is no longer required and goes out of scope. Difference between normal and smart pointer The main difference between a normal and smart pointer is that normal pointer do not get deleted unless delete operator is called. On other hand