Monday, April 29, 2013

Access Page Methods Using Script Manager In Asp.net

Sometimes we want to execute server side code from clientside using ajax then we can do this in two ways:-
  • Using jQuery to directly call ASP.NET AJAX page methods.
  • Using Script manager to access page methods.
Here i am going to explain how to use Script manager to call server side methods.There are 5 basic things we have to keep in mind while doing this.
  1. The Page Method should be static.
  2. Set the script manager enable PageMethods="true".
  3. Use java script PageMethods.<Method Name>(value, OnSucceeded, OnFailed).
  4. OnSucceeded - function to executed on success.
  5. OnFailed - function to executed on fail.
Default.aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<html>
<head id="Head1" runat="server">
    <title></title>
        <script type="text/javascript">
        function validatuser(soruce) {
            var valueuseremail = soruce.value;
            if (valueuseremail != "") {
                PageMethods.ValidateUser(valueuseremail, OnSucceeded, OnFailed);
            }
        }
        function OnSucceeded(result, usercontext, methodName) {
            document.getElementById('<%= lblValidation.ClientID %>').innerHTML = result;
        }
        function OnFailed(error, userContext, methodName) {
            alert("Error");
        }
         </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager 
            ID="ScriptManager" 
            runat="server" 
            EnablePageMethods="true" />
        <asp:TextBox 
            ID="txtEmail" 
            runat="server" 
            onkeyup="validateuser(this);">
        </asp:TextBox>
        <asp:Label 
            ID="lblValidation" 
            runat="server">
        </asp:Label>
    </form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
       public static string ValidateUser(string struname)
    {
        string uerror = string.Empty;
        try
        {
            bool userExists = false;
            ///
            /// Check if user exists
            ///
            if (struname.ToLower().Equals("bob"))
            { userExists = true; }
            if (userExists)
            { uerror = "UserName already exists!"; }
            else
            { uerror = "UserName available!"; }
        }
        catch
        {
            uerror = "Error";
        }
        return uerror;
    }        
}

Wednesday, April 17, 2013

Data Text Field Showing System.Byte[] in Radio Button List when concatenating multiple columns

While working on one of the project's i came across a scenario when data text field i binded in radio button list showed data on local but online it showed System.Byte[] instead of text.I was using Mysql database and for data text field i was concatenating 3 values .When i run that query on mysql it returned me data.I got expected results while running on local but when same code was deployed on server an unexpected thing occur. After lot of investigation and goggling i found one interesting thing that it was not the problem with code,it was merely a mysql .NET connector, version 5.1.6.Actually on local i was having .NET connector, version 3.51 According to mysql.com it is not a bug ,but it is expected behaviour.According to mysql.com if we are having any query that concatenates two or more columns ,Then one of the scenario will occur:-
  • mysql> SELECT CONCAT("Tonci", " ", "Grgin") AS Name; Returns the string that results from concatenating the arguments. May have one or more arguments. If all arguments are non-binary strings, the result is a non-binary string.
  • mysql> SELECT CONCAT("Tonci ", 1, " Grgin") AS Name; BINARY flag is set (this is where your problem is!) This will return binary string.
  • Now here is the solution to the problem: Cast the result of concatenate query as Char and then use it.Hence the issue of System.Byte array in Data Text Field will be solved. mysql> SELECT CAST(CONCAT("Tonci ", 1, " Grgin") AS CHAR) AS Name; For further details Visit:http://bugs.mysql.com/bug.php?id=37485

    Friday, April 12, 2013

    How to view parameterised query parameters that are passed to a command in visual studio during debugging

    The Immediate window is used to debug and evaluate expressions.To access the immediate window in debug mode one has the following options: Type Control-Alt-I In the command window, type imme Or find the option “Immediate Window” in the “view” menu. Most often we want to view what exactly is going into parametrized query at run time,in such a scenario immediate window can be very helpful to us.If we want yo view any parameters value in sql command we can just view those values in immediate window. Eg:- Suppose we are passing parameters to a command object as db.cmd.parameters.AddWithValue("@id",somevalue) Now if we want to know what exactly has gone as parameter in cmd we can view that in Immediate Window ?db.cmd.Parameters("@id").Value For more details regarding various commands for immediate window please visit the following URL http://msdn.microsoft.com/en-in/library/f177hahy(v=vs.80).aspx

    Monday, April 8, 2013

    Insert Explicit Value for Identity Column in Table

    When we want to insert explicit value for a column that is already set to identity and auto incrment,then we are likely to gt an error"Cannot insert explicit value for identity column in table 'IdentityTable' when IDENTITY_INSERT is set to OFF."
    The trick is to enable IDENTITY_INSERT for the table.
    
    SET IDENTITY_INSERT IdentityTable ON
    
    INSERT IdentityTable(TheIdentity, TheValue)VALUES (3, 'First Row')
    
    SET IDENTITY_INSERT IdentityTable OFF
     
    Note:
    Identity_Insert can be enabled  on only one table in database if you enable on second table .you will get error in first and we have to provide value for identity column when we use identity _insert enabled  as On.
    After we insert identity as off again,sql server set identity seed as current value.
    
    

    Conversion from type 'DBNull' to type 'String' is not valid Invalid Cast Exception

    Many a times when we are getting data from database and showing them on page in asp.net we came across this error "Conversion from type 'DBNull' to type 'String' is not valid Invalid Cast Exception"
    The main reason for this error is that when we are getting data from database and we get Null value and we try to cast it into string or any other data type .We can easily resolve this error by just adding small condition before casting into any data type
    I have included syntax in vb  as well as c#.Here is the trick what we have to do:
    Vb.Net
    string s=IIf(IsDBNull(db.rd("column")), String.Empty, db.rd("column"))
    C#
    string s = ( IsDBNull(db.rd("column")) ? String.Empty : db.rd("column") );
    

    Upload To FTP with FileUpload control

    Sometimes we come across a situation when we want get file from user through file upload and upload it to remote server through ftp.In this type of situation we can just create  a request stream variable and using that request stream we can write the contents of fileupload to remote server.For this we have to get the content of file upload control in bytes.Here is  a sample how i accomplish the same thing.Here spath is the path ftp path to remote server.ftpuser is user name and ftppassword is password to remote server.
    
    Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(spath), System.Net.FtpWebRequest)
    request.Credentials = New System.Net.NetworkCredential(ftpuser, ftppassword)
    request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
    Dim ftpStream As Stream = request.GetRequestStream()
    ftpStream.Write(FileUpload1.FileBytes, 0, FileUpload1.FileBytes.Length)
    ftpStream.Close()
    ftpStream.Dispose()
    Note:Don't forget to add following lines at the end of the code
    ftpStream.Close()
    ftpStream.Dispose()
    
    

    Thursday, April 4, 2013

    Ternary operator in VB.Net

    Recently in one of the project I was working with VB.NET language and I was eager to know if there is a ternary operator equivalent there or not. After searching on internet I have found two ways to do it.
    We have two operators in vb.net to accomplish this task
    1) if(condition,true,false)
    2) iif(condition,true,false) You can see that both IIF and If operator has three parameter first parameter is the condition which you need to check and then another parameter is true part of you need to put thing which you need as output when condition is ‘true’.
    We can use any of the two operators and get same output.

    Monday, April 1, 2013

    Create setup that runas administrator using Visual Studio

    Here is a property named "AdminUser" which can help to achieve your goal.
    Please follow these steps.
    1) Open your Setup Project, View->Launch Conditions.
    2) Right click on Launch Conditions, and add a new Condition in your Launch Conditions.
    3) Right click the Condition, choose Properties Window.
    4) Set Condition to AdminUser.
    5) Build and install.