Posts

Showing posts from 2016

Custom Validation

Example validating within a data layer  I was having a conversation with a new .net colleague the other day and he indicated that he had learned about custom validators and was all excited about validating some properties within DTO's .  The validator pattern he was using however was designed for the Web app and not the data layer where most of our models and all of our DTO's resided.  So I showed him an alternative way to accomplish the same thing without corrupting his data layer by pulling in System.Web.  Below are both methods. Here is the method he initially wanted to plop into the data project  - more aptly designed to work with a  web application  - since this method of course depends on System.Web - it would not be compatible with data layer.  Both methods accomplish the same thing. namespace MyProject.ModelValidation {    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]    public sealed class ValidFutureDate : Valid

Linq - Linked Tables on Common identifier

Lets say you have Table A and Table B and a Table which has a sole function of joining the two - not so uncommon.  You want all the records from Table A and corresponding records from Table B but you don't want to include your join table. Using Entity Framework you could do something like this. The highlighted row is what I want to draw your attention to.  See that instead of a true join I have selected the collection of TableB records in Table A     A.TableB public IQueryable < Network > getjoinedData( int Id)         {             var myRequest = ( from A in db.TableA                              from B in A.TableB                              join C in db.TableC  on B.programId equals c.programId                              where A.active == true                              && B.active == true                               && C.active == true                              select n);                 return myR

Catch me catch me if you can - Errors on MVC

There are so many articles about the various ways to handle errors that you probably don't need another one. I am just going to focus on some key points and some gotchas! The 404 Error (Page or Route not found -                     is not as much an error as an exception and it is handled differently) This is why we typically reference a special page for 404 errors in our config     <customErrors mode="On" defaultRedirect="error" >              <error statusCode=" 404 " redirect="~/error/error_notfound"/>     </customErrors> Make sure in your App_Start FilterConfig file that you are adding the filter for HandleErrorAttribute    filters.Add(new HandleErrorAttribute()); I have implemented a custom Error handler  as well so I have a filter included for that file       filters.Add(new CustomErrorHandling());     public class CustomErrorHandling : HandleErrorAttribute,  IExceptionFilter {     public overr

Hex Icons

Image
Hex Icons are so much better than using images for buttons. In this example I am using the Hex code to illustrate the magnifying glass inline with an input texbox. I have used inline styles so that it is easy to see the styles I applied. The Hex code is the value of the input and shows the icon inline with the texbox to the right. <div style="background-color: white; height: 30px; width: 258px;"> @Html.TextBox("SearchTerm", null, new { @placeholder = "Enter Search Term", @style="width:220px;" }) <input id="searchBtn" style="border: 0; cursor: pointer; display: inline; height: 100%; margin-right: 0px; margin-top: 0px; width: 30px;" type="submit" value="&#x1f50e;" /> </div> I like this site for finding Hex Icons: http://graphemica.com/ Including a little lock on Admin sections 🔒 is nice

Environment Config Setup

Image
If you have multiple environments like most of us do and need to accommodate different settings in each there is an easy approach by using the Configuration Manager and the Web Transformations. To get started go to Setup environment (integration, acceptance, etc) Then right click web.config and choose “Add Config Transform” that will add your environments in (as I have done in image below) Now if you have a setting that is different between your debug, and Release you can put the setting in each config but in the override one you will add in the Transform and Locator attributes as shown.   <add key="filestoragepath" value="\\mypath\Dev\"  xdt:Transform="Replace"   xdt:Locator="Match(key)" />

A prettier way to use Enums

I think we have all struggled with using Enums with Linq, most especially when trying to plug them into your results.  A far better approach is to decorate your classes with them.  Let me explain We start by declaring a typical Enum class - something like this.   public enum OrderStatus     {         /// <summary>         /// Pending         /// </summary>         Pending = 10,         /// <summary>         /// Processing         /// </summary>         Processing = 20,         /// <summary>         /// Complete         /// </summary>         Complete = 30,         /// <summary>         /// Cancelled         /// </summary>         Cancelled = 40     } Then when we want to take advantage of it - in our Orders class we declare a string of OrderStatus - keep in mind our database only has OrderStatusId.  Here is what this property looks like.  public OrderStatus OrderStatus         {             get             {

Windows Authentication, Custom Roles, MVC 5

There are no doubt other ways to accomplish Role Management while still keeping Windows authentication but the way I am showing you here has to be one of the easier implementation. Let's start with the config.  After the authentication we can add in the roleManager reference.  The 'defaultProvider' is the name of our file for our CustomRoleProvider .   <system.web> ...   <authentication mode="Windows"/>     <authorization>       <deny users="?"/>     </authorization>     <roleManager enabled="true" defaultProvider="CustomRoleProvider">       <providers>         <clear />         <add name="CustomRoleProvider" type="MyNameSpace.CustomRoleProvider"/>       </providers>     </roleManager>   </system.web> Once we have the config setup we will need to add in two files Authorization file which will inherit from AuthorizeAttribute

Comparing Strings in Linq

I like this method best var customer = db.Customers.Where(d => string.Compare(d.Email,email,true)==0).FirstOrDefault(); It replaces the ToUpper() comparison and is nice and clean

Case Statement inside LINQ

Example of a mock Case Statement inside LINQ wrapped inside the parens.  var territoryInfo= (from e in  Franchisee_Zips                             where e.AccountCode == accountcode                             select new  Data.FullTerritory                             {                                 AccountCode = e.AccountCode,                                 VendorName = e.VendorName,                                 Territory_Type = (e.TerritoryType == 0 ? "TAFS" :                                 e.TerritoryType == 1 ? "Purchased Territory" :                                 e.TerritoryType == 3 ? "Option" :                                 e.TerritoryType == 4 ? "Vendor" : "Unknown"                                 ),                                 OptionBegins = e.OptionBegins,                                 OptionExpires = e.OptionExpires,                                 Action = "Add"              

Cascading Dropdown Lists with JSON Result

T o do a Cascading or dependent dropdownlist we start with a bound dropdownlist  - could look something like this: The objective is to create or bind another dropdown after the selection of the networkId  <select id="programId" name="programId" class="form-control"></select> Begin by adding the following function to your page - this clears any existing results, pulls in new results and populates our 2nd dropdownlist (programid)  $(function () { The last thing we need is to look at our JsonResult query  @Html.DropDownList("networkId", null, "Select a Network", htmlAttributes: new { @class = "form-control" }) So first we need to add a placeholder:    There are several ways to do this but we are going to do it with Jquery and a JsonResult in our controller.             $('#networkId').change(function () {                              $('#programid').html("");                   

CSS Necessities

READ ONLY TEXT BOXES When you need to return your model data in a textbox control but you don't want it to look like a textbox, apparently non-geeky people can't just accept that it is read only - they need to have it out of a textbox! Easy way to do this- add this to your styles input[readonly] {     border: none;     background: none; } And make your text box readonly     @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @readonly=true } }) DECORATING REQUIRED FIELDS You know the little red asterisk that you typically see to the right of the required field label.  An easy way to accomplish that with css is like this: .required:after {     content: " *";     font-weight: bold;     color:#ff0000; } Then add the class anywhere you want it to apply: @Html.LabelFor(model => model.agreement.programID, new { @class = "col-sm-2 form-control-label required " }) INCLUDE A PRINT BUTTON Add CSS //(#tabletoPr