Monday, December 22, 2014

Thursday, December 18, 2014

How to solve problem "Cannot find the requested object." while create an X509Certificate2 object?


It throws this exception for following line:
X509Certificate2 certificate = new X509Certificate2(@"c:\temp\server.pvk", "password");

It means: the certificate file is not valid.
The most common reason is:
Need pvkimprt tool to generate PFX files

Reference:
http://msdn.microsoft.com/en-us/library/ms148420(v=vs.110).aspx
This constructor creates a new X509Certificate2 object using a certificate file name and a password needed to access the certificate. It is used with PKCS12 (PFX) files that contain the certificate's private key. Calling this constructor with the correct password decrypts the private key and saves it to a key container.

Following are the steps to generate X509Certificate2

"C:\Program Files (x86)\Windows Kits\8.1\bin\x64\makecert" -r -pe -n "CN=Test" -sky exchange c:\temp\server.cer -sv c:\temp\server.pvk -sr currentuser
"C:\Program Files (x86)\Windows Kits\8.1\bin\x64\cert2spc"  c:\temp\server.cer server.spc
pvkimprt -pfx server.spc server.pfx

Tuesday, December 16, 2014

In MS SQL, how to count total number of major objectsr, such as table, view, store procedure etc?

Select type_desc as Type, COUNT(*) AS Count from SYS.OBJECTS
Where type_desc not in ('SYSTEM_TABLE','INTERNAL_TABLE','SERVICE_QUEUE')
group by type_desc

The Art of Programming


https://medium.com/@erikaheidi/the-creative-programmer-2dde54f83e3a

Thursday, December 11, 2014

What is the simplest way to solve "Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on"

Code Example

Replace
list.Items.Add(status);
with:
                    this.Invoke((MethodInvoker)delegate
                    {
                        //list.Items.Add(status);
                    });


C# Naming Conventions with example

use PascalCasing for class names and method names.
use camelCasing for method arguments and local variables
use noun or noun phrases to name a class.
prefix interfaces with the letter I.  Interface names are noun (phrases) or adjectives.

References:
http://msdn.microsoft.com/en-us/library/ms229043.aspx
http://www.dofactory.com/reference/csharp-coding-standards

Wednesday, December 10, 2014

How to list all of listening ports in Windows command prompt?

netstat -anb | findstr /R /C:"[LISTENING]"

How to solve problem "No connection could be made because the target machine actively refused it"

#1 reason is: target machine TCP not listening.
Can run following command line to check:
netstat -anb

What is difference between 0.0.0.0 and 127.0.0.1?

127.0.0.1 is localhost. Only same machine can access this address.
But 0.0.0.0 means all of ip addresses binding to this machine.

Reference:
http://blog.lauramamina.com/article?title=0.0.0.0%20vs%20127.0.0.1

Workflows of Refactoring

http://www.infoq.com/presentations/workflow-refactoring





Uri Templates

https://github.com/tavis-software/Tavis.UriTemplates

Usage:
        var url = new UriTemplate("http://example.org/{tenant}/customers")
            .AddParameter("tenant", "acmé")
            .Resolve();

        Assert.Equal("http://example.org/acm%C3%A9/customers", url);

Monday, December 8, 2014

5 Incredible Features in the Visual Studio 2015 Preview


http://developer.telerik.com/featured/5-incredible-features-visual-studio-2015-preview

Friday, December 5, 2014

How to solve Invalid Xml syntax error after updated an older Visual Studio project



Error message:
This application has failed to start because the application configuration is incorrect. Review the manifest file for possible errors.
Reinstalling the application may fix this problem. For more details, please see the application event log.

In EventView, the error message is:
Activation context generation failed for XXXXX
XXXX on line 1. Invalid Xml syntax.

The first line in config file is
<?xml version="1.0" encoding="Windows-1252"?>

Solution:
Change to
<?xml version="1.0" encoding="utf-8"?>

Wednesday, December 3, 2014

Free browser base UML modelling tool

https://www.draw.io/

How many kind of UML diagrams in total?


Class Diagram
Component Diagram
Deployment Diagram
Object Diagram
Package Diagram
Profile Diagram
Composite Structure Diagram
Use Case Diagram
Activity Diagram
State Machine Diagram
Sequence Diagram
Communication Diagram
Interaction Overview Diagram
Timing Diagram


http://creately.com/blog/diagrams/uml-diagram-types-examples



Tuesday, December 2, 2014

How to install SQL Server management studio only?

On the download page:
http://www.microsoft.com/en-us/download/details.aspx?id=29062

Select the file just for SQL Server management studio installation:
ENU\x64\SQLManagementStudio_x64_ENU.exe

How to get list of SQL Server instances on local machine?

In command line prompt (Run as admin):
reg query "HKLM\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL"

Monday, November 17, 2014

Coding advice for new developers:Readable, Reliable, Correct and Efficient


Why this order?
Each attribute is fundamental to the next.
If code isn't readable, you stand no chance of making it reliable.
If code isn't reliable, it will never be correct, except by accident.
If code isn't correct, then what's the point?
If code isn't efficient, it is unlikely to be viewed as broadly useful.
http://jefflunt.com/rrce/

Thursday, November 13, 2014

How to pass paramters in Angular for http$.get and http$.post?


For http$.get
    $scope.ButtonClickEventGet = function () {
        $http.get(
            'ControllerName/Action',
            { params: { postcode: $scope.PostalCode } }
        ).success(
            function (data, status, headers, config) {
                $scope.Result = data;
            }
        );
    };

For http$.post (Don't know why it is different with get method)

    $scope.ButtonClickEventPost  = function () {
        $http.post('ControllerName/ActionName', { postcode: $scope.models.PostalCode }).success(
            function (data, status, headers, config) {
                $scope.Result = data;
            }
        );
    };

10 Developer Job Interview Tips To Land The Best Job You Can

http://simpleprogrammer.com/2013/03/24/10-developer-job-interview-tips-to-land-the-best-job-you-can/

Thursday, November 6, 2014

CDN for Angular

https://developers.google.com/speed/libraries/devguide

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

Wednesday, November 5, 2014

C# Autocomplete Demo Using Bing Code Search Engine

http://codesnippet.research.microsoft.com/#example

Screw You, Angular

"Recently there has been a great little triangle of battles going on among Ember, React and Angular. The reason why these debates are so great is that each of the frameworks have various pieces that are pure genius (ex. Angular DI, React Virtual DOM, Ember Router) and it is not abnormal to see developers in one framework borrow the great idea from another framework (ex. Angular UI Router from Ember Router)."

https://medium.com/@jeffwhelpley/screw-you-angular-62b3889fd678

What is XOR(^) operator in C#

A XOR B shows that it outputs true whenever the inputs differ

Sometimes, it is so easy to find a solution when you are back to basics.

References:
http://msdn.microsoft.com/en-us/library/zkacc7k1.aspx
http://en.wikipedia.org/wiki/Exclusive_or#Relation_to_modern_algebra

Friday, October 24, 2014

Wednesday, October 15, 2014

How to check temp table exist in MS SQL Server?

IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL
    DROP TABLE #TempTavle

How to write error information into MS SQL Server log?

DECLARE @isExists INT
exec master.dbo.xp_fileexist 'C:\FileName.csv',
@isExists OUTPUT
IF @isExists <> 1
begin
RAISERROR ('Can not find csv file', -- Message text.
16, -- Severity.
1 -- State.
) WITH LOG;
end

How to check exists file in MS SQL server

DECLARE @isExists INT
exec master.dbo.xp_fileexist 'C:\FileName.csv',
@isExists OUTPUT
IF @isExists <> 1
begin
RAISERROR ('Can not find csv file', -- Message text.
16, -- Severity.
1 -- State.
) WITH LOG;
end

101 Great Answers to the Toughest Interview Questions: Fourth Edition

http://allanjwilson.weebly.com/uploads/1/3/4/0/13401940/101_great_answers_to_the_toughest_interview_questions.pdf

Thursday, October 9, 2014

If url includes Dot/Period, will cause 404 error for ASP.NET routing

Need to change web.config setting at:

<system.webServer>

<modules runAllManagedModulesForAllRequests="true">

<remove name="FormsAuthenticationModule" />

</modules>

</system.webServer>

Enable hotlinking on Bayimg

I made a tool to upload image to bayimg and get raw image url right way:
http://bayimghelper.apphb.com/

But Bayimg blocks hotlinking. So write a function to enable it.
For example:
Original Bayimg link:
http://image.bayimg.com/38ba4e167a8f6ee9dc800b604cb0cfc6663bd720.jpg
You can use following to get access this image
http://bayimghelper.apphb.com/i/38ba4e167a8f6ee9dc800b604cb0cfc6663bd720.jpg


The source code is located at:
https://github.com/raysaspnet/bayimghelper

How to prevent image hotlinking in ASP.NET?

In IIS Server by URL rewrite:

http://www.it-notebook.org/iis/article/prevent_hotlinking_url_rewrite.htm

HOW TO DOUBLE YOUR APP DOWNLOADS WITH KEYWORD OPTIMIZATION

http://blog.discofingers.com/blog/2014/10/8/how-to-double-your-downloads-with-keywords-optimization

Monday, September 29, 2014

Wednesday, September 24, 2014

How to solve problem while upgrade to EF6: System.InvalidOperationException: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

To solve this problem for me is to add EntityFramework.SqlServer.dll into project reference:

System.InvalidOperationException: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Tuesday, September 23, 2014

How to add Facebook comment in ASP.NET MVC project?


You can download solution on Github by

https://github.com/raysaspnet/facebookcomment

1. Create a partial view, call fbComment

2. Add this partial view into any view for comments
@RenderBody()
@Html.Partial("fbComment")


https://developers.facebook.com/docs/plugins/comments

Monday, September 22, 2014

The case-insensitive regular expression for Canada postal code

^[abceghjklmnprstvxyABCEGHJKLMNPRSTVXY]\d[a-zA-Z]\d[a-zA-Z]\d$

Friday, September 19, 2014

How to display Textbox input to upper case in ASP.NET MVC razor view?

1. Create css class
.uppercase
{
text-transform: uppercase;
}

2. Add this class into Textbox in razor view
@Html.TextBoxFor(model => model.PostCode, new { @class = "uppercase" })

Note: the value still keeps original value.

Thursday, September 18, 2014

How to write Singleton pattern in C#?

http://msdn.microsoft.com/en-us/library/ff650316.aspx
using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

No more JS frameworks

http://bitworking.org/news/2014/05/zero_framework_manifesto

Tuesday, September 2, 2014

What Is Clean Code?

http://java.dzone.com/articles/what-clean-code-%E2%80%93-quotes
I like this one by Dave Thomas, founder of OTI and godfather of the Eclipse strategy:
It has unit and acceptance tests.
It has meaningful names.
It provides one way rather than many ways for doing one thing.
It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API.
Code should be literate since, depending on the language, not all necessary information can be expressed clearly in code
alone

If programming languages were weapons

http://bjorn.tipling.com/if-programming-languages-were-weapons

C# is a powerful laser rifle strapped to a donkey, when taken off the donkey the laser doesn’t seem to work as well.

Monday, August 25, 2014

How to get sql query from LINQ?

Before getting linq data, using ToString method. Will see the generated SQL.
It is not easy to read and understand.

   var soldOutProducts = 
            from p in products 
            where p.UnitsInStock == 0;

   string sql =  soldOutProducts.ToString();

Wednesday, August 13, 2014

Scheduled Tasks In ASP.NET With/Without Quartz.Net

With:
http://www.mikesdotnetting.com/Article/254/Scheduled-Tasks-In-ASP.NET-With-Quartz.Net

Without:
        protected void Application_Start()
        {
            System.Timers.Timer myTimer = new System.Timers.Timer(10 * 60 * 1000);
            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(ScheduledTaskMethod);
            myTimer.AutoReset = true;
            myTimer.Enabled = true;
 }

Wednesday, July 23, 2014

Norris Numbers

http://www.teamten.com/lawrence/writings/norris-numbers.html

Norris’ number, the untrained programmer can write 1,500 lines.
With Thoughtful class and package decomposition will let you scale up to 20,000 lines.

Friday, July 18, 2014

Tool to choose a open source lincens

http://choosealicense.com/

If you don't use any license, the default copyright laws apply.

Thursday, July 17, 2014

How to use Bulk insert to insert one column in a mutitple columns table?

One of solutions is:
Create a view from that table with only column you want to update.
The use bulk insert:
bulk insert TableView
from 'July17_2014.csv'
with (fieldterminator = ',', rowterminator = '\n')

Monday, June 30, 2014

What Makes a Good Programmer?

http://henrikwarne.com/2014/06/30/what-makes-a-good-programmer/

1. PROBLEM DECOMPOSITION
2. SCENARIO ANALYSIS
3. NAMING

Thursday, June 26, 2014

How to implement Dependency Injection by Autofac in MvcApplication class (ASP.NET MVC Global.asax)?

There are a lot of code examples for how to implement Dependency Injection for controller in ASP.NET MVC, but not too much about MvcApplication class in ASP.NET MVC.

Following is my implementation for Dependency Injection in MvcApplication class


public class MvcApplication : System.Web.HttpApplication
    {

        protected void Application_Start()
        {
            RegisterDependencies();
            //pass service into other class that need this service
            var c = new OtherClassNeedService(_IYourService);
        }

        private AutofacDependencyResolver IoCcontainer { get; set; }
        private IYourService _IYourService
        {
            get
            {
                if (IoCcontainer == null) return null;
                return IoCcontainer.ApplicationContainer.Resolve();
            }
        }

        public void RegisterDependencies()
        {
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            builder.RegisterType()
                .As(); //.InstancePerHttpRequest(); if added InstancePerHttpRequest, will get error: No scope with a Tag matching 'httpRequest' is visible from the scope in which the instance was requested.

            IContainer container = builder.Build();
            var aResolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(aResolver);
            IoCcontainer = aResolver;
        }



        protected void Application_End(object sender, EventArgs e)
        {
            IoCcontainer.ApplicationContainer.Dispose();
        }
    }

Thursday, June 19, 2014

How to get dropdown list from html by Html Agility Pack

private List GetDropdownList(string HtmlSource, string selectName)
        {
            HtmlDocument doc = new HtmlDocument();
            HtmlNode.ElementsFlags.Remove("option");
            doc.LoadHtml(HtmlSource);
            return doc.DocumentNode.SelectNodes(string.Format("//select[@name='{0}']//option", selectName)).Select(v => v.Attributes["value"].Value).ToList();
        }
Need to add HtmlNode.ElementsFlags.Remove("option");
before loading html source.

Wednesday, June 18, 2014

How to solve, Entity Framework return duplicated records from a view if there is no key in the view


1. Make sure the view should be a key there. And marked as Entity key
2. If do not have a key, add one by Row number
ID= ROW_NUMBER() OVER (ORDER BY fieldName DESC)

Do not forget: marked that field as Entity key in Edmx file

Reference:
http://jepsonsblog.blogspot.in/2011/11/enitity-framework-duplicate-rows-in.html?showComment=1348809764880#c1389404724781617559

Monday, June 16, 2014

How to solve problem, An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.

When saw this error, go to web.config file, disable the customer error. Then you will see the real error.   Set to RemoteOnly if in the production environment, so only real error in local.
<customErrors mode="Off" >


Reference
http://msdn.microsoft.com/en-us/library/h0hfz6fc(v=vs.85).aspx

Friday, June 6, 2014

How to get list of div that contains specific class name in Html Agility?

            var DivListContainSpeciicClassName = htmlDoc.DocumentNode.Descendants("div").Where(
                d => d.Attributes.Contains("class")
                &&
                d.Attributes["class"].Value.Contains("cssClassName"));

Wednesday, June 4, 2014

How to kill all current connections to a database in SQL Server ?

In case of you want to restore an database.

There are many ways to do so.
See link on Stackoverflow
http://stackoverflow.com/questions/11620/how-do-you-kill-all-current-connections-to-a-sql-server-2005-database


Or there is another simple way:
1. In SQL Server studio, click Activity Monitor button
2. Filter by database
3. Right click to kill all of connection to that database

Monday, June 2, 2014

How to solve problem, Invalid column name 'Discriminator'?

Get this error while upgrade Entity Framework from 5.0 to 6.x.
Install Entity Framework by Nuget. The version got is 6.1

Then get this weird error: Invalid column name 'Discriminator'
All of fields for that table are in the database table, so [NotMapped] is not applicable in here

The solution to me is to revert to 6.02, problem solved.

How to solve problem, "No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'."

Entity framework is using older version 5.0 and on .Net 4.0, need to install a new one.

Go to Package Manager Console:
Run
Install-Package EntityFramework

Thursday, May 29, 2014

How to remove ASP.NET response headers Server, X-AspNet-Version, X-AspNetMvc-Version and X-Powered-By?

Need two steps:
Step 1: add following code into Global.asax
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpContext.Current.Response.Headers.Remove("X-Powered-By");
            HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
            HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
            HttpContext.Current.Response.Headers.Remove("Server");
        }

AND

Step 2
Add following config into web.config file

    
      
        
        
      
    
  

Is ASP.Net vNext The New Node.js

http://blog.jaywayco.co.uk/?p=210

Monday, May 26, 2014

How to valid URL in ASP.NET MVC data annotation?


[Display("URL")]
[RegularExpression(@"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$", ErrorMessage = "Invalid URL")]
public string Url { get; set; }


Reference:
Website to test regular expression
http://regex101.com/

Common Regular Expressions
http://msdn.microsoft.com/en-us/library/ff650303.aspx

Wednesday, May 21, 2014

How to fix problem, MSDTC on server xxx is unavailable?

Following are the steps I did to fix the problem:
- Uninstall: msdtc -uninstall
- Install: msdtc -install
- restarting DTC service;

Do not FORGET
- Restart SQL Server service

Tuesday, May 20, 2014

Wednesday, May 7, 2014

Why need method/function overloading in C#?

Keep same naming convention. Can not find any other benefit for overloading.

Optional parameter should be the first choice to try.
Do not put different purposes thing under same name.

Friday, May 2, 2014

How to add number only validation in ASP.NET MVC data model by Data Annotation attribute?

[Range(0, int.MaxValue, ErrorMessage = "Number please")]

How to solve, 401 unauthorized issue for ASP.NET Windows authentication in Visual studio 2013

Go to folder:
Documents\IISExpress\config

Open config file and Set windowsAuthentication to true
<windowsAuthentication enabled="true">

Wednesday, April 30, 2014

How to sovle problem, JavaScript runtime error: Object doesn't support property or method 'on'

To me,
I fixed this problem by using higher version jQuery
Originally, it was 1.5.3, changed to 1.8.3

Code snippet for reading configuration from config file

System.Configuration.ConfigurationManager.AppSettings["SettingKey"] == null ? "defaultValue" : System.Configuration.ConfigurationManager.AppSettings["SettingKey"].ToString();

Wednesday, April 23, 2014

Why need Closure in JavaScript

Safe and faster
//Global
var names = ['zero', 'one', 'two',  'three', 'four', 'five', 'six',  'seven', 'eight', 'nine'];
var digit_name = function (n) {
 return names[n];
};
alert(digit_name(3)); // 'three'

//Problem: not safe. It is global variable, other code could change it


//Slow
var digit_name = function (n) { 
 var names = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; 
 return names[n];
};
alert(digit_name(3)); // 'three'
//Problem: Safe but slow. Names hide in function scope, but need to initialize every time


//Closure
var digit_name = (function () {
 var names = ['zero', 'one', 'two',  'three', 'four', 'five', 'six',  'seven', 'eight', 'nine'];
 return function (n) {
 return names[n];
 };
}());
alert(digit_name(3)); // 'three
//Safe and fast 

But why closure version code is faster?
http://stackoverflow.com/questions/6614572/javascript-performance-with-closure

Why Most Unit Testing is Waste

http://www.rbcs-us.com/documents/Why-Most-Unit-Testing-is-Waste.pdf

Summary:
Keep regression tests around for up to a year — but most of those will be system-level tests rather than unit tests.
• Keep unit tests that test key algorithms for which there is a broad, formal, independent oracle of correctness, and for which there is ascribable business value.
• Except for the preceding case, if X has business value and you can text X with either a system test or a unit test, use a system test — context is everything.
• Design a test with more care than you design the code.
• Turn most unit tests into assertions.
• Throw away tests that haven’t failed in a year.
• Testing can’t replace good development: a high test failure rate suggests you should shorten development intervals, perhaps radically, and make sure your architecture and design regimens have teeth
• If you find that individual functions being tested are trivial, double-check the way you incentivize developers’ performance. Rewarding coverage or other meaningless metrics can lead to rapid architecture decay.
• Be humble about what tests can achieve. Tests don’t improve quality: developers do.

Play video in Html 5




Reference:
http://en.wikipedia.org/wiki/HTML5_video

Tuesday, April 22, 2014

What is sparse array?

http://en.wikipedia.org/wiki/Sparse_array
a sparse array is an array in which most of the elements have the same value (known as the default value—usually 0 or null).

How to render an action without layout in ASP.NET MVC?

    public class HomeController : Controller
    {
        public string Create()
        {
     return "Hello";
 }
    } 
There are a couple of other ways:
http://stackoverflow.com/questions/5318385/mvc-3-how-to-render-a-view-without-its-layout-page
Change Layout default setting etc.
But return a string or json result, it is great way in some scenarios.

Thursday, April 17, 2014

Wednesday, April 16, 2014

How to solve problem: Proxy class not generated by wsdl command line or add service reference?

Use svcutil command line
svcutil  yourwsdlfile.wsdl
http://msdn.microsoft.com/en-us/library/aa347733.aspx
ServiceModel Metadata Utility Tool is a newer version than wsdl

Tuesday, April 15, 2014

How to manually update ASP.NET MVC 3 project to ASP.NET MVC 4?

Tried  nugget first, failed. If a simple project, should try this first.
https://www.nuget.org/packages/UpgradeMvc3ToMvc4

Then follow instruction from Microsoft to upgrade manually:
http://www.asp.net/whitepapers/mvc4-release-notes#_Toc303253806

In addition to reference above:
1. Change web.config file in view folder  as well
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />

<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

2. Add reference to System.Web.Optimization
By run nuget package: Install-Package Microsoft.AspNet.Web.Optimization

How to create a Windows EventLog source by command line?

Open command line window with admin permission
eventcreate /ID 2 /L APPLICATION /T INFORMATION /SO YourEventSourceName /D "Application infor"

Thursday, April 10, 2014

Where to check IIS server version

Check file property:
C:\Windows\System32\inetsrv\InetMgr.exe

Tuesday, April 8, 2014

How to prevent cache in ASP.NET Single Page Application when use Javascript Ajax calls?

Turn off cache in Jquery Ajax call
        $.ajax({
            url: "url",
            cache: false,
            dataType: 'json',
            async: true,
            success: function (data) {
            },
            error: function (xhr, ajaxOptions, thrownError) {
            }
        });
    }

How to solve ASP.NET precompile problem, The type or namespace name does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)

Set Copy local to true for this project reference: System.Web.Mvc
And Clear solution

How to enable static content caching in ASP.NET?

Add following configuration into web.config file

      
    
Reference:
http://www.iis.net/configreference/system.webserver/staticcontent/clientcache


When run pagespeed, sometime will get following warning:
Leverage browser caching
Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over


Enable ASP.NET static content cache to improve speed

Monday, April 7, 2014

Where to get ASP.NET MVC project MVC version?

Project reference -> system.web.mvc -> Properties- > Version

Wednesday, April 2, 2014

How to add Facebook login function into ASP.NET MVC project?

Step 1: create a Facebook app, and get appid
Step 2: Add following code into login view file


Step 3: Create an action in AccountController
        [HttpGet]
        public ActionResult FacebookLogin(string token)
        {
            WebClient client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat(
                   "https://graph.facebook.com/me?access_token=", token));

            var serializer = new JavaScriptSerializer();
            dynamic value = serializer.DeserializeObject(JsonResult);
            
            var model = new RegisterModel()
            {
                Email = value["email"],
                FirstName = value["first_name"],
                LastName = value["last_name"]
            };

            FormsAuthentication.SetAuthCookie(model.Email, true /* createPersistentCookie */);
            return RedirectToAction("Index", "Home");
        }

How to solve problem, Given URL is not allowed by the Application configuration Facebook application error?

Go to https://developers.facebook.com/
->Your app ->Settings -> Addvanced -> Valid OAuth redirect URIs -> put your login url in here

How to create a web page screenshot by Javascript lib, html2canvas

http://html2canvas.hertzen.com/screenshots.html

What Javascript Frameworks are used at Twitter.com?

http://vitalflux.com/ui-frameworks-used-twitter-com/

DropzoneJS, an open source library that provides drag'n'drop file uploads with image previews

http://www.dropzonejs.com/

Tuesday, April 1, 2014

How to Correctly Detect Credit Card Type

http://creditcardjs.com/credit-card-type-detection

Card Type
Card Number Prefix
American Express34, 37
China UnionPay62, 88
Diners ClubCarte Blanche300-305
Diners Club International300-305, 309, 36, 38-39
Diners Club US & Canada54, 55
Discover Card6011, 622126-622925, 644-649, 65
JCB3528-3589
Laser6304, 6706, 6771, 6709
Maestro5018, 5020, 5038, 5612, 5893, 6304, 6759, 6761, 6762, 6763, 0604, 6390
Dankort5019
MasterCard50-55
Visa4
Visa Electron4026, 417500, 4405, 4508, 4844, 4913, 4917