Posts

Showing posts from 2015

Storing and Retrieving Images in SQL Server

I typically use the File System for storing images, that doesn't work so well when using a web farm.  Below is an example of storing the image information into SQL server and then retrieving and rendering image back on the page. The datatype for the image column I am using is the varbinary(max).  For this example I am allowing the upload of an image so I limit both the size and file extension type. Upload Action [HttpPost] public ActionResult Upload(HttpPostedFileBase file, DataModel.MyClass imginfo) { if (ModelState.IsValid)    {      if (file == null)     {            } else if (file.ContentLength > 0)     { int MaxContentLength = 1024 * 1024 * 3; //3 MB - Could put this in a config string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".JPG", ".jpeg", ".JPEG", ".GIF", ".PNG" }; if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.La

Cast Nullable Ints inside your Select in Linq

Needed to return a single value and cast it as an int instead of an int?     public int getFranchiseePOS(string AccountCode)         {             var qry = (from s in MyEntities.Franchisees                        join p in MyEntities.POS on s.POSID equals p.POSID into XX                        from subgroup in XX.DefaultIfEmpty()                        where s.AccountCode == AccountCode                        select s.POSID==null ? 0 :(int) s.POSID                       ).FirstOrDefault();             return qry;         }

Best Practices

This article is a bit dated but I believe it is still applicable: Best Practices from MSDN

DataEntities & Stored Procedures

Image
There are lots of ways to connect to your data. I really like working with DataEntities but I still appreciate the efficiency of stored procedures, so don't forget that they can work peacefully together. For this example I have selected a stored procedure that does some behind the scenes manipulation. It compares a table that I have just added records to from an Excel upload and it inserts those records into another table if they don't exist already, then it deletes the initial group of records. It also returns the number of records that it moved from one table to the other. Create PROCEDURE [dbo].[UpdateExtensions] --This is the output parameter that we will pass from the method which will return the number of changed records @row_count int OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. INSERT Account_StoreExtensions (AccountCode, ExtensionURL, Store_Extension) Select AccountCode, ExtensionURL

Best way to Read Excel Files with MVC

There of course are multiple ways to upload and read an Excel file.  After creating a version the long way I ran into file storage, permission issues etc so started looking for a better way to do this. I found a solution that does not actually upload the excel file, so no storage issues, no permission issues ... and a lot less code.  I am using a package available from Nuget called EPPlus.  So first thing you will want to do is grab this package - here is the nuget command line: install-package EPPlus Be sure and add this to your Controller: using OfficeOpenXml; public ActionResult UploadExtensions(HttpPostedFileBase file) { if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName)) { string fileName = file.FileName; string fileContentType = file.ContentType; byte[] fileBytes = new byte[file.ContentLength]; var data = file.InputStream.Read(file

A real world query with where's and ifs and nulls and multiple joins oh my!

I was looking for a good example of a Join but the examples I found were simple and did not include the other elements such as the where statement and multiple tables. So here is an example that works that includes those elements. I have eliminated some of the fields if you are wondering why I have so many joins that I didn't appear to use. The following query has multiple joins, one of the joins is joining on two columns with a defaultifempty applied - essentially making it a left join. One of the fields is an integer but I wanted to switch out a string instead - hopefully this will help someone who is looking for the answer for one of these linq constructors. MyEntities tfs = new MyEntities(); var rptCon = (from e in tfs.Company_Zips join b in tfs.Franchisees on e.AccountCode equals b.AccountCode join c in tfs.Account_StoreExtensions on new{ e.Zip_StoreExtensionID,e.Accountcode} equals new{ c.StoreExtensionID,c.AccountCode} into ex join p in tfs.Postal_Code_Territor

Build an ActionLink with a Value from the Page

Normally I would use an Html.BeginForm and wrap my link inside it to force it to the controller to handle any variables, but every so often you may need to add a link on the page which is populated with a variable from a textbox and you choose not to post back to the controller. In this example I want to pass an account number in my ActionLink So I start by adding the textbox on the page  Enter Account Number: @Html.TextBox("account") And the Actionlink (using some bootstrap formatting)   @Html.ActionLink("View", "Customer", null, new { id = "View", @class="btn btn-danger" }) Then I handle the click event in script on the page <script>     $(function () {         $('#View').click(function () {             var fran = $('#account').val();             this.href = this.href + '?id=' + encodeURIComponent(fran);         });     }); </script> My link now resolves to something like thi

Pivot Data and Roll up 12 months of Summaries

Image
The need was for a report that rolled up sales by item by month for the year on the MVC Razor page.  Here is how I did it. First I created a Model that looked like this   public  class DTO_SkuReport     {         public string SKU { get; set; }         public int Month { get; set; }         [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]         public decimal linetotal { get; set; }         public decimal JanTotal { get; set; }         public decimal FebTotal { get; set; }         public decimal MarTotal { get; set; }         public decimal AprTotal { get; set; }         public decimal MayTotal { get; set; }         public decimal JunTotal { get; set; }         public decimal JulTotal { get; set; }         public decimal AugTotal { get; set; }         public decimal SepTotal { get; set; }         public decimal OctTotal { get; set; }         public decimal NovTotal { get; set; }         public decimal DecTotal { get; set; }  

The Beautiful Razor WebGrid

The webgrid is truly a work of art.  The fastest way to show results of a query in a friendly, sortable, easily formattable fashion. Conditionally formatting our data can sometimes offer struggles so here are a couple of tips. Have a pesky nullable date column? You can add something like this inside your grid - here I am working with both a status and a nullable date.  So if the status equals "NA"  (I set that in my query if the step wasn't relevant), I am returning a black box into the cell otherwise i am returning the sew date (item.Sew) which can be nullable - here I am returning an empty cell if null or a nicely formatted date if not. IF STATEMENT IN GRID  ,grid.Column(header:"Sew", format: (item) =&gt;                 {                     if (item.SewStatus == "NA")                     { return Html.Raw(string.Format("<text><img height=40 width=100% src=\"{0}\" alt=\"Image\"/></text>&q

Update multiple columns from other Table via Join

 update franchisees  set  franchisees.posid=temp.POSID,  franchisees.poskey=temp.[POS Key]   from franchisees f   inner join [Table_Two] temp on f.AccountCode=temp.AccountCode

Binding a Dropdownlist on a blank form to a Model using a dictionary

In my Models folder I have a class for United States that looks like this:  public class UnitedStates     {           public static readonly IDictionary Cust_States = new Dictionary<string, object>                 {{"AL", "AL"},{"AK", "AK"},{"AZ", "AZ"},{"AR", "AR"},{"CA", "CA"},{"CO", "CO"},                 {"CT", "CT"},{"DE", "DE"},{"FL", "FL"},{"GA", "GA"},{"HI", "HI"},{"ID", "ID"},                 {"IL", "IL"},{"IN", "IN"},{"IA", "IA"},{"KS", "KS"},{"KY", "KY"},{"LA", "LA"},                 {"ME", "ME"},{"MD", "MD"},{"MA", "MA"},{"MI", "MI&q

Posting out to 3rd party API

Example of taking data in the form of a Model from your site and sending it out somewhere else and getting back a httpresponsemessage. [HttpPost]   public HttpResponseMessage Post(Appt_Model_DTO  appt)         { >>>>You could eliminate this portion   if (ModelState.IsValid)             { //not necessary but you can run some checks to make sure the data is good //that the model is valid and there is not  //you posted this data from your MVC site to your API Controller //Now we are going to send it off to a third party site                 if (appt.ID == null) {                     appt.ID = my_provider.getRecordwithSameIdentity(appt.AccountCode);                 }                 appt.StartDateTime = DateTime.Now;                 if (appt.POSID ==0)                 {                     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);                 }   >>>>>> And start here                               

SQL Cleanup set field value in one table from another

update franchiseeTable set franchiseeTable .postal_code_territory_id= a.postal_code_territory_id from franchisee_zips z inner join postal_code_territory a on z.pid=a.tdg_pid

Where Statement in Linq with nullable field

So you can't do this: where e.myfield=myEnum.myvalue or this where e.myfield=1 when myfield is a nullable integer In that situation you need to use .Equals Like this: where e.myfield.Value.Equals(myEnum.myvalue) Voila!

Calling an External Web API from Controller - No Jquery

The challenge is to call an external API and put it into a model you can use. The example below has a simple model STAPI_DTO which has two string fields - one of which is a client key which is what I am after string serviceURL = "https://someurl" + appt.POSID; var client = new WebClient(); //where STAPI_DTO is my model  STAPI_DTO st = new STAPI_DTO();   STAPI_DTO result = JsonConvert.DeserializeObject (client.DownloadString(serviceURL));  string clientkey = result.APIKEY;

Simple Breadcrumbs in Razor

If you wish to add Breadcrumb navigation to your site. This is a quick and easy way to do it.  This is only effective if every controller has an Index view and if you are passing route variables such as 'acct=xxx' then this will not accommodate those values so you have to make sure your app is able to manage without the variables and offer another option. @Html.ActionLink("Home", "Index", "Home") @if(ViewContext.RouteData.Values["controller"].ToString() != "Home") { @Html.ActionLink(ViewContext.RouteData.Values["controller"].ToString(), "Index", ViewContext.RouteData.Values["controller"].ToString()) } @if(ViewContext.RouteData.Values["action"].ToString() != "Index"){     @Html.ActionLink(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString()