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;
}
}
}
Showing posts with label #Code Snippet. Show all posts
Showing posts with label #Code Snippet. Show all posts
Thursday, September 18, 2014
How to write Singleton pattern in C#?
http://msdn.microsoft.com/en-us/library/ff650316.aspx
Wednesday, April 30, 2014
Code snippet for reading configuration from config file
System.Configuration.ConfigurationManager.AppSettings["SettingKey"] == null ? "defaultValue" : System.Configuration.ConfigurationManager.AppSettings["SettingKey"].ToString();
Friday, March 16, 2012
How to set new password without old one in ASP.NET Membership?
Reset password, then use reseted password as old password to set new one.
MembershipUser user = Membership.GetUser(username);
string oldpassword = user.ResetPassword();
user.ChangePassword(oldpassword, "newpassword");
MembershipUser user = Membership.GetUser(username);
string oldpassword = user.ResetPassword();
user.ChangePassword(oldpassword, "newpassword");
Monday, August 15, 2011
Multiple Submit Buttons in ASP.NET MVC
In Razor view
@using (Html.BeginForm())
{
<p>
<input type="submit" name="AddButton" value="Add" />
<input type="submit" name = "RemoveButton" value="Remove" />
</p>
}
[HttpPost]
public ActionResult TwoButtonss(string AddButton, string RemoveButton)
{
var AddButtonClick = AddButton ?? RemoveButton;
return View();
}
Reference:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=705
@using (Html.BeginForm())
{
<p>
<input type="submit" name="AddButton" value="Add" />
<input type="submit" name = "RemoveButton" value="Remove" />
</p>
}
In Controller:
public ActionResult TwoButtonss(string AddButton, string RemoveButton)
{
var AddButtonClick = AddButton ?? RemoveButton;
return View();
}
Reference:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=705
Friday, August 5, 2011
How to check a string is in valid number format in C#?
public static bool IsNumber(string
str)
{
double Number;
if (double.TryParse(str,
out Number)) return
true;
return false;
}
Thursday, June 30, 2011
What is OR operator in jQuery selector, Multiple selector
Comma (,)
Put comma
between difference selectors, you can get combine result. OR operator.
$("div,span,p.myClass").css("border","3px solid red");
In jQuery, call Multiple selector
Reference: http://api.jquery.com/multiple-selector/
Monday, June 27, 2011
How to use Microsoft Translator service with screenshots and example
As the web grows, more and more international businesses are turning to the web. The demand for a multi-lingual website has never been so great. There are currently a few pay services out there that offer a translation API and also a few free ones (Google and Microsoft). One of the services that I have been looking at recently is the Microsoft Translator service. The API has support for SOAP, AJAX and HTTP which is a great addition to the API.
http://deanhume.com/Home/BlogPost/microsoft-translator-api/55
http://deanhume.com/Home/BlogPost/microsoft-translator-api/55
Saturday, June 18, 2011
Facebook like button
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Frayaspnet.blogspot.com%2F"
scrolling="no" frameborder="0"
style="border:none; width:350px; height:20px"><iframe></iframe></iframe>
scrolling="no" frameborder="0"
style="border:none; width:350px; height:20px"><iframe></iframe></iframe>
Tuesday, June 7, 2011
How to hide iframe from inside iframe by Javascript?
parent.document.getElementById('iframecontainer').style.display = 'none';
//iframecontainer is the id of iframe.
//iframecontainer is the id of iframe.
Monday, June 6, 2011
How to disable scrolling bars for iframe?
How to disable scrolling bars for iframe?
<div style="overflow:hidden;" >
<iframe></iframe>
</div>
Wednesday, June 1, 2011
Code Indentation and Nesting
Code Indentation and Nesting - Speed of Light
The greatest benefit of this style is bailing early. Instead of deeply nesting your code (and thus heavily indenting it), you have simple statements designed to end execution in as few instructions as possible, and designed to be as simple to follow as possible. Consider the examples:
The greatest benefit of this style is bailing early. Instead of deeply nesting your code (and thus heavily indenting it), you have simple statements designed to end execution in as few instructions as possible, and designed to be as simple to follow as possible. Consider the examples:
- (void)doSomethingWithString:(NSString *)s {
if (nil != s) {
if ([s length] > 0) {
NSLog(@"%@", s);
}
}
}
// VS
- (void)doSomethingWithString:(NSString *)s {
if (nil == s)
return;
if (![s length])
return;
NSLog(@"%@", s);
}
Friday, May 27, 2011
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;
}
}
}
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;
}
}
}
Tuesday, May 24, 2011
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();
}
Saturday, May 21, 2011
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.
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
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)
Monday, May 16, 2011
What is Indexed view in MS SQL Server
Views are also known as virtual table, you can improve performance by creating a unique clustered index on the view.
Using the NOEXPAND View Hint
SELECT Column1, Column2, ... FROM Table1, View1 WITH (NOEXPAND) WHERE
http://msdn.microsoft.com/en-us/library/aa933148(v=SQL.80).aspx
Friday, May 13, 2011
How to get the checked radio button by jQuery
$(':radio').change(functio n () {
$(':radio:checked'). each(function () {
if ($(this).val() == 2) {
//Do stuff
return;
}
});
});
How to set focus for first textbox in the web page by jQuery
$("#div1 :input[type='text']:first").focus();
Wednesday, May 11, 2011
Subscribe to:
Posts (Atom)