Thursday, March 29, 2012

How to get a user's client IP address in ASP.NET?

Hi,
use this method
private string GetUserIP()
{
return Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? Request.ServerVariables["REMOTE_ADDR"];
}
or
HttpContext.Current.Request.UserHostAddress;
or
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

To get the IP address of the machine and not the proxy use the following code

HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

Saturday, March 24, 2012

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

The error means the connection pool is out of connections. The usual cause is forgetting to close a connection after you use it, like:

var con = new MySqlConnection("Server=YourDB;Database=YourDb;...");
con.Open();
var com = con.CreateCommand();
com.CommandText = "select * from YourTable";
This code forgets to close the connection, so the pool has one less connection. You could fix this by adding:

con.CLose();
at the end. But if the query throws an exception, the Close will be skipped, and you're still down 1 connection.

A much better way is the using statement:

using (var con = new MySqlConnection("Server=YourDB;Database=YourDb;..."))
{
con.Open();
var com = con.CreateCommand();
com.CommandText = "select * from YourTable";
}
You can troubleshoot this easily by adding max pool size at the end of your connection tring, like:

Server=YourDB;Database=YourDbUid=YourUser;Pwd=YourPwd;max pool size=1;
This gives you a pool size of 1, instantly triggering an error condition if you forget to free up your one connection.

Saturday, March 17, 2012

Learn Visual C#

Learn Visual C#

Discover a wealth of resources for learning Visual C#, for both the beginner and the experienced developer.


 

Forms Authentication In Asp.Net 2.0 3.5


Forms Authentication in ASP.NET 2.0 is technique to decide how users can access your web application.
Using froms authentication we can decide certain users can access only certain pages or we can control the anonymous access, we can implement folder level access and access based on roles


1. First of all create a new website and add a new form , name it Login.aspx
Drag login control on it from the toolbox
Make sure you have a web.config file in root of your application

2. Right click on solution explorer and add new folder , name it membersArea
Add a new from and name it members.aspx
Add a web.config file in this folder.

Now to implement Forms Authentication we need to configure web.config file (in the application root)

For this we need to add Authentication and Authorization tags inside <system.web> tag of web.config
<system.web>
<authentication mode="Forms">
<forms defaultUrl="Default.aspx" loginUrl="~/Login.aspx"
slidingExpiration="true" timeout="20">
</forms>
</authentication>
</system.web>

Now To restrict access to the membersonly page which is inside membersonly folder so that only members can access this page we need to create a another web.config file inside this folder to provide it's access rules
In this web.config write this inside <system.web> tag
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>

Now for login process and checking the username and password we need to write this code, double click on the login control placed on the Login.aspx page, it will generate Login1_Authenticate event
protected void Login1_Authenticate
(object sender, AuthenticateEventArgs e)
{
bool isMember = AuthenticateUser(Login1.UserName, Login1.Password,
Login1.RememberMeSet);

if (isMember)
{
FormsAuthentication.RedirectFromLoginPage(Login1.UserName,
Login1.RememberMeSet);
}
}

And this for checking username and password, i m using hard coded values
private bool AuthenticateUser(string userName, string password, bool rememberUserName)
{
string userName = "amiT";
string password = "password";

if (userName.Equals(userName) && password.Equals(password))
{
return true;
}
else
{
return false;
}
}

Wednesday, March 14, 2012

Find Duplicate Rows in SQL

Find how many repeated(duplicate) rows  in table
---------------------------------------------------------

select stdname,count(stdname) from tablename group by stdname having count(*) > 1

Len in SQL

create table tableLen(stdname varchar(50))

insert into tableLen values ('abi')
insert into tableLen values ('paranthaman')
insert into tableLen values ('ramesh')
insert into tableLen values ('raj')
insert into tableLen values ('sah')

select * from tableLen where Len(stdname) >  3

output
--------
paranthaman
ramesh

Count in SQL

count(*)
--------
select count(*)  from tablename ---- It will return total number of rows in the table

count(1)
--------
select count(1) from tablename    ---- It's also return total number of row in the table

count(column name)
--------------------
select count(columnname) from tablename  ---- It will return total number number of rows
                                                                                   with  data(without null) in that column

Example:
----------
create table tablecount(stdname varchar(50))
insert into tablecount values ('abi')
insert into tablecount values ('paranthaman')
insert into tablecount values (null)             -----this row inserted null values

select count(*) from tablecount
output-->  3

select count(1) from tablecount
output--> 3

select count(stdname) from tablecount
output--> 2

MVC3 Autocomplete Jquery


View

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
    rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<h2>
    AutocompletereturnsError</h2>
<div class="demo">
    <div class="ui-widget">
        <input type="text" name="name-list" id="name-list" />
    </div>
</div>
<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        $("#name-list").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=Url.Action("FindBarcode", "ASPForum")%>',
                    data: "bc=" + request.term + "&limit=5",
                    type: "GET",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                label: item.barcode,
                                value: item.id
                            }
                        }))
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        debugger;
                        alert(textStatus);
                    }
                });
            }
        });
    });
</script>

Controller

public ActionResult AutocompletereturnsError()
        {
            return View();
        }
        public JsonResult FindBarcode(string bc, int limit)
        {
            var result = (new[] { new { id=1, barcode = "abc" } }).ToList();
            result.Add(new {id=2,  barcode = "abcb" });
            result.Add(new {id=3,  barcode = "abcd" });
            result.Add(new {id=4,  barcode = "abce" });
            result.Add(new {id=5,  barcode = "abcr" });
            result.Add(new {id=6,  barcode = "abcf" });
            result.Add(new {id=7,  barcode = "abcg" });
            result.Add(new {id=8,  barcode = "abch" });
            result.Add(new {id=9,  barcode = "abcj" });
            result.Add(new {id=10,  barcode = "abcff" });
            result.Add(new {id=11,  barcode = "abcffd" });
            result.Add(new {id=12,  barcode = "cfsdfsdf" });
            result.Add(new {id=13,  barcode = "ckkk" });
            result.Add(new {id=14,  barcode = "ckkkrr" });
            result.Add(new {id=15,  barcode = "ckkkggg" });
            result.Add(new {id=16,  barcode = "ckkkfffdsfd" });
            result.Add(new {id=17,  barcode = "ckkkfdfd" });
            return Json(result.FindAll(c => c.barcode.IndexOf(bc) == 0).Take(limit), JsonRequestBehavior.AllowGet);
        }

Tuesday, March 13, 2012

Define Generics


C# has two separate mechanisms for writing code that is reusable across different
types: inheritance and generics. Whereas inheritance expresses reusability with a
base type, generics express reusability with a “template” that contains “placeholder”
types. Generics, when compared to inheritance, can increase type safety and reduce
casting and boxing.
Thanks.......

Saturday, March 10, 2012

Array,Split,IndexOf,CharAt,parseInt In Javascript



Below code for Decimal Value Convert to Integer Using JavaScript Split,Array,IndexOf,CharAt


        var inst=document.getElementById("txtAmount").value;
        if (inst.indexOf(".") != -1 )
        {        
            var temp   = new Array();
                  temp   = inst.split(".");
                  temp   = temp[1];
            var check = temp.charAt(0);   
            if(parseInt(check) >= 5)
            {
               inst = parseInt(inst) + 1;
            }
        }
        

Wednesday, March 7, 2012

How to create a dynamic control

We can create the dynamic control in the Page_Init() event or Page_Load() event

protected void Page_Load(object sender, EventArgs e)
    {
        TextBox dynamicTextBox = new TextBox();
        dynamicTextBox.ID = "DynamicTextBox";
        dynamicTextBox.AutoPostBack = true;
        dynamicTextBox.Text = "InitData";
        dynamicTextBox.TextChanged += new EventHandler(dynamicTextBox_TextChanged);
        this.Form.Controls.Add(dynamicTextBox);
    }
    void dynamicTextBox_TextChanged(object sender, EventArgs e)
    {
        Response.Write("hello");
    }