Archive for category .NET

Templates can be used only with field access… error using ToShortDateString()

While binding a partial view to a model, I noticed the my nullable DateTime field was showing the time portion. Adding attributes to the model didn’t work, so I attempted to use the ToShortDateString() method:

@Html.TextBoxFor(model => Model.StartDate.Value.ToShortDateString(), new { @class = “form-control”, @maxlength = “10” })

However, this caused the error “Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions”.

To get around this, set the shortened date value to a string, and used that as the binding to the textbox:

var startDate = Model.StartDate.Value.ToShortDateString();

@Html.TextBoxFor(model => startDate, new { @class = “form-control”, @maxlength = “10” })

Advertisements

Leave a comment

Unable to find the requested .Net Framework Data Provider. It may not be installed.

While moving a web application to a new web server, an application which used Entity Framework returned this message when loading:

ArgumentException: Unable to find the requested .Net Framework Data Provider. It may not be installed.

   System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName) +959971

   System.Data.EntityClient.EntityConnection.GetFactory(String providerString) +26

 

And this message also appeared a bit lower on the yellow screen of death:

ArgumentException: The specified store provider cannot be found in the configuration, or is not valid.

 

The problem was with the DbProviderFactories elements in the machine.config file – it didn’t have the correct drivers installed. To fix it, I opened Notepad (Visual Studio wasn’t installed on the server) as an administrator because the file wouldn’t let me save it otherwise. I scrolled down the <system.data> section, which initially looked like this:

<system.data>

<DbProviderFactories />

</system.data>

 

I replaced it with the section below which I pulled from my local machine. I have left in all the libraries in case that helps, though in our environment, we didn’t use the SQL Server CE drivers:

<system.data>

             <DbProviderFactories>

<add name=”ODP.NET, Managed Driver” invariant=”Oracle.ManagedDataAccess.Client” description=”Oracle Data Provider for .NET, Managed Driver” type=”Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342″/>

<add name=”ODP.NET, Unmanaged Driver” invariant=”Oracle.DataAccess.Client” description=”Oracle Data Provider for .NET, Unmanaged Driver” type=”Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342″/>

<add name=”Microsoft SQL Server Compact Data Provider 4.0″ invariant=”System.Data.SqlServerCe.4.0″ description=”.NET Framework Data Provider for Microsoft SQL Server Compact” type=”System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91″/>

<add name=”Microsoft SQL Server Compact Data Provider” invariant=”System.Data.SqlServerCe.3.5″ description=”.NET Framework Data Provider for Microsoft SQL Server Compact” type=”System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91″/>

               </DbProviderFactories>

</system.data>

Leave a comment

401 – Unauthorized in an ASP.NET project

While debugging a new to me (I didn’t write it) ASP.NET project locally, I came across this error when the default.aspx page loaded:

401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page using the credentials that you supplied.

There are several reasons why this could happen, but in my case, it was because the application was set to reject unauthenticated users. In the web.config file, there was this section:

    <authorization>
      <deny users="?" />
    </authorization>

Disabling the <deny> tag resolved the issue.

Leave a comment

Web API getting 404

When trying to perform a simple GET request using Web API in my MVC application, I was getting a 404 message. I was accessing it through Ajax, and the URL was correct:

    $.ajax({
        url: 'http://localhost:1234/api/UserApi',
        type: 'GET',
        cache: false,
        contentType: 'application/json'
    });

The problem was actually environmental. At a particular job site, the machines were locked down, including not being able to run PowerShell command – thus, an impediment to using NuGet. So I had to do several things to get my project working, but hopefully, if you’re having a similar issue, one of these is the key for you.

Several DLLs needed to be replaced, as the version were too old:

  • System.Net.Http
  • System.Net.Http.Formatting
  • System.Web.Http

The WebApiConfig.cs file was missing from the App_Start folder, so I added it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace ScottProject.App_Start {
    public class WebApiConfig {
        public static void Register(HttpConfiguration config) {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

The Global.ascx.cs file was missing the referene to the WebApiConfig file:

     protected void Application_Start() {
         // Other file snipped out
         GlobalConfiguration.Configure(WebApiConfig.Register);
     }

So this particular situation was specific to my situation, but perhaps one of those issues will help someone else.

Leave a comment

Calling a .NET web service using jQuery

I was attempting to call a .NET web service using jQuery, but was getting this error message:

An attempt was made to call the method \u0027GetCoasters\u0027 using a GET request, which is not allowed

The key to fixing this was to attach the “ScriptMethod” attribute to the web service and setting the “UseHttpGet” property to “true”, which I show below:

[System.Web.Script.Services.ScriptService]
public class OdometerService : System.Web.Services.WebService {

        [System.Web.Script.Services.ScriptMethod(UseHttpGet = true, 
              ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
        [WebMethod]
        public string GetCoasters() {
            return "Hello World";
        }
 }

And here is me calling the web service – try to contain your excitement:

$.ajax({
 type: "GET",
 url: "http://localhost:12345/CoasterService.asmx/GetCoasters",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (msg) {
      alert('Woohoo!');
 }, error: function (e) {
      alert('Bad stuff - ' + e.responseText);
 }
});

Leave a comment

Passing a list of numbers into an Oracle procedure

I wanted to pass in a list of numbers to an Oracle procedure for use in an “IN” statement, called from C# code. First, the C# code:

  string list = "1,2,3";
  using (OracleCommand comm= new OracleCommand("MyProcedure", connection)) {
     comm.CommandType = CommandType.StoredProcedure;
     comm.Parameters.Add(":pList", OracleDbType.Varchar2, 50).Value = list;
     comm.Parameters.Add(":p_cursor", OracleDbType.RefCursor).Direction = ParameterDirection.Output;

My Oracle procedure was equally awesome:

    PROCEDURE MyProcedure(pList IN VARCHAR2, p_cursor OUT sys_refcursor) IS
        
    BEGIN
        OPEN p_cursor FOR
            SELECT name 
            FROM coasters
            WHERE id IN (SELECT TO_NUMBER(column_value) AS IDs FROM XMLTABLE(pList));
    END;

You can see the “FROM XMLTABLE” statement is doing all the good stuff of splitting the list into the appropriate format. Good times.

Leave a comment

Encrypting the connection string for Entity Framework

I needed to encrypt the connection string that Entity Framework uses for its magic. So I encrypted the value in the “connectionString” attribute:

<connectionStrings>
   <add name="ConnString" connectionString="x4eAeGmvVTwzSOE2js7oWjQgdf" 
      providerName="System.Data.EntityClient" />
</connectionStrings>

I then updated the class in my application that is derived from the DbContext class, decrypting (using the creatively named “ScottsDecryption” (and no, that’s not the actual name)) the string in the call to “base”:

public partial class Entities : DbContext {
   public Entities()

       : base(ScottsDecryption(ConfigurationManager.ConnectionStrings["Entities"].ConnectionString)) { }
}

By the way, I received a ‘Keyword not supported: “data source”‘ error when first trying to get this working. I needed to replace the “&quot;” entries with actual single quote marks in the connection string, as described in this Stack Overflow post. So I had to change this connection string:

metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.SRModel.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string=&quot;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=blah)(PORT = 1234))(CONNECT_DATA=(SERVICE_NAME=scott.no.way)));User Id=MyID;Password=nope;&quot;

To this:

metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.SRModel.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string='Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=blah)(PORT = 1234))(CONNECT_DATA=(SERVICE_NAME=scott.no.way)));User Id=MyID;Password=nope;'

Leave a comment