Archive for category .NET

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:

public class OdometerService : System.Web.Services.WebService {

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

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

 type: "GET",
 url: "http://localhost:12345/CoasterService.asmx/GetCoasters",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (msg) {
 }, 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
        OPEN p_cursor FOR
            SELECT name 
            FROM coasters
            WHERE id IN (SELECT TO_NUMBER(column_value) AS IDs FROM XMLTABLE(pList));

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:

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

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=(;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=(;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;

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

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

                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

Calling an Oracle function from .NET

At some point in every man’s life, he asks himself “How do I call an Oracle function from C# code?” Well, time to answer that question.

I have an Oracle package, and in the package header, I have declared my function:


In the package body, I have my function implementation:

        pMessage VARCHAR(100);
        mId VARCHAR(10);
        pMessage := 'OK';
        SELECT COUNT(*)
        INTO mId
        FROM MyTable
        WHERE id = pId;
        IF mId = 0 THEN
            pMessage := 'The ID supplied is not valid';
        END IF;

        RETURN pMessage;

It’s a simple function that verifies that the ID in question exists in the database, and returns a status based on that.

In my C# code, I use some fun and exciting ADO.NET code to call said function:

     public static string ValidateId(string id) {

         string message = String.Empty;

         using (OracleConnection conn = new OracleConnection(connString)) {
             using (OracleCommand comm = new OracleCommand("pplant.cool_package.ValidateId", conn)) {
                 comm.CommandType = CommandType.StoredProcedure;
                 comm.Parameters.Add(new OracleParameter() {
                   Direction = ParameterDirection.ReturnValue, OracleDbType = OracleDbType.Varchar2,
                     Size = 150
                 comm.Parameters.Add(":pId", OracleDbType.Varchar2, 10).Value = id;

                 message = comm.Parameters[0].Value.ToString();

         return message;

A couple of things to note about returning a value from the function. The return value is declared as the first parameter, and has a direction of “ReturnValue”. Also notice that the return parameter does not have a name.

Leave a comment