Archive for geissingert

Nullable SqlParameter passing a null

To pass a value that could be null use the following:

int? recordID = null;
var parameter = new System.Data.SqlClient.SqlParameter {
                    ParameterName = "@id", 
                    SqlDbType = SqlDbType.Int, 
                    Value = (object)recordID ?? DBNull.Value, 
                };

Javascript Post Data

This will post a AJAX call to the server and pass 2 items: First is an array of selected id’s and the second is a nullable int.

function updateData() {
    $.ajax({
        type: "POST",
        url: '/ControllerName/ActionName',
        datatype: "json",
        traditional: true,
        data: { ids: keys, statusID: statusID },
        success: function (data) {
            // process success here
            window.location.reload(true);
        },
        fail: function (result) {
            // process failure here
        },
    });
}

The Action on the server is as follows:

public JsonResult ActionName(List<string> ids, int? statusID)
{
    var data = "Message Retured to Client";
    return new JsonNetResult(data, JsonRequestBehavior.AllowGet);
}

Javascript Date Validation

I needed to validate a date in javascript. I am using moment in my current project. But for 2017-05-154 it failed and returned true for IsValid(). I created the following to handle validating dates.

function dateValid(dateText) {
    var valid = true;
    var year = 0;
    var month = 0;
    var day = 0;
    if (dateText) {
        var parts = dateText.split('/');
        if (parts.length == 1) {
            parts = dateText.split('-');
        }
        if (parts.length == 3) {
            if (parts[0].length == 4) {
                month = parseInt(parts[1]);
                day = parseInt(parts[2]);
                year = parseInt(parts[0]);
            }
            else if (parts[2].length == 4) {
                month = parseInt(parts[0]);
                day = parseInt(parts[1]);
                year = parseInt(parts[2]);
            }
            else {
                valid = false;
            }
            var date = new Date(year, month - 1, day);
            var dateMonth = date.getMonth() + 1;
            var dateDay = date.getDate();
            var dateYear = date.getFullYear();
            if (dateMonth != month || dateDay != day || dateYear != year) {
                valid = false;
            }
        }
        else {
            valid = false;
        }
    }
    else {
        valid = false;
    }
    return valid;
}

C# reading a CSV file and parsing with linq

I have a csv file that I need to read and wanted to parse the result using linq.

At first I was using the following:

public dynamic ReadCSVData(string path, bool firstRowFields = true)
{
    var query = from l in File.ReadAllLines(path)
                let f = l.Split(",".ToCharArray())
                select new
                {
                    Zero = f[0],
                    One = f[1],
                    Two = f[2],
                    Three = f[3],
                    Four = f[4],
                    Five = f[5],
                };
 
    return query.Skip(firstRowFields ? 1 : 0).ToList();
}

This reads data that only has the fields separated with just a comma.

The file I am reading also has fields that are enclosed with quotes.

After doing some research I came across the TextFieldParser in the Microsoft.VisualBasic.dll.

After adding the dll to the project I was able to adjust the code and now it looks as follows:

public dynamic ReadCSVData(string path, bool firstRowFields = true)
{
    dynamic data = null;
    // Have to add Microsoft.VisualBasic.dll to project
    using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(path))
    {
        parser.HasFieldsEnclosedInQuotes = true;
        parser.Delimiters = new[] { "," };
        var list = new List<string[]>();
        while (parser.PeekChars(1) != null)
        {
            string[] fields = parser.ReadFields();
            list.Add(fields);
        }
 
        var query = from f in list
                    select new
                    {
                        Zero = f[0],
                        One = f[1],
                        Two = f[2],
                        Three = f[3],
                        Four = f[4],
                        Five = f[5],
                    };
 
        data = query.Skip(firstRowFields ? 1 : 0).ToList();
    }
    return data;
}

The second method may not be usable if the file is large or fast parsing is needed.

For my project it is a small file and speed is not an issue.

This parses the file correctly as well as being part the .Net framework.

Mono Gtk Adding Widgets to a Table Widget

I am continuing to convert my application from .Net to Mono.

I am working with a table widget to layout one of my screens. After searching for a long time I was unable to find a clear way to add widgets to the table and understand where they will go.

I was finally able to figure it out and created an extension method for it.

public static void Cell(this Gtk.Table table, Gtk.Widget widget, uint row, uint column)
{
    table.Attach(widget, column, column + 1, row, row + 1);
}

When working with a table I am used to using a row and a column to add items to it.

The Attach method has 5 parameters: 1 for the widget and 4 others. After testing and working with it I was able to establish how to use row and column to add the widget to the table at the location I wanted.

.Net Create Database for SQLite

I am converting a project from Linq to Sql to Entity Framework with Sqlite.

One of the methods I was using is CreateDatabase function. When first called the function it returned the following exception:

CreateDatabase is not supported by the provider.

As I looked online most of the results mentioned to create the new structure from the existing schema.

By using the connection getschema method I noticed that the create statements are returned as a column named TABLE_DEFINITION when GetSchema is called for tables.

My end result is the following which creates a new Sqlite database with the schema from an existing database.

public class SQLiteDatabaseCreate {
    public void CreateDatabase(string newDatabase, string schemaDatabase) {
        var connectionString = string.Format("data source='{0}'", schemaDatabase);
        var dt = new System.Data.DataTable();
        using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString)) {
            conn.Open();
            dt = conn.GetSchema(System.Data.SQLite.SQLiteMetaDataCollectionNames.Tables);
        }
 
        using (var conn = CreateConnectionForSchemaCreation(newDatabase)) {
            if (conn.State != System.Data.ConnectionState.Open) {
                conn.Open();
            }
            foreach (System.Data.DataRow dr in dt.Rows) {
                var createSql = dr["TABLE_DEFINITION"].ToString();
                var cmd = new System.Data.SQLite.SQLiteCommand(createSql, conn);
                cmd.ExecuteNonQuery();
            }
        }
    }
 
    public System.Data.SQLite.SQLiteConnection CreateConnectionForSchemaCreation(string filename) {
        var conn = new System.Data.SQLite.SQLiteConnection();
        conn.ConnectionString = new System.Data.Common.DbConnectionStringBuilder {
            {"Data Source", filename},
            {"Version", "3"},
            {"FailIfMissing", "False"},
        }.ConnectionString;
        conn.Open();
        return conn;
    }
}

To use it call it as follows:

var newDatabase = Path.Combine(Application.StartupPath, "NewDatabase.db");
var schemaDatabase = Path.Combine(Application.StartupPath, "SchemaDatabase.db");
var sdbc = new SQLiteDatabaseCreate();
sdbc.CreateDatabase(newDatabase, schemaDatabase);

Asp.net Master Page Image Reference

Based upon where a Master page is referenced can determine how a reference to an image needs to be. The following will maintain a consistent reference for a master page.

<img alt="Site Logo" src="<%= Page.ResolveUrl("~")%>Images/logo.jpg" />

Resize images and keep aspect ratio

I needed to store uploaded images in various sizes. It required using a max size and re-sizing it while keeping the aspect ratio.

The following is the result:

public System.Drawing.Image ResizeImage(System.Drawing.Image image, int max_size)
{
    var imageHeight = Convert.ToDouble(image.Height);
    var imageWidth = Convert.ToDouble(image.Width);
 
    // maintaining aspect ratio
    var scaleFactor = 0.0;
    var maxsize = Convert.ToDouble(max_size);
    var newWidth = Convert.ToInt32(imageWidth);
    var newHeight = Convert.ToInt32(imageHeight);
 
    // if new size is larger than original the keep original size
    if (max_size > image.Height && max_size > image.Width)
    {
        newHeight = image.Height;
        newWidth = image.Width;
    }
    else if (imageWidth >= imageHeight)
    {
        scaleFactor = maxsize / imageWidth;
        newHeight = Convert.ToInt32(imageHeight * scaleFactor);
        newWidth = max_size;
    }
    else
    {
        scaleFactor = maxsize / imageHeight;
        newWidth = Convert.ToInt32(imageWidth * scaleFactor);
        newHeight = max_size;
    }
 
    var thumbnail = new System.Drawing.Bitmap(newWidth, newHeight);
    var graphic = System.Drawing.Graphics.FromImage(thumbnail);
 
    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
    graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
 
    graphic.DrawImage(image, 0, 0, newWidth, newHeight);
 
    return thumbnail;
}

Rotating images based upon exif image data

My current project involves using tablets to take picture and upload them to the server.

Once we started testing we noticed that the images were of different orientations.

We wanted the images to display the same so I have created the following rotation information:

#region exif image processing
public enum ExifOrientations : byte
{
    Unknown = 0,
    TopLeft = 1,
    TopRight = 2,
    BottomRight = 3,
    BottomLeft = 4,
    LeftTop = 5,
    RightTop = 6,
    RightBottom = 7,
    LeftBottom = 8,
}
 
public static System.IO.Stream RotateImageStream(System.IO.Stream stream, string filename)
{
    System.IO.Stream return_stream = stream;
 
    var fi = new System.IO.FileInfo(filename);
 
    var image_file = true;
 
    var image_format = System.Drawing.Imaging.ImageFormat.Jpeg;
    switch (fi.Extension)
    {
        case ".jpg":
        case ".jpeg":
            image_format = System.Drawing.Imaging.ImageFormat.Jpeg;
            break;
        case ".png":
            image_format = System.Drawing.Imaging.ImageFormat.Png;
            break;
        case ".gif":
            image_format = System.Drawing.Imaging.ImageFormat.Gif;
            break;
        case ".bmp":
            image_format = System.Drawing.Imaging.ImageFormat.Bmp;
            break;
        default:
            image_file = false;
            break;
    }
 
    if (image_file)
    {
        var image = System.Drawing.Image.FromStream(stream);
        var rotated_image = RotateImageByExif(image);
        var ms = new System.IO.MemoryStream();
 
        rotated_image.Save(ms, image_format);
        return_stream = ms;
    }
 
    return_stream.Position = 0;
 
    return return_stream;
}
 
public static System.Drawing.Image RotateImageByExif(System.Drawing.Image image)
{
    var orientation_property_id = 274;
    var pi = image.PropertyItems.Where(x => x.Id == orientation_property_id).FirstOrDefault();
    if (pi != null)
    {
        var orientation = (ExifOrientations)BitConverter.ToInt16(pi.Value, 0);
        switch (orientation)
        {
            case ExifOrientations.Unknown:
            case ExifOrientations.TopLeft:
                break;
            case ExifOrientations.TopRight:
                image.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipX);
                break;
            case ExifOrientations.BottomRight:
                image.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
                break;
            case ExifOrientations.BottomLeft:
                image.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY);
                break;
            case ExifOrientations.LeftTop:
                image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipX);
                break;
            case ExifOrientations.RightTop:
                image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
                break;
            case ExifOrientations.RightBottom:
                image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipY);
                break;
            case ExifOrientations.LeftBottom:
                image.RotateFlip(System.Drawing.RotateFlipType.Rotate270FlipNone);
                break;
        }
    }
 
    return image;
}
 
#endregion

Setting up a Asp.net page for callback

On my current project I wanted to add simple callback functionally. After searching google for a while and finding various solutions that I couldn’t get to work I came across the following posting from Microsoft:

Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages

It was very straight forward and I was able to get my callback going.

The following is the code behind that I used to get it working:

  void Page_Load(object sender, EventArgs e) {
    PageCallbackSetup();
  }
 
  /// <summary>
  /// Setup for the callback for a page
  /// </summary>
  private void PageCallbackSetup() {
    var cm = Page.ClientScript;
 
    // Client side function that will be executed when callback is finished
    var cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");
 
    // Function that is called to start the callback to the server
    var callbackScript = "function CallServer(arg) {" + cbReference + "; }";
 
    // Register script with the page for the callback
    cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
  }
 
  #region ICallbackEventHandler Members
 
  /// <summary>
  /// Returns result to client
  /// </summary>
  /// <returns>string of results from the server</returns>
  public string GetCallbackResult() {
    return "This is the time from the callback: " + DateTime.Now.ToString();
  }
 
  /// <summary>
  /// Raised when the callback takes place
  /// </summary>
  public void RaiseCallbackEvent(string eventArgument) {
  }
 
  #endregion

The following is the HTML markup:

<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>
 
<!doctype html>
<html lang="en">
<head runat="server">
  <title></title>
  <script type="text/javascript">
    function ReceiveServerData(arg) {
      MessageFromServer.innerText = arg;
    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="button" value="Callback" onclick="CallServer('CallSubmittedFrom')" />
    <br />
    <span id="MessageFromServer"></span>
  </div>
  </form>
</body>
</html>