Thursday, December 26, 2013

jQuery Tips: Develop infinite scrolling

[Originally posted on http://onlyms.net]
This simple below JQuery code can use for infinite scrolling. Just look into it, its extremely simple and easy task. Just follow below codes

Java Script
Include JQuery file as below:

< scri pt sr c="js/ jquery-1.10.2.js">

    < sc ript src="js/jquery-1.10.2.min.js">
and java script code as :


        $ ( func tion () {
            $(win dow) .scr oll(fu nction (ev ent) {
                cons ole.log($(".lo ad-more").off set().top < $(wi ndow).scroll Top() + $(win dow).outer Height()); // You can track if result is true or false
                if ($(". load-more").off set().top < $(win dow).scroll Top() + $(window).outer Height() == true) {
                    //Method to load next page
                }
                else {
                    //Do nothing or do as you want
                }
            });
        });
    < / sc ript


CSS section as below, just used for selector. You can update if you need.

        .load-more {
        }
    </ sty l e


HTML part as below:

< d iv>
    < text area style="wi dth: 50%; hei ght: 110vh;">
    This is to fill full screen, so load more button go to invisible section
< / text area>
    < in put clas s="load-more" val ue="load more" typ e="button" />
</ d iv>



Sunday, December 22, 2013

Hello World with SignalR

[Original Post from my blog OnlyMS.Net for better visibility read it from OnlyMS.Net]  

Programming with distributed technology is my passion. Earlier I have worked with Remoting, Socket, Web Service and a bit with WCF. So when I first came to know about SignalR technolog, really I can not wait to start coding on it. Now I can able to write own chat application for AlapMe and really its working fine. Most of all by using SignalR I can use socket of HTML5. I shall write multiple posts on SignalR as tutorial as I did in past with C# Socket programming. I shall publish these posts on this blog and on my socket programming blog as well.

I have started SignalR programming with Visual Studio Express 2013 which is freely downloadable from here. Also you can read full documentation from Microsoft from this link. As my target to share some practical example with ready to use code hence I shall not describe in detail about the technology. You can follow Microsoft documentation website for it. 

To start with SignalR first coding you need to follow steps are below.
Lunch your VS 2013 and create a blank project and add new item of SignalR Hub Class (v2) set its name as you wish, for my case its MyHub.cs. When you will add this class Visual Studio automatically add all related references and jquery classes. To add these things it may take some time may be 2-3 minutes. This new item will come with a sample method 'Hello()', for now just follow these later I shall describe what is these things and why these are. Full code will look like below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalR_Learning
{
    public class MyHub : Hub
    {
        public void Hello()
        {
            Clients.All.hello();
        }
    }
}


Now go to next step and add next item in project, that is OWIN Startup class. I am giving its default name 'Startup1.cs' for my sample project. Visual Studio will create this file with some pre-added code. We will extend these code as per your needs. Code as below:

 

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(SignalR_Learning.Startup1))]
namespace SignalR_Learning
{
    public class Startup1
    {
        public void Configuration(IAppBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
        }
    }
}
 In method Configuration I shall add just a line of code 'app.MapSignalR();' so full method will look like:

 

public void Configuration(IAppBuilder app)
{
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
    app.MapSignalR();
}
 Now we will move to front end coding and this part will develop with simple HTML page, however you can use ASPX page as well. Now I have added a HTML page with name 'index.html'

  < me ta http-equiv="X-UA-Compatible" content="IE=edge" / >

    < ! --Script references. -->
    < ! --Reference the jQuery library. -->
    < s cript src="Scripts/jquery-1.10.2.js">< / scr ipt>
    < s cript src="Scripts/jquery-1.10.2.min.js">< / scr ipt>   
    < s cript src="Scripts/json2.js"></ scr ipt>
    < ! --Reference the SignalR library.  - - >
    < s cript src="Scripts/jquery.signalR-2.0.0.js">< / scr ipt>
    < s cript src="Scripts/jquery.signalR-2.0.0.min.js">< / scri pt>
    < ! --Reference the autogenerated SignalR hub script. - - >
    "/signalr/hubs">
    < ! --Add script to update the page and send messages.-- >

 < s cript type="text/java scri pt" >

        var chat;
        $(function () {
            // Declare a proxy to reference the hub.
            //chat = $.hubConnection.myhub;
            chat = $.connection.myhub;
            //alert(chat);
            chat.client.hello = function (message) {
                alert(message);
            };
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#btnhello').click(function () {                   
                    alert(chat);
                });
            });
        });
< / scr ipt> 
 < in put ty pe="button" value="Hello" id="btnhello" / >

 

 Thank you for visiting my blog.

 

Monday, December 16, 2013

Mobile App development with PhoneGap

[Original Post from my blog OnlyMS.Net]

I am now starting to get into mobile app development and to start mobile app development using a suitable tool, I choose PhoneGap. I choose PhoneGap because to develop mobile app using PhoneGap I do not need to learn anything new as I know HTML, JavaScript, CSS and these things are using here to develop any mobile app for iOS, Android, Windows, Blackberry, Bada etc mobile OS.

To start PhoneGap first install node.js from here.
Next go to command line in your windows and type following (link here)
C:\> npm install -g phonegap

It will start installing the software.


Read full learning from here and can read basic stuff from  here.

Tuesday, November 26, 2013

jQuery Ajax: Create HTML Table with User details at Client based on Server Data

[This post initially posted on my MS Technical blog here. Visit http://onlyms.net for better readability]. 

I am sharing information on JQuery-AJAX on ASP.Net in incremental order to learn it properly. In last post on this topic I shared information about how to change some HTML control based on server data using jQuery. Now I shall share information how to create a user data list or table with some data which is coming from server. Here I am taking example of some user data with one image. In my project I am using one sample JPG image with IMG folder in project (available in 1st post attached project on that topic). 

Step 1: Create back-end server code to provide data. Look carefully at below server code to prepare a web-service [webmethod] method.


[WebMethod]public static string CreateUserList(){        List<object> user = new List<object>();        user.Add(new { Id = "10", Name = "A", Image = "img/sample.jpg" });        user.Add(new { Id = "20", Name = "B", Image = "img/sample.jpg" });        user.Add(new { Id = "30", Name = "C", Image = "img/sample.jpg" });        user.Add(new { Id = "40", Name = "D", Image = "img/sample.jpg" });
        return (new JavaScriptSerializer().Serialize(user));
}
In the above code I am creating a List object with property ID, Name and Image. For my case ID and Name is different but all are same image. In real life project you can change it with some different image name. I am adding these user data into List object and finally I am serializing the array/list to send it to client as JSON data format.  Using below line of code:

return (new JavaScriptSerializer().Serialize(user));
Step 2: Prepare HTML section as below:
< fo rm id="form1" runat="server">    
        jQuery Ajax: Create HTML Table with User details at client based on server data.


        
        < t able id="tblList">
        
        "btnClick" type="button" value="Click Me!" />    

In this HTML code I have declared a HTML Table where I shall append rows to design a table with server provided user data. The button will be used to invoke server method using JQuery. HTML section is extremely easy and simple.

Step 3: Invoke server webmethod/web service using JQuery AJAX.



"server">
"js/jquery-1.9.1.js">

< scr ipt type="text/javasc ript">    $(document).ready(function () {
        $("#btnClick").click(function () {
            $.ajax({                type: "POST",                url: "ArrayToList.aspx/CreateUserList",             
                contentType: "application/json; charset=utf-8",                dataType: "json",
                success: function (msg) {
                    var user = eval(msg.d);                    $.each(user, function () {                        $("#tb lList").app end("
User Id: "
+ thi s.Id + ",Name:"
+ this.Name + "< i m g al t= '' hei ght ='100' sr c='"
+ this.Image + "' /></ t r>");                    });                }            });        });    });
</ he ad>

Here I am coping full HEAD section where I have called JQuery 1.9.1 and then have written JQuery code (to know more about these part on each step by step from here). Here I am calling 'CreateUserList' web method and on successful AJAX call 'Success:' will executed where main table design will performed.
All JSON data will come at client as serialized and it will be parsed by eval() method based on message's properly. Next it will start looping with 'each' method will concatenate string with column value like 'this.Id','this.Name','this.Image'. Here need to note that Id, Name and Image was the column/parameter name in List. Finally this concatenated string is adding or appending at as row in declared table.

The whole thing will look like below image in browser.



Get source code from below attached files.
Thank you for reading my blow, please comeback again for next post, how to create a user search list as like facebook.

Saturday, November 16, 2013

JQuery-AJAX: Change a HTML control name from server



I want to share a very basic and simple but a bit advance sample code on ASP.Net Ajax using JSON and JQuery. Now I want to change a control name or text based on server response data.

To demonstrate this thing I shall change my clicked button name based on server. This type of sample code is very easy to learn and you can use similar concept to develop solution for lots of requirement. Say you are developing some code where you have a button to 'Like' but after clicking on it the button  name will change to 'Unlike', or in a social network one user will start following some group or person; so when user will click on 'Follow' button will be changed to 'Following' etc.
Lets have a look in to the code:

HTML for this solution as below -
in put id="btnClick" type="button" value="Click Me!"

Here button 'btnClick' text will be changed. Next look into the back-end C# code.


[WebMethod]
public static string ChangeButtonNameJQuery(string btnName)
{     
      return btnName+ " - changed from Server";
}



Very simple Web Method or WebService in page 'ChangeButtonName.aspx'. To declare a page method as WebService we need to use namespace 'System.Web.Services', which I have used in using namespace section. Besure this method is 'static' type and its 'public'. Return type of webservice is string and invoking with one string parameter 'btnName'.

Now look at the jQuery code.



"js/jquery-1.9.1.js">
"text/javascript">
      $(document).ready(function () {
            $("#btnClick").click(function () {               
                
                $.ajax({
                    type: "POST",
                    url: "ChangeButtonName.aspx/ChangeButtonNameJQuery",
                    data: JSON.stringify({ btnName: $("#btnClick").val() }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {                       
                        $("#btnClick").val(msg.d);                       
                    }
                });
            });
        });

I have used here Jquery version 1.9.1 and calling my method when document becomes ready to execute which will call just after loading completion of page.



$(document).ready(function ()
{
}

the above code is doing this thing (to know details about Jquery Ajax calling from ASP.Net, read my 1st post on Jquery-Ajax). In my present code We are calling web method 'ChangeButtonNameJQuery' from current page (ChangeButtonName.aspx/ChangeButtonNameJQuery). Once successful web method execution client browser is getting response and invoking method 'success:' with response in object 'msg'. We can access server response from 'msg' property 'd' by using 'msg.d' and that I am setting to change button value, by


$("#btnClick").val(msg.d);

I hope you have enjoyed this post and has helped to learn little more on ASP.Net ajax using JQuery. Continue reading my next blog post to know more on Ajax using JQuery.

Thank you for visiting my blog. Happy coding.

Wednesday, November 13, 2013

JQuery-AJAX:Pass two parameters and concatenate two string at server side with ASP.Net

[Original Post from my another blog] - visit it for better design and reading friendly.

This is advance article of my previous post on JQuery-AJAX in ASP.Net JQuery-AJAX: Get Server Time using jQuery AJAX in ASP.Net. In earlier post I have describe how to get server time using ASP.Net with Jquery ajax technology. How I shall describe little bit advance things, that is how to pass two parameter from client and catch these values in server then concatenate in server and response result to client to show it.

Step 1: As previous declare a webmethod or webservice at backend.

[WebMethod]
    public static string ConcateName(string fname,string lname)
    {
        return fname +" "+lname;
    }

Note here I have passed two parameter with name 'fnale' and 'lname'. In JQuery you have to invoke method with exactly same name of parameter otherwise code will not run.

Step 2: Declare HTML control, tow text box, a button and a DIV to show server response. (visit my primary blog for better view of HTML and JQuery).

For 'First Name' input HTML id="txtFName" type="text".
Last Name: input id="txtLName" type="text" and a button.    
with id="btnClick" type="button" value="Concat Name".
And response in a DIV with id="dvResponse".

 Step 3: Write JQuery code in ASPX page as below:

        $(document).ready(function () {
            $("#btnClick").click(function () {
                //alert($("#txtFName").val());
                $.ajax({
                    type: "POST",
                    url: "ConcatName.aspx/ConcateName",
                    data: JSON.stringify({ fname: $("#txtFName").val(), lname:$("#txtLName").val() }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        $("#dvResponse").append(msg.d+"
"
);
                        //$("#dvResponse").html(msg.d);
                    }
                });
            });
        });
    
 Note here most important two lines as below:

url: "ConcatName.aspx/ConcateName",
data: JSON.stringify({ fname: $("#txtFName").val(), lname:$("#txtLName").val() }),


First line is describing which WebService should invoke and next line the parameter for webservice. Note here I have mentioned exactly same name of WebService parameter.

When you will run this code and type value in two text box and then click on button, browser will invoke server WebService and concatenate two name and then response to server. Which will catch by JQuery ajax part and result will be shown in DIV 'dvResponse'.
How you have enjoyed my post and it has helped for your learning on JQuery AJAX technology in ASP.Net-C#.

Tuesday, November 5, 2013

JQuery-AJAX: Get Server Time using jQuery AJAX in ASP.Net

[Original post from my blog http://onlyms.net//]

Friends, Now I want to share my codes with on ASP.Net AJAX by using jQuery. Earlier I have worked with UpdatePanel for AJAX work but it seems to this is not the best approach however its most easiest and simplest way for AJAX. So when you do not need maximum performance then definitely you can consider it to save time. But if you need maximum performance then my recommendation always jQuery AJAX. I shall share my blog post for AJAX work using jQuery and JSON with ASP.Net and C# with sample code which will help reader to learn this technology very easily.

In my first post I shall show how to get server time using jQuery with AJAX that means without page post back.


Step 1: Create a WebService which will response to client to inform server time. WebService as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
public partial class GetTime : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod]
    public static string GetDate()
    {
        string str="[Response from Webservice]
Current Server Time is: "+ DateTime.Now.ToString() + "." + DateTime.Now.Millisecond.ToString();
        return str;
    }   
}

Nothing more require at back-end now I shall show at front end part of code.Full back-end code as below:
Note to declare a WebService first we have use namespace 'using System.Web.Services;' and then have declared method as '[WebMethod]'

Step 2: Declare a HTML button for clicking and a DIV to show server response.

Step 3: Set jQuery Part. Here first need to link jquery code which I am using version jquery-1.9.1.js and I have placed at my project at js folder. 

Step 4: Write jQuery code to access WebService. First look into the code next I am trying to clarify about these code.

JavaScript Script as below:
        $(document).ready(function () {
            $("#btGetDate").click(function () {               
                $.ajax({
                    type: "POST",
                    url: "GetserverTime.aspx/GetDate",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {                       
                        $("#dvDate").html(msg.d );
                    }
                });
            });
        });
This code will be activated when document becomes ready and when we will click on button 'btnGetDate' these next code will start execution using AJAX technology. Its sever calling type will be 'POST' and it will try to invoke 'GetDate' webservice will has created under 'GetserverTime.aspx' page and it's type will be JSON as describe next line.Once server response will receive successfully this code will go for next section 'success:function...' and jQuery will set server response at our declared DIV element 'dvDate'. From next post I shall not mention jQuery AJAX declaration in so detail and will discuss on main section only. Server response will show like below screenshot:

Get full source code with better alignment of blog from my blog.

Sunday, August 4, 2013

Lossless Image Compression in C#.Net and VB.Net

Last time I shared C# code which can resize an image with desired size by keeping same Height vs. Width ratio. Now I am going to share next step of image processing code, which can compress an image without (almost) losing it quality. 

Usually an image which you may have taken from one 10 Mega pixel digital camera generates image around 5MB file size. To store same size in webserver and showing it in user’s desktop will slowdown users website browsing experience. For that reason now all website especially photo sharing and social network websites, like facebook.com or google plus etc. compress these images in smaller file size without losing image quality and store in webserver. This technique saves webserver storage and saves network bandwidth when user opens these.

Here I am sharing one method which has written in C# and VB.Net code (base code found somewhere in google then I updated as I need). This method can invoke by just one single line of code and can get compressed image.


How can I use this code in my application?


To use/invoke this method:

CompressJPEGImage(Bitmap Image, Image Name With Full Path)

To use this method you need to create an object of the class where you will define this method and then need call it with parameters ‘image object’ and ‘image full name with path’ where compressed will be saved. On successful compression this method will return 'true' else 'false'.

In my application I have written two overload methods to save the compress image and sometimes to get compressed image object as a return of the method as based on my requirement. 

Full code in C#.Net as below:

  public bool CompressJPEGImage(Bitmap bmp1, string tempImgNameWithPath)

    {
        ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);

        // for the Quality parameter category.
        System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;

        EncoderParameters myEncoderParameters = new EncoderParameters(1);
        EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 75L);
        myEncoderParameters.Param[0] = myEncoderParameter;
        try
        {
            bmp1.Save(tempImgNameWithPath, jgpEncoder, myEncoderParameters);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

Full code in VB.Net as below:

Public Function CompressJPEGImage(bmp1 As Bitmap, tempImgNameWithPath As String) As Boolean
 Dim jgpEncoder As ImageCodecInfo = GetEncoder(ImageFormat.Jpeg)

 ' for the Quality parameter category.
 Dim myEncoder As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.Quality

 Dim myEncoderParameters As New EncoderParameters(1)
 Dim myEncoderParameter As New EncoderParameter(myEncoder, 75L)
 myEncoderParameters.Param(0) = myEncoderParameter
 Try
  bmp1.Save(tempImgNameWithPath, jgpEncoder, myEncoderParameters)
  Return True
 Catch generatedExceptionName As Exception
  Return False
 End Try
End Function


How can I change image quality and generated size based on my requirement?

For my application I have compressed 75% (75L) but you can change it as per your requirement. If you increase this value then file size and image quality both will increase. Run this code with different parameter value and get image as per your requirement.

Thanks for reading my blog I hope this code will help you to write code.

Sunday, July 28, 2013

Lossless image resize in C# by keeping same aspect ratio.

Now I am developing an image sharing and Indian social network application (www.Alap.Me) where I need to resize image (JPG for my case). This is a very common situation to all coders and it helps us if we get some readymade method which can serve our purpose. I found basic code of this somewhere from Google and later I modified it as I need and finally developed this code.
This code can resize any image by keeping aspect ratio, so your image always will be same in width vs. height ratio.

How to use it?


This is very easy to use this code; just you need to call it with image file name with full path and maximum height and width. My code automatically detects height or width, which is maximum at your parameter and based on this, code will set another parameter based on aspect ratio and finally resize your image.

ResizeImage(fileLocationWithName, maxWidth, maxHeight);

Complete Code in C#.Net


   public Bitmap ResizeImage(string fileNameWithPath, int maxWidth, int maxHeight)
    {        
        FileStream stream = new FileStream(fileNameWithPath, FileMode.Open);
        Stream streamImage = (Stream)stream;
        Bitmap originalImage = new Bitmap(streamImage);
        int newWidth = originalImage.Width;
        int newHeight = originalImage.Height;
        double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
         if (aspectRatio > 1 && originalImage.Width > maxWidth)
        {            
            newWidth = maxWidth;            newHeight = (int)Math.Round(newWidth / aspectRatio);
        }        
        else 
            if (aspectRatio <= 1 && originalImage.Height > maxHeight)
            {            
                newHeight = maxHeight;            newWidth = (int)Math.Round(newHeight * aspectRatio);
            }         
        Bitmap newImage = new Bitmap(originalImage, newWidth, newHeight);
        Graphics g = Graphics.FromImage(newImage);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;

        g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);         

        originalImage.Dispose();        
        stream.Close();        
        stream.Dispose();        
        return newImage;
    }


Complete code in VB.Net:

Public Function ResizeImage(fileNameWithPath As String, maxWidth As Integer, maxHeight As Integer) As Bitmap
 Dim stream As New FileStream(fileNameWithPath, FileMode.Open)
 Dim streamImage As Stream = DirectCast(stream, Stream)
 Dim originalImage As New Bitmap(streamImage)
 Dim newWidth As Integer = originalImage.Width
 Dim newHeight As Integer = originalImage.Height
 Dim aspectRatio As Double = CDbl(originalImage.Width) / CDbl(originalImage.Height)

 If aspectRatio > 1 AndAlso originalImage.Width > maxWidth Then
  newWidth = maxWidth
  newHeight = CInt(Math.Round(newWidth / aspectRatio))
 ElseIf aspectRatio <= 1 AndAlso originalImage.Height > maxHeight Then
  newHeight = maxHeight
  newWidth = CInt(Math.Round(newHeight * aspectRatio))
 End If

 Dim newImage As New Bitmap(originalImage, newWidth, newHeight)

 Dim g As Graphics = Graphics.FromImage(newImage)
 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear
 g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height)

 originalImage.Dispose()
 stream.Close()
 stream.Dispose()

 Return newImage
End Function

I have compressed attached picture by using my code and see here difference.
This is after re-size (around 30KB)



This is original size photo (around 5MB)

























I hope this will help you to make easier your coding. Thank you for reading my blog.