Archive for category .NET

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.

Advertisements

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

HttpContext.Current.Session is null in web service

I was working with an web service (the old school .asmx kind), and I was encountering an issue where my Session object was null. Not a particular Session variable – all Session objects. When I would try to reference the following line, I was getting the “Object reference not found” message when I hovered over the “Session” part of the line in the debugger:

Session["Result"] = result;

To get around this, I added the “EnableSession” to true in the WebMethod attribute:

    [WebMethod(EnableSession = true)]
    public string RegisterNewUser(string bname, string first, string last) {
       // Do stuff
    }

Leave a comment

Empty string returned from long Oracle text field

I was returning data from an Oracle procedure using an OracleDataAdapter. I noticed that one text field that can hold large values was returning an empty string. So in the following, the “description” value was empty, when I knew the “ParkDescription” field in the database had a value:

string description = ds.Tables[0].Rows[0]["ParkDescription"].ToString();

Running the query in Toad, I could see the data was there. To resolve this, I needed to set the InitialLONGFetchSize  propety of the data adapter’s SelectCommand object to -1:

OracleDataAdapter adp = new OracleDataAdapter(comm);
adp.SelectCommand.InitialLONGFetchSize = -1;

Leave a comment

Showing page numbers when an ITextSharp table spans multiple pages

I’ve been using ITextSharp to create reports in PDF format in my MVC application. Normally, when I need to create page numbers, I use the PdfPageEventHelper to create a header row, including the date, title, and page number, like so:

        public partial class Header : PdfPageEventHelper {
            int counter = 1;
            private Font headerFont;

            public Header() { }

            public override void OnEndPage(PdfWriter writer, Document doc){
                PdfPTable headerTable = new PdfPTable(3);
                headerTable.WidthPercentage = 90.0f;
                headerTable.TotalWidth = doc.PageSize.Width - 10;
                headerTable.HorizontalAlignment = Element.ALIGN_LEFT;

                PdfPCell cell = new PdfPCell(new Phrase(DateTime.Now.ToShortDateString(), headerFont));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                headerTable.AddCell(cell);

                cell = new PdfPCell(new Phrase("SCOTT'S REPORT", headerFont));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                headerTable.AddCell(cell);

                cell = new PdfPCell(new Phrase("Page: " + counter++, headerFont));
                cell.Border = 0;
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                headerTable.AddCell(cell);

                headerTable.WriteSelectedRows(0, -10, 10, doc.PageSize.Height - 5, writer.DirectContent);
            }
        }

However, certain reports consisted of tables that would span multiple pages, and the event was firing. Instead, what I needed to do was use the IPdfPTableEventSplit  interface. So I first created a class that implemented the interface, then created a counter to keep track of the page. The final line then placed the page number in the top right corner:

        public class TableRowCounter : IPdfPTableEventSplit {
            private int pageCount = 0;

            public void SplitTable(PdfPTable table) {
            }

            public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
                var writer = canvases[PdfPTable.BASECANVAS].PdfWriter;

                BaseFont baseFont = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false);
                Font font = new Font(baseFont, 9);

                pageCount += 1;
                var text = "Page: " + pageCount.ToString();

                ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_LEFT, new Phrase(text, font), 775, 525, 0);
            }
        }

To fire off this event, I added my new class to the PdfPTable’s TableEvent event:

PdfPTable table = ReportTable.CreateTableHeader(endDate.Day);
table.TableEvent = new TableRowCounter();

Leave a comment