Tuesday, May 31, 2011

How to disable checkin on a single file in TFS 2010?

Right click on the file in Source Control explorer
Select Properties
Select Security Tab
Select contributers
Deny CheckOut and Check In

Calling Web Service Page Methods Using JQuery

ASP.NET Web Forms : Calling Web Service Page Methods Using JQuery

Building a Facebook Graph API application using ASP.NET

Building a Facebook Graph API application using ASP.NET « Peter Mourfield's Blog

Call ASP.NET server side method from jQuery UI Dialog

http://mkdot.net/blogs/hajan/archive/2011/05/31/call-asp-net-server-side-method-from-jquery-ui-dialog.aspx

Real World Performance

Performance testing and tuning is a science moreso than an art. There are certain tips and tricks that you can generally apply once you have some experience, caching being one of the easiest ones, but many times these will only mask the underlying problem. When it comes to tuning an application to eliminate performance bottlenecks, it’s important to measure a baseline, then form a hypothesis, make a configuration change, and then measure its effect. This is the scientific method in practice, and it generally works much more effectively than randomly applying hacks to your code in places you think (but don’t know, not having measured) will help.

http://stevesmithblog.com/blog/real-world-performance-and-the-stir-trek-web-site/

Monday, May 30, 2011

How to set specific namespace for one edmx file in Entity Framework

Right click edmx file in solution explorer. And change Custom Tool Namespace

How to solve "The specified named connection is either not found in the configuration, not intended to be used with the EntityClient Provider, not valid.


If your EDMX file in one project, you consume it in another.
You need copy the connection string from the app.config in the project with your model to the project where you want to consume that model.


http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/70f124b6-5003-4011-8142-9c7e4ac6c4a0/

How to change TFS Team Foundation Server template?


Install Team Foundation Server Power tool.
Then you will get Process Editor for changing TFS template.






Process Editor


An add-in to the Tools menu, the Process Editor provides a graphical user interface for editing Team Foundation Server process templates inside the Visual Studio IDE. This tool also provides a GUI for viewing the values assigned to all fields defined in a project collection.





Using jQuery Mobile with ASP.NET MVC

http://mourfield.com/2011/03/02/using-jquery-mobile-with-asp-net-mvc/

URL Routing with Web Forms

http://dotnetslackers.com/articles/aspnet/Understanding-and-Using-URL-Routing-with-Web-Forms.aspx

Bin Deploying ASP.NET MVC 3

http://haacked.com/archive/2011/05/25/bin-deploying-asp-net-mvc-3.aspx



If your server doesn’t have ASP.NET MVC 3 installed, you’ll need to make sure the following set of assemblies are deployed in the bin folder of your web application:
  • Microsoft.Web.Infrastructure.dll
  • System.Web.Helpers.dll
  • System.Web.Mvc.dll
  • System.Web.Razor.dll
  • System.Web.WebPages.Deployment.dll
  • System.Web.WebPages.dll
  • System.Web.WebPages.Razor.dll 

Sunday, May 29, 2011

Friday, May 27, 2011

None of Us Knows What We’re Doing

http://www.feross.org/none-of-us-knows-what-were-doing/


The Myth of the Superhuman

They believe, it seems, that “successful people” like Steve Jobs, Mark Zuckerberg, Bill Gates, Paul Graham, Walt Disney, etc. have some sort of in-built superhuman awesomeness that makes them smarter, cleverer, more brilliant than the rest of us.
They believe that something about these people is unique, that their feats would beunachievable by anyone else.
To be fair, it sort of makes sense, right? I mean, these folks succeeded spectacularlywhere thousands of others failed forgettably. So, the successful people must be more brilliant than average folk like you and me, no?

Creating Custom Ajax Control Toolkit Controls

http://stephenwalther.com/blog/archive/2011/05/26/creating-custom-ajax-control-toolkit-controls.aspx

ASP.NET FaceBook Login UserControl

http://www.eggheadcafe.com/tutorials/aspnet/fca40a96-aa44-4956-8382-447bf53f6035/aspnet-facebook-login-usercontrol.aspx

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FacebookLogin
{
    public partial class FBLogin : System.Web.UI.UserControl
    {
         public static string FaceBookAppKey = ConfigurationManager.AppSettings["facebookAppKey"];

        protected void Page_Load(object sender, EventArgs e)
         {
             if(String.IsNullOrEmpty( FaceBookAppKey ))
                throw new InvalidOperationException("You must have a valid Facebook App Key in AppSettings element \"facebookAppKey\"");

             if (Request.Cookies["fbs_" + FaceBookAppKey] == null)
            {
                lblMessage.Text = "Not logged in.";
                 return// No cookie returned from Facebook!!
            }


            string cookie = Request.Cookies["fbs_" + FaceBookAppKey].Value;
                cookie = cookie.Replace("\""""); //fix Facebook bug...
                NameValueCollection facebookValues = HttpUtility.ParseQueryString(cookie);

                  // send an http-request to facebook using the token from the cookie
                 //and parse the JSON response
                string json = GetFacebookUserJSON(facebookValues["uid"], facebookValues["access_token"]);
                Hashtable jsonHash = (Hashtable) JSON.JsonDecode(json);

                 //ok, let's actually read some data from FB response
                string facebookName = jsonHash["name"as string;
                string firstName = jsonHash["first_name"as string;
                string lastName = jsonHash["last_name"as string;
                string facebookId = jsonHash["id"as string;
                string email = jsonHash["email"as string;
                     //We explicitly requested email (see fb-button)
            lblMessage.Text = "Welcome, " + firstName + " " + lastName + " [" + email + "]";

             // Can store name, email etc. in db here, get user profile, store info in Session, etc.
        }

         /// <summary>
        /// sends http-request to Facebook and returns the response string
        /// </summary>
        private static string GetFacebookUserJSON(string userid, string access_token)
        {
            string url = string.Format("https://graph.facebook.com/{0}?access_token={1}&fields=email,first_name,last_name", userid, access_token);
            WebClient wc = new WebClient();
            string s = wc.DownloadString(url);
             wc.Dispose();
             return s;
        }
    }
}

Thursday, May 26, 2011

How to solve "Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created."


Disable “Prevent saving changes that require the table re-creation” 
1.    Open SQL Server 2008 Management Studio (SSMS). Click Tools menu and then click on Options… as shown in the snippet below.

2.    In the navigation pane of the Options window, expand Designers node and select Table and Database Designers option as shown in the below snippet. Under Table Options you need to uncheck “Prevent saving changes that require the table re-creation” option and click OK to save changes.


Globalization in ASP.NET MVC, JavaScript and jQuery


There's a couple of basic things to understand though, before you create a multilingual ASP.NET application. Let's agree on some basic definitions as these terms are often used interchangeably.
  • Internationalization (i18n) - Making your application able to support a range of languages and locales
  • Localization (L10n) - Making your application support a specific language/locale.
  • Globalization - The combination of Internationalization and Localization
  • Language - For example, Spanish generally. ISO code "es"
  • Locale - Mexico. Note that Spanish in Spain is not the same as Spanish in Mexico, e.g. "es-ES" vs. "es-MX"


Site search by MVC using the Bing Search API

http://www.iwantmymvc.com/site-search-using-bing-api-in-mvc

Bing Maps example for Windows Phone 7

http://www.codeproject.com/KB/windows-phone-7/Catel_Part6.aspx

Wednesday, May 25, 2011

Design a website like IKEA? Ikea as Rat-Maze


It’s a cliché that casinos are designed to prevent people from recognizing how much time has passed (no windows) and to steer people away from exit routes and back to the tables.
But much more salient, to me at least, is the infuriating design of Ikea stores. Invariably, my wife and I separate at some point and then, once I’m done browsing, I end up spending 20 minutes walking in circles trying to find the route back to children’s furniture (or some other designated meeting spot). I wind up passing the same mock studio apartment half a dozen times, blood pressure rising with each new sighting.
This confusion is carefully planned and orchestrated by Ikea, explained Alan Penn, a professor of architectural computing at University College London, in a recent lecture, in which he makes use of some very cool maps and digitized models of customer flow. One result of Ikea’s rat-maze design: 60% of the things people buy there were not on their original shopping list.
The company also pulls off a rather difficult balancing act: “There are a lot of people who go there and don’t enjoy it, but still seem to keep going back,” Penn says.



Ikea as Rat-Maze - Ideas Market - WSJ

The Cost of an Exception Application Performance, Scalability and Architecture – The dynaTrace Blog

Not using exceptions because of their potential performance impact is a bad idea. Exceptions help to provide a uniform way to cope with runtime problems and they help to write clean code



The Cost of an Exception Application Performance, Scalability and Architecture – The dynaTrace Blog

Tuesday, May 24, 2011

The history of networks


What is HTTP 418 ERROR?

:)

http://en.wikipedia.org/wiki/Http_status_codes#4xx_Client_Error

How to solve problem “Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.”


How to solve problem “Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.”

Reason: 
Usually do not close its associated connection when use a DataReader.


Three ways to solve:
1 SqlDataReader sdr = sCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

2 Explicitly close the connection
sc.Close();

3 Using block
using (SqlConnection sc = new SqlConnection(connString))
{
SqlCommand sCmd = new SqlCommand("SELECT * FROM Shippers", sc);
sc.Open();
Console.WriteLine("Conns opened " + i.ToString());
SqlDataReader sdr = sCmd.ExecuteReader();
sdr.Close();
}



ASP.NET MVC 3 Filters

ASP.NET MVC 3 Filters

Unleashing ASP.net Calendar Control

Microsoft Programmers | Unleashing ASP.net Calendar Control

Convert your ASP.Net app to Windows Azure

Convert your ASP.Net app to Windows Azure - Web expression

Using Task in ASP.NET MVC Today

http://devhawk.net/2011/05/19/using-task-of-t-in-asp-net-mvc-today/

Each major release of .NET to date has introduced a new async API pattern. .NET 1.0 had the Async Programming Model (APM). .NET 2.0 introduced the Event-based Async Pattern (EAP). Finally .NET 4.0 gave us the Task Parallel Library (TPL). The await keyword only works with APIs writen using the TPL pattern. APIs using older async patterns have to be wrapped as TPL APIs to work with await. The Async CTP includes a bunch of extension methods that wrap common async APIs, such as DownloadStringTaskAsync from the code above.

Monday, May 23, 2011

What is MvcScaffolding and why use it?


MvcScaffolding is tool available to ASP.NET MVC developers using Visual Studio that generates customizable controllers and views for any number of entities in your data model. In other words, MvcScaffolding is a way to quickly create an application layout based on data. This means there are less routine tasks that developers need to do, for example, creating your own controllers/views, CRUD methods, and validation, and more time spent on solving business problems.

MvcScaffolding generates the files as plain old .cs and .cshtml code files, with no designer files, so you're free to modify them as you want. You can scaffold controllers, views, repositories, etc... for CRUD operations in an app with a few commands, and have a fully functional application to work with. Combine the power of MvcScaffolding with Entity Framework's Code First feature, and you can start knocking out web apps much faster than before.

http://rachelappel.com/ready-set-scaffold-build-asp.net-mvc-3-applications-quickly-with-mvcscaffolding

Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper « Steve Sanderson’s blog

Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper « Steve Sanderson’s blog

Saturday, May 21, 2011

What is the best knowledge structure for ASP.NET developer

Entry level:
.Net framework
Language: C# or VB 
Visual Studio
ASP.NET Web Forms controls
Viewstate/Session/Cookie/Application variable

Intermediate Level:
JavaScript
HTML
CSS
Hypertext Transfer Protocol

Advanced:
ASP.NET Routing
Security 

Google Maps Vs. Bing Maps: Summer Vacation Planning Showdown


If there was a point system attached to these categories, Google would probably get a slight win over Bing based on its performance in basic mapping as well as business listings/directions. But Bing’s emphasis on aerial imagery was extremely helpful with vacation planning, and MapQuest’s search presets also got us the local info we were looking for right when we needed it.
In other words, there’s no obvious winner in this maps showdown.

http://searchengineland.com/google-maps-vs-bing-maps-summer-vacation-planning-showdown-77699

RenderPage And Data in ASP.NET MVC 3 Web Pages

http://www.dotnetcurry.com/ShowArticle.aspx?ID=646

AsyncController v/s SessionLess Controller

http://weblogs.asp.net/imranbaloch/archive/2011/05/10/asynccontroller-v-s-sessionless-controller.aspx



          AsyncController is introduced in ASP.NET MVC 2 while SessionLess controller is introduced in ASP.NET MVC 3. AsyncController allows you to perform long running I/O operation(s) without making your thread idle(i.e., waiting for I/O operations to complete). On the other hand, SessionLess controller allows you to execute multiple requests simultaneously for single user, which otherwise execute multiple requests sequentially due to session synchronization. Understanding these concepts may be easy for you but I have seen a lot of guys become confused on these concepts. In this article, I will show you how to use AsyncController and SessionLess controller in ASP.NET MVC application. I will also compare them and tell you what to use when, where, and the why.

Thursday, May 19, 2011

A nice free addon for SQL management studio, SQL Search 1.0


SQL Server developers and DBAs use SQL Search to:

  • Find fragments of SQL text within stored procedures, functions, views and more
  • Quickly navigate to objects wherever they happen to be on a server
  • Find all references to an object 

http://www.red-gate.com/products/sql-development/sql-search/

How to show time cost for one query in T-SQL?


      DECLARE @starttime DATETIME2 = SYSDATETIME(), @alltime datetime2 = sysdatetime();
      DECLARE @finishtime INT;

/* Your query is in here */

      SELECT @finishtime = DATEDIFF(millisecond, @starttime, SYSDATETIME());
      PRINT '(ms): ' + CONVERT(VARCHAR, @finishtime)

What do programmers really do?

What do programmers really do?
Programmers are translators of human ideas into the language of computers.

Securing your ASP.NET MVC 3 Application

You cannot use routing or web.config files to secure your MVC application. The only supported way to secure your MVC application is to apply the [Authorize] attribute to each controller and action method (except for the login/register methods). Making security decisions based on the current area is a Very Bad Thing and will open your application to vulnerabilities

http://blogs.msdn.com/b/rickandy/archive/2011/05/02/securing-your-asp-net-mvc-3-application.aspx

Wednesday, May 18, 2011

Cleaning up code smells


Worst code smells

  • Long classes
  • Duplicated code
  • Unused methods
  • Unnecessary casting
  • Overuse of design patterns

How to solve decimal binding problem in ASP.NET MVC

http://digitalbush.com/2011/04/24/asp-net-mvc3-json-decimal-binding-woes/



Phil Haack to the rescue! After doing some searching I stumbled across this post which fixes binding to string values with comma separators. It solves the same problem I'm having, so I'll repost the bits here:
using System;
using System.Globalization;
using System.Web.Mvc;
public class DecimalModelBinder : IModelBinder {
    public object BindModel(ControllerContext controllerContext,
                                    ModelBindingContext bindingContext) {
        ValueProviderResult valueResult = bindingContext.ValueProvider
            .GetValue(bindingContext.ModelName);
        ModelState modelState = new ModelState { Value = valueResult };
        object actualValue = null;
        try {
            actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                CultureInfo.CurrentCulture);
        }
        catch (FormatException e) {
            modelState.Errors.Add(e);
        }

        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return actualValue;
    }
}
Then stick this into your Global.asax.cs Application_Start:
protected void Application_Start() {
    ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
    // Your other stuff goes here.
}
Once I did that and re-ran the code above, everything works as expected. See for yourself:

Model values after adding DecimalModelBinder

Friday, May 13, 2011

What is WebGL

HTML5 canvas by Javascript for 3D

Demo:
http://helloracer.com/webgl/

Web-based Graphics Library
http://en.wikipedia.org/wiki/WebGL

What is Clear html code? Show by diagram

Weird behavior when hit Browser back button in ASP.NET webforms

http://www.west-wind.com/weblog/posts/2007/May/22/__doPostBack-and-the-Back-Button

How to get the checked radio button by jQuery

$(':radio').change(function () {
       $(':radio:checked').each(function () {
            if ($(this).val() == 2) {
                //Do stuff
                return;
            }
        });
    });

How to make a div stay fixed while scroll the page by CSS


style="position:fixed; top: 0%;"
NOT Opx 

How to set focus for first textbox in the web page by jQuery


$("#div1 :input[type='text']:first").focus();

Wednesday, May 11, 2011

How to make a full web page div (not full screen)?


            $('#divid').height($(document).height());

Update: Best Javascript & jQuery websites/blogs References


Best Javascript & jQuery websites/blogs References

Learning Advanced JavaScript: 
By John Resig from jQuery


CSS Selectors: (If you want to master jQuery selector, this is good reference for you)

JavaScript Language Specification(ECMA-262), HTML Version

PDF version 




CSS3

What is Agile

Dilbert.com

Monday, May 9, 2011

How to make div transparent cross browsers?

How to make div transparent cross browsers?

.transparent
{
   filter:alpha(opacity=45)
   -moz-opacity0.45
   opacity0.45
}