Search This Blog

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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>


Thursday, March 27, 2014

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;
          }


      }

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;

Tuesday, September 18, 2012

Populate drop down list with XML in C#

Create XML File  named CollectionModeinSales.xml in root folder:

<?xml version="1.0" encoding="utf-8" ?>
<CollectionModes>
  <CollectionMode>
    <text>Cash</text>
    <value>Cash</value>
 
</CollectionMode>
  <CollectionMode>
    <text>Cheque</text>
    <value>Cheque</value>
  </CollectionMode>

  <CollectionMode>
    <text>D.D</text>
    <value>D.D</value>
  </CollectionMode>

  <CollectionMode>
    <text>TT</text>
    <value>TT</value>
  </CollectionMode>

  <CollectionMode>
    <text>Credit</text>
    <value>Credit</value>
  </CollectionMode>

</CollectionModes>





Add asp:DropDownList in ASPX file

 <asp:DropDownList ID="ddlCollectionType" runat="server" Width="106px">
                                                                   </asp:DropDownList>

C# Code behind file:

            DataSet dsCollectionType = new DataSet();
           
    dsCollectionType.ReadXml(AppDomain.CurrentDomain.BaseDirectory + "CollectionModeinSales.xml");
    ddlCollectionType.DataSource = dsCollectionType.Tables[0];
    ddlCollectionType.DataTextField = "text";
    ddlCollectionType.DataValueField ="value";
    ddlCollectionType.DataBind();