Monday, October 31, 2016

Make an HttpContent child for an HttpClient and add a header too.

I wanted to do something like this, but it took a bit of a different shape...

using System;
using System.Net.Http;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace HPS.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         using (var client = new HttpClient())
         {
            var package = new { Foo = "bar", Baz = "qux" };
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(package);
            Uri uri = new Uri("http://www.example.com/api/toucheme/");
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            content.Headers.Add("X-EXTRA", "whatever");
            var response = client.PostAsync(uri, content).Result;
         }
         return View();
      }
   }
}

 
 

Note that the second parameter for the .PostAsync is an HttpContent and you cannot just new one of these up. It's an abstract class and you need an actor that inherits from it. In the case of the StringContent (our actor) I recommend having all three parameters I specify to avoid 415 (unsupported media type) errors.

Sunday, October 30, 2016

old school generic connection string

"Data Source=cloudland.paradise.example.com;Initial Catalog=SummerWind;Persist
      Security Info=True;User ID=jblow;Password=letmein"

Friday, October 28, 2016

How do I know that the ViewState has not been tampered with?

This line of copy at the top of a web form's aspx markup is called an @Page directive:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
      Inherits="Damisam.UserInterface.Default" %>

 
 

...and putting EnableViewstateMac="true" inline here ensures that the ViewState has not been tampered with form-submission-to-form-submission.

window.onload

JavaScript's window.onload will occur after all the content on a page, images and all, has finished loading while jQuery's $(document).ready() happens when just the HTML is done loading. Use window.onload like so:

window.onload = function() {
   alert('whatever');
};

Material Design for Bootstrap

A good question to ask when someone is telling you about their ASP.NET MVC application is "How do you make paginated lists?" because the answer probably has to do with something more than just .ToPagedList. There is probably a third party control library of some sort such as DevExpress. Material Design for Bootstrap is one of them. Some links:

Thursday, October 27, 2016

Did you know there is an OnException action filter in MVC?

It's a lot like the OnAuthorization action filter...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Something.Models;
namespace Something.Controllers
{
   public class HomeController : Controller
   {
      protected override void OnAuthorization(AuthorizationContext filterContext)
      {
         
//whatever
      }
      
      protected override void OnException(ExceptionContext filterContext)
      {
         
//whatever
      }

 
 

...and these four characters. It's one of the six filtering methods one may use at a controller.

DbUnit is used with JUnit in the Java space.

It's for making dummy objects for your unit tests to muck with.

I just screwed up the world's easiest interview question so I guess that merits a blog posting.

What is the difference between outer and inner joins? My answer: The main table to which another table is joined may return numerous rows for the "joined-in" data for every row it returns in an outer join, but in an inner join there is a strict one-to-one relationship.

 
 

Wrong. This is not so. In both cases the main table to which another table is joined may return numerous rows for the "joined-in" data for every row it returns, however it's best, and perhaps a little counterintuitive, to think of the "joined-in" table as in the driver's seat. All of the records will be returned from the joined table except for those for which there is not a match in the main table, and if the join happens on a foreign key restraint relationship where a child is joined up to a parent then forget the "except" part of what I say altogether leaving: All of the records will be returned from the joined table. So what is the difference between outer and inner joins? If the main table has records which do not have a dance partner in the joined table these records will appear in outer joins and will not appear in inner joins. In these records the columns that come back for the joined table data points in the record set the query coughs up will just have null values.

 
 

Addendum 10/31/2016: What I say above about only one record per record for the joined table above really isn't true, certainly not if you join a parent to a child. The thing to really remember is that an inner join shows just the records where both tables have data while a left join will also show the main table's data even if there is not corresponding data in the joined table for a row returned.

Wednesday, October 26, 2016

LINQ ABCs

Having learned C# 2.0 first, for the longest time I just wrote foreach loops and would let ReSharper refactor them into LINQ or Lambda shapes. More recently, I've gotten pretty confident in writing Lambda expressions. LINQ seems to come up for less simplistic refactorings, but I was looking over this on Monday and it's really not rocket science. If you can write T-SQL you can write LINQ. It sure feels similar. Observe:

var whatever = from person in people
select person;
 

Obviously, what's above is a simple select. If we have an IEnumerable or List of Person in people then we would comically be just getting an IEnumerable of the same stuff. Clearly we need to filter. We do that like so, and again this is gonna look a lot like T-SQL...

var whatever = from person in people
where person.FirstName == "Clive"
select person;
 

Use double ampersands or double pipe symbols in the where clauses for and/or logic in filtering Clive records. Order the Clives like so:

var whatever = from person in people
where person.FirstName == "Clive"
orderby person.LastName descending
select person;
 

The let keyword is for a midstream transformation!

var whatever = from person in people
let maybedutches = person.LastName.Split(' ')
from maybedutch in maybedutches
where maybedutch == "Van"
select person;
 

I had heard that joins are pretty painful in Entity Framework and since the selects are all LINQ statements I can see why! Look at this:

var whatever = from person in people
join phone in phones on phone.Number equals person.Phone
select new { Name = person.FirstName, Country = phone.Country };
 

Well yuck, anonymous types! Yeesh! The first link I provide also goes into some esoteric groupings. Basically you can break a collection into a collection of collections all sorted out by something-er-other. You end up with an IEnumerable<IGrouping<string, Person>> which is straying beyond that which is common and simple.

Tuesday, October 25, 2016

what you can and cannot do with Session and Html.RenderAction

What if this controller...

using System;
using System.Web.Mvc;
namespace Something.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         Session["state"] = 0;
         return View();
      }
      
      public ActionResult Yin()
      {
         int state = Convert.ToInt32(Session["state"] as string);
         state = state - 1;
         Session["state"] = state;
         return PartialView("_Yin", state);
      }
      
      public ActionResult Yang()
      {
         int state = Convert.ToInt32(Session["state"] as string);
         state = state + 1;
         Session["state"] = state;
         return PartialView("_Yang", state);
      }
   }
}

 
 

...coughed up this action?

@{
   Layout = null;
}
<html>
   <head>
      <script type="text/javascript" src="~/Scripts/jquery-1.10.2.min.js"></script>
   </head>
   <body>
      <div>
         <button id="yinbutton">yin</button>
         <div id="yin">
            @{
               Html.RenderAction("Yin");
            }
         </div>
         <button id="yangbutton">yang</button>
         <div id="yang">
            @{
               Html.RenderAction("Yang");
            }
         </div>
      </div>
      <script type="text/javascript">
         $('#yinbutton').bind('click', function () {
            var route = '@Url.Action("Yin", "Home", new {})';
            $.ajax({
               url: route,
               type: "GET"
            }).done(function (partialViewResult) {
               $("#yin").html(partialViewResult);
            });
         });
         $('#yangbutton').bind('click', function () {
            var route = '@Url.Action("Yang", "Home", new {})';
            $.ajax({
               url: route,
               type: "GET"
            }).done(function (partialViewResult) {
               $("#yang").html(partialViewResult);
            });
         });
      </script>
   </body>
</html>

 
 

Let's also have these two partial views in the mix.

  1. _Yin.cshtml:
    @model int
    <div>Partial One: @Model.ToString()</div>
     
  2. _Yang.cshtml:
    @model int
    <div>Partial Two: @Model.ToString()</div>

 
 

I had a hunch here that state could not be communicated between partials with Session, but this is only partially true. Observe what happens when we run our code.

 
 

What is above shows what happens both when the view spins up and when either of the buttons is clicked. The buttons should increment the number kept in Session up and down, but they do nothing. However, I should stress that if nothing else, at least the zero set upfront is communicated out to the partials. It just seems the partials lack the "page lifecycle" (forgive the web forms analogy) to set something in Session. What if we use the cache instead?

using System;
using System.Runtime.Caching;
using System.Web.Mvc;
namespace Something.Controllers
{
   public class HomeController : Controller
   {
      private static ObjectCache _objectCache
      {
         get { return MemoryCache.Default; }
      }
      
      public ActionResult Index()
      {
         CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
         _objectCache.Add(new CacheItem("state", 0), cacheItemPolicy);
         return View();
      }
      
      public ActionResult Yin()
      {
         int state = Convert.ToInt32(_objectCache["state"]);
         _objectCache.Remove("state");
         state = state - 1;
         CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
         _objectCache.Add(new CacheItem("state", state), cacheItemPolicy);
         return PartialView("_Yin", state);
      }
      
      public ActionResult Yang()
      {
         int state = Convert.ToInt32(_objectCache["state"]);
         _objectCache.Remove("state");
         state = state + 1;
         CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
         _objectCache.Add(new CacheItem("state", state), cacheItemPolicy);
         return PartialView("_Yang", state);
      }
   }
}

 
 

What is below is given upon the spin up initially before any of the buttons are clicked. We can see that the original zero value may not only be communicated outward, but may also be updated!

 
 

The two buttons work too! They will move the number in the cache up and down and communicate that up to the UI by way of an AJAX refresh of some HTML.

browserLink/requestData error at the console with Visual Studio 2013

To get rid of this, right-click on the icon of a circluar arrow bending back on itself in a loop that is just to the right of the option with a green arrow for previewing your code in a browser with the debugger (should be the only button with a rightward pointing green triangle) and then toggle "Enable Browser Link" to stop this.

Sunday, October 23, 2016

Windows Communication Foundation is what the WCF in WCF web services stands for.

...XML and SOAP stuff.

ITT Technical Institute loses accreditation!

I just ran into a friend who has an associates degree from ITT Tech and now that degree is worthless. He is going to start a legal process to wiggle away from his student debt which was accrued for not. What a gut punch. ITT used to stand for International Telephone and Telegraph so they must have been around for forever. Now they are gone.

Abstraction is a technique for arranging complexity.

I know that's vague. (It's what Wikipedia says.) It's teasing two concerns apart and letting them touch through modest isolation from each other. An abstract class in C# has some extra methods that the thing inheriting from it gets to use, etc. This as opposed to having one big fat class with no inheritance break out. That which gets abstracted out in this case could be repurposed by a second child.

Friday, October 21, 2016

Thursday, October 20, 2016

OnResultExecuting and OnResultExecuted

These ASP.NET MVC events happen in this order:

  1. OnActionExecuting
  2. OnActionExecuted
  3. OnResultExecuting
  4. OnResultExecuted

 
 

OnResultExecuting and OnResultExecuted are for coughing up the view after the Action is done with its handover.

some notes on Entity Framework

The code first approach comes with some troubles. A DBA cannot just add a column at a table and expect that to be matched by a developer adding a corresponding getsetter on a POCO. The change has to be hydrated to the database from the code. Data Migrations with Code First expect a very specific configuration and are otherwise sabotaged if code first is not indeed, code first. Code first and the "read from schema" .edmx thing are BOTH bad as it turns out, but we are not stuck with just two bad choices as it turns out. There is another approach called Reverse Engineering Code First which creates classes off an existing schema. You should not, with this approach, start with Code First and then generate a second code base off of drinking up the database tables as the two code bases will be different. You need to start with the database. I was told all this verbally yesterday and I also learned that the hydrated code from the database all ends up in one folder and that that folder may just be destroyed and rerendered when the schema changes. When my mind attempts to picture this it also pictures that that which I would put in the Infrastructure and that which I would put in the Core in an Onion Architecture to be sprinkled about in the same folder together. Maybe the third choice has a dark side?

pseudoSQL inside NHibernate

You break into HQL when you admit the ORM ain't all that and HQL stands for Hibernate Query Language. The problem is that it's not quite SQL and you have to learn this other, goofy thing.

Wednesday, October 19, 2016

Who are the gang of four?

They are the authors of "Design Patterns: Elements of Reusable Object-Oriented Software"

  1. Eric Gamma
  2. Richard Helm
  3. Ralph Johnson
  4. John Vlissides

Robert Cecil "Uncle Bob" Martin and Martin Fowler on not on the list. I just made this mistake in an interview. :(

casting fails!

Consider the following C# classes:

  1. namespace Something.Models
    {
       public class Cat
       {
          public int Lives { get; set; }
          
          public Cat()
          {
             Lives = 9;
          }
       }
    }
     
  2. namespace Something.Models
    {
       public class BakersCat : Cat
       {
          public BakersCat()
          {
             Lives = 13;
          }
       }
    }
     
  3. using Something.Models;
    namespace Something.Utilities
    {
       public static class Killer
       {
          public static Cat Kill(Cat cat)
          {
             cat.Lives = cat.Lives - 1;
             return cat;
          }
          
          public static void Kill(ref Cat cat)
          {
             cat.Lives = cat.Lives - 1;
          }
       }
    }

 
 

Well this won't work...

BakersCat muffin = new BakersCat();
muffin = Killer.Kill(muffin);

 
 

...and this won't work either!

BakersCat cookie = new BakersCat();
Killer.Kill(ref cookie);

Tuesday, October 18, 2016

Well, I see cobwebs on my resume. It must time for Halloween.

I can't remember what HubSpot and Manticore even are! Mozilla Thunderbird is an email client.

XSL stands for eXtensible Stylesheet Language

...and XSLT and XSL-FO are the two varieties. I had not heard of XSL-FO before today. It seems to be the markup that is under the hood in an Adobe Acrobat PDF (Portable Document Format) file.

.NET 3.0 came out of the box with Visual Studio 2008.

You had to install an update to get .NET 3.5 which unlocked C# 3.0 and the LINQ (Language Integrated Query) and Lambda stuff that came with it. C# 2.0 and C# 3.0 used the same runtime engine and basically the 3.0 stuff gave you different things to compile to CLR without any of the CLR itself being new.

Monday, October 17, 2016

Merge Sort Algorithms

I just read this and found it interesting. I'm intrigued by the O(n²) challenge of a loop running inside a loop and how to optimize it. One suggestion, which will NOT fit every case, may be to break that which is being crawled up into chunks. If there are sixteen items to crawl and sixteen squared is two hundred fifty-six, then if we broke the sixteen up into four fours and four squared is just sixteen again and sixteen times four is just sixty-four, then we are starting off in a better place than with two hundred fifty-six. When we cross-compare our four chunks I guess we have to do it wisely, but hopefully the optimization keeps us from climbing as high as two-hundred fifty-six, etc.

.SingleOrDefault

...in LINQ is a lot like .FirstOrDefault. If you are familiar with .FirstOrDefault you can probably guess what .SingleOrDefault does, huh?

  1. It will return the default value for the type if there are no matches.
  2. It will return what it finds if there is one match.
  3. It will throw an exception if there is more than one match.

You can have two columns with the same name come back in a T-SQL select.

...but it can't be healthy.

struct copies in C#

A struct, when copied, will carry into the new copy new value types such an int and DateTime and clearly changing these at one copy does not alter them at the other copy... but what about reference types for pointers? If it's a string, there will be a new string at the copy with a new pointer and changing one string does not affect the other, but if it's a class, the two structs will both have pointers to the same spot on the heap for the class. If you use structs instead of classes as your secondary actors then you cannot change up the getsetters on them after the fact, you to new up a new secondary struct to make a change to a copy of a class clinging to it at a property. The same trick obviously can be done to get around dupe pointer problems with classes.

You may NOT have a getsetter in a class that has the same name as the class in C#.

Meh.

One may just make an MVC action return null and it will serve up no HTML.

Cool.

There is such a thing a nullable value types in C#!

There is a mut keyword one may use in structs to bring in mutability. It's hacky.

A screen door on a stored procedure is not as silly as a screen door on a submarine.

Instead of having one sproc which gets a bunch of cats by int key and another that gets the cats by varchar special name identifier, it is best if there is one sproc with some complicated front door logic (if not null for one, then find the other) to keep the sprocs from being copied into two places and requiring logic that trickily will need maintenance in two places when the Cat table gets a new column. Meow!

Resolve Conflict

Going to: Resolve > Resolve Conflict ...tends not to actually clean up the mine/theirs in code and instead just marks a file as resolved so you may check it back into source control without source control complaining. Be careful with this.

else if!

namespace Something.Something
{
   public static class Whatever
   {
      public static int GetNumber(bool? foo)
      {
         int bar = 13;
         if (foo == null)
         {
            bar = 42;
         }
         else if (foo == true)
         {
            bar = 69;
         }
         else
         {
            bar = 86;
         }
         return bar;
      }
   }
}

protected override

Consider:

using AutoMapper;
namespace Payme.Whatever
{
   public class FooMapping : Profile
   {
      public override string ProfileName => GetType.Name;
      
      protected override void Configure()
      {
         Mapper.CreateMap<Foo, Bar>();
      }
   }
}

 
 

Random thoughts on this...

  1. I'm not sure what setting the Profile name in AutoMapper's way of doing things gets us.
  2. protected override is a thing. Think IDisposable.
    • This may or may not be a Liskov violation. It depends on the intent of "contract" and would be changes.
      • If you do your own thing in an IDisposable pattern and then call base.Dispose() it's not a violation.

how to make a field in a DevExpress MVC grid a link

settings.Columns.Add(m => m.Name, column =>
{
   column.SetDataItemTemplateContent(content =>
   {
      ViewContext.Writer.Write(
         Html.ActionLink(Context.Text, "Action", "Controller", new { foo =
                DataBinder.Eval(content.DataItem, "Name")}, null).ToHtmlString()
      );
   });
});

 
 

Yes, you have to have that null. Trust me.

Sunday, October 16, 2016

MyGrid.ClearFilter();

...will clear the filter fields at an MVC DevExpress grid.

how to conditionally hide a DevExpress grid if the model bound (a collection) has no records BUT NOT WHEN FILTERING ROWS HIDES ALL ROWS

We need something like this, but more complicated, and so...

s.SetVisible ( s.GetVisibleRowsOnPage() > 0 );

 
 

...should be replaced with handing s into a more complicated function.

function MaybeHide(s) {
   if(s.GetVisibleRowsOnPage() > 0) {
      s.SetVisible(true);
   } else {
      var actors = $('input[type=text]').toArray();
      var isFiltering = false;
      for (var i=0; i < actors.length; i++) {
         if(i !=0 && i != (actors.length-1)){
            if (actors[i].value) {
               isFiltering=true;
            }
         }
      }
      if(!isFiltering) {
         s.SetVisible(false);
      }
   }
}

 
 

Above:

  • for (var i=0; i < actors.length; i++) { checks to see if a field for filtering is doing its thing, but not every field. We are making some assumptions and only checking to see if the fields which are not the first and last field have copy in them. The last field is likely the pagination drop down. The first field in this example? Oh, perhaps a different control elsewhere on the page. This has to be set on a case-by-case basis. Tailor it to your stuff!
     
  • if (actors[i].value) { is going to be falsey if the filter field is empty and truthy otherwise. Get it?

The Ankh way of cleaning up conflicts in Visual Studio is a lot cleaner than figuring out the mine/theirs stuff which it kinda hides from you.

  • Go to: View > Other Windows > Pending Changes
  • Find an applicable line item here and pick "Edit Conflicts" after right-clicking upon it.
  • Check checkboxes.
  • Click "Accept Merge" at the upper right.
  • Once more find your line item, right-click upon it and pick: Resolve > Resolve Conflict

how to conditionally hide a DevExpress grid if the model bound (a collection) has no records

settings.ClientVisible = Model.Any();
settings.ClientSideEvents.EndCallback = "function(s,e) { s.SetVisible (
      s.GetVisibleRowsOnPage() > 0 ); }";

It is probably wise to have nullable ints instead of ints at signatures for actions driving partials.

This makes them less error prone. If they are called without a value being handed in they will not squawk an exception.

Use the "Network" tab under the F12 tools in Google Chrome to see if a controller action is even being hit. It will show traffic.

  • Uncaught TypeError: Cannot read property 'validator' of undefined
  • Uncaught TypeError: $ is not a function

These errors appear in the console of Google Chrome if jQuery's script tag doesn't come before the script tags for DevExpress. The DXR.axd will be mentioned. jQuery's script tag really needs to go at the top of the page and not in the footer.

State maintenance in the MVC DevExpress paradigm is super painful!

The how to for communicating records from a view to a partial across a callback refresh in the DevExpress paradigm is tricky. You cannot use a backing store in the traditional sense (a field or a getsetter) which basically means you are left with:

  1. putting things in the cache
  2. or serializing types to strings, letting strings travel from C# into JavaScript and then back to C# and then deserializing

In the first approach, you will use a magic string (maybe a GUID) for a key to a bit of the cache that should expire in fifteen minutes (strongly recommend, and I mean the cache contents should expire not the GUID, mkay?) and that magic string will, like serialized gunk, go from C# to JavaScript and back to C#. You can also go to the database every time you reload a partial to rehydrate obviously if you want to forgo lingering state conceptually altogether. It's up to you as to if that makes sense. I assume you cannot just use Session. I've had the worst AJAX experiences with Session.

Addendum 10/25/2016: You can somewhat use Session, in a sickly way. See: this

big theta and big omega are other ways to grade algorithms like big O

this and this touches on Big-ϴ and Big-Ω

another generic example of a DevExpress MVC GridView with a lot of the functionality wired up

@{
   Html.DevExpress().GridView<Foo>(
      settings =>
      {
         settings.Columns.Add(m => m.Bar, column =>
         {
            column.Width = Unit.Percentage(25);
         });
         settings.Name = "Whatever";
         settings.Styles.Header.CssClass = "myHeader";
         settings.Styles.PagerBottomPanel.CssClass = "gridPager";
         settings.Styles.AlternatingRow.CssClass = "meh";
         settings.Settings.ShowFilterRow = true;
         settings.Settings.ShowFilterRowMenu = true;
         settings.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
         settings.SettingsBehavior.AllowGroup = false;
         settings.SettingsBehavior.AllowSort = false;
         settings.SettingsPager.AlwaysShowPager = true;
         settings.SettingsPager.PageSizeItemSettings.Visible = true;
         settings.SettingsAdaptivity.AdaptivityMode =
               GridViewAdaptivityMode.HideDataCells;
         settings.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = true;
         settings.EditFormLayoutProperties.SettingsAdaptivity.AdaptivityMode =
               FormLayoutAdaptivityMode.SingleColumnWindowLimit;
         settings.EditFormLayoutProperties.SettingsAdaptivity
               .SwitchToSingleColumnAtWindowInnerWidth = 600;
         settings.SettingsPager.PagerSizeItemSettings.Items = new string[] { "10", "25",
               "50" };
      }
   ).Bind(Model).GetHtml();
}

 
 

A few things about this:

  1. This markup really needs to go in a partial all by itself. It's OK if there is some other Razor markup in there to loop in a List of Foo as the Model for example, but there cannot be another bit of markup in the partial which makes other HTML that sits side by side with our princess as otherwise princess will misbehave.
  2. That which is in yellow is our List of Foo.
  3. That which is in purple is a needed note to suggest that in contrast to what the collection might be hydrating the whole list, an individual line item is of Foo. Doesn't this seem silly? It sure does to me. It seems like DevExpress could just figure this out for you. It makes me think of .min.js.map, but I digress.
  4. That which is in purple must be there in order for that which is in teal to work.
  5. That which is in white may be crafted in an alternative way as shown below. Choose wisely.

@(
   Html.DevExpress().GridView<Foo>(
      settings =>
      {
         settings.Columns.Add(m => m.Bar, column =>
         {
            column.Width = Unit.Percentage(25);
         });
         settings.Name = "Whatever";
         settings.Styles.Header.CssClass = "myHeader";
         settings.Styles.PagerBottomPanel.CssClass = "gridPager";
         settings.Styles.AlternatingRow.CssClass = "meh";
         settings.Settings.ShowFilterRow = true;
         settings.Settings.ShowFilterRowMenu = true;
         settings.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
         settings.SettingsBehavior.AllowGroup = false;
         settings.SettingsBehavior.AllowSort = false;
         settings.SettingsPager.AlwaysShowPager = true;
         settings.SettingsPager.PageSizeItemSettings.Visible = true;
         settings.SettingsAdaptivity.AdaptivityMode =
               GridViewAdaptivityMode.HideDataCells;
         settings.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = true;
         settings.EditFormLayoutProperties.SettingsAdaptivity.AdaptivityMode =
               FormLayoutAdaptivityMode.SingleColumnWindowLimit;
         settings.EditFormLayoutProperties.SettingsAdaptivity
               .SwitchToSingleColumnAtWindowInnerWidth = 600;
         settings.SettingsPager.PagerSizeItemSettings.Items = new string[] { "10", "25",
               "50" };
      }
   ).Bind(Model).GetHtml()
)

Adobe XD is going to be another prototyping tool like Sketch or Balsamiq.

XD is short for Experience Design!

AutoMapper after version 4.2 requires that you hand in your own version of IMapper for Mapper and is going to want more verbose code in general going forward from that divide?

Well no, perhaps IMapper hand-ins are not required after all. jbogard suggests "5.0 is just Mapper.Initialize still. I didn't kill the static stuff, just Mapper.CreateMap" and moreover "Mapper.Initialize. There's a lambda there you add your CreateMap to. All config done once at startup"

Why is DevExpress throwing up JavaScript alerts filled with unformatted HTML and error messages?

When updating a DevExpress control with a callback in the MVC paradigm it is all important that the DevExpress control be in a partial by itself without a bunch of other HTML (or any) sprinkled inside the control as this will sabotage the callback and when the callback is called the effect of a bunch of HTML barfing up in a JavaScript alert will materialize. Also you have to update DevExpress controls (from other controls) this way (callbacks). The AJAX HTML scrape-n-splice trick won't allow DevExpress controls to function healthily. If you isolate controls into their own partials and you still see these funny errors, attach the debugger in Visual Studio 2015 and try breaking on all exceptions.

Make one DevExpress control update another in MVCland.

If you are more or less just refreshing HTML this trick for updating an MVC partial with AJAX will work, however if the partial to be updated contains another DevExpress control, lookout! You’re in trouble and things are about to get interesting. The AJAX refresh approach will paint to the screen a DevExpress control which behaves sickly with its JavaScript mechanics jacked up. For example, you might be able to display a GridView but not sort the grid. Awesome! So, what to do about that? Let's say we want one DevExpress ComboBox to update another when it's changed. Perhaps there is some sort of hierarchal relationship and the second ComboBox is subordinate to and dependent on the first with regards to what its own contents are. Alright, the actor DOING the affecting looks like so:

@Html.DevExpress().ComboBoxFor(m => m.Id, settings =>
   {
      settings.Name = "MerchantSelection";
      settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
      settings.Properties.ValueField = "Key";
      settings.Properties.ValueType = typeof(int);
      settings.Properties.TextField = "Value";
      settings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s,e){
            BuyerSelection.PerformCallback(); }";
   }
).BindList(ViewBag.MerchantMatches.GetHtml()

 
 

Well, OK. It's not doing that much really, huh? It's just calling the callback on another control, the subordinate ComboBox. Both ComboBoxes need to be in MVC partials all by themselves. The second actor looks like this:

@Html.DevExpress().ComboBoxFor(m => m.BuyerId, settings =>
   {
      settings.Name = "BuyerSelection";
      settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
      settings.ValueField = "Key";
      settings.ValueType = typeof(int);
      settings.Properties.TextField = "Value";
      settings.CallbackRouteValues = new { Controller="Buyer", Action="ProfileBuyers" };
      settings.CLientSideEvents.BeginCallback = "function(s,e){
            e.customArgs['merchantId'] = MerchantSelection.GetValue(); }";
   }
).BindList(ViewBag.BuyerMatches).GetHtml();

 
 

In the example at the link above (at the beginning of this blog posting) s.lastSuccessValue is handed into buyerId at a JavaScript function signature, and immediately above merchantId, sniffed off of the other ComboBox which just got set to something new, is going to be handed into the ProfileBuyers action at BuyerController, hydrating a variable there. The action will then do its thing and resurface a partial view, and it is the partial view holding the control immediately above. Get it?

Name partial views in MVC with a leading underscore and then Pascal case wording.

Similarly, regular views should be in Pascal case and match in the name of the Action that is to summon them.

When "Sql Source Control" starts acting like it can't make a connection because another instance of SSMS is open...

...you'll need to get rid of that other thing. I ended up just restarting my VM to solve this.

Saturday, October 15, 2016

When a model binds null values in the DevExpress MVC paradigm...

Per this, this:

[HttpPost]
public ActionResult Whatever(Foo foo)
{

 
 

...may need to become this:

[HttpPost]
public ActionResult Whatever([ModelBinder(typeof(DevExpressEditorsBinder))] Foo foo)
{

There is no way to insert something into a dictionary in C# and not have it last most in the perceived ordering.

Hack around this by creating a list and getting it in the right shape and then doing a .ToDictionary on it.

A lambda expression is an anonymous function in C#.

...but for the most part there are no functions in C#. One cannot use the terms function and method interchangeably as one may in some situations in JavaScript where every method is a function if not the other way around. (A method is a function hanging off of a JSON object as a property therein.) There are also Equals O'Arrow anonymous functions too in C#:

delegate void TestDelegate(string s);
TestDelegate foo = (x) => { Console.WriteLine(x); };
foo("Hello World!");

how to use a DevExpress ComboBox to update a partial view

@Html.DevExpress().ComboBoxFor(m => m.BuyerId, settings =>
   {
      settings.Name = "BuyerSelection";
      settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
      settings.Properties.ValueField = "Key";
      settings.Properties.ValueType = typeof(int);
      settings.Properties.TextField = "Value";
      settings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s,e){
            UpdatePartials(s.lastSuccessValue) }";
   }
).BindList(ViewBag.PotentialMatches).GetHtml()

 
 

ViewBag.PotentialMatches above is a collection being handed in to the ComboBoxFor while s.lastSuccessValue is going to be handed into buyerId at the first line of code in some JavaScript (with some jQuery) here:

function UpdatePartials(buyerId){
   var route = '@Url.Action("Whatever", "Buyer", new { cacheKey="guidgoeshere",
         buyerId=0 });
   route = route.replace('0', buyerId);
   route = route.replace('guidgoeshere', '@ViewBag.CacheKey');
   route = route.replace('&', '&');
   $.ajax({
      url: route,
      type: "GET"
   }).done(function(partialViewResult) {
      $("#whateverWrapper").html(partialViewResult);
   });
}

 
 

DevExpress controls will behave rather sickly if there is not explicitly some callouts at the top of the view to loop in needed JavaScript and CSS like so:

@Html.DevExpress().GetStyleSheets(new Stylesheet
{
   ExtensionType = ExtensionType.CheckBox
})
@Html.DevExpress().GetScripts(new Script
{
   ExtensionType = ExtensionType.CheckBox
})

 
 

These bits of Razor markup are control-specific so, in our case, we will need to loop in the ComboBox:

@Html.DevExpress().GetStyleSheets(new Stylesheet
{
   ExtensionType = ExtensionType.GridView
}, new Stylesheet
{
   ExtensionType = ExtensionType.ComboBox
})
@Html.DevExpress().GetScripts(new Script
{
   ExtensionType = ExtensionType.GridView
}, new Script
{
   ExtensionType = ExtensionType.ComboBox
})

 
 

The style part needs to go in the head before other styles and stylesheets. The JavaScript part could be broken out for elsewhere. Indeed the DevExpress JS should come AFTER jQuery's script tag.

This think this is how you add something to the cache in C# which will die in 15 minutes.

_cache.Add(ViewBag.Cache, buyers, DateTime.Now.AddMinutes(15));

 
 

Herein _cache is an instance of ObjectCache and buyers a List of T.

Use Html.Action to render a partial while also running its Action.

@Html.Action("Foo", "Bar", new {bar="Qux"})

 
 

...is gonna run this action in the BarController:

public ActionResult Foo(string baz)
{

DevExpress Razor markup for a callback panel in the MVC paradigm

@Html.DevExpress().CallbackPanel(settings => {
   settings.Name = "myCallback";
   settings.CallbackRouteValues = new { Controller="Foo", Action="Bar" };
   settings.SetContent(() => {});
}).GetHtml()

 
 

These are not as life and death vital in MVC as they are in web forms. I wrote the code above seventeen days ago, never got it working, and have never needed it since. In MVC implementations of DevExpress controls one may just call out to other controls to make them refresh without a helper wrapper around everything. You don't need this stuff. You may make the callback happen from, for example, the change of a ComboBox control like so:

settings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s,e){
      myCallback.PerformCallback(); }";

The connectors for lightning ports have pins on the outside and the connectors for USB Type C have pins on the inside but are otherwise about the same.

Lightning ports replace a 30 pin connector's connection at iPhone 5 and up while the older phones expect that you have USB to 30 pin cords.

deterministic versus nondeterministic

That which is deterministic will return consistent results every time, like math functions, while that which is nondeterministic has a little play in the steering if you will. DateTime.Now doesn't give you the same thing whenever you ask for it in C# for example.

IAC or InterActive Corp which owns match.com, Tinder, and OkCupid pretty much has a lock on the dating site space.

eHarmony is going to be an exception to the not-quite monopoly.

In abandoning "check in early and often" and trying to have as few merges as possible, it begs the question: Should I merge "early and often" eh?

...or alternatively should I just have one big merge at the end. There is no consensus amongst my coworkers. If I have one big merge at the end, it should make it easier to make a safety copy of the whole codebase (if repeated as a chore constantly this is annoying) in advance of pulling down possibly breaking changes.

You may make free phone calls over Facebook.

I didn't know this until recently but it's pretty cool. Both parties need to have Facebook up and to be connected to the internet over Wi-Fi I think. I don't really know much about it.