Latest News

Thursday, November 19, 2015

Crop and Upload Image with Thumbnail using jQuery and HTML5 in ASP.Net


This following code will help to crop image before upload in asp.net C#

HTML Markup

<input type="file" id="FileUpload1" accept=".jpg,.png,.gif" />
<br />
<br />
<table border="0" cellpadding="0" cellspacing="5">
    <tr>
        <td>
            <img id="Image1" src="" alt="" style="display: none" />
        </td>
        <td>
            <canvas id="canvas" height="5" width="5"></canvas>
        </td>
    </tr>
</table>
<br />
<input type="button" id="btnCrop" value="Crop" style="display: none" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" Style="display: none" />
<input type="hidden" name="imgX1" id="imgX1" />
<input type="hidden" name="imgY1" id="imgY1" />
<input type="hidden" name="imgWidth" id="imgWidth" />
<input type="hidden" name="imgHeight" id="imgHeight" />
<input type="hidden" name="imgCropped" id="imgCropped" />


Scripts


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.rawgit.com/tapmodo/Jcrop/master/js/jquery.Jcrop.min.js"></script>
<script type="text/javascript">
$(function () {
    $('#FileUpload1').change(function () {
        $('#Image1').hide();
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#Image1').show();
            $('#Image1').attr("src", e.target.result);
            $('#Image1').Jcrop({
                onChange: SetCoordinates,
                onSelect: SetCoordinates
            });
        }
        reader.readAsDataURL($(this)[0].files[0]);
    });
    $('#btnCrop').click(function () {
        var x1 = $('#imgX1').val();
        var y1 = $('#imgY1').val();
        var width = $('#imgWidth').val();
        var height = $('#imgHeight').val();
        var canvas = $("#canvas")[0];
        var context = canvas.getContext('2d');
        var img = new Image();
        img.onload = function () {
            canvas.height = height;
            canvas.width = width;
            context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
            $('#imgCropped').val(canvas.toDataURL());
            $('[id*=btnUpload]').show();
        };
        img.src = $('#Image1').attr("src");
    });
});
function SetCoordinates(c) {
    $('#imgX1').val(c.x);
    $('#imgY1').val(c.y);
    $('#imgWidth').val(c.w);
    $('#imgHeight').val(c.h);
    $('#btnCrop').show();
};
</script>

Code Behind .cs




protected void Upload(object sender, EventArgs e)
{
    string base64 = Request.Form["imgCropped"];
    byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
    using (FileStream stream = new FileStream(Server.MapPath("~/Images/Cropped.png"), FileMode.Create))
    {
        stream.Write(bytes, 0, bytes.Length);
        stream.Flush();
    }
}

Monday, August 3, 2015

Simple way to implement GCM

 Just follow these you will implement GCM



Step 1: Registering with Google Cloud Messaging

       a.Goto Google APIs Console page and create a new project. (If you haven’t created already otherwise it will take you to dashboard)

       b.After creating project you can see the project id in the url. Note down the project id which will be used as SENDER ID in android project. (Example: in #project:00000000 after semicolon 460866929976 is the sender id)
Step 1:Register device with GCM Server

Register the device which is going to receive notification from GCM

    /*GCM*/
    GoogleCloudMessaging gcm;
    String regId = "", err = "";
    private String PROJECT_NUMBER = "............";



    public class AsyncTaskGCMRegister extends AsyncTask<String, String,String> {
        String UserEmail="";
        @Override
        protected void onPreExecute() {
        }
        @Override
        protected String doInBackground(String... arg0) {
            try {
                if(!mUserName.getText().toString().equals("")&&!mUserName.getText().toString().equals(null))
                    UserEmail=mUserName.getText().toString();
                else {
                    sharedPref = getActivity().getSharedPreferences(getResources().getString(R.string.tagUserPrefSession), 0);
                    UserEmail= sharedPref.getString("username", null);
                    if(UserEmail==null||UserEmail=="")
                        UserEmail="N/A";
                }
                /*GCM  TRY & CATCH*/
                gcm = GoogleCloudMessaging.getInstance(getActivity());
                try {
                    if (!checkPlayServices())
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(getActivity(), "Google Play Services not su
pported. Please install and configure Google Play Store.", Toast.LENGTH_LONG)
                                        .show();
                            }
                        });
                    else {
                        Log.d("IM", "registration thread happening");
                        regId = gcm.register(PROJECT_NUMBER);
                        Log.d("IM", "id: " + regId);
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                /*Toast.makeText(getActivity(), "Play Store.", Toast.LENGTH_LONG)
                                        .show();*/
                                new AsynchroTask(getActivity(), getResources().getString(R.string.tagGCMSaveDevice))
                                        .execute(getResources().getString(R.string.GCMSaveDeviceUrl) + UserEmail + "/" + regId + "/" + "M");
                            }
                        });
                    }
                } catch (Exception e) {
                    err = e.toString();
                    Log.d("IM register", "io exception: ");
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String strFromDoInBg) {
        }
    }

     private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
        if (resultCode != ConnectionResult.SUCCESS) {
            return false;
        }
        return true;
    }


Step 2:Android Manifest.xml

Add the permission,receiver and service for GCM


    <permission
        android:name="{package name}.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="{package name}.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.READ_OWNER_DATA" />

    <!--GCM-->
        <receiver
            android:name=".Utils.GcmBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND"
            android:enabled="true">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="**PackageName**" />
            </intent-filter>
        </receiver>
        <service android:name=".Utils.GCMIntentService"
            android:enabled="true"/>
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />



Step 3:GcmBroadcastReceiver.Java

    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.support.v4.content.WakefulBroadcastReceiver;
    import android.widget.Toast;
   
    /**
     * Created by jayaprakash.s on 7/16/2015.
     */
    public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
   
        @Override
        public void onReceive(Context context, Intent intent) {
            //Toast.makeText(context, "GCMIntent Service Successful!", Toast.LENGTH_LONG).show();
            // Explicitly specify that GcmIntentService will handle the intent.
            ComponentName comp = new ComponentName(context.getPackageName(),
                GCMIntentService.class.getName());
            // Start the service, keeping the device awake while it is launching.
            startWakefulService(context, (intent.setComponent(comp)));
            setResultCode(Activity.RESULT_OK);
        }
    }



Step 4: GCMIntentService.Java


    /**
     * Created by jayaprakash.s on 7/16/2015.
     */

    import **PackageName**.MainActivity;
    import **PackageName**.R;
    import **PackageName**.helperclass.NotificationHandler;
    import com.google.android.gcm.GCMBaseIntentService;
    import com.google.android.gms.gcm.GoogleCloudMessaging;


    import android.app.IntentService;
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.media.RingtoneManager;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v4.app.NotificationCompat;
    import android.support.v4.app.TaskStackBuilder;
    import android.util.Log;

    import java.util.logging.Handler;
    import java.util.logging.LogRecord;

    public class GCMIntentService extends GCMBaseIntentService {
        static int count = 0;

        public GCMIntentService() {
            super("GcmIntentService");
        }

        @Override
        protected void onError(Context arg0, String error) {
            Log.d("ApphoshiesFramework", "onError: " + error);
        }


        @Override
        protected void onRegistered(Context context, String regId) {
            Log.d("ApphoshiesFramework", "onRegistered: " + regId);
            //DeviceToken.registerDeviceForGCM(context, regId);
        }


        @Override
        protected void onUnregistered(Context context, String regId) {
            Log.d("ApphoshiesFramework", "onUnregistered: " + regId);
            //DeviceToken.unregisterDeviceFromGCM(context, regId);
        }


        @Override
        protected void onMessage(Context context, Intent intent) {
            Log.d("ApphoshiesFramework", "onMessage");

            // Please customize!
            // This is how to get values from the push message (data)
            String message = intent.getStringExtra("message");
            if(!message.equals("")&&!message.equals(null)){
            long timestamp = intent.getLongExtra("timestamp", -1);
            if (!message.equals("") && !message.equals(null)) {
                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
           
                Intent resultIntent = new Intent(context, MainActivity.class);
                 resultIntent.putExtra("GCM", message);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addParentStack(MainActivity.class);
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPending = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                  Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Bitmap notificationLargeIconBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.app_icon);
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                    .setAutoCancel(true)
                    .setSound(uri)
                    .setVibrate(new long[]{1000, 1000})
                    .setColor(context.getResources().getColor(R.color.ecstasy))
                    .setLargeIcon(notificationLargeIconBitmap)
                    .setSmallIcon(R.drawable.app_icon, 5) // notification icon
                    .setContentTitle("Notification") // main title of the notification
                    .setContentText(message) // notification text
                    .setContentIntent(resultPending);
                  NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
                bigTextStyle.setBigContentTitle("Notification");
                bigTextStyle.bigText(message);
                mBuilder.setStyle(bigTextStyle);
                notificationManager.notify(5, mBuilder.build());
            }
            }
        }
    }