Compress JPEG Image using C#

by gayancc13. January 2012 23:46

Recently I had to make some photo upload task with compression enabled I thought to share the code that I used on my project. The code will help you to compress the JPEG images using C#. here is the code snippet.

public static void CompressImage(string path, int quality)
{
if (quality < 0 || quality > 100)
{
throw new
ArgumentOutOfRangeException("Quality must be between 0 and 100.");
}
string tmp = Path.GetTempFileName();
File.Copy(path, tmp, true);using (var image = Image.FromFile(tmp))
{
var qualityParam =
new EncoderParameter(Encoder.Quality, quality);
var jpgCdc = ImageCodecInfo.GetImageEncoders()
.Where(imageCodecInfo => imageCodecInfo.MimeType == "image/jpeg")
.FirstOrDefault();
var encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
image.Save(path, jpgCdc, encoderParams);
var prevImageSize = new FileInfo(tmp).Length;
var nextImageSize = new FileInfo(path).Length;
Console.WriteLine("Image compressed. Size saved :{0} bytes",
prevImageSize - nextImageSize);
}
File.Delete(tmp);
}

Happy Coding :)

Tags:

www permanent redirection with asp.net

by gayancc13. October 2011 04:38

When we build SEO friendly website we always care of how to handle sub-domain policy with www and non www sub-domains. Google and most of SEO specialist recommended to use of one sub-domain policy (www or non www) for better indexing. basic concept is to use of this avoid duplicate content on same domain. Google badly hurting to indexing when if it saw a duplicate content. So it’s good idea to have a sub-domain policy.

OK, lets say we choose to use non www for our sub-domain policy. the next problem is

what about other URLs with www sub-domain?

that’s why we forcedly permanent redirect to the non www URLs

How we achieve this with asp.net way?

Here is the simple approach with code I use own HttpModule to handle www URLs.Here we go

we use regex to match URLs with www

private static readonly Regex LinkRegex = new Regex(
"(http|https)://www\\.", RegexOptions.IgnoreCase | RegexOptions.Compiled);

then implementation with IHttpModule Interface like this

public void Init(HttpApplication context)
{
context.BeginRequest += OnBeginRequest;
}

 

private static void OnBeginRequest(object sender, EventArgs e)
{
var context = ((HttpApplication)sender).Context;
var url = context.Request.Url.ToString();if (!context.Request.PhysicalPath.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase)) return;if (!url.Contains("://www.")) return;if (!LinkRegex.IsMatch(url))return;
url = LinkRegex.Replace(url, "$1://");if (url.EndsWith("default.aspx", StringComparison.OrdinalIgnoreCase))
url = url.ToLowerInvariant().Replace("default.aspx", string.Empty);
context.Response.Clear();
context.Response.StatusCode = 301;
context.Response.AppendHeader("location", url);
context.Response.End();
}

 

Important !! this is when you define this module on web.config file this module should be the first defined one, so will fire before any other modules.

Hope this helped you to put some smile on you code editor. :)

Tags: ,

Programming

Ajax Only Request on Controllers action (Using Action Filters Attribute)

by gayancc12. October 2011 06:47

With Asp.net MVC3 one of the problem was when we want to allow some controller action only for ajax request, basically custom mechanism to handle unauthorized request there is no way with asp.net mvc3. after some research on google I came up with cool solution with customize controller action attributes.

I wrote my own attribute for check request type and it’ll only allow ajax requests. what have I done is basically extend class.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AjaxOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
base.OnActionExecuting(filterContext);else
throw new InvalidOperationException("This operation can only be accessed via Ajax requests");
}
}

Tags: ,

Programming

New Features in ASP.NET MVC 4 Developer Preview

by gayancc23. September 2011 17:44

Asp.net mvc4 developer preview released and shortly thereafter it became available for everyone to play with.

you can get it either way

  • Web Platform Installer – Installs the MVC4 Project Templates.
  • Nuget package – perfect for upgrading an existing MVC3 project.
  • Stand Alone Installer- Installs the MVC4 Project Templates.

    MVC4 comes with many great new features including an updated face lift of the design.

     

    In addition to CSS design there is improved functionality in the new template. The template support technique called adaptive rendering to support theme on both desktop and mobile browsers.another good thing is jquery integration with new template.

    How to Update MVC3 to MVC4?

    you can do the following steps to manually update the asp.net mvc3 to mvc4 but new release of Visual Studio (vNext) 2011 version automatically convert the project solution to mvc4.

    1. In Web.config file replace every instance of following text.
      System.Web.Mvc, Version=3.0.0.0
      System.Web.WebPages, Version=1.0.0.0
      System.Web.Helpers, Version=1.0.0.0
      System.Web.WebPages.Razor, Version=1.0.0.0

      with following corresponding test

      System.Web.Mvc, Version=4.0.0.0
      System.Web.WebPages, Version=2.0.0.0
      System.Web.Helpers, Version=2.0.0.0,
      System.Web.WebPages.Razor, Version=2.0.0.0,
    2. update the webPages:Version element to "2.0.0.0" and add a new PreserveLoginUrl key that has the value "true":
      <appSettings><add key="webpages:Version" value="2.0.0.0" /><add key="PreserveLoginUrl" value="true" /><appSettings>
    3. In solution explorer make the following changes to update the assembly references. Here are the details
      • System.Web.Mvc (v3.0.0.0)
      • System.Web.WebPages (v1.0.0.0)
      • System.Web.Razor (v1.0.0.0)
      • System.Web.WebPages.Deployment (v1.0.0.0)
      • System.Web.WebPages.Razor (v1.0.0.0)
      Add a references to the following assemblies:
      • System.Web.Mvc (v4.0.0.0)
      • System.Web.WebPages (v2.0.0.0)
      • System.Web.Razor (v2.0.0.0)
      • System.Web.WebPages.Deployment (v2.0.0.0)
      • System.Web.WebPages.Razor (v2.0.0.0)
    4. In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.
    5. Locate the ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.
    6. Save the changes, close the project (.csproj) file you were editing, right-click the project, and then select Reload Project.

    That’s all you got!!!! now you can good play with awesome framwork asp.net mvc4.

    Happy Coding :)

Tags: , ,

Programming | Technology

Facebook Like with Google Plus Extension for BlogEngine 2.5

by gayancc24. July 2011 19:59

last few weeks I was very busy with my new project faceboogle which users allow to find searches and easily share the searches with social network like facebook and google plus. eventually when I get a free time I tried to expand my previous written extension for new release BlogEngine2.5. so I added new feature google plus to the extension so I called it to socialbarextension.

the main difference between my previous extension and socialbarextension is I have remove all  iframe supported like widgets and added new XFBML version with send button support. plus google plus button ;) . also I didn’t test this extension for previous release of blogengine but I assume that it’s work with other versions too.

mainly as I mention earlier you guys can modify the extension as you want with keeping the author information.All you have to do with extension is just drag and put it in to extension folder in App_Code folder. I’m going to add new features as soon as possible when I get a free time for now enjoy the new extension thanks.

File : SocialBarExtension.rar (2.07 kb)

Tags: ,

What Is Caller ID Spoofing?

by gayancc7. July 2011 06:38

Caller Identification is a telephone feature that shares callers detail with callee. This service can comes with the optional service associating name with caller id. The information always shows on the display of callee’s telephone device or separate attached device.

What is Actually Caller ID Spoofing?

If person cause the provider network and display the number which is of the number of the originating caller number, it’s says Caller Id Spoofing. Since caller id spoofing  can make a call to anyone and shows look like it’s coming from any other number which caller wants to show and because anyone can get prank usually assume a call coming from actually coming from the number being displayed. All kind of thing can be done with such a manipulative ability.

Why Do I Need to Spoof  My Caller ID?

Sometimes large company uses it for their call centers or telemarketing department. Individuals uses this spoofing also they don’t wants to show their numbers to other such as small business man calls to his client from his personal mobile phone but he doesn’t needs to let clients know his number. But some can give us call with spoofing caller ID unscrupulous and there is a gray area in the regards to using this for joke reason prank person, there are many legitimate uses too. But important thing is all calls track somewhere and can be tracked back to originated called number and location.

What Can I Do With Using Caller ID Spoofing?

With the use of additional services can use this to change the caller voice and also record the call on your place too. And now we can see there are some services that provide SMS spoofing too. With this great practice people uses for good reason and also for the bad intentions.

How Does Caller ID Spoofing Work?

Caller ID Spoofing users verity if different mythologies most common way to get caller ID spoofing is call get through the use of voice over internet protocol (VOIP) and/or  Primary Rate Interface (PRI) Lines. Another method is emulating the Bell 202 FSK signal. This method also called orange boxing, use of software generate the audio signal that can couple to the transmission line during the telephone call. The orange box cannot truly spoof incoming caller ID prior to answering, and relies on the cunning of the caller. Other method is switch access to the SS7 network; Another method that is not used as often is VXML.

PS: Because of the legally restriction I missed to mention most important part which describes how does programmatically way to contributing to this technique which called Caller ID Spoofing. Because simplyy I don’t want go in to penitentiary. :P ;)

Tags:

General | Technology

ASP.NET Tips and Tricks

by gayancc26. June 2011 19:14

Asp.net is a awesome framework developing web sites and web applications.with visual studio asp.net become cooler and cooler. I have wrote an article Visual Studio 2010 New Tips and Shortcut previously. now I thought to write for asp.net tips and tricks because as the way you are using the framework it’ll be hard or easier to understand and do some work with minimum codes. Ok here we go we’ll see what are the cool features offer asp.net for .net web developers.

1. Maintain the position of scrollbar on postback : since asp.net 1.1 it was a very hard to maintain the position of scrollbar when doing postback. it’s was very necessary feature when we edit some data and after submit find position that we were editing. In asp.net 2.0 you can simply add the MantainScrollPositionOnPostBack attribute to the page directive.

<%@ Page Language="C#" MaintainScrollPositionOnPostback="true" AutoEventWireup="true" CodeFile="..." Inherits="..." %>

2. Set Default Button for form when user hit the enter key : In asp.net 1.1 required to write javascript to set default key for when form submit after hit Enter key. fortunatly you can use HtmlForcontrol’s DefaultButton property to set which button should be clicked when the user hit the enter

<form id="frm" DefaultButton="btnSubmit" runat="server">
  ...
</form>

3. Set the default focus to control when page loads : as mention above also we can set default focus for page load like below

<form id="frm" DefaultFocus="txtUserName" runat="server">
  ...
</form>

4. Strongly type access to the cross-page postbacks : asp.net 2.0 introduced the concept of cross page post back where one page could post back information to another page.if you add public property in to code behind page that initiate the postback operation, you can access property in strong type manner by adding PreviouPageType directive in to target page of the post back.

<%@ PreviousPageType VirtualPath="Default.aspx" %>

by adding this directive to pageyou can access the TextBox defind in previous page in strongly type manner.

TextBox tb = PreviousPage.SearchTextBox; 

there are a lot of other things that could be mentioned and I’ll try to keep post update. don’t forget to share your thought below comment field. thanks

Happy Coding :)

Tags: ,

Programming

How to get Stack Information Programmatically

by gayancc1. June 2011 13:54

If you are looking for the way to get stack trace information programmatically  (c#). This snippet will helps you to get these information. Stack information is very helpful feature to developers to trace the errors while they debugging their applications. Basically This is using System.Diagnostics namespace.

StackTrace stackTrace = new StackTrace();
StackFrame[] stackFrames = stackTrace.GetFrames();foreach (StackFrame stackFrame in stackFrames)
{
Console.WriteLine("Method name : [{0}]", stackFrame.GetMethod().Name);
}

Tags: ,

Programming

What is ASP.NET Caching?

by gayancc11. May 2011 23:03

Here with I decided to discuss about asp.net caching and how to getting advantage with asp.net caching technique for you application. Before that you should have an idea about what is caching and how it can help to improve your site performance. Basically caching is the incredible solution that significantly enhances your web response time. Caching is the process of storing frequently used data on the server to fulfill subsequent requests. It’s so good to grabbing data from memory instead recreating the web pages or items contained in them from scratch.

Why Caching?.. Basically caching will improve performance and scalability of your site. However it’s also consuming lot of server performance and memory usage.

Type of caching that using asp.net development

  • Output caching (page caching)
    • VeryByParam
    • VerybyControl
    • VeryByCustom
    • VeryByHeader
  • Partial page Caching (user control)
  • Data Caching

Limitations of ASP.NET Caching

Asp.net caching is amazing easy technique which most of developers are not taking advantages. The built-in ASP.NET caching is app-domain specific, so caching on a web farm is problematic. If you put something into the cache on one server the same cache does not exist on other server. A project in its infancy from Microsoft, codenamed Velocity, will help address this issue. With my next post will discuss about usage of above caching techniques.

Tags:

Programming

Gmail Motion Prank turned in to Real

by gayancc5. April 2011 13:49

gmail team made awesome prank for april fools and most of users enjoyed it even when i was seeing the video came to beleive. as the video said new feature that lets you use body gestures to compose and send emails in Gmail and send.It was obviously an April Fools’ joke, but now it’s also real ohhhhhhhhh can't beleive? ha haaaa here is the link for google motion prank video check out

[youtube:Bu927_ul_X0]

The technology is jokingly dubbed SLOOW – Software Library Optimizing Obligatory Waving – Microsoft Kinect camera uses control Gmail. they are using the technology which is actually called Flexible Action and Articulated Skeleton Toolkit (FAAST), to play World of Warcraft using only body motions in December 2010.

Amazingly enough, it works pretty much as Google had intended. You can type text into Gmail by using body gestures and send an email by “licking” the stamp and slapping it onto an imaginary envelope. Check out the video below for a demonstration.

[youtube:Lfso7_i9Ko8]

Tags:

Technology