Posts

Showing posts from 2011

Understanding MVC Razor layouts

Image
Q) What are ASP.NET MVC3 Razor Layouts? You want a disclaimer, header and a menu on left to appear on all pages to bring in consistency to your web application. If you're from webforms background, you'd be quick enough to think of using a Master Page. Similar to Masterpage, MVC 3 introduces concepts of layout . Similar to selecting master page in ASPX pages in page directive, in MVC you can specify layout at global or specific view level. Q) When and how are they created? When you add a new MVC3 application (either blank or internet or intranet), Visual Studio automatically adds a default layout file called “ _layout.cshtml ” , placed in shared folder of view. Note: There is no special extension for layout file. This layout is  automatically wired in another auto generated file called “ _viewStart.cshtml ” which contains following code: @{     Layout = "~/Views/Shared/CustomLayout.cshtml"; } Of course, you can replace CustomLayout.cshtml with your custom html or alter

Handling CSS with JQuery

1. Modify class at runtime 1.1. If an element has multiple classes attached and you need to remove one of class (say 'oldclass') $(selector).removeClass("oldclass") 1.2. If you want to add a new class to an element (say 'newclass') $(selector).addClass('newclass') 1.3. If you want to replace one of the class associated with element (say replace 'oldclass' with 'newclass') $(selector).removeClass('oldclass').addclass('newclass') 1.4. If you want to replace all classes with a different class $(selector).attr('class','newclass') // with this one 2. Notes on using multiple classes. 2.1. If you want to specify multiple classes to an element, separate them with space. <div class="class1 class2 class3"></div> OR $('div').addClass('classA classB') OR $('div').addClass('classA').addClass('classB') 2.2. More than the sequence in which classes are spe

Throw your own - Custom Exceptions

The key to understanding custom exception concept lies in knowing how to catch them. You have to know syntax, and you have to know how to use it. First, the syntax itself try {} catch (CustomException $e) {} catch (OtherException $e) {} catch (Exception $e) {} Basicaly it looks like an switch/case statement. The above code could be written as the next one, and all will be valid and will work perfectly. The try catch syntax is actually automatically handled multiple if statement! try {} catch (Exception $e) { if ($e instanceof CustomException) {} else if ($e instanceof OtherException) {} else {} } Throw your own Note that by distinguishing exceptions you can decide which are the fatal errors and which exceptions are only passing you an information that something is wrong and it is a handled case. This means that you have to use Exceptions not only on critical situations. Throw them for your handled situations too. class MyAuthException extends Exception {} class MyTest { pri

Throw your own - Losing the fear of Exceptions

The best way to lose the fear of exceptions is to start throwing them. Recipe is simple: whenever you come to case that something is wrong and your function or method can not accomplish its task, just throw an exception. Example 1 My favorite case is when I'm using a configuration values in my applications. Ops, there is no value at all, not an numeric value? I'll just throw an exception and stop thinking about that. This case is especially important if your application will have several installations. This way you are ensuring that nobody (including you) can not forget to fill in configuration. Or, when such case happen anyway, problem will be immediately identified. class MyIni { private $_config; public function __construct( $config) { $this->_config = $config; } public function getProductId() { if (!isset($this->_config['productId'])) throw new Exception( 'Required config parameter [productId] is not set'); if (!is_numeric( $this

Starting a Thread targeting method with parameters

Lets say you want to start a thread. How would you do it? Thread  T1 =  new   Thread ( new   ParameterizedThreadStart (SomeMethodName)); Restriction imposed by .NET is that Method which T1 targets can have only one parameter of object type. Hence, above code will work only if method signature is: public   static   void  SomeMethodName( object  o) But what if I want to invoke a method like: public   static   void  xyz ( int  a,  int  b) ??? Answer is to use delegates here and start thread as: Thread  T3 =  new   Thread ( delegate () { xyz(3, 4); }); or Thread  T3 =  new   Thread (() => xyz(3, 4));

The following module was built either with optimizations enabled or without debug information Visual Studio

Image
If you are facing this issue for long you must be on verge of banging your head or throw away your PC. There are many cause for this error. You might have tried options and may have missed a few. Following is a summary of different things that have helped me in resolving this issue (Hope it helps you out too): 1. In your Visual Studio, Go to Tools>Options>Debugging>General and check "Enable just my code as shown below" 2. If your application is configured to run using a IIS URL instead of dynamic localhost port, just ensure that IIS directory is pointing to your directory. Often while testing we make different copies of application and keep pointing application in IIS to one or the other. This actually resolved my issue. 3. Clean your solution, close VS, open again, rebuild application and try 4.Open properties of your project and ensure configuration as below: 5. Continuing from above, press advance button in Build settings below which opens a popup. Ensure, Debug I

Delete network credential from IE

If you have mistakenly opted for "remember password" while opening sharepoint site (or any other site which opens a popup up for network credentials), then forcing IE to again start prompting for credentials is a pain unless you know the right think to do. Everywhere you will get replies to delete cookies and other files by going into IE8>Settings>Content>AutoComplete>Delete Files. But this doesn't works for network credentials as they actually get stored by windows. Instead do following: STEPS (applies to windows 7) 1. Click on start button 2. Type passwords and select Manage network passwords option from filtered list.      You will find saved URLs and passwords of saved credentials 3. Select Delete option for the saved credential you want to remove

disabling Page Cache

1. Create a new .cs file "MyHttpModule.cs"      public   class MyHttpModule :  IHttpModule     {          public   void  Dispose()         {                      }          public   void  Init( HttpApplication  context)         {            context.PostRequestHandlerExecute += new   EventHandler (context_PostRequestHandlerExecute);         }          public   void  context_PostRequestHandlerExecute( object  sender,  EventArgs  e)         {              HttpContext .Current.Response.Cache.SetCacheability( HttpCacheability .NoCache);         }     } } 2. Register this module in web.config  < httpModules >           < add   name = " sessionmodule "   type = " WebApplication1.sessionmodule " />        httpModules >    system.web > Your all requests will automatically be skipped from caching.

Latest Javascript framework tags

Image
Get latest javascript framework links from http://scriptsrc.net/

SocialAuth.NET - OAuth with Facebook, Yahoo, Google, Twitter & more

Image
So last time when you visited your favourite site, you were pleased to see that it allowed login through facebook also besides direct registration . This is such a convenient functionality as user tend to be lazy to fill in registration forms and then wait for email with activation link. If you are looking for implementing similar functionality in your application then you can simply use "Facebook Button" from Facebook. But what if you want to implement authentication with Yahoo, Google and MSN as well? Well there is an out of the blue easy solution to achieve it! Meet SocialAuth.NET. SocialAuth.NET is a .NET class library that can be used to implement authentication with Facebook, Yahoo, Google and MSN. Using this library is so easy, that even if you are aware of writing simple application with ASP.NET, you can easily use this library. This library provides following features: - Authentication with Yahoo, Google, Facebook, MSN, Twitter, LinkedIn, MySpace - Retrieval of user

Connect with 32bit DSN from 64bit .NET

Recently I ran into a trouble. I was using a specific database which supported only 32bit ODBC connections. However my machine was 64bit Win7. If I connected to my 32bit DSN from Excel, I could get the data but from Visual Studio I received error :" There is an architectural mismatch". The reason was that by default my .NET communicated with 64bit driver. To force it to use, I changed my project Platform target from "ANY CPU" to "x86".. and it worked!! :)

Blittable types

Blittable types have an identical presentation in memory for both Managed & Unmanaged environments, and can be directly shared by them. Hence, it does not require special attention from the interop marshaler. • System.Byte • System.SByte • System.Int16 • System.UInt16 • System.Int32 • System.UInt32 • System.Int64 • System.IntPtr • System.UIntPtr Additionally, one-dimensional arrays of these types as well as complex types containing only fields of these types are blittable. The following are some commonly-used non-blittable types in the .NET framework: System.Boolean, System.Char, System.Object, System.String

Optimization for Mac OS X with SSD

To reduce disk writing, I have made some changes after Google the solution. Sleeping mode Check default value $ sudo pmset -g | grep hibernatemode hibernatemode 3 Change value $ sudo pmset -a hibernatemode 0 Remove sleep image $ sudo rm /var/vm/sleepimage Sudden Motion Sensor $ sudo pmset -a sms 0 Spotlight $ sudo mdutil -a -i off Hard drive sleep Go to "System Preferences" -> "Energy Saver" uncheck "Let disk fail sleep when possible" Hope that could helpful.

Youtube to MP3 converter (online)

Came accross this amazing URL "http://www.listentoyoutube.com/" Just input any youtube URL and download its mp3 version

Resolution change manually on Ubuntu 10.04

Show current setting $ xrandr -q Screen 0: minimum 320 x 200, current 1024 x 768, maximum 8192 x 8192 VGA1 connected 1024x768+0+0 (normal left inverted right x axis y axis) 338mm x 270mm 1024x768 60.0* 800x600 60.3 56.2 848x480 60.0 640x480 59.9 Get new mode line with new resolution $ cvt 1280 1024 60 # 1280x1024 59.89 Hz (CVT 1.31M4) hsync: 63.67 kHz; pclk: 109.00 MHz Modeline "1280x1024_60.00" 109.00 1280 1368 1496 1712 1024 1027 1034 1063 -hsync +vsync Create a new mode for new resolution $ sudo xrandr --newmode "1280x1024_60.00" 109.00 1280 1368 1496 1712 1024 1027 1034 1063 -hsync +vsync Add the new mode $ sudo xrandr --addmode VGA1 "1280x1024_60.00" Check if new mode exist? $ xrandr -q Screen 0: minimum 320 x 200, current 1024 x 768, maximum 8192 x 8192 VGA1 connected 1024x768+0+0 (normal left inverted right x axis y axis) 338mm x 270mm 1024x768 60.0* 800x600 60.3 56.2 848x480
Use VirtualPathUtility to obtain information like requested path, extension etc in web environment. It is Web version of System.IO.Path VirtualPathUtility .GetExtension( HttpContext .Current.Request.RawUrl)

NITDroid installation

I'm disappointed that NOKIA announced they will use WM for their new N9 series phone, and that makes me wanting to give up Maemo. I've used iPhone before. Its a good experience to use a smart phone. But it is too expensive for me. So, I want to migrate to Android based. For some reasons: Android had good integration with Google services, that's helpful to me. Android also has lots of applications on AppMarket. Android based phone is cheaper than iPhone. So, I tried to install NITDroid on my NOKIA N900. I want to thanks to the NITDroid project! Its very easy to install NITDroid on NOKIA N900 for now. The following is the notes I've been tried. Preparing a microSD card, and 2G size is recommended. Add a repo: extra-devel on Maemo's application manager. Install a package named nitdroid-installer on Maemo. Click the Application icon or run 'nitdroid' with superuser for automatic installation. After the installation, reboot the phone to entering the Android world

Returning the null value from a method

This example demonstrates the drawbacks of returning null from your methods. I allays preach to my colleagues that when something is wrong, your method should throw an exception instead of returning a null. But sometimes, especially if I'm writing some tools for myself, because of the laziness, I use the return null too. Few days ago I done that, and very soon I released that it was mistake which caused me unnecessary problems. Story goes like this: There is an initial list of ids and result of a process is a array of fully populated objects. I use that procedure on two places in my tool: for generating RSS file and for generating a view script. The tool is written in Zend Framework, it uses a log file, when exception occurs displays a customized error page and sends a email to me. Initially it was all flawless, but at some point, I released that I'm not able to read data for some of initial ids. So I modified a loading method in something like this: public function loadItem( $

LibreOffice installation with PPA on Ubuntu

I love to use LibreOffice on my linux desktop, so I always replace OpenOffice.org with LibreOffice when the desktop was newly installed. $ sudo add-apt-repository ppa:libreoffice/ppa $ sudo apt-get update && sudo apt-get install libreoffice Now I can use it!

equinox-theme installation on Ubuntu/Debian

Please follow steps below: Find equinox project on launchpad.net, then you can see the ppa path in the page. Install Ubuntu sudo add-apt-repository ppa:tiheum/equinox Debian sudo vim /etc/apt/sources.list Add a line: deb http://ppa.launchpad.net/tiheum/equinox/ubuntu lucid main sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 4631BBEA sudo apt-get update sudo apt-get install equinox-theme faenza-icon-theme Open preference/appearence and change theme to Equinox Evolution Then, you can enjoy it!

UNetbootin installation on Ubuntu 9.10 (Karmic) and later

$ sudo add-apt-respository ppa:gezakovacs/ppa $ sudo apt-get update $ apt-cache search unetbootin --> To check if we can find unetbootin $ sudo apt-get install unetbootin

LaTeX installation with beamer class on Ubuntu

$ sudo apt-get install latex-cjk-chinese latex-beamer Then, you can create slide with LaTeX beamer class.

Rename folders from Chinese to English in Ubuntu/Debian

$ export LANG=en_US $ xdg-user-dirs-gtk-update A dialog will popup and change it. Non-empty folders will be keep. Move all files to new folders named in English from original folders. $ export LANG=zh_TW.UTF-8

Latex installation on Archlinux

Nowadays, if we want to use LaTeX, we have to install the texlive package for it. And it is very easy to install all of those needed packages on Archlinux. $ sudo pacman -S texlive-core texlive-langcjk texlive-latexextra texlive-pictures Then, you can enjoy it now!