try {
}
catch {
}
finally {
}
Remember the finally. This is a good place to close that SqlConnection you opened.
try {
}
catch {
}
finally {
}
Remember the finally. This is a good place to close that SqlConnection you opened.
In 2008 I took an SOA training taught by Udi Dahan. I wish I could find my notes. I think they are sitting on a server Headspring has probably gotten rid of. :(
Udi's NServiceBus wraps MSMQ (Microsoft Message Queuing) and takes the pain out of using it. I say that having never used NServiceBus myself.
Here I found a link to here listing the 8 fallacies of distributed computing:
This goes into the five types of coupling:
This touches on searching folders in Windows 7 and in particular suggests that you go to:
Organize > Folder and search options > Search
...from the Orgainize button on the file view for a given folder to tweak search settings.
Again: Value types are immutable (they cannot change) while reference types are mutable, and value types go on the stack and reference types go on the heap.
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap asserts:
http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx goes into boxing and unboxing which has to do with converting a value type to an object or, in the case of unboxing, an object back to a value type. An example of boxing:
int i = 123;
object o = i;
...of unboxing:
o = 123;
i = (int)o;
This image shows how another piece of memory is allocated in the boxing process. Hence, there are some performance issues with boxing as a value type on the stack gets copied to the heap as it is boxed. (That said, you are very likely better off worrying about how to optimize database integration in the name of reducing lag instead of having angst over boxing and unboxing.)
Value objects are not always just simple types:
http://tom-jaeschke.blogspot.com/2011/12/entities-have-both-state-and-lifecycle.html has my notes from when I saw Paul Rayner speak on DDD. He suggested that Eric Evans suggests that objects which are not entities (and thus do not have a lifecycle) should be (if not DTOs) value types. Examples given of value domain objects that one might speak about in ubiquitous language were:
http://www.htmlgoodies.com/html5/tutorials/create-drop-down-menus-with-css3.html#fbid=LCLjK-3H7T9 shows off making drop down menus without the need for JavaScript to hide and unhide things. Use logic like this:
.drop-menu:hover .sub-menu {
display: inline-block;
}
I found this posting on getting rid of phone number hyperlinks. It suggests turning them off like so:
<meta name="format-detection" content="telephone=no">
...and on like so:
<a href="tel:1-408-555-5555">1-408-555-5555</a>
I have yet to try it.
This told me about this:
if (!Foo.ContainsKey(person.Id.ToString()))
{
Foo.Add(person.Id.ToString(), person.Name);
}
var allBazes = Foo.GetBazes(qux).Concat(Bar.GetBazes(qux)).Distinct().ToList();
I figured out how to make an endless grid of hexagons spiral outwards from a central point.
I took the SQL here and added this to it:
CREATE TRIGGER dbo.AddressTrigger
ON dbo.Address
AFTER INSERT
AS
INSERT INTO Person (PersonId, Name, AddressId)
VALUES (NEWID(),'I need a name','1ba51989-84fb-4a61-8c35-9e6a007bc0fb')
In doing so I created a trigger that will fire whenever a row is inserted into the Address table. The trigger will make a new row in the Person table. I wanted the process to assign the Person the Address of the Address just created, but I find in hard to know what the uniqueidentifier most recently used is. :(
I found this stuff in Googling to figure out the above:
Some of the above touches on @@IDENTITY and SCOPE_IDENTITY() would have been handy for solving the problem above if I were using ints for ids instead of guids.
It's very often best to just admit that you're not 100% sure you want what you think you want. If you have a voice inside saying "I think I want that glowy grabme, but I wish I also had a way to change my mind once I put my hands on it" such a thought is not only normal, but healthy. The nature of the Agile process allows one to push big commitments as far down the pipe as possible to allow all parties involved to have some time to chew on whether or not they really want to do a specific thing. In building a jigsaw puzzle, when one picks up a given puzzle piece, rotates it in hand, and chews on if he/she really wants to use it, typically one has the benefit of surveying how all of the other pieces have come together to date and thus the current shape of things effects the decision at hand more than any other factor might. It is good to have all of the information possible to make an informed decision and it is good to a make decisions that will allow you to make such informed decisions. Running a project with an Agile process will allow one to make informed decisions a lot more so than a Waterfall process.
We are just now starting an Agile process. We are fighting our way through some of the pain points, such as not baking enough story points. We are doing better. We are in a second leg of our project.
In the first leg: A liaison (middleman) between our team and the product owners had written a huge functional spec around what he felt the users wanted and we were trying to jam hunks of the Word document into stories and we were... pretending to have an Agile process around the pseudostories.
There is not an Agile process without stakeholder feedback however. We were chipping away at the functional spec in a Waterfall manner.
Eventually the middleman's management style caught up to him and he felt the need to quit. In his absence we started doing things the right way. We are now interfacing directly with the customers that we had been "protected from."
That said, plenty of time has been wasted in going down tangents:
I've now seen firsthand, on the same project, the difference between Waterfall and Agile. I wanted to share my tale. The lesson: Don't try to have all of the answers upfront.
It's OK to feel conflicted.
My previous understand of Closures is bad.
Some of his code:
var createGreeting = function(greeting) {
return function (name) {
document.write(greeting + ', ' + name + '.');
};
};
helloGreeting = createGreeting("Hello");
howdyGreeting = createGreeting("Howdy");
helloGreeting("John"); |
// Hello, John. |
$(document).ready(function () {
var target = $('#portletwrapper');
var widget = target.Portlet({
foo: "bar",
baz: "qux"
});
});
setup: function (defaultStateIsOpen) {
self.options.stateIsOpen = defaultStateIsOpen;
self.options.container = self.element;
self.definePortletHeader(self.options.container.children(":nth-child(1)"));
self.definePortletContent(self.options.container.children(":nth-child(2)"));
self.alterAppearanceBasedOnOpenState();
self.options.portletHeader.click(function () {
self.toggle();
});
self.reveal();
},
setup: function (defaultStateIsOpen) {
var self = this;
self.options.stateIsOpen = defaultStateIsOpen;
self.options.container = self.element;
self.definePortletHeader(self.options.container.children(":nth-child(1)"));
self.definePortletContent(self.options.container.children(":nth-child(2)"));
self.alterAppearanceBasedOnOpenState();
self.reveal();
},
alterAppearanceBasedOnOpenState: function () {
var self = this;
if (self.options.stateIsOpen) {
self.options.portletHeader.children("span").removeClass('ui-icon-plusthick');
self.options.portletHeader.children("span").addClass('ui-icon-minusthick');
self.options.portletContent.removeClass('hide');
} else {
self.options.portletHeader.children("span").addClass('ui-icon-plusthick');
self.options.portletHeader.children("span").removeClass('ui-icon-minusthick');
self.options.portletContent.addClass('hide');
}
},
options: {
stateIsOpen: false, //REQUIRED
stateIsPersisted: false
}
This post on jasmine-jquery method calling was a little confusing for me when I tried to use it for my own reference. So, instead see the following:
var target = $('#portletwrapper');
var widget = target.Portlet();
var act = widget.Portlet('setup', false);
That calls this method:
setup: function (defaultStateIsOpen) {
var self = this;
more code here...
},
https://github.com/velesin/jasmine-jquery offers that one may use this trick to see if an element has a class or not:
expect($('#foo')).not.toHaveClass('hide');
I fished the following out of here:
In web programming, it is an emulation of pushing data, implemented by repeated polling with delayed response.For instance, data may be "pushed" to an HTTP client by using a long-standing HTTP request with protracted response, hence the term "long poll". A true push data model is not otherwise available to the client because it cannot receive incoming HTTP connections.
Try to get around the problem in which an inappropriate project defaults to be the starup project in a solution with:
Tools > Options... > Environment > Startup > At startup:
outerWidth(true) is wider than outerWidth is wider than innerWidth is wider than width
Widths are gagued without regard to whitespace. One has to use the hack to account for whitespace.
default(Foo) gives the default configuration for the type of Foo. I don't understand it yet.
http://weblogs.asp.net/avnerk/archive/2006/05/21/Non_2D00_generic-default-values-in-C_23003F00_-Why-not_3F002100_.aspx
Serializing using a stream should side step any default string size limitations. You can do it like this:
var serializer = new Newtonsoft.Json.JsonSerializer();
var writer = new StringWriter();
serializer.Serialize(writer, obj);
writer.Flush();
string serializedObject = writer.GetStringBuilder().ToString();
Open call stack (while debugging) from: Debug > Windows > Call Stack
Use it to see what method is invoking the method which is failing.
I wrote this class:
using System;
namespace FuncExperiment.Models
{
public class SomethingFunky
{
private Func<string> _whatever;
private Func<Int16> _flapdoodle;
public SomethingFunky()
{
_whatever = () => "just getting started";
_flapdoodle = () => 7;
}
public string SprayFunc()
{
return _whatever();
}
public void PushInStringValue(string value)
{
_whatever = () => value;
}
public void PushInIntegerValue(Int16 digit)
{
_flapdoodle = () => digit;
}
public void MakeStringFromInteger()
{
_whatever = () => TryToGiveGermanNameForSingleDigit(_flapdoodle());
}
private static string TryToGiveGermanNameForSingleDigit(Int16 digit)
{
//follow this link to see the guts of this method
...and got it under test like so:
using FuncExperiment.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace FuncExperiment.Tests
{
[TestClass]
public class TestsForSomethingFunky
{
[TestMethod]
public void test_constructor()
{
SomethingFunky skunk = new SomethingFunky();
Assert.AreEqual(skunk.SprayFunc(), "just getting started");
}
[TestMethod]
public void test_changing_string()
{
SomethingFunky skunk = new SomethingFunky();
skunk.PushInStringValue("this is new");
Assert.AreEqual(skunk.SprayFunc(), "this is new");
}
[TestMethod]
public void test_goofy_German_translation()
{
SomethingFunky skunk = new SomethingFunky();
skunk.PushInIntegerValue(2);
skunk.MakeStringFromInteger();
Assert.AreEqual(skunk.SprayFunc(), "zwei");
}
[TestMethod]
public void must_explicity_call_integer_to_string_translation()
{
SomethingFunky skunk = new SomethingFunky();
skunk.PushInIntegerValue(2);
Assert.AreNotEqual(skunk.SprayFunc(), "zwei");
}
}
}
I wrote this class...
namespace PrivateMethodTesting.Models
{
public class SummationScienceExperiment
{
public int DependentVariable { get; private set; }
public int IndependentVariable { get; private set; }
public double? DivisionCalculation { get; private set; }
public SummationScienceExperiment(int ofStone, int ofClay)
{
DependentVariable = ofStone;
IndependentVariable = ofClay;
DivisionCalculation = craftDecimal(ofStone, ofClay);
}
public void Update(int ofClay)
{
IndependentVariable = ofClay;
DivisionCalculation = craftDecimal(DependentVariable, ofClay);
}
private double? craftDecimal(int ofStone, int ofClay)
{
if (ofClay == 0) return null;
return (double)ofStone/(double)ofClay;
}
}
}
...and then I wrote the following four tests around it. The last test uses reflection to test the private method.
using System;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PrivateMethodTesting.Models;
namespace PrivateMethodTesting.Tests
{
[TestClass]
public class SummationScienceExperimentTests
{
[TestMethod]
public void constructor_should_craft_a_decimal()
{
SummationScienceExperiment foo = new SummationScienceExperiment(5,2);
Assert.AreEqual(5, foo.DependentVariable);
Assert.AreEqual(2, foo.IndependentVariable);
Assert.AreEqual(2.5, foo.DivisionCalculation);
}
[TestMethod]
public void update_should_craft_a_decimal()
{
SummationScienceExperiment foo = new SummationScienceExperiment(5, 2);
foo.Update(4);
Assert.AreEqual(5, foo.DependentVariable);
Assert.AreEqual(4, foo.IndependentVariable);
Assert.AreEqual(1.25, foo.DivisionCalculation);
}
[TestMethod]
public void may_divide_zero()
{
SummationScienceExperiment foo = new SummationScienceExperiment(0, 2);
Assert.AreEqual(0, foo.DependentVariable);
Assert.AreEqual(2, foo.IndependentVariable);
Assert.AreEqual(0, foo.DivisionCalculation);
}
[TestMethod]
public void may_not_divide_by_zero()
{
Type type = typeof(SummationScienceExperiment);
var infos = type.GetMethods(BindingFlags.NonPublic|BindingFlags.Instance);
MethodInfo info = infos[3];
SummationScienceExperiment foo = new SummationScienceExperiment(5, 2);
Assert.AreEqual(info.Invoke(foo, new object[] { foo.DependentVariable, 0 }),null);
}
}
}
using System;
using System.Dynamic;
using System.Diagnostics;
using System.Linq;
using OurApp.Core.Repositories;
using OurApp.Core.Services;
namespace OurApp.Web.UI.CommandProcessing
{
[DebuggerStepThrough]
public class DynamicCommandInvoker: DynamicObject, IDynamicCommandInvoker
{
private readonly string CommandsNamespace = "";
public DynamicCommandInvoker(string commandNamespace = "")
{
this.CommandsNamespace = commandNamespace;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args,
out object result)
{
result = default(object);
var processorName = BuildCommandProcessorName(binder.Name);
var type = Type.GetType(processorName);
//ensure processor type exists and is present in local assembly
if (type == null) throw new Exception(string.Format("please make sure your
command processor class exists and is in the {0} namespace)",
CommandsNamespace));
var processor = Activator.CreateInstance(type, args);
ResolveDependencies(processor);
//ensure processor is an ActionCommand
if (processor == null || !(processor is CommandBase)) throw new Exception("please
make sure your command processor inherits from ActionCommand");
result = ((CommandBase)processor).Process();
return true;
}
private void ResolveDependencies(object command)
{
var type = command.GetType();
var props = type.GetProperties(System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Instance).Where(prop => prop.CanWrite &&
prop.PropertyType.GetInterfaces().Any(iface => iface == typeof(IRepository) ||
iface == typeof(IService)));
props.ForEach(prop =>
{
var value = ServiceLocator.Get(prop.PropertyType);
if (value != null) prop.SetValue(command, value, null);
});
}
private string BuildCommandProcessorName(string methodName)
{
string formatString = CommandsNamespace + ".{0}Command";
return string.Format(formatString, methodName);
}
}
public interface IDynamicCommandInvoker
{
}
}
My last blog posting is terrible. Use this instead:
<div id="badbrowserspecifications"></div>
<script src="/Scripts/jquery-latest.js" type="text/javascript"></script>
<script type="text/javascript">
var ua = $.browser;
var txt = "<p>The browser you are using: ";
if (ua.mozilla) {
txt += "Firefox";
} else {
if (ua.msie) {
txt += "Internet Explorer";
} else {
if (ua.safari) {
ua.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
if (ua.chrome) {
txt += "Chrome";
} else {
txt += "Safari";
}
} else {
if (ua.opera) {
txt += "Opera";
} else {
txt += "not Firefox, IE, Safari, Chrome, or Opera";
}
}
}
}
txt += "<br />...versioned at: " + jQuery.browser.version + "</br>";
txt += "......is insufficient for our application.</p>";
document.getElementById("badbrowserspecifications").innerHTML = txt;
</script>
Sources for my change of heart:
http://www.w3schools.com/js/js_browser.asp taught me that I may sniff my browser's specifications with JavaScript like so:
<div id="badbrowserspecifications"></div>
<script type="text/javascript">
var txt = "<p>The browser you are using: " + navigator.appName + "<br />";
txt += "...codenamed " + navigator.appCodeName;
txt += " and versioned at: " + navigator.appVersion + "</br>";
txt += "......is insufficient for our application.</p>";
document.getElementById("badbrowserspecifications").innerHTML = txt;
</script>
@{
ViewBag.Title = "Unsupported Browser";
Layout = null;
}
<h1>@ViewBag.Title</h1>
I wish I understood the = () => operator one uses with Func in C#. I don't even know what it is called. It seems that you may prep a Func within a class (in this case DateHelper) like so:
public static Func<DateTime> Now = () => DateTime.UtcNow;
...and then sort of override it by way of a monkey patch like so in another situation (in this case in a test):
DateHelper.Now = () => new DateTime(2000, 1, 1);
using System;
using System.Web.Mvc;
using OurApp.Core.Entities;
using OurApp.Web.UI.CommandProcessing;
using OurApp.Web.UI.CommandProcessing.Commands;
using OurApp.Web.UI.Models.InputModels.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace OurApp.Tests.Unit.UI.CommandProcessing.Commands
{
[TestClass]
public class OrderCommandTestsTemplate : CommandTestBase
{
[TestMethod]
public void boiler_plate_testing_skeleton_sample()
{
//input model
var inputModel = new OrderInputModel();
//output model
var order = new Order();
//mock your behaviors
MocksRegistry.OrderRepositoryMock.Setup(x => x.Save(order));
Func<ActionResult> success = () => new ViewResult();
Func<ActionResult> fail = () => new ViewResult();
//build target
var command = new EditOrderCommand(inputModel,
new Actions(null).OnSuccess(success).OnFailure(fail));
//excersise sut
command.Process();
//expectations
Assert.IsFalse(inputModel.Processed);
}
}
}
This is how you would call our Command Processor from a controller action and dive into a wormhole:
[HttpPost]
public ActionResult Edit(OrderInputModel inputModel)
{
return CommandProcessor.EditOrder(inputModel, Actions
.OnSuccess(() => RedirectToAction("Index"))
.OnFailure(() => View("Edit", BuildSelectListsForModel(inputModel))));
}
Joel Holder hosted an informative meeting today on an approach to architecture that he has put together with Rafael Torres. Wormholes are key term in the new vision for the objects to come in our app. The way that CRUD around objects has materialized in our application has been unsophisticated so far and has come with a lot of problems. Going forward, as we start to build out the richer objects with lifecycles (the sort of objects that Eric Evans would consider entities) we want to get things right, and in particular we want to make things easier to test. Joel, pictured here, started the meeting by explaining why it was painful to have controllers interact directly with repositories in the DAL (Data Access Layer) within a Palermo Onion.
This is the traditional way to build an ASP.NET MVC app, but it is proving hard to test. Controllers are making calls to repositories and handing repository references down into models. Testing a controller requires going on a spelunking expedition for the things one needs to mock just in the name of getting a would-be test to the point where it fails instead of throwing an exception. Instead, Joel feels that controllers should have no collaborators that are managed objects (no repository references). He models his MVC approach on what he sees as a growing trend away from having controller do more than routing and he mentioned that in the node.js framework called Express that controllers were eventually renamed to be "routers" in a wise move. He feels a layer for Command Processors (light circles below) should sit between the rest of our onion and the Controllers (darker circles below) and that communication should occur through wormholes (red item below).
The Command Processors will in turn "talk" to service layers in our onion which will "talk" to the DAL and back. The wormholes make our Command Processors different than the Command Processors of Headspring which were baked before the dynamic objects of C# 4.0. The wormhole analogy suggests putting something into a tunnel and knowing that it will emerge from the tunnel somewhere, but not being able to see where from the entry point. Using the dynamic feature of C# 4.0, Joel has empowered the ability to call a method of any name on a Command Processor's DynamicCommandInvoker. If one calls .EditOrder for example, our app will try to find a file dubbed "EditOrderCommand.cs" to find an appropriate class for the "method" called, but to the controller doing the calling calls .EditOrder blind to as much. The controller calling .EditOrder basically asserts a desire to:
ProcessCommand(), shown above, is the method inside any one particular command file that will do the deed and will be the one method to really test, test, test.
TempData["foo"] = "bar";
...is not going to linger as long as...
Session["foo"] = "bar";
http://stackoverflow.com/questions/1500402/when-to-use-tempdata-vs-session-in-asp-net-mvc suggests it is "for redirects, and redirects only."
@if (ViewBag.ShouldShowSuccessMessage != null)
{
ViewBag.ShouldShowSuccessMessage = null;
<script type="text/javascript">
showSuccess("Your changes have been saved!");
</script>
}