Thursday, June 27, 2013

The requested page cannot be accessed because the related configuration data for the page is invalid error when hosting WCF service in iis

Very often while hosting a wcf service in iis we get the error "The requested page cannot be accessed because the related configuration data for the page is invalid ". The reason it cannot read the config file is because the process running your web app does not have permission to access the file/directory. So you need to give the process running your web app those permissions. The access rights should be fairly straightforward, i.e. at least Read, and, depending on your app, maybe Write. Above, you mention IUSR etc. not being in the properties for web.config. If by that you mean that IUSR is not listed in the security tab of the file then it's a good thing. One doesn't want to give IUSR any kind of permission to web.config. The role IUSR is an anonymous internet user. The file web.config should only be accessible through your application. You need to assign permissions for IIS_IUSRS on the local machine (but you don't have to assign for IUSR, in fact it will work even if you explicitly deny permissions). To assign permissions, just right click on the folder and on the security tab make sure to grant the correct permissions, and if the user is not listed then click "ADD", and enter IIS_IUSRS (and make sure that under "domain" the local computer is selected, or enter in the name fieldYourLocalComputerName\IIS_IUSRS), and then you are good to go.

Monday, May 27, 2013

How to handle null value returned when using Linq to get Max Value for a column

Very often we use Select query to get Max value for a column in Ado.net like
 SELECT MAX(UnitPrice) FROM products
. We can do the same thing in Linq but what about if we donot have any row to return.In sich a case you will probably rest up in getting casting error "Unable to convert null to specific type".
How to handle such situations in Linq
.net framework provides nullable type Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.
Now if we write the same query in Linq
int? query = (from o in context.Products select (int?)o.UnitPrice).Max(); 
This query will result in null value.We can cast this null value into our requested datatype Convert.ToInt32(query);

Monday, May 6, 2013

Copy Sql server database files(MDF and LDF) without stopping SQL Server services


The better approach for transferring database is to take a backup of database and move backup file anywhere but even if you wish to copy MDF and  LDF file, you can have above approach. If you are using your database, you are not able to copy the data or log files.For copying these files you need to stop sql services but  you can do it without even stopping services of SQL with following small script.

 ALTER DATABASE <Databasename>
 SET OFFLINE WITH ROLLBACK IMMEDIATE;

 It's not good but better than stopping SQL Server services
ALTER DATABASE <Databasename> SET ONLINE;

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.