Search This Blog

Tuesday, August 5, 2014

Bit ly Shorten Url -MVC/C# Code


Server Side Code: 

using System.Text;
using System.Xml;
 public class Utility
    {
         public static string BitlyShortenUrl(string strUser, string strApiKey, string strLongUrl)
         {
             StringBuilder uri = new StringBuilder("http://api.bit.ly/shorten?");
             uri.Append("longUrl=");
             uri.Append(HttpUtility.UrlEncode(strLongUrl));
             uri.Append("&login=");
             uri.Append(HttpUtility.UrlEncode(strUser));
             uri.Append("&apiKey=");
             uri.Append(HttpUtility.UrlEncode(strApiKey));
             uri.Append("&format=xml");

             HttpWebRequest request = WebRequest.Create(uri.ToString()) as HttpWebRequest;
             request.Method = "GET";
             request.ContentType = "application/x-www-form-urlencoded";
             request.ServicePoint.Expect100Continue = false;
             request.ContentLength = 0;
             WebResponse objResponse = request.GetResponse();
             XmlDocument objXML = new XmlDocument();
             objXML.Load(objResponse.GetResponseStream());

             XmlNode nErrorCode = objXML.SelectSingleNode("//errorCode");
             XmlNode nErrorMessage = objXML.SelectSingleNode("//errorMessage");
             XmlNode nShortUrl = objXML.SelectSingleNode("//shortUrl");

             if( nErrorCode.InnerText != "0" )
             {
                 return "Error returned";
             }
             else
             {
                 return nShortUrl.InnerText;
             }
         }
 }

Call From Views:
@{
//Create account in http://bitly.com and collect  API key  from https://bitly.com/a/settings/advanced
      string bitlyShortUrl = "";
      string bitlyLogin="....";
      string bitlyApiKey="....";

      bitlyShortUrl = Utility.BitlyShortenUrl(bitlyLogin, bitlyApiKey, Request.Url.ToString());
      if (bitlyShortUrl == "Error returned")
      {
          bitlyShortUrl = Request.Url.ToString() ;

      }
}
<a href="@bitlyShortUrl">@bitlyShortUrl</a>


Monday, March 31, 2014

Android Network Connection Check


Add below code in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />


Reference :
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.app.Activity;
import android.content.Context;

Function:

public  boolean isNetworkConnected(Activity  activity  ) {
ConnectivityManager connMgr = (ConnectivityManager)activity
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connMgr.getActiveNetworkInfo();

if (ni == null) {
  Toast.makeText(Ac,"No internet connection can be found.", Toast.LENGTH_LONG).show();
return false;
} else
return true;
}
Note: For normal activeity isNetworkConnected(this)

public static final boolean isNetworkConnected(Context  con) {
ConnectivityManager connMgr = (ConnectivityManager)con
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = connMgr.getActiveNetworkInfo();

if (ni == null) {
Toast.makeText(con,"No internet connection can be found.", Toast.LENGTH_LONG).show();
return false;
} else
return true;
}
Note: For Context isNetworkConnected(context)  .i.e. inside OnClickListener

Thursday, March 27, 2014

Summary and code samples for GPS calls and detection :HTML5

The HTML5 Geolocation API is used to get the geographical position of a user. Since this can compromise user privacy, the position is not available unless the user approves it.

Use the watchPosition () method to get the user's position. The example below is a simple Geolocation example returning the latitude and longitude of the user's position:

if (navigator.geolocation) {
    navigator.geolocation.watchPosition(function (pos) {
     
       var lat = pos.coords.latitude;
        var lng = pos.coords.longitude; 
        if (lat != 0) {
            $("#lat").val(lat);// Assign hidden input field
            $("#lng").val(lng); // Assign hidden input field
        }
    });
}
else {
   
    alert( "Geolocation is not supported by this browser.");
   
}

Note : Add this code inside  <script> .....</script>  tag in your page

Example explained:
  • Check if Geolocation is supported
  • If supported, run the watchPosition() method. If not, display a message to the user
  • If the watchPosition () method is successful, it returns a coordinates object to the function specified in the parameter (pos)
  • The pos () function gets the displays the Latitude and Longitude

Handling Errors and Rejections:

For Handling Error We can use below code.
navigator.geolocation.getCurrentPosition(success, error, options);
var options = {
    enableHighAccuracy: true,
    timeout: 50000,
    maximumAge: 0
};

function success(pos) {
    var crd = pos.coords;
};

function error(err) {
    alert('ERROR(' + err.code + '): ' + err.message);

};

C# Send email by using gmail smtp With Attachment

Namespace:

using System.Net;
using System.Net.Mail;

Method Call: 


Sendmail("Subject", "Body", "fromaddress@XXX.YYY", "toaddress@aaa.ccc", "FilePath");

Method:
        public static void Sendmail(string subject, string body, string from, string to, string newFileName)
        {
            MailAddress mailfrom = new MailAddress(from);
            MailAddress mailto = new MailAddress(to);
            MailMessage msg = new MailMessage(mailfrom, mailto);


            Attachment att = new Attachment(newFileName);
            msg.Attachments.Add(att);
            msg.Subject = subject;
            msg.Body = body;
            var client = new SmtpClient("smtp.gmail.com", 587)
           {
                    Credentials = new NetworkCredential("username@gmail.com", "gmailpassword"),
                    EnableSsl = true
             };

            client.Send(msg);
        }

Monday, March 24, 2014

Send Android Push Notifications via GCM(Google Cloud Messaging) By C#.Net


Create Google Api key  and Client ID 

Please go to https://console.developers.google.com/project   and create new project for using api

After creating new project we will get project number which is necessary for future work.
Please select  "APIs" from left site menu which is under "APIs & auth" .

After selecting   "APIs" we will get avaliable api list in right site listview.For doing Android Push Notifications we need to active "Google Cloud Messaging for Android".Please click "OFF" for making "ON"

After Click "OFF"

Create new Client ID :

Please select  "Credentials" from left site menu which is under "APIs & auth"  and Click "Create new Client ID" button from Write side.

Please fillup the popup window.First select "Installed application" and then select "Android". After that insert "Package name" which will come from you android project and also insert  "Signing certificate fingerprint (SHA1)" which is your project SHA1. Please select "Enabled" option and click "Create Client ID".

After that you will get Client Id which will show inside your "Credential" window.


We will use "884643418365-ho8n0fcn161s2p7uucmkeh727989knuf" as Client ID in the C# code and Android code.


Create new Key :

Click "Create new Key " button from Write side. 

And click "Server Key" from popup window.Then another popup window will come and click again "Create " button without fillup anything.

Then we will get Api Key for server applications
We will use "AIzaSyDD0kNEqml-ToGk08RtLT0w0NNT0VjSIok" as Google Api key  in the C# code .

Android Code
Install Google Cloud messaging  for Android Library  from Android SDK Manager.




Add class inside named GCMService (path: >src>com.test.myexample) and add below code


package com.test.myexample;

import java.util.Random;


import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
import com.google.android.gms.gcm.GoogleCloudMessaging;

public class GCMService extends GCMBaseIntentService{

public static   int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
Context ctx;
public GCMIntentService() {
super("884643418365-pl1p16evmgcqe5ib9708qrovn728efgv");
}
 
private static final String TAG = "===GCMIntentService===";
 
 
@Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
}
 
@Override
protected void onUnregistered(Context arg0, String arg1) {
Log.i(TAG, "unregistered = "+arg1);
}
 
@Override
protected void onMessage(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
  ctx = context;
   Log.i(TAG, "new message= "+intent.getExtras().getString("message"));
   
   String message= intent.getExtras().getString("message");
   String title =intent.getExtras().getString("title");
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + intent.getExtras().toString(),title);
Log.i("onReceive","type_error");
else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED .equals(messageType)) {
sendNotification("Deleted messages on server: " + intent.getExtras().toString(),title);
Log.i("onReceive","deleted");
else {
sendNotification(message, title);
Log.i("onReceive","received:"+ intent.getExtras().toString());
}
 
Log.i("onReceive","done");
}
// Put the GCM message into a notification and post it.
private void sendNotification(String msg,String title) {
Random randomGenerator = new Random();
NOTIFICATION_ID = randomGenerator.nextInt(1000);
   mNotificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
   PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, new Intent(ctx, GCMIntentService.class), 0);
  NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(ctx)
 .setSmallIcon(R.drawable.ic_launcher2 )
 .setContentTitle(title)
 .setStyle(new NotificationCompat.BigTextStyle().bigText(msg ))
 .setContentText(msg);
  mBuilder.setContentIntent(contentIntent);
  mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
 
@Override
protected void onError(Context arg0, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
 
@Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}
}

.............................................................................................................................

Add code in AndroidManifest.xml

<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
   <permission android:name="com.wired.mealio.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.wired.mealio.permission.C2D_MESSAGE" />

   Add this code inside application tree of AndroidManifest.xml.
      
       <receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
 
<category android:name="com.test.myexample" />

</intent-filter>
 </receiver>
   <service android:name=".GCMService" />

C# Code 

Call AndroidPush function with  parament message,deviceId,title

Note: Please register your client device by GCMRegistrar  through your android project  and collect device id and save it your own database .

Necessary Reference:
using System.Net;
using System.Text;
using System.IO;



 public static string AndroidPush(string message, string deviceId, string title = "Project Title")
      {

          try
          {

               WebRequest webRequest;
                                                                                               
              var googleApikey = "AIzaSyDD0kNEqml-ToGk08RtLT0w0NNT0VjSIok";                                  
              var clientID = "884643418365-ho8n0fcn161s2p7uucmkeh727989knuf";


              webRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
              webRequest.Method = "post";
              webRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
              webRequest.Headers.Add(string.Format("Authorization: key={0}", googleApikey));
              webRequest.Headers.Add(string.Format("Sender: id={0}", clientID));

              //Data post to server                                                                                                                                      
              string postData =
               "collapse_key=score_update&time_to_live=108&delay_while_idle=1"
               +"&data.message=" + message
               + "&data.title=" + title
               +"&data.time=" + System.DateTime.Now.ToString()
               +"&registration_id=" + deviceId + "";
              Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
              webRequest.ContentLength = byteArray.Length;
              Stream dataStream = webRequest.GetRequestStream();
              dataStream.Write(byteArray, 0, byteArray.Length);
              dataStream.Close();

              WebResponse webResponse = webRequest.GetResponse();
              dataStream = webResponse.GetResponseStream();

              StreamReader streamReader = new StreamReader(dataStream);

              String responseFromServer = streamReader.ReadToEnd();
              streamReader.Close();

              dataStream.Close();
              webResponse.Close();
              return responseFromServer;
          }
          catch (Exception ex)
          {
              return ex.Message;
          }


      }

Monday, March 17, 2014

Call ProgressDialog inside onCreate


  • Add 
             import android.app.ProgressDialog;
  • Declare progress dialog  globally in this page
         ProgressDialog progressDialog;
  • Add some code in the onCreate method before task start
        progressDialog = new ProgressDialog(ClassName.this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setIndeterminate(false);
progressDialog.show(); 
  •      Now you can add you Thread. Write your necessary code inside Thread.After finsih you tast and before leaving Thread,please dismiss your progressDialog.

             new Thread(new Runnable() {
public void run() {
                                              /* Wirte your Codes which take long time and are not in the main
                                                  thread  i.e. HttpClient call
                                                */
                                              progressDialog.dismiss();

}

}).start();

Thursday, March 6, 2014

C# DateTime to Milliseconds Conversion


double milliseconds=0;
milliseconds = [YourDate].ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;