Untitled
| Created: | 6/15/2011 2:46 PM |
neat to have a controller constructor use structure map to get a univeral repository
out is kind of like ref
| Created: | 7/26/2011 9:34 AM |
...perhaps research later
RedirectToRoute and @Html.RouteLink
| Created: | 6/16/2011 10:07 AM |
RedirectToRoute("Default", new { controller = "Conference", action = "Save" });
use the Default route and pass the following values for controller and action
@Html.RouteLink("Conferences", "Default", new { controller = "Conference", action = "Index" })
so "Conferences" as the link name and the next two parameters are effectively the same as the two parameters in RedirectToRoute
Get Rid of Repeated Markup
| Created: | 6/17/2011 9:31 AM |
MVC Templates...
Somewhat like partial views but not as complex
Driven based on types
Editor and Display templates
Lighter than partials
Meatier than HtmlHelper extensions
Drive content from model metadata
Building options Html Helpers
String-based
@Html.Display("FirstName"
Expression-based
@Html.DisplayFor(x=> x.FirstName)
Model-based
@Html.DisplayForModel %
Also EditorXyz for each of the displays...
<%= Html.EditorForModel() %>
Untitled
| Created: | 6/15/2011 12:12 PM |
@if (someCondition) { <text>This is plain text content</text> } ...the text tag will not appear
Untitled
| Created: | 6/15/2011 1:58 PM |
public virtual void RegisterFor(Conference conference)
{
Conference
ViewData.Model
| Created: | 6/16/2011 7:51 AM |
ViewData.Model behind the scenes works like return View(model);
Make Models for every view so that when they change you do not: 1 sabotage another screen or 2 expose too much information (behold YAGNI)
A View is to render the View Model...
View is shown based on the action name and the controller name
If .NET cannot find a view in the appropriate folder it will then try to look into the shared folder
Untitled
| Created: | 6/15/2011 3:04 PM |
I was wrong about EditFor
change that dropdown that just says 'master'
| Created: | 6/21/2011 8:25 AM |
In MSSQL Management Studio Express 2005 there is a dropdown that says 'master' to the left of the Execute button for running a query. Change this to be the name of an appropriate database to run a query against the database.
Routes
| Created: | 6/16/2011 9:00 AM |
routes.MapRoute("catalog", "{action}",
new {controller = "Catalog"},
new {action = @"basket|checkout"});
routes.MapRoute("catch-all", "{*catchall}",
new { controller = "Error", action = "NotFound" });
this will catch anything else that is not found and is good for
figure out the route table... doesn't make sense...
<%= Html.ActionLink("WDG0001", "show", "catalog",
new { widgetCode = "WDG0001" }, null) %>
this renders the following which be
<a href="/WDG0001">WDG0001</a>
...
initialize AutoMapper Profiles
| Created: | 6/16/2011 1:47 PM |
http://mhinze.com/2009/07/06/automapper-in-nerddinner/
namespace NerdDinner.Helpers.AutoMapper{
public class AutoMapperConfiguration {
public static void Configure() {
Mapper.Initialize(x => x.AddProfile<ViewModelProfile>());
}
}
}
using AutoMapper;
namespace CodeCampServerLite.UI.Helpers
{
public static class Bootstrapper
{
public static void Initialize()
{
Mapper.Initialize(x => x.AddProfile<ViewModelProfile>());
Mapper.Initialize(x => x.AddProfile<EditModelProfile>());
}
}
}
in proc and out of proc
| Created: | 7/14/2011 12:58 PM |
in proc is of persistent concerns kept at a server, session and state
out of proc would lie beyond the bounds of a server, cookie for example
http://httputility.com/various/razorhelperscheatsheet.html
| Created: | 6/15/2011 3:06 PM |
is a cheatsheet of Razor helpers
example of appending a file while writing (it is the word true that really matters here)
| Created: | 7/29/2011 9:43 AM |
//splicing in a means to write queries to a .txt file
//remember: using System.IO;
StreamWriter strWriter = new StreamWriter("C:\\text.txt", true);
strWriter.WriteLine(sQueryString);
strWriter.Flush();
strWriter.Close();
@Html.ActionLink("Change Me Up", "Edit/" + @conference.ConferenceId, "Conference")
| Created: | 6/15/2011 2:43 PM |
example of link, first parameter is link text, then action/id, finally controller
Razor Link
| Created: | 6/15/2011 3:32 PM |
A link: @Html.ActionLink("Edit", "Edit", new { conference.Id }, null) ..the third piece is just a dictionary behind the scenes
try/catch/finally
DTO - DataTransfer Objects and AutoMapper
| Created: | 6/16/2011 1:21 PM |
transition from Domain Model => View Model can be frustrating
Options
View-specific queries/DB views/tables
Projection (SQL, ORM, LINQ)
Mapping for domain layer
example of AutoMapper
new EventListModel
{
};
Flattening
var customer = new Customer
Mapper.Initialize(cf =>
{
cfg.AddProfile<CustomerProfile1>();
cfg.AddProfile<CustomerProfile2>();
});
internal class CustomProfile2: Profile
{
protected override void Configure()
{
}
}
ActionResult is another extension point for Filters
| Created: | 6/16/2011 10:53 AM |
ActionResult is another extension point for Filters
Controller inheirts from Base Controller inheirts from AccountController
one can Overload based on get and post, one can overload Actions (get, post)
SQL Distinct
| Created: | 6/29/2011 12:59 PM |
Distinct will return the rows that are not duplicate
How do you find the duplicate records in a table with one column name email?
SELECT email, COUNT(email) AS NumOccurrencesFROM usersGROUP BY emailHAVING ( COUNT(email) > 1 )
competition for dlls
| Created: | 6/30/2011 9:20 AM |
Visual NUnit seems to complete with Visual Studio for .dlls. If Visual NUnit takes a hold of a .dll it seems to sabotage the ability of Visual Studio.
Untitled
| Created: | 6/15/2011 12:13 PM |
@if (someCondition) {
@:This is palin text content
}
This and the prior note are for plain text
Untitled
| Created: | 6/15/2011 12:10 PM |
@Html.Rax(Model.Message)
one has to Opt in to escape HTML encoding
Install SQL Server Express Locally
| Created: | 6/18/2011 8:25 PM |
Install SQL Server Express Locally: http://www.microsoft.com/sqlserver/en/us/editions/express.aspx
Adding a column to a DataTable
| Created: | 6/30/2011 12:27 PM |
dtDataSourceForLensAddonGroup.Columns.Add("rowIndex", typeof(Int32));
iLensAddonGroupCounter = 0;
foreach (DataRow row in dtDataSourceForLensAddonGroup.Rows)
{
row["rowIndex"] = iLensAddonGroupCounter;
iLensAddonGroupCounter++;
}
rpLensAddonGroup.DataSource = dtDataSourceForLensAddonGroup;
rpLensAddonGroup.DataBind();
Testing iPhone note
Testing adding a note on my iPhone
jQuery cheatsheet
| Created: | 6/20/2011 7:21 AM |
basic jQuery...
<script type="text/javascript">
var sanitychecking = "no";
$(document).ready(function() {
$("#AddBanner").click(function() {
sanitychecking = "yes";
});
});
function formValidation() {
if(sanitychecking == "yes")
{
return false;
}
return true;
}
</script>
basic jQuery...
Untitled
| Created: | 6/15/2011 2:03 PM |
View("Hello World"); will allow one to pass a string as a default model... you could get it back with ViewData.Model
HtmlHelperExtensions
| Created: | 6/17/2011 2:02 PM |
public static MvcHtmlString Button(
this HtmlHelper helper)
{
var button = MvcHtmlString.Create(@"<input type=""
return button;
}
Assemblies are actual .dll files
| Created: | 6/20/2011 9:02 AM |
http://24x7aspnet.blogspot.com/2009/05/assemblies-in-aspnet.html
Filters
| Created: | 6/17/2011 8:25 AM |
Use filters as Attributes on Actions, Controllers, base classes that extend Controllers, and Global. Add an Order parameter to an Attribute to specify the order in which filters fire off.
ValueProviders are for gathering values
ModelBinder is binding the values
Untitled
| Created: | 6/15/2011 1:23 PM |
add [] at the end of @model. CodeCampServerLite.UI.Models.ConferenceListModel to make it an array
AcceptVerbs
| Created: | 6/16/2011 2:22 PM |
[AcceptVerbs(HttpVerbs.Post)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection formCollection)
{ .. }
ExceptionFilters and ResultFilters
| Created: | 6/16/2011 10:38 AM |
FilterPipeline:
try{
Authorize -
Action -
Result -
}
catch {
Exception Filter
}
OnResultExecuted
OnResultExecuting
ReadOnly mode for StringReader
| Created: | 7/27/2011 12:41 PM |
Date manipulations in SQL
| Created: | 7/13/2011 1:28 PM |
SELECT vc_color_name AS vc_color_name_, in_color_id, *
FROM order_item WHERE in_product_id = 281863
AND in_order_id IN (SELECT y.in_order_id FROM dbo.[order] y WHERE y.dt_order >= DATEADD(dd, -30, GETDATE()))
order by vc_color_name
specific error
| Created: | 6/16/2011 12:47 PM |
[HandleError (View="NoConferenceError", ExceptionType = typeof(NullReferenceException), Order = 100)]
why would I implement my own HtmlInput
| Created: | 6/17/2011 9:45 AM |
why would I implement my own HtmlInput
<input type="text" />
<input type="email /> .... starting to get widely adopted by mobile devices
[UIHint("LongDateTime")]
public DateTime Birthday
...a model based hint
TemplateHint from ModelMetadata ([UIHint])
DataTypeName from ModelMetadata
The name of the type
If the object is not complex: "String"
If the object is complex and an interface: "Object"
If the object is complex and not an interface: Recure through the inheritance hierachy for hte type, trying every type name
on ValidationAttribute
System.ComponentModel.DataAnnocations.DataTypeAttribute
System.ComponentModel.DataAnnotations.RangeAttribute
System.Comp .RegularExpressionAttribute
.RequiredAttribute
.StringLengthAttirbute
Visual Studio 2010 Service Pack 1 Deployable Dependencies
| Created: | 7/22/2011 6:00 AM |
INHibernateQueryable<T>
| Created: | 6/15/2011 4:35 PM |
var list = (from conf in _repository.Query()
where conf.SessionCount >= minSessions
select new ConferenceListModel
{
Name = conf.Name,
SessionCount = conf.SessionCount,
AttendeeCount = conf.AttendeeCount,
ConferenceId = conf.Id
}).ToArray();
the .Query() above is simply facilitated by...
public INHibernateQueryable<T> Query()
{
return Session.Linq<T>();
}
Untitled
| Created: | 6/15/2011 1:47 PM |
Jimmy jokes that the M is silent in MVC - What works best... Controller does not have support for pulling things out of a database where this is not the case in other frameworks...
Controller Factory in an IoC controller can instatiate a controller
| Created: | 6/16/2011 11:00 AM |
Execution Pipeline
1. MvcHandler.ProcessRequest
2. ControllerFactory.CreateController
3. IController.Execute
4. Controlller.ActionInvoker.InvokeAction
5. ControllerActionInvoker
@using (Html.BeginForm()) {
| Created: | 6/15/2011 3:25 PM |
Untitled
| Created: | 6/15/2011 12:25 PM |
ActionLink and RouteLinks are HtmlHelper link methods
you can still make text blink!
| Created: | 7/11/2011 2:30 PM |
nest things behind if debug
| Created: | 6/17/2011 3:05 PM |
nest things behind if debug...
WinMerge
| Created: | 7/11/2011 10:33 AM |
WinMerge is a comparison tool
better than Thread.Sleep
| Created: | 6/17/2011 3:12 PM |
make an AJAX call set some values and then check against the values...
Untitled
| Created: | 6/15/2011 1:59 PM |
using Iesi.Collections.Genreic;
POCO is plain old common objects
Untitled
| Created: | 6/15/2011 11:53 AM |
Wait For Single Event (of threading)
| Created: | 7/26/2011 9:26 AM |
http://www.ms-news.net/f3598/how-to-implement-createevent-and-wait-for-single-event-in-c-2141327.html is a link from Google on "Wait For Single Event in C#"
Ravi said:
1. A "Wait For Single Event" is a "mutex"
2. We need an Out of Process event and not a "Critical Session" or "Semmipher" which are in-process events
3. We will fire up or check for the event from both apps. This is not unlike writing or checking for a cookie.
4. Behind the scenes a Virtual Table will be recreated for manging the events across apps
5. We are going to need to listen for an event or a callback function to know if it is OK to do file writing
setting the value of web forms DropDownLists in C#
| Created: | 7/25/2011 10:24 AM |
ddlPD1.Items.FindByValue("whatever").Selected = true;
ddlPD2.SelectedIndex.Equals(33);
go to Properties of UI to fix bringing up Razor as a page
| Created: | 6/16/2011 10:05 AM |
uncheck keep Properties as page and instead lean towards bringing up a specific page
leave the specific page blank and .NET will bring up the / for the app
What is an Area
| Created: | 6/16/2011 3:03 PM |
Search for Area first
-`/<area>/<controller>/<action>.aspx
Searches Global\Shared last
Master pages can be area-specific too
add Areas before URL
<area>/<controller>/<action>.aspx
put an admin site into an area...
remember to change namespace in Area.
remember to
<script type="text/javascript">
| Created: | 6/17/2011 12:21 PM |
<script type="text/javascript">
#("tr:odd").
</script>
client side table column sorting!!!
<thead>
<tr>
<th>Animal</th>
<th>Price</th>
<th>Coolness</th>
</tr>
</thead>
<tbody>
</tbody>
<script type="text/javascript">
$('table').dataTable({
"aaSorting": [[1, "desc"]]
]
]);
</script>
Intro3.html
go to dataTables.net and go to documentation...
go to sorting plugin...
jQuery.fn.dataTablesExt.oSort['dollar-asc'] = function (a, b) {
var x = a.replace("$","");
var y = b.replace("$","");
}:
<a href="javascript:void(0);"
Untitled
| Created: | 6/15/2011 12:11 PM |
loops <% foreach(var item in items) { %><span><%: item.Prop %></span><% } %>
in razor it is: @foreach(var item in items) { <span>@item.Prop</span> <% ] %>
Views <% Html.RenderPartial("LogOnUserControl"); %>
| Created: | 6/16/2011 2:48 PM |
controls from web forms
Custom Controls
User Controls
Master Pages
and yes, Folder Structure
Duplicatoin and Organization in MVC
HtmlHelper extensions
Templates
Partials
Child action
Areas
What are Partials and Child actions
.Can inheirt from Page or Control class
For shared content
For encapsulation content
<div id="logindisplay">
<% Html.RenderPartial("LogOnUserControl"); %>
</div>
Partials:
Inherit from ViewUserControl or ViewUserControl<T>
Model passed in from parent
Most common for sharing widgets (set view data for page with CustomActions or CustomControllers
.aspx will outweight .ascx when using a partial
Child actions
Kicks off an interal action
Pass in route informaton
Html.Action/RenderAction
sfdaafsdadsf
Decorate action with ChildAction
Untitled
| Created: | 6/15/2011 3:28 PM |
@Html.EndForm() is the end of a form
Wait For Single Event
| Created: | 7/28/2011 6:43 AM |
I had a conversation at work about "Wait For Single Event" (which I have not yet researched) and how it can be applicable to two different apps trying to read and write to a .txt file wherein file locking becomes problematic.
This concept is of a mutex (spelling?) which can be used across processes. I was told we would need an "Out of Process" event and not a "In-Process Event" such as a Critical Session or Semiphor (spelling?)
Apparently the Out of Process event will create a virtual table managing state for file IO operations that can be looked at by one app to see if a file is being manhandled by another app thus demanding a delay (wait for the manhandling to end) before latching onto the .txt file.
put scripts at bottom of the page
| Created: | 6/17/2011 1:45 PM |
let the browser render content first
weird SQL column sorting
| Created: | 7/13/2011 7:48 AM |
SELECT vc_color_name AS vc_color_name_,in_color_id,* FROM order_item WHERE in_product_id = 83637 order by vc_color_name
OK... this returns all of the columns by way of the star but makes two of the columns appear first for ease of reading. Yay!
However, please note that in this scenario one has to to the AS casting on the name the is being used in the order by logic as otherwise this error is thrown:
Msg 209, Level 16, State 1, Line 1
Ambiguous column name 'vc_color_name'.
Untitled
| Created: | 6/15/2011 12:16 PM |
Untitled
| Created: | 6/15/2011 12:14 PM |
UrlHelpers generate URLs, Action() is an example as is Content() and Encode() and RouteUrl()
<%=Url.Action("Edit", new { sponsorId = Model.Id }) %> this will create a dictionary
This is created by anoynmous types
Untitled
| Created: | 6/15/2011 12:21 PM |
@using (Html.BeginForm())
{
@Html.ValidationSummary(true, "Account creation") ---outputs what was wrong with model
@Html.LabelFor(m => m.UserName) -- create a lable for m. in a span tag
}
Welcome to Evernote
Welcome to Evernote |
| Use Evernote to save your ideas, things you see, and things you like. Then find them all on any computer or device you use. |
A few simple ideas to get you started- Click New Note and take down an idea or task.
- Clip and save a webpage using a Web Clipper.
- Use Evernote on your phone to snap a photo of a whiteboard, business card, or wine label. Evernote automatically makes text in your snapshots searchable!
Lots of useful features- Take notes, save images, create to-dos, view PDFs, and more
- Access your Evernote notes from any computer or phone you use
- Search and find everything, even printed or handwritten text in images
Install and use Evernote everywhere- Download and install Evernote on all of your computers and phones
- Install a Web Clipper into your web browser
- Email notes to your Evernote email address
- Save Twitter messages by following @myEN
- Import photos from your digital camera
| | Click the link to install Evernote to your computer:Click the link to install Evernote onto your mobile device: Get the latest news |
http://support.mozilla.com/en-US/kb/Exporting%20bookmarks%20to%20an%20HTML%20fil
| Created: | 6/27/2011 7:54 AM |
Razor Helper
| Created: | 6/17/2011 2:08 PM |
create an App_Code folder
in App_Code create FormHelpers.cshtml
in that file put
@helper Button(){
HTML here
}
should then be able to call @FormHelpers.Button in a Razor page
@helper Button(string value = "Save"){
HTML including @value and more HTML
Example: <input type="submit" value="@value" />
}
call like @FormHelpers.Button("Save the Changes")
Untitled
| Created: | 6/15/2011 1:32 PM |
small caviate with public ActionResult Index(int misession = 0)
will not work with Expression<Func<ConferenceController, object>> action = controller => controller.Index();
C# character manipulations
http://www.kodecsharp.org/examples/7.htmland
have to do with string and character manipulations
private string refineNickName(string sNickName)
{
if (sNickName.Contains(")"))
{
string sCharacterToSplitUpon = ")";
string[] sPiecesOfNickName = sNickName.Split(sCharacterToSplitUpon.ToCharArray());
sNickName = sPiecesOfNickName[1];
char[] sNickNameCharacters = sNickName.ToCharArray();
sNickName = sNickName.TrimStart();
}
return sNickName;
}
200 is happy while 403 is an authorization error
| Created: | 6/17/2011 1:54 PM |
everything in the Views folder will run the _ViewState.cshtml
| Created: | 6/17/2011 7:45 AM |
Untitled
| Created: | 6/15/2011 3:33 PM |
@Html.HiddenFor(m = m.Id) is a hidden field
jQuery (and JavaScript) Notes
...basic jQuery...
<script type="text/javascript">
var sanitychecking = "no";
$(document).ready(function() {
$("#Foo").click(function() {
sanitychecking = "yes";
});
});
function formValidation() {
if(sanitychecking == "yes")
{
return false;
}
return true;
}
</script>
...change a style...
$("#Foo").attr('style', 'display: block;');
...add remove classes...
$("#button1").mouseover(function() {
$(this).removeClass("thing1");
$(this).addClass("thing2");
highlight($(this));
}).mouseout(function() {
$(this).addClass("thing1");
$(this).removeClass("thing2");
unhighlight($(this));
}).mousedown(function() {
window.location="/about/";
});
...functions...
function highlight(objectid) {
$(objectid).children().each(function(ichild, thischild) {
$(this).removeClass("thing1");
$(this).addClass("thing2");
});
}
function unhighlight(objectid) {
$(objectid).children().each(function(ichild, thischild) {
$(this).addClass("thing1");
$(this).removeClass("thing2");
});
}
...simpler onload call...
$(function() {
...disabling dropdown lists, using substrings, radio buttons...
<script type="text/javascript">
$(function() {
$("input[name=myradio]").click(function() {
var checky = $('input[name=myradio]:checked').val();
$("#rx_login_option_1").attr("style", "display: block;");
$("#<%=x.ClientID %>").attr('selectedIndex', 0);
$("#<%=y.ClientID %>").attr('selectedIndex', 0);
if (checky.indexOf("NoAddFields") >= 0) {
$("#<%=x.ClientID %>").attr("disabled", "disabled");
$("#<%=y.ClientID %>").attr("disabled", "disabled");
} else {
$("#<%=x.ClientID %>").removeAttr("disabled");
$("#<%=y.ClientID %>").removeAttr("disabled");
}
});
});
</script>
...uncheck a radiobutton...
$("#myRadio").removeAttr('checked');
...see if ANY radiobutton in a series is checked...
var checky = "" + $('input[name=myradio]:checked').val();
if (checky.indexOf("somethingcommon") >= 0) {
...see if a checkbox is checked...
if ($('#multiplePDs').is(':checked')) {
...flag...
alert("Hey!");
...set HTML contents of div...
function display(id, str) {
document.getElementById(id).innerHTML = str;
}
...another way...
$("#div1").html("whatever");
...scrape the contents of a div...
var loginControl = $('#logincontrol').html();
...grab dropdown contents...
var x=$("#z option:selected").val();
var y=$("#z option:selected").text();
...get position of div...
var positionLeft = parseInt($("#myDiv").css("left"));
...manipulating checkboxes...
$("#checkbox4").click(function() {
$('#checkbox1').attr('checked', false);
$('#checkbox2').attr('checked', false);
$('#checkbox3').attr('checked', false);
...animation...
$("#linkA").animate({ opacity: 0, marginRight: "300px" }, 0)
.animate({ opacity: 1, marginRight: "0px" }, 900);
...delay...
var mouseisover = false;
$(document).ready(function() {
$('#detail2b').mouseenter(function() {
removeBackground($('#detail2a'));
$('#detail2a').addClass('menubackgroundends');
removeBackground($('#detail2b'));
$('#detail2b').addClass('menubackgroundmiddle');
removeBackground($('#detail3a'));
$('#detail3a').addClass('menubackgroundright');
$('#detail3c').attr('style', 'display: none;');
$('#detail6c').attr('style', 'display: none;');
$('#detail2c').clearQueue()
.attr('style', 'display: block;')
.delay(800).queue(function() {
if (!mouseisover) {
$('#detail2c').attr('style', 'display: none;');
}
});
}).mouseleave(function() {
removeBackground($('#detail2a'));
$('#detail2a').addClass('menubackgroundright');
removeBackground($('#detail2b'));
$('#detail2b').addClass('menubackgroundblank');
removeBackground($('#detail3a'));
$('#detail3a').addClass('menubackgroundblank');
});
$('#detail2c').mouseenter(function() {
mouseisover = true;
})
.mouseleave(function() {
mouseisover = false;
$('#detail2c').attr('style', 'display: none;');
});
...disable a button...
<html>
<head>
<script type="text/javascript" src="http://admin.fd2009.dev.fdwork.com/include/script/jquery-1.4.4.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").mouseup(function() {
$("#submit").clearQueue().delay(200).queue(function() {
$('#submit').attr("disabled", "disabled");
});
});
});
</script>
<input id="submit" type="submit" />
</body>
</html>
...acting on focus and changing focus...
<script type="text/javascript">
$(function () {
$("#placeholder").click(function () {
$("#placeholder").addClass("displaynone");
$("#passwordgate").removeClass("displaynone");
$("#passwordgate").focus();
});
$("#placeholder").focus(function () {
$("#placeholder").addClass("displaynone");
$("#passwordgate").removeClass("displaynone");
$("#passwordgate").focus();
});
});
</script>
...check to see if an element exists...
if ($('#whatever')[0]) {
...Here's a good top ten list/I guess they are not all fluff...
...keep a link from "linking"...
<a href="JavaScript:void(0);" ondblclick="alert('Well done!')">Double Click Me!</a>
...using hover...
<script language="javascript" type="text/javascript">
$(function () {
$('.changePointerForPrograms').hover(function () {
$(this).attr('style', "cursor: move;");
},
function () {
$(this).attr('style', "cursor: default;");
}
);
});
</script>
...bind/live/delegate...
$('#foo').bind('click', function() {
alert($(this).text());
});
$('#bar').live('click', function() {
alert($(this).text());
});
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
...looks like delegate takes three parameters...
...bind effects immediate entities...
...live effects those that may appear later too...
...delegate is a marginally more performant version of live...
...delegate must be declared before the thing it effects comes into memory I think...
...this will cause problems with jQuery UI's draggable in IE9 as if a TH (with moveableColumn as a class) is "draggable" when one drags and mouses away the cursor will remain as...
the move cursor until one clicks
<script language="javascript" type="text/javascript">
$(function () {
$('.moveableColumn').hover(function () {
$(this).attr('style', "cursor: move;");
},
function () {
$(this).attr('style', "cursor: default;");
}
);
});
</script>
...this is the fix...
<script type="text/javascript">
$(function () {
$('.moveableColumn').hover(function () {
$(this).css('cursor', 'move');
});
});
</script>
...using split...
<script type="text/javascript">
(function () {
var fsd = $('#SiliconSampleDefinition_FirstShipDate').val().split(' ')[0];
$('#SiliconSampleDefinition_FirstShipDate').val(fsd);
})();
</script>
...determine if a string contains a string, cast a string to lowercase, and use Razor markup...
var currentCrudAct = "@ViewBag.Title";
if (currentCrudAct.toLowerCase().indexOf("edit") >= 0) {
...get the value from a drop down...
var currentSampleType = $('#SelectedSampleTypeId').val();
...get the public-facing value from a drop down...
var currentSampleType = $("#SelectedSampleTypeId option:selected").text();
...blur versus focus (blur should be after the fact, focus should be on touch)...
$(function () {
$('#one').blur(function() {
whatever();
});
$('#two').focus(function() {
whatever();
}).click(function() {
whatever();
});
});
...fake a click...
$('#programsPlansGroup-available-clear').click();
Multi-domain UCC SSL certificates on Nginx with 1 IP address
| Created: | 6/30/2011 3:09 PM |
http://playnice.ly/blog/2011/01/03/multi-domain-ucc-ssl-certificates-on-nginx-with-1-ip-address/
rounding in C#
| Created: | 6/20/2011 1:40 PM |
double dCellCount = dtLensGroupList.Rows.Count;
double dRowCount = Math.Round(dCellCount/4,0);
also to round up....
double dRowCount = Math.Ceiling(dCellCount / 4);
of file locking and checking to see if a file is locked
| Created: | 7/15/2011 2:48 PM |
<% and @
| Created: | 6/16/2011 7:59 AM |
In Views
<% you can write C# code in here (needs semicolon)
<%= you return a value and paint the screen (no semicolon)
<%: you return an HTML.Encoded View
<%# old web forms markup for repeaters
In Razor
@foreach
of
@{
foreach
}
something has to be pressed against the @ symbol
@: will do rendering... it is for plain text... you can also wrap text in <text></text>
with @: you have to keep things on the same line (perhaps do quotes)
@Model.FirstName
_layout is the analog of MasterPages
AreaRegistration
| Created: | 6/17/2011 7:40 AM |
part of what an Area does under the coves is specify a namespace
Extend RegularExpressionAttribute - Make your own validations...
| Created: | 6/17/2011 11:58 AM |
public class EmailAttribute : RegularExpressionAttribute
{
public override bool IsValid(object value)
{
try
{
var address = new MailAddress(value.ToString()).Address;
return true;
}
catch
{
return false;
}
}
}
[Email]
one must use override to override a method
[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "Whatever.")]
is depreciated and of MVC 2
[Compare("NewPassword")] is more current... this would match the getsetter with the value of that of NewPassword
CastleMonorail is an MVC Pattern for ASP.NET that is old
| Created: | 6/16/2011 7:42 AM |
The controller is the "traffic cop" - It takes an incoming request and decides that what to do with it... it builds some sort of model. Controller's inherit from the IController Interface.
An Action is both a public method on a control, and a route (an endpoint for a URL) - returns an ActionResult
ViewData can be access: by dictionary based access such as ViewData["key"] or one can do ViewData.Model
Untitled
| Created: | 6/15/2011 12:17 PM |
public ViewResult Edit(Guid sponsorId)
{
...uses...
<%=Url.Action("Edit", new { sponsorId = Model.Id }) %>
on a Dell Laptop...
| Created: | 7/20/2011 8:17 AM |
...hold the Fn button and press the up and down arrows to increase brightness and contrast
get C:\ path to current page as defined by IIS
| Created: | 7/29/2011 6:43 AM |
string sConfigPath = HttpContext.Current.Server.MapPath(XMLConfig);
route constraints
| Created: | 6/17/2011 8:15 AM |
set classes in the App_Code folder to compile in Visual Studio 2010
| Created: | 7/21/2011 3:01 PM |
to allow classes in the App_Code folder to be used in VS2010, right-click on them and set their build state to "Compile" instead of "Content"
@using (Html.BeginForm())
| Created: | 6/15/2011 12:05 PM |
Begin Form markup
@using (Html.BeginForm())
{
@Html.ValifationSummary(true, "Account creation")
<div>
@Html.LabelFor(m => m.Username);
</div>
}
Razor: Html Encoded
@{ int x= 123;
string y = "because";
}
take away filters or action results
| Created: | 6/16/2011 11:02 AM |
If one is copying and pasting controller logic,
Filters and Custom Action Results are a good place to cure that
ControllerActionInvoker
Finds action to execute
Finds filters to execute
Executes ActionResult
Execute
Create a display template
| Created: | 6/17/2011 3:06 PM |
Create a display template... String.ascx
http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx
| Created: | 6/15/2011 3:11 PM |
quick-reference.aspx (another Razor cheatsheet)
6 % 4 is different from 6 / 4
| Created: | 7/26/2011 9:27 AM |
in C#
6 / 4 will return 1.5 (simple division)
6 % 4 will return 2 (returns the remainder of a division)
Untitled
| Created: | 6/15/2011 12:27 PM |
use <text>}</text> to actually print a curly brace to the screen
@@ allow one to use an @sign
Razor will not parse email addresses
remember the difference between SelectedValue and SelectedIndex
| Created: | 7/26/2011 10:34 AM |
...when working with DropDownLists in ASP.NET web forms
Untitled
| Created: | 6/15/2011 3:15 PM |
surround items on the first cheatsheet with @Html. .... and ... For(m => m.Whatever)
see if an element exists in plain old JavaScript
| Created: | 7/18/2011 2:50 PM |
Register Global Filters and Error Handling
| Created: | 6/16/2011 12:16 PM |
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
This code snippet will register global filters. Put it in global.asax.cs
Throw an exception at/upon an Action
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
// Force a 401 exception for testing
throw new HttpException(401, "Unauthorized");
}
}
}
one has to turn CustomErrors at the Web.Config
create a custom action result
| Created: | 6/16/2011 12:51 PM |
someone is to call my service to get an XML representation of my
we will serialize with
public static class XmlSerializationHelper
{
public static string Serialize<T>(this T value)
{
var xmlSerializer = new XmlSerializer(typeof(T));
var writer = new StringWriter();
xmlSerializer.Serialize(writer, value);
return writer.ToString();
}
public static T Deserialize<T>(this string rawValue)
{
var xmlSerializer = new XmlSerializer(typeof(T));
var reader = new StringReader(rawValue);
T value = (T)xmlSerializer.Deserialize(reader);
return value;
}
}
XmlResult<T> : ActionResult
public abstract class DefaultController: Controller
{
protected XmlResult<T> Xml<T>
}
look through Jimmy's code for XmlResult and Default Controller
Controller Action:
public XmlResult<ConferenceXmlModel[]> Index()
{
var list = _repository.GetAll()
.Select(e => new ConferenceXmlModel
{
}
functions and stored procedures
| Created: | 7/13/2011 10:59 AM |
as a function...
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[temporary_counter] (@in_product_id int, @in_color_id int)
RETURNS int AS
BEGIN
DECLARE @in_return int
SELECT @in_return = COUNT (in_color_id) FROM order_item WHERE in_product_id = @in_product_id AND in_color_id = @in_color_id
RETURN @in_return
END
as a stored procedure...
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[temporary_counter] (@in_product_id int, @in_color_id int)
AS
BEGIN
DECLARE @in_return int
SELECT @in_return = COUNT (in_color_id) FROM order_item WHERE in_product_id = @in_product_id AND in_color_id = @in_color_id
RETURN @in_return
END
DropDownList and ListItem web forms headaches
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("item 1", "Item 1");
list.Add("item 2", "Item 2");
list.Add("item 3", "Item 3");
list.Add("item 4", "Item 4");
ddlSphereR.DataSource = list;
ddlSphereR.DataTextField = "Value";
ddlSphereR.DataValueField = "Key";
ddlSphereR.DataBind();
ddlSphereR.SelectedIndex = 2;
ddlSphereL.DataSource = dtProductPrescription;
ddlSphereL.DataBind();
ddlSphereL.Items.Insert(0, new ListItem("Sphere", "0"));
ddlSphereL.SelectedIndex = 5;
ddlSphereR.Items.Add(new ListItem("Sphere", "0")); ...adds a new item
ddlSphereL.Items.Clear(); ...removes items
Untitled
| Created: | 6/15/2011 12:45 PM |
private IConferenceRepository conferenceRepository;
public ConferenceController(IConferenceRepository var)
{
conferenceRepository = var;
} NEW UP a REPOSITORY CALL with StructureMap
IIS is timeing out too quick, what to do?
| Created: | 6/21/2011 8:27 AM |
Right-click on a project and then select "Advanced Settings"
Expand "Connection Limits" and then change the seconds value at "Connection Time-out (seconds)"
controllerContext.
| Created: | 6/17/2011 8:59 AM |
controllerContext
return new AppSettingsValueProvider():
public class AppSettingsValueProviderFactory : ValueProviderFactory
{
public bool ContainsPrefix(string prefix)
{
return ConfiguraionManager.AppSettings.AllKeys.Contains(prefix);
}
}
ValueProviders are providers of Values that are your Action
in Application_Start()
ValueProviderFactories.Factories.Ass(new AppSettingValueProviderFactory());
Untitled
| Created: | 6/15/2011 12:24 PM |
BeginForm and EndForm create beginnins and end of tag.
CheckBox, Hidden, Password, Textbox, etc are examples of forms
Microsoft Web Platform Installer and Razor Coloring
| Created: | 6/16/2011 7:19 AM |
web forms DataLists have a DataKeyFields property
| Created: | 6/28/2011 7:00 AM |
the DataKeyFields property has to be moved to a hidden variable when migrating data from DataLists to Repeaters
Routing in MVC
| Created: | 6/16/2011 8:11 AM |
Direct incoming to controller/action
HTTP Request > Routing > Chooses > Controller > Action
Construct outgoing URLs referring to controller/action
View > Routing
Design for Testability + MVCContrib
| Created: | 6/17/2011 2:51 PM |
public class WebTestBase
{
[Setup]
public void FixtureSetup()
{
const string baseUrl = "http://localhost:8084";
Browser = new WatinDriver(new IE(baseUrl), baseUrl);
}
[TearDown]
public void TearDown()
{
Browser.Dispose();
Browser = null;
}
protected IBrowserDriver Browser { get; private set; }
}
$("#getSomething").click(function() {
| Created: | 6/17/2011 12:33 PM |
$("#getSomething").click(function() {
$("#ajaxTarget").load("/Intro/Mysterious.htm");
}
$.ajax("google.com", null, function(){
}
$.get("google.com", null, function(){
}
}
$('.datetime').datepicker
jQueryUI
$("body").
Untitled
| Created: | 6/15/2011 12:26 PM |
<text> just doesn't break out of curly brackets
SQL to create a database
| Created: | 7/19/2011 3:04 PM |
CREATE DATABASE Selenium
Border Radius HTC
download boarder-radius.htc...
http://code.google.com/p/curved-corner/downloads/detail?name=border-radius.htc
#summary-header {
margin:0;
padding:10px 0;
width:100%;
background-color:#65658e;
behavior:url(border-radius.htc);
-moz-border-radius:5px;
-webkit-border-radius:5px;
-khtml-border-radius:5px;
border-radius:5px;
text-align:center;
font-size:12px;
font-weight:600;
color:#fff
}
the webkit border-radius feature was mentioned to me today too...
var fillColor = this.currentStyle.backgroundColor; ...is a line in the .htc file that concerns me
for <div class="select-add oversel"> to work I have to have <div class="select-add" style="display: none;"></div>
.oversel {
text-align:left;
position:relative;
width:120px;
}
what is Delphi
| Created: | 7/14/2011 6:46 AM |
CUSTOM MODEL BINDING!!! ValueProviders and ModelBinders
| Created: | 6/17/2011 8:36 AM |
Google ModelBinding Factories later
CustomModelBinding
public ActionResult Edit(Conference confname)
{
}
public class ConferenceModelBinder : IModelBinder
{
public object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext
)
{
ValueProviderResult result = bindingContext
string confname = null;
var repository = ObjectFactory.GetInstance<IConferenceRepository>();
var conference = repository.GetByName(confname);
}
}
in Application_Start()
add
ModelBinders.Model...
Untitled
| Created: | 6/15/2011 1:33 PM |
...controller.Index(0); is better
Filters
| Created: | 6/16/2011 10:27 AM |
Filters may be for: Action, Authorization, Exceptions, Result
Index() action gets executed by something
Action Filters execute before/after action is exectued
build by inheirting form IActionFilter OR inheir from ActionFilterAttribute
The methods are
OnActionExecuted (after action executes)
OnActionExecuting (before the action executed and not DURING as the name implies)
why would you do this...
Populate common ViewData
Pre/Post process data
Common execution paths
Built-in:
OutputCacheAttribute
AsyncTimeoutAttibute
can get to the HttpContext to have at cookies...
Common Authorization Filters usage
NOT just security
Halt execution of action
Provide alternate result
IAuthorizationFilter
Derived Types
try/catch is a context variable
| Created: | 6/23/2011 3:39 PM |
try/catch is a context variable
Selenium .dlls
| Created: | 7/28/2011 5:53 AM |
.dlls needed to empower Selenium:
nmock.dll
nunit.core.dll
nunit.core.interfaces.dll
nunit.framework.dll
nunit.uiexception.dll
nunit.uikit.dll
nunit.util.dll
nunit-console-runner.dll
nunit-gui-runner.dll
ThoughtWorks.Selenium.Core.dll
ThoughtWorks.Selenium.IntegrationTests.dll
ThoughtWorks.Selenium.UnitTests.dll
in the absence of nunit.framework.dll I believe that will not work
[TestFixture] , [SetUp] , [TearDown] , [Test]
...will not work
push a value to an .ascx with inline call
| Created: | 7/28/2011 2:59 PM |
At the in line call for as .ascx in a .aspx page, add a parameter...
then create a get-setter in the code behind of the .ascx
[Bindable(false), Category("Appearance"), DefaultValue("")] needs to sit atop the method
what is a DataRowView
protected void rptrAddon_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.DataItem != null && e.Item.DataItem is DataRowView)
{
DataRowView drvRow = (DataRowView)e.Item.DataItem;
use the error list window in Visual Studio
| Created: | 7/13/2011 8:12 AM |
look at your warnings and not just your errors
data scrapped from text documents and static
data scrapped from text documents can be cached in static method calls and thus erroneous
Routing and Amazon
| Created: | 6/16/2011 8:34 AM |
Amazon will have URLs like so: amazon.com/this-is-some-seo-text-that-isnt-used-in-routing/hp/12352342342323
In the global.asax you will see the route table
curly braces are what the routing engine uses
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
in the last line one may tell the router that the values are not required to exist
add a new route
routes.MapRoute("privacy_policy", "privacy",
new {controller = "Help", action = "Privacy" });
more specific routes go first....
the first piece of a MapRoute is the name of the Route ...in the case below it is widgets
routes.MapRoute("widgets", "{widgetCode}/{action}",
new {controller = "Catalog", action = "Show"},
new {widgetCode = @"WDG[0-9]{4}"});
the last piece here is a widget code to try to match a widget instead of a controller
WDG followed by exactly four numbers
public ActionResult Show(string widgetCode)
{
var widget = GetWidget(widgetCode);
if (widget == null)
{
Response.StatusCode = 404;
return View("404");
}
return View();
}
this is how to use a custom route value as a variable
Untitled
| Created: | 6/15/2011 1:23 PM |
public ActionResult Indx(int minSessions = 0)
gives default value
conditional value assignment
| Created: | 7/2/2011 12:56 PM |
myLabel.Text = myPrice > 0 ? Currencycl.FormatCurrency(myPrice) : "FREE";
return a file with MVC (also flush a fileWriter)
| Created: | 7/19/2011 4:52 PM |
namespace EyeScrape.Controllers
{
public class ScrapeController : Controller
{
public ActionResult Index(string foo, string bar)
{
string url = UrlMaker.CraftUrl(foo);
string scrapping = returnScrapping(url);
string pathToWriteTo = bar;
StreamWriter fileWriter = new StreamWriter(pathToWriteTo);
fileWriter.Write(scrapping);
fileWriter.Flush();
fileWriter.Close();
return File(pathToWriteTo, "text/plain");
}
private string returnScrapping(string url)
{
StringBuilder stringBuilder = new StringBuilder();
byte[] binaryData = new byte[99999];
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
request.GetResponse();
Stream stream = response.GetResponseStream();
string stagingGround = null;
int counter = 0;
do
{
counter = stream.Read(binaryData, 0, binaryData.Length);
if (counter != 0)
{
stagingGround = Encoding.ASCII.GetString(binaryData, 0, counter);
stringBuilder.Append(stagingGround);
}
} while (counter > 0);
return stringBuilder.ToString();
}
}
}
Child Actions
| Created: | 6/16/2011 2:59 PM |
have an action that does something common
append a child action to modifty a common action
Dervied MvcHandler
(ChildActionMvcHandler)
Re-using existing route variables
Entire MVC pipeline executed
NO external request generated
With partials, everything has to be on the main controller and everything in main viewdata
Child Action
-No magic strings
-View dictates necessity
-No contrived controller hierarchy
Untitled
| Created: | 6/15/2011 1:27 PM |
extension methods have to be in static classes
Untitled
| Created: | 6/15/2011 12:42 PM |
a contructor is the Person method inside of the person class if you will
Untitled
| Created: | 6/15/2011 2:06 PM |
ViewBag is dynamic ... one may just add on parameters
ViewBag uses ViewData under the covers
@Html.EditFor(x => x.UserName)
| Created: | 6/17/2011 9:39 AM |
@Html.EditFor(x => x.UserName)
@Html.EditFor(x => x.Password)
public
What populates metadata
Attributes
-System.ComponentModel
style the disabled state in CSS
| Created: | 7/11/2011 11:00 AM |
[disabled] {
font-size:10px;
font-weight:bold;
color:#fff;
overflow: hidden;
text-transform: uppercase;
}
jQuery Underscore
Untitled
| Created: | 6/15/2011 2:02 PM |
public ActionResults Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
ViewData.Model = "Hello world";
return View();
}
Untitled
| Created: | 6/15/2011 3:00 PM |
@Html.LabelFor( m => m.Whatever) is an Label while I think EditFor is for editing
prepping .NET 4.0 in IIS
| Created: | 7/28/2011 10:09 AM |
Item 24: Express Callbacks with Delegates
start an asynchronous thread and have it check in periodically
callbacks are expressed as delegates in C# ...the most common use of delegates is events
anytime you want less coupling between classes without using interfaces use delegates
the .NET runtime defines many common delegate forms: Predicate<T>, Action<T>, Func<T,bool> see http://twitpic.com/5ywx5m
[ChildActionOnly]
| Created: | 6/17/2011 7:49 AM |
[ChildActionOnly]
public ActionResult RenderLogonControl()
{
RenderAction will do a response.write (is buffered) (really helpful if I'm rending the whole page as a string) and
Action will return the string
ones that return string can be helpful... in that it can be used with other strings
@Html.Action("RenderLogonControl", "Account", new { area = "Security" })
this is how to access a Child Action!!!!
@if(Resquest.IsAuthenticated) {
something
} else {
something else...
{
this is something that some be accessed carefully
@{
var model = ViewData["UserAccountInfo"];
}
Untitled
| Created: | 6/15/2011 1:46 PM |
in Ruby on Rail the M and MVC is a database table... most MVC frameworks have an option on what the M in MVC is for
Untitled
| Created: | 6/15/2011 1:12 PM |
create a strongly typed view - you will need to complie for your model to appear in the models dropdown list, then refer to your model at "model"
Razor View Tricks!!!
| Created: | 6/17/2011 1:56 PM |
@RenderSection("Footer", false)
the requiered parameter... the second parameter is true by default
@section Footer{
Plain copy goes here
}
filling in the sections does not behold to the usual read code only convention...
Postback Example from Justin Pope
| Created: | 6/17/2011 1:04 PM |
<script language="javascript" type="text/javascript">
$(function () {
$('#showAttendees').click(function () {
var url = '@Url.Action("Show", "Attendee", new { confname = Model.Name })';
// Keep a reference to the show attendees button for later
var button = $(this);
var callback = function (data, textStatus) {
// Place HTML returned from AJAX inside special p tag below
$('#attendees').html(data);
// Hide the show attendees button
button.hide();
};
// Issue an AJAX GET, to return HTML (and not JSON)
$.get(url, null, callback, 'html');
});
});
it might be wise to use:
if (textStatus == 200) above $('#attendees').html(data);
Model Binder
| Created: | 6/16/2011 1:03 PM |
Model Binder is the piece in MVC that coverts HTTP variables to types that are easily used in a Model
ValueProviders
new ValueProviderFactoryCollection {
new ChildActionValueProviderFactory(),
new FormValueProviderFactory(),
new JsonValueProviderFactory(),
new RouteDataValueProviderFactory(),
new QueryStringValue...
new HttpFileCollectionValue...
}
the items above are what model binders look for (order matters)
MVC2 introduced concept of Value Providers
IModelBinder
Derived Types
BindModel(ControllerContext, ModelBindingContext):Object
TeamViewer and Skype are free alternatives to gotomeeting.com which costs $49 a month
TeamViewer and Skype are free alternatives to gotomeeting.com which costs $49 a month. TeamViewer is technically free if you are not using it for business purposes.
John Locke's gradient effects (CSS 3)
| Created: | 7/12/2011 6:12 AM |
.lr-progress {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fdfefd', endColorstr='#afb6ca'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#fdfefd), to(#afb6ca)); /* for webkit browsers */
background: -moz-linear-gradient(top, #fdfefd, #afb6ca); /* for firefox 3.6+ */
border:1px solid #9397b4;
border-left:1px solid #fff;
border-right:1px solid #9397b4;
width:33%;
height:14px
}
.progress-achieved {
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#e1e0f7', endColorstr='#8684bf'); /* for IE */
background: -webkit-gradient(linear, left top, left bottom, from(#e1e0f7), to(#8684bf)); /* for webkit browsers */
background: -moz-linear-gradient(top, #e1e0f7, #8684bf); /* for firefox 3.6+ */
border:1px solid #9397b4;
border-left:1px solid #fff;
border-right:1px solid #9397b4;
width:33%
}
Untitled
| Created: | 6/15/2011 2:08 PM |
if you rename something in a model it will update views
<li><%: Html.RouteLink("Conferences", "Default",
| Created: | 6/17/2011 2:56 PM |
<li><%: Html.RouteLink("Conferences", "Default",
new { controller = "Conference", action = "Index", area = ""],
new { rel = SiteNav.Conferences });
[Test]
public void Should_be_able_to_edit_conferences()
{
NavigateLink(SiteNav.Conferences);
protected virtual void NavigateLink(string rel)
{
[Test]
public void Should_edit_the_event_name_correctly()
embed CSS in HTML
| Created: | 6/22/2011 9:46 AM |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>My first styled page</title>
<style type="text/css">
body { color: purple;
background-color: #d8da3d
}
</style>
</head>
Untitled
| Created: | 6/15/2011 2:04 PM |
ViewData.Model is the very generic model that just contains a string value
Untitled
| Created: | 6/15/2011 12:08 PM |
<span><%: Model.Message %></span>
This is Razor Markup
<span>@Model.Message</span>
$(function()
| Created: | 6/17/2011 1:50 PM |
$(function()
is evi to the ondocument load call
duration???
| Created: | 6/27/2011 12:58 PM |
function ShowHide(){
$("#slidingDiv").animate({"height": "toggle"}, { duration: 300 });
}
Untitled
| Created: | 6/15/2011 2:15 PM |
Razor interprets HTML tags and HTML tags and other content as code unless using the <text></text> wrapper
@RenderSection(string name, bool required) is the new ContentArea
| Created: | 6/17/2011 12:56 PM |
@RenderSection(string name, bool required)
look into Google Chrome Network Tools
| Created: | 6/15/2011 3:38 PM |
Html.EnableClientValidation
| Created: | 6/17/2011 9:58 AM |
Html.EnableClientValidation
include this one line to do all validation on Client side instead of the server side....
public class TravelRange {
[Required]
Date Start { get; set; }
}
clear cache and cookies in Firefox
Untitled
| Created: | 6/15/2011 3:20 PM |
there is no HttpHelper for a button
Scott Gutherie encouraged testing
| Created: | 6/17/2011 2:26 PM |
...in the Alt.NET conference where he demoed MVC for the first time
How to access controller methods from a view in ASP.NET MVC http://bit.ly/rmUQgT
| Created: | 7/31/2011 5:33 PM |
http://jeffreypalermo.com/blog/how-to-access-controller-methods-from-a-view-in-asp-net-mvc/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+jeffreypalermo+%28Jeffrey+Palermo+%28.com%29%29&utm_content=Twitter
Untitled
| Created: | 6/15/2011 12:38 PM |
<li>@Html.ActionLink("Conference", "Conference", "Home")</li> is a ActionLink
_ViewStart.cshtml will execute everytime one of the cshtml pages runs. There is no distinction between partials and full. When one uses a partial one has to specify the underscore.
| Created: | 6/15/2011 12:03 PM |
_ViewStart.cshtml will execute everytime one of the cshtml pages runs. There is no distinction between partials and full. When one uses a partial one has to specify the underscore.
FileWriter fileWriter = new FileWriter(pathToFile, isAppendable)
| Created: | 7/15/2011 2:08 PM |
I learned today that one may pass a Boolean value to a FileWriter to denote if the file should append to the file as opposed to overwrite the file.
private IPs
| Created: | 6/20/2011 6:14 AM |
10.0.0.0 through 10.255.255.255
169.254.0.0 through 169.254.255.255 (
APIPA only)
172.16.0.0 through 172.31.255.255
192.168.0.0 through 192.168.255.255
these are private IP ranges while others are public
APIPA has to do with the Dynamic Host Configuration Protocol (DHCP) is an automatic configuration protocol used on IP networks.
Untitled
| Created: | 6/15/2011 12:46 PM |
public ConferenceController(IConferenceRepository var)
{
conferenceRepository = var;
} NEW UP a REPOSITORY CALL with StructureMap
JSON to XML translations
| Created: | 7/15/2011 9:16 AM |
http://json.org/example.html
cd ..
| Created: | 7/29/2011 5:53 AM |
at the cmd window
cd .. -moves up a folder
cd foldername -moves down a folder
Partial View will typically begin with an underscore
| Created: | 6/15/2011 11:54 AM |
Untitled
| Created: | 6/15/2011 1:51 PM |
var conference = new Conference("Austin Code Camp");
var attendee = new Attendee("Joe", "Schmoe")
attendee.RegisterFor(conference);
SOLR and (Tomcat)
| Created: | 7/28/2011 7:14 AM |
URL does not exist in current context helpers
| Created: | 7/9/2011 11:52 PM |
force text to be capitalized
| Created: | 7/11/2011 10:49 AM |
text-transform: uppercase;
Untitled
| Created: | 6/15/2011 12:19 PM |
AntiForgeryToken(), AttributeEncode(), EnableClientValidation() is canned jQuery validation (this field is required), Encode() (usually implicit), HttpMethodOverride()
testing
| Created: | 6/17/2011 2:39 PM |
WatiN - Web Application Testing in .NET
JSLint is a tool to standardize Javascript
Gallio is an automated test framework tool
Watin can take screenshots of the browser when something goes wrong
Gallio allow one to take the screenshots and impede them in the reports that appear when the tests fail
WatiR - Web application testing in Ruby
[Test]
public void Should_be_able_to_edit_conference()
{
using (var ie = new IE("http://localhost:8084"))
{
var conferenceLink = ie.Link(Find.ByText("Conferences"));
conferencesLink.Click();
var editCodeMashLink = ie.Link(Find.ByTest("Edit"));
editCodeMashLink.Click();
var nameBox = ie.TextField(Find.ByName("Name"));
nameBox.TypeText("CodeHashFoo");
var submitBtn =
Untitled
| Created: | 6/15/2011 12:23 PM |
@Html.LabelFor(m => m.UserName) -- create a lable for m. in a span tag
REMOTE_ADDR versus LOCAL_ADDR
| Created: | 6/21/2011 6:39 AM |
I think
Stringcl.GetValue(Request.ServerVariables["REMOTE_ADDR"] returns the IP of a user's computer while
Stringcl.GetValue(Request.ServerVariables["LOCAL_ADDR"] returns the IP of the server asking for an IP. This per
http://www.w3schools.com/asp/coll_servervariables.asp
Untitled
| Created: | 6/15/2011 1:05 PM |
create strongly typed view http://www.howmvcworks.net/OnViews/BuildingAStronglyTypedView
set a CSS style for IE8 only
| Created: | 7/12/2011 2:24 PM |
http://stackoverflow.com/questions/660652/ie8-css-selector
Magento Cheatsheet
| Created: | 6/20/2011 5:50 AM |
http://www.siteground.com/tutorials/magento/
Attributes Tutorial
| Created: | 7/29/2011 7:04 AM |
One may mix razor view engine pages with .ascx and .aspx traditional Views
| Created: | 6/15/2011 12:02 PM |
Control Panel > User Accounts > Give other users access to this computer
permission other users at a Windows 7 Laptop to be administrators
install a MSSQL Management Studio Express Database locally
- http://www.microsoft.com/express/Database/
- go to
- .\sqlexpress to connect
- To restart sqlserver express, right click on the .\sqlexpress node and click Restart. !!! Please wait until message appears: "Are you sure you want to restart the MSSQL$sqlexpress service on <your server name> " Click "Ok" to restart process. if you don't wait and for some reason the process gets into a bad state, then restart your machine, and this will restart the process.!!!
|
|
|
|
|
|
|
|
|
permissions for a user in MSSQL Management Studio Express
in MSSQL Management Studio Express go to Security > Logins and right-click on a log in. Then click properties.
Navigate to "User Mapping" to assign permissions to a user for a Database
style submit type inputs
ASP.NET MVC: PagedList<T>
http://blog.wekeroad.com/blog/aspnet-mvc-pagedlistt/
button helper
@helper Button(string value = "Save", string url = "/"){
<input type="button" value="@value" onclick="window.location = '@url';" />
}
use like this:
@FormHelpers.Button("Add New","/program/add/")
create a Razor link to view
@Html.ActionLink("Create New", "Create")
@Html.TextBox("Search") is a Razor textbox
Razor Cheatsheet
[Ignore] in Unit Tests
http://www.roelvanlisdonk.nl/?p=1595
Ontology/Taxonomy
Ontology has to do with the relationships between entities while Taxonomy is of grouping of entities
Article on the effects of Label Placement
| Created: | 8/14/2011 5:22 PM |
Encapsulation
| Created: | 8/15/2011 6:42 AM |
In a programming language
encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination
[1][2] thereof:
- A language mechanism for restricting access to some of the object's components.[3][4]
- A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.[5][6]
Justin Pope's example of using a callback from Headspring's ASP.NET MVC Boot Camp
| Created: | 8/17/2011 12:59 PM |
<script language="javascript" type="text/javascript">
$(function () {
$('#showAttendees').click(function () {
var url = '@Url.Action("Show", "Attendee", new { confname = Model.Name })';
// Keep a reference to the show attendees button for later
var button = $(this);
var callback = function (data, textStatus) {
// Place HTML returned from AJAX inside special p tag below
$('#attendees').html(data);
// Hide the show attendees button
button.hide();
};
// Issue an AJAX GET, to return HTML (and not JSON)
$.get(url, null, callback, 'html');
});
});
</script>
.get is an asynchronous call akin to .json and Justin asserted that .ajax was the most powerful of these animals
an example of a .json call from an app I authored is:
$.getJSON("/json/", null, function(data) {
var hasFullAccess = data.isAdmin;
if (hasFullAccess == true) {
var errorMessage = "<%= errorMessage %>";
if (errorMessage == "")
{
$('#menuSystem').attr('style', 'display: block;');
} else {
$('#errorMessage').attr('style', 'display: block;');
}
} else {
window.location.replace("/login/");
}
});
PDF.js
...spiders a PDF and casts its contents to an HTML canvas
regular expressions
| Created: | 8/26/2011 6:12 AM |
Guid
acumen1.RegularExpression = @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$";
DateTime
acumen3.RegularExpression = @"^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$";
Money, two decimals
acumen5.RegularExpression = @"^\d+(\.\d{0,2})?$";
Email address
acumen2.RegularExpression = @"^\w+([-+.']\w+)*@\w+([-+.']\w+)*\.\w+([-+.']\w+)*$";
960fluid
...is a port of 960grid that uses ems in lieu of px
encrypting thingy from an old project
namespace AdministrableApplication.Core
{
public class EncryptionEnactor
{
public static string Garble(string unencryptedValue)
{
System.Security.Cryptography.MD5CryptoServiceProvider objCript =
new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(unencryptedValue);
bs = objCript.ComputeHash(bs);
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
return s.ToString();
}
}
}
Austin CodeCamp 2011 notes
| Created: | 9/10/2011 5:04 PM |
data-whatever
...in HTML 5 is your own attribute
CSS or Less
| Created: | 9/19/2011 3:20 PM |
http://leafo.net/lessphp/lessify/
Ontology
| Created: | 9/26/2011 3:11 PM |
an organization scheme based on schematic concepts
CSS for mobile sites
| Created: | 10/4/2011 8:11 PM |
http://www.smashingmagazine.com/2010/11/03/how-to-build-a-mobile-website/
<link rel="stylesheet" href="site.css" media="screen" /> |
| <link rel="stylesheet" href="mobile.css" media="handheld" /> |
<link rel="stylesheet" href="mobile.css" media="only screen and (max-device width:480px)"/>
@import url("screen.css"); |
| @import url("antiscreen.css") handheld; |
| @import url("antiscreen.css") only screen and (max-device-width:480px); |
love and hate CSS links
| Created: | 10/23/2011 9:08 AM |
h1 a:link {
text-decoration: none;
color: #FF6600;
cursor: pointer;
}
h1 a:visited {
text-decoration: none;
color: #FF6600;
cursor: pointer;
}
h1 a:hover {
text-decoration: underline;
color: #FF6600;
cursor: pointer;
}
h1 a:active {
text-decoration: none;
color: #FF6600;
cursor: pointer;
}
Ken Jackson once recommended situating (remembering) the four states for links in a LoVe and HAte way in which the L, V, H, A stand for link, visited, hover, and active respectively.
transparency in CSS3
| Created: | 10/23/2011 9:28 AM |
opacity: 0.6;
filter:alpha(opacity=60);
make the top two lines of the document like so:
<!DOCTYPE html>
<html lang="en" class="static ">
make a div cling the the bottom of another div
| Created: | 10/23/2011 9:42 AM |
Cardinality
| Created: | 10/24/2011 9:09 AM |
cardinality seems to be a unique shape of an object or collection
boilerplates
| Created: | 11/3/2011 9:10 AM |
boilerplates are templates for code reuse in that they provide a beginning point for how to do a thing that a team will do again and again in different places with different variations
cyclomatic complexity
| Created: | 11/3/2011 10:16 AM |
cyclomatic complexity is a metric to determine the number of paths through a feature
Tim Ash has a book on landing page optimization called: Landing Page Optimization
| Created: | 11/17/2011 7:20 AM |
He's a smart guy.
First Class Concepts
| Created: | 11/17/2011 1:39 PM |
A first class concept is a part of the out of the box implementation.
CTA
...stands for Call To Action
some NHibernate for an object called Settings
| Created: | 11/27/2011 7:18 PM |
SettingsMap.csusing AdministrableApplication.Core;
using FluentNHibernate.Mapping;
namespace AdministrableApplication.DataIntegration
{
public class SettingsMap : ClassMap<Settings>
{
public SettingsMap()
{
Map(x => x.emailConfirmationBody);
Map(x => x.emailConfirmationSubjectLine);
Map(x => x.emailDetailsSubjectLine);
Map(x => x.emailFrom);
Map(x => x.emailTo);
Map(x => x.globalPassword);
Map(x => x.homeAlternativeLinkNameI);
Map(x => x.homeAlternativeLinkNameII);
Map(x => x.homeAlternativeLinkNameIII);
Map(x => x.homeAlternativeLinkNameIV);
Map(x => x.homeAlternativeLinkUrlI);
Map(x => x.homeAlternativeLinkUrlII);
Map(x => x.homeAlternativeLinkUrlIII);
Map(x => x.homeAlternativeLinkUrlIV);
Map(x => x.homeCalloutBodyI);
Map(x => x.homeCalloutBodyII);
Map(x => x.homeCalloutBodyIII);
Map(x => x.homeCalloutBodyIV);
Map(x => x.homeCalloutHeadI);
Map(x => x.homeCalloutHeadII);
Map(x => x.homeCalloutHeadIII);
Map(x => x.homeCalloutHeadIV);
Map(x => x.homeCalloutLinkII);
Map(x => x.homeCalloutLinkIII);
Map(x => x.homeCalloutLinkIV);
Map(x => x.homeDescription);
Map(x => x.homeKeywords);
Map(x => x.homeTitle);
Map(x => x.homeUrl);
Map(x => x.locationOfSitemap);
Map(x => x.seoHtml);
Id(x => x.settingsId);
Map(x => x.urlContactButtonResolvesTo);
Map(x => x.urlGetStartedButtonResolvesTo);
Map(x => x.urlPrivacyPolicyLinkResolvesTo);
Map(x => x.urlTermsOfUseLinkResolvesTo);
}
}
}
SettingsRepository.cs
using NHibernate;
using Settings=AdministrableApplication.Core.Settings;
namespace AdministrableApplication.DataIntegration
{
public class SettingsRepository : ISettingsRepository
{
public Settings retrieveSettings()
{
var sessionFactory = CreateSessionFactory();
using (var session = sessionFactory.OpenSession())
{
IList iList = session.CreateCriteria(typeof(Settings)).List();
IList<Settings> allSettingsList = getSettings<Settings>(iList);
Settings[] allSettings = new Settings[] { };
allSettings = allSettingsList.ToArray();
session.Flush();
session.Close();
sessionFactory.Close();
sessionFactory.Dispose();
if (allSettings.Length == 1)
{
return allSettings[0];
} else {
return null;
}
}
}
public void updateSettings(Settings settings)
{
var sessionFactory = CreateSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
session.SaveOrUpdate(settings);
session.Flush();
transaction.Commit();
session.Close();
transaction.Dispose();
sessionFactory.Close();
sessionFactory.Dispose();
}
}
}
public static IList<T> getSettings<T>(IList iList)
{
IList<T> result = new List<T>();
foreach (T value in iList)
{
result.Add(value);
}
return result;
}
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure().Database(
MsSqlConfiguration.MsSql2005
.ConnectionString(c => c
.FromAppSetting("FluentNHibernateConnection"))
)
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<SettingsRepository>())
.BuildSessionFactory();
}
}
}
Covariance and contravariance (computer science)
| Created: | 12/10/2011 7:36 PM |
Within the type system of a programming language, covariance and contravariance refers to the ordering of types from narrower to wider and their interchangeability or equivalence in certain situations (such as parameters, generics, and return types).
- covariant: converting from wider (double) to narrower (float).
- contravariant: converting from narrower (float) to wider (double).
- invariant: Not able to convert.