Monday, December 31, 2012

How to ask user if want to leave current page in JavaScript?


Add function into onbeforeunload
var unsavedChanges = false;
window.onbeforeunload = function() {
  if (unsavedChanges) return 'You have unsaved changes!';
}

https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload

Saturday, December 29, 2012

How to convert SQL Server's timestamp column to datetime?

No. You can't
SQL Server's timestamp just an incrementing number and does not preserve a date or a time.

How to get client IP address?

How to get client IP address?
HttpContext.Request.UserHostAddress

How to fix "The name does not exist in the current context" in ASP.NET webforms?

Delete all of content in designer.cs, let Visual Studio generate again.

10 Web Predictions for 2012: the Results!

http://www.sitepoint.com/2012-web-prediction-results/

Wednesday, December 26, 2012

Why session id changes every time in ASP.NET?

Why session id changes every time in ASP.NET?
protected void Session_Start(Object sender, EventArgs e) 
{
    Session["init"] = 0;
}
http://msdn.microsoft.com/en-ca/library/system.web.sessionstate.httpsessionstate.sessionid.aspx
a new session ID is generated for each page request until the session object is accessed. If your application requires a static session ID for the entire session, you can either implement the Session_Start method in the application's Global.asax file and store data in the Session object to fix the session ID, or you can use code in another part of your application to explicitly store data in the Session object.

Monday, December 24, 2012

How to get first td in each tr of one table by jQuery?

$("#myTable tr td:first-child").addClass("diyi");

Thursday, December 20, 2012

How to change entity framework connection string dynamically

Use constructor with connection string
http://msdn.microsoft.com/en-us/library/bb739017.aspx

var db = new dbContext(connectionString);

How to change ASP.NET membership database connection string dynamically?

By reflection:
        private void SetProviderConnectionString(string connectionString)
        {
            // Set private property of Membership, Role and Profile providers.
            FieldInfo connectionStringField = Membership.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic); 
            if (connectionStringField != null)
                connectionStringField.SetValue(Membership.Provider, connectionString);

            FieldInfo roleField = Roles.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
            if (roleField != null)
                roleField.SetValue(Roles.Provider, connectionString);

            FieldInfo profileField = ProfileManager.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
            if (profileField != null) 
                profileField.SetValue(ProfileManager.Provider, connectionString);
        }

How to call WCF service in ASP.NET ?

Add following setting in web.config:


  
    
      
      
    
  
  
    
      
        
      
    
  

http://msdn.microsoft.com/en-ca/library/bb763177(v=vs.90).aspx

How to solve "CustomError for 403 Forbidden not working"?


In IIS 7 add following settings into web.config
  
    
      
      
      
      
    
   
  

How to use QR code in ASP.NET MVC?

The lib is: QRCODENET
http://qrcodenet.codeplex.com/


public ActionResult QRImage(int id)
        {
            string url = string.Format("http://myevents.apphb.com/event/details/{0}", id);
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H);
            QrCode qrCode = qrEncoder.Encode(url);

            GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
            MemoryStream ms = new MemoryStream();
            renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);
            byte[] image = ms.ToArray(); ;
            return File(image, "image/png");
        }

Wednesday, December 19, 2012

Reverse polish notation in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Threading;
 
namespace RPNEvaluator
{
    class RPNEvaluator
    {
        static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
 
            string rpn = "3 4 2 * 1 5 - 2 3 ^ ^ / +";
            Console.WriteLine("{0}\n", rpn);
 
            decimal result = CalculateRPN(rpn);
            Console.WriteLine("\nResult is {0}", result);
        }
 
        static decimal CalculateRPN(string rpn)
        {
            string[] rpnTokens = rpn.Split(' ');
            Stack stack = new Stack();
            decimal number = decimal.Zero;
 
            foreach (string token in rpnTokens)
            {
                if (decimal.TryParse(token, out number))
                {
                    stack.Push(number);
                }
                else
                {
                    switch (token)
                    {
                        case "^":
                        case "pow":
                            {
                                number = stack.Pop();
                                stack.Push((decimal)Math.Pow((double)stack.Pop(), (double)number));
                                break;
                            }
                        case "ln":
                            {
                                stack.Push((decimal)Math.Log((double)stack.Pop(), Math.E));
                                break;
                            }
                        case "sqrt":
                            {
                                stack.Push((decimal)Math.Sqrt((double)stack.Pop()));
                                break;
                            }
                        case "*":
                            {
                                stack.Push(stack.Pop() * stack.Pop());
                                break;
                            }
                        case "/":
                            {
                                number = stack.Pop();
                                stack.Push(stack.Pop() / number);
                                break;
                            }
                        case "+":
                            {
                                stack.Push(stack.Pop() + stack.Pop());
                                break;
                            }
                        case "-":
                            {
                                number = stack.Pop();
                                stack.Push(stack.Pop() - number);
                                break;
                            }
                        default:
                            Console.WriteLine("Error in CalculateRPN(string) Method!");
                            break;
                    }
                }
                PrintState(stack);
            }
 
            return stack.Pop();
        }
 
        static void PrintState(Stack stack)
        {
            decimal[] arr = stack.ToArray();
 
            for (int i = arr.Length - 1; i >= 0; i--)
            {
                Console.Write("{0,-8:F3}", arr[i]);
            }
 
            Console.WriteLine();
        }
    }
}

How to change checkbox size?

The behavior is different in browsers. And maximum size is limited.


How to solve "Service has zero application endpoints" in WCF host

Check service name in config file
Make sure it is a full name with all the namespace path

Building Back-end Data and Services for Windows 8 Apps: ASP.NET Web API

http://devhammer.net/blog/building-back-end-data-and-services-for-windows-8-apps-asp.net-web-api

Glimpse, A client side Glimpse to your server



http://getglimpse.com/Help/Plugin/Server

Monday, December 17, 2012

How to convert int32 into binary string (0/1)?

How to convert int32 into binary string (0/1)?
function createBinaryString (nMask) {
  // nMask must be between -2147483648 and 2147483647
  for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32; nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
  return sMask;
}
  
var string1 = createBinaryString(11);
var string2 = createBinaryString(4);
var string3 = createBinaryString(1);
  
alert(string1);
// prints 00000000000000000000000000001011, i.e. 11
var bits=string1.split("");

Friday, December 14, 2012

What is difference between "throw" and "throw ex" in catch block?

Please use "throw" only,  this way, will keep original exception

ASP.NET and Web Tools 2012.2

http://www.asp.net/vnext/overview/fall-2012-update

Enhancements to Web Publishing
New Web API functionality
New templates for Facebook Application and Single Page Application
Real-time communication via ASP.NET SignalR
Extensionless Web Forms via ASP.NET Friendly URLs
Support for the new Windows Azure Authentication

How to display currency in Javascript?

Number.prototype.formatMoney = function (c, d, t) {
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "," : d,
        t = t == undefined ? "." : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

//Usage: 

(123456789.12345).formatMoney(2, '.', ',');

http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript

Inline Editing With The WebGrid

http://www.mikesdotnetting.com/Article/202/Inline-Editing-With-The-WebGrid



Thursday, December 13, 2012

How disable a key by jQuery?

$('html').bind('keypress', function(e)
{
   if(e.keyCode == 80 || e.keyCode == 112)
   {
      return false;
   }
})

Wednesday, December 12, 2012

How to solve problem "Configuration file is not well-formed XML" in web.config with ampersand

replace ampersane & with &amp;

Why: web.config is in the format of XML 1.0:
The ampersand character (&) and the left angle bracket (<) may appear in their literal form only when used as markup delimiters, or within acomment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings "&amp;" and "&lt;" respectively

Monday, December 10, 2012

How to iterate an Enum in C#?

            Array values = Enum.GetValues(typeof(MyEnumType));
            foreach (MyEnumType val in values)
            {
                var enumName = Enum.GetName(typeof(MyEnumType), val);
            }

Why should not use Session variable for better performence in ASP.NET?

However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. 

http://msdn.microsoft.com/en-au/library/ms178581(v=vs.100).aspx

Re-Use MVC Views Across Projects With Razor Generat

http://blog.mirajavora.com/re-use-mvc-views-across-projects-with-razor-generator
Razor-Generator-Extension

Friday, December 7, 2012

Think First, Code Later

http://24ways.org/2012/think-first-code-later/

You, or someone just like you, have been building a website, probably as part of a skilled and capable team. You’re a front-end developer, focusing on JavaScript – it’s either your sole responsibility or shared around. It’s quite a big job, been going on for months, and at last it feels like you’re reaching the end of it

Thursday, December 6, 2012

How to fix "An unhandled Microsoft.NET Framework exception occured in w3wp.exe"

Change the ApplicationPoolIdentity of the application pool for your project to an account such as Local System.

How to install ASP.NET MVC4 into Visual Studio 2010?

http://www.microsoft.com/en-us/download/details.aspx?id=30683

How to disable session in ASP.NET MVC?

Two levels:
Application level is in web.config
<sessionState mode="Off" />

Controller level
[SessionState(SessionStateBehaviour.Disabled)]
public class MyController : Controller
{}

Wednesday, December 5, 2012

Monday, December 3, 2012

Why All The Lambdas in ASP.NET MVC?

http://odetocode.com/blogs/scott/archive/2012/11/26/why-all-the-lambdas.aspx


- If Model is null, the code will fail with an exception.
- We aren't providing any client side validation support.
- We have no ability to display an alternate value (like an erroneous value a user entered on a previous form submission – we want to redisplay the value, show an error message, and allow the user to fix simple typographical errors).


What is .d in Json result?


it protects from a tricky JSON hijacking scenario that exists when the outer JSON entity is an array.
http://stackoverflow.com/questions/2811525/removing-the-d-object-from-asp-net-web-service-json-output

http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/

3.5 JSON Response in Firebug