Archive for category C#

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

Converting a List of strings to a SelectList

I had a brief list of comma-separated strings that I was storing in the web.config file, and I needed to convert them into a SelectList to bind to a DropDownListFor control in MVC. For that, there was a very simple method:

TempData["FundingTypes"] = new SelectList(ConfigurationManager.AppSettings["CoasterTypes"]

If I had needed a List<SelectListItem> instead, I would have done this:

            TempData["FundingTypes"] = ConfigurationManager.AppSettings["CoasterTypes"]
                .Select(f => new SelectListItem() {
                    Text = f.ToString(),
                    Value = f.ToString()

Leave a comment

Converting a string to an enum

I needed to take a string value and convert it to an enum for further processing. My enum was defined like so:

    public enum PinColor {
        white = 0,
        green = 1,
        yellow = 2,
        red = 3

I needed to do some calculations based on the color of the pin that was returned, which was done in a function (not shown). So to return the proper enumeration value for the color red, I needed to use the Enum.Parse method, casting the return value and parameter to my enumeration:

PinColor test = (PinColor)Enum.Parse(typeof(PinColor), "red", true);


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

Defining a method in a view

I know there will be much gnashing of teeth from MVC purists for even thinking about designing a view this way, but if you need to define a method inside a view, you can do it like I show below. In this instance, I am writing a method that will take a date, determine if it is null, and return either the short date or an empty string:

First, the method, defined at the top of the view:

 var getDate = new Func<DateTime, string>((date) => date != DateTime.MinValue ? date.ToShortDateString() : String.Empty);

And then calling the method:

@foreach (Models.Coaster item in Model.Coasters) {

Leave a comment

Formatting a double as a decimal in MVC

Pretty simple to do using a DisplayFormat attribute on the property you are trying to format:

[DisplayFormat(DataFormatString = "{0:0.0}", ApplyFormatInEditMode = true)]
public double Hours { get; set; }

My initial attempt failed because I was using the String.Format nation of {0:0N}, which didn’t work.

You can also using String.Format in the view to format the decimal into a string. In the example below, “item.Rate” is a double that I wanted to format to two decimal places, regardless of length:

@String.Format(“{0:0.00}”, item.Rate)

Leave a comment