Jquery keypress event handler

Written by Cagdas Erman AFACAN on 05/02/2013 Categories: Javascript, JQuery Tags: , , , ,

JQuery keypress event for numeric control

$("your-css-selector").keypress(function (event) {

     // Sign control - +
     if (event.which < 43 || event.which > 57) {
         event.preventDefault();
     }

     // Is Numeric Control except , .
     if ((event.which == 43 || event.which == 45) ) {
         event.preventDefault();
     }
});
No Comments

jQuery Indicator plug-in

Written by Cagdas Erman AFACAN on 01/25/2013 Categories: Javascript, JQuery, Uncategorized Tags: , , , , ,

Indicator plug-in is in version 1.0 which is really simple and useful.

First you must add scripts between head tags.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js "></script>

and then JQuery Indicator

<script type="text/javascript">// <![CDATA[
/* File Created: October 4, 2012      Author: CagdaşsErman AFACAN     Web: http://www.codemein.net     Plug-in Name: Infdicator     Description: This plugin is used to show and hide loader image when you do mouse request that you decide. */ (function ($) {     $.fn.indicator = function (options) {         // Create some defaults, extending them with any options that were provided         var settings = $.extend({             'path': '',                 'width': '20px',                 'height': '20px',                 'callBack': function () {}         }, options),             loaderObj = settings.path.length > 0 ? $("<img id='loader' src='" + settings.path + "' style='width:" + settings.width + "; height:" + settings.height + ";' alt='loader' />") : $("<span id='loader'>Loading...<span/>");

        return this.each(function () {
            var obj = $(this);

            if (obj.attr('type') !== "checkbox") {
                // Click event binding           
                obj.bind('click', function () {
                    obj.after(loaderObj);
                    obj.attr("disabled", "true");
                     debugger;
                    if (typeof (settings.callBack) === "function") {
                        settings.callBack();
                    }
                });
            } else if (obj[0].nodeName === "INPUT" && obj.attr('type') === "checkbox") {
                // Click event binding           
                obj.bind('change', function () {
                    obj.after(loaderObj);
                    obj.attr("disabled", "true");
                     debugger;
                    if (typeof (settings.callBack) === "function") {
                        settings.callBack();
                    }
                });
            }

        });

    };

})(jQuery);

//This is the function can be called after your job done to clean indicator from UI. Feel free to change selector (.pirpir) with yours.
function cleanIndicator() {
    var loaders = $("img#loader , span#loader");

    loaders.remove();
    $(".pirpir").removeAttr("disabled");
};
// ]]></script>

Now all you need to do is activate Indicator plug-in with code below.
For an example I requested Twitter api to get my (@Climberman) tweet dates

//HOW TO USE IT
$(".pirpir").indicator({
    'path': 'http://www.loadinfo.net/images/preview/33_ball_two_24.gif?1200916238',
     'callBack': function () {
        $.ajax({
            url: 'http://api.twitter.com/1/statuses/user_timeline.json/',
            type: 'GET',
            dataType: 'jsonp',
            data: {
                screen_name: "climberman",
                include_rts: true,
                count: 10,
                include_entities: true
            },
            success: function(data, textStatus, xhr) {
                debugger;
                var i=0;
                for(;  i < data.length; i++ ){
 					$('#result').append(data[i].created_at + "<br/>");      
                }
            }   
 
        }).done(function(){cleanIndicator()});
    }
});

Without callback param it looks more simple then previous.

$(".pirpir").indicator({
    'path': 'http://www.loadinfo.net/images/preview/33_ball_two_24.gif?1200916238', /*Path is the indicator img link*/
});

Anyway you can use the Indicator plugin as you wish. I also give

DEMO

on JsFiddle

No Comments

Asynchronous Foreach loop Javascript

Written by Cagdas Erman AFACAN on 01/11/2013 Categories: Javascript Tags: , , , ,

Javascript is really fast language to process something except dom operations. Dom operations are getting the UI slower and makes it hiccup.

Tired browser

In order to do browser rendering much more faster. You should give a time to catch it’s breath. If you are familiar with programming on C# “Thread.Sleep(500)” which means sleep for 500 milliseconds meanwhile CPU rests for 500 ms and exactly does catching breath to the cpu.

It is same with browser if you are reaching to html dom a lot then you should give the browser some time to rest and render previous actions on dom. In order to do that.

 


/***************************************************************
* Async For looper
* USAGE: asynchForeach(startIndex, array,  miliseconds, callbackfunc);

****************************************************************/
var asynchForeach = function (i, arr, msec, callBack) {
setTimeout(function () {
if (typeof (arr[i]) === "function") {
arr[i].call();
}

//do iteration
if (i < arr.length - 1) {
asynchForeach(i+1, arr, msec, callBack);
return;
}
else if (typeof (callBack) === "function") {
callBack();
}
}, msec);
}

Example in JSFiddle

Hope you liked it and feel free to comment out below.

 

No Comments

New Vacancies in Triodor

Written by Cagdas Erman AFACAN on 12/06/2012 Categories: Android Developer, Flash Developer, Iphone Developer, Vacancy Tags: , , , ,

Hi everybody those links below are new vacancies of my company in Turkey. Links have details inside.

Cheers guys.

No Comments

Asp.Net MVC 3.0 Convertion of Synch Action to Asynch

Written by Cagdas Erman AFACAN on 10/23/2012 Categories: ASP.NET, C#, MVC Tags: , , , ,

Converting Synchronous Action Methods to Asynchronous Action Methods

I have been working with asp.net for 5 years and for the first time. I am having problems with iis and .net when concurrency got involved.

my current project is a real time app which serves to Metal Exchange people. So that the system have to handle for 500ms request period to 1000 concurrent users. But the think is .net sucks at that. I used Mongodb to make it faster when i get and format data in action (mongodb .net client is not so efficient) and it couldn’t handle our heavy requests then i tried Memcached for the same reason which i did by  mongodb. It did not work either but better than mongodb so i decided to use memcached.

Now i am sure of one think you should not do any kind of heavy operations on iis when the concurrency get involved because iis can barely response 60 at the sametime. There is one thing you can do is converting your synchronous actions  to async  then maybe iis can handle 1000 unfortunately.

Classical Action of Yours

public class PortalController: Controller {
    public ActionResult News(string city) {
        NewsService newsService = new NewsService();
        ViewStringModel headlines = newsService.GetHeadlines(city);
        return View(headlines);
    }
}

Asynch Action Sample

First  change your controller base with asynch controller and then devide your action two partitions one is {yourActionName}Asynch and {yourActionname}Completed

public class PortalController : AsyncController {
    public void NewsAsync(string city) {

        AsyncManager.OutstandingOperations.Increment()
        ... //do your operations
        AsyncManager.Parameters["parametesOfYours"] = your operations result
        AsyncManager.OutstandingOperations.Decrement();

    }

    public ActionResult NewsCompleted(object headlines) {
        return View("News", new YourViewModel
        {
            NewsHeadlines = headlines
        });
    }
}

I hope this will save your project :P and also before i forget, you can try to increase the number of iis worker threads from iis configurations that might be help as well.

No Comments

.Net To Json Resource File Convertion

Written by Cagdas Erman AFACAN on 05/14/2012 Categories: ASP.NET, C#, MVC Tags: , , , ,

In my current project i needed to use lots of ajax calls because %80 percent of the project is based on javascript so i had to use resource files at javascript files. In order to do that i had to convert my resource file to JSON somehow.

Function below provides you to get JSon data typed of user culture resource file. My resource file names are like ResourceMetal.en.resx”. Function  has a parameter which is user culture like “en-EN” , “tr-TR” etc… 

public string GetResourcesJavaScript(string culture)
{
      _resource = new Dictionary<string, string>();
      culture = culture.Substring(0, 2);

      if (culture == "en")
          culture = string.Empty;
      else
          culture = "." + culture;

      ResXResourceReader rsxr = new ResXResourceReader(Server.MapPath("~\\App_GlobalResources\\ResourceMetal" + culture + ".resx"));
      Dictionary<string, string> res = new Dictionary<string, string>();
      foreach (DictionaryEntry d in rsxr)
      {
         res.Add(d.Key.ToString(), d.Value.ToString());
      }
      _resource = res;

      //Close the reader.
      rsxr.Close();

      
      return Json.Serialize(_resource );
}

You may be interested to serialize .net to Json object.
and also you might be interested to read How to make ajax call to MVC project click

No Comments

How To Make An Ajax Call To MVC Action

Written by Cagdas Erman AFACAN on 05/08/2012 Categories: ASP.NET, C#, JQuery, MVC Tags: , , , ,

Ajax is a powerful technology that provides us to make server calls without postback. There are lots of client libraries to do that but in this post we’ll use Jquery.

So how do we make ajax call? It is pretty simple though.

function doAjaxCall(){
$.ajax({
        url: '/Home/GetAjaxResult',
data: {}, //if you need to pass parameters through ajax request add inside javascript object {} like {firstData:"data", second: 123}
        async: true,
  //Success function is a call back function which is to call if the ajax call become success
     success: function (data) {
             var parsedData= JSON.parse(data);
            alert("Result: " + parsedData[0] + " Error:" + parsedData[1]);
        }
//Error function is a call back function which is to call if the ajax call become success
       error: function (xhr, status, error) {
             console.log("doAjaxCall()", xhr, status, error);
   }
});
}

(more…)

No Comments

How to Restart Windows Services Programmatically

Written by Cagdas Erman AFACAN on 05/07/2012 Categories: ASP.NET, C# Tags: , , , , , ,

Hi; This post is for managing windows services by asp.net c#. In practice Web applications are complated by some services (which provide data to your app) so that sometimes you might want to manage this services programmatically (actions like start, stop).

So how can we reach to system like an administrator user. Firstly we need to login as an administrator from code file by using windows api’s. In order to do that firstly we have to create a new windows user as an administrator and also we have to assign a password on it. please check

(more…)

No Comments

How to Refresh Partial view With Ajax ASP.NET

Written by Cagdas Erman AFACAN on 05/03/2012 Categories: ASP.NET, C# Tags: , , ,

Partial views are contained within their own files and are reusable across views, which can help
reduce duplication, especially if you need to render the same kind of data in several places in your
application.

To add the partial view, right-click the /Views/Shared folder in your project and
select Add.

So you have a general  layout  and a partial view to contain latest news in it. That is called like below.

@Html.Partial("_LatestNews", (List<Models/NewsViewModel>)ViewBag.LatestNews);

(more…)

No Comments

How to Create Table Template with Jquery

Written by Cagdas Erman AFACAN on  Categories: Javascript, JQuery Tags: , ,

JQuery Template Plugin

Jquery Template plugin is extremly useful to create a reusable templates (compiled from markup).  instead of writing a lot  of html, just one template enough for all of them. so that lets give an example .

Essentials are JQuery and Jquery Template libraries that you have to add into head tags of your html.

(more…)

No Comments