Coming back to work after a long weekend I found this on my iMac. Lets just say it wasn't working so well. 50 GB worth of memory paged out to the swap file due to a Memory Leak in Firefox. And they wonder why I prefer Safari. By the way I only had three tabs open. :/
This is my personal blog and mainly contains technical solutions, open source code, and other projects I have worked on. Much of the technical solutions are very niche so your milage may vary.
Friday, September 7, 2012
Thursday, August 30, 2012
Maximum File Upload Size in IIS 7
I have investigated and done a lot of testing as the information online is somewhat inaccurate/misleading. In the end i Determined that the following setting all need to be configured to allow for large file uploads. If not the default settings will stop uploads greater then about 20 MB.
The following change need made to the web.config file.
<system.web>
The executionTimeout is extending the maximum script execution to 10 minutes witch will be required for larger uploads. The maxRequestLength is the maximum size in kilobytes while the maxAllowedContentLength is the same maximum size but in bytes. So maxAllowedContentLength should be 1000 times the maxRequestLength.
These numbers of course can be adjusted as needed.
On a final note you may want to check C:\Windows\System32\inetsrv\config\applicationHost.config and verify that the following line is present and set to Allow.
The following change need made to the web.config file.
<system.web>
<httpRuntime requestValidationMode="2.0" executionTimeout="600" maxRequestLength="2000000" />
<system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2000000000" />
</requestFiltering>
</security>
</system.webServer>
The executionTimeout is extending the maximum script execution to 10 minutes witch will be required for larger uploads. The maxRequestLength is the maximum size in kilobytes while the maxAllowedContentLength is the same maximum size but in bytes. So maxAllowedContentLength should be 1000 times the maxRequestLength.
These numbers of course can be adjusted as needed.
On a final note you may want to check C:\Windows\System32\inetsrv\config\applicationHost.config and verify that the following line is present and set to Allow.
<section name="requestFiltering" overrideModeDefault="Allow" />
Umbraco Using Courier to Deploy MultiType Data
When using Umbraco and doing production deployments with the Courier package I ran into an issue. We have had the process working fine with built in components but recently I deployed a new property that used the MultiType DataType which allows for arrays of data fields grouped together. For example we have the following grouping and multiple images can be added to the one parameter in Umbraco.
RotatingImages
Item
ImageSrc(Media Picker)
MobileSrc(Media Picker)
AltText(Text)
LinkTo(Content Picker)
The problem comes in when we publish this item, the content and media pickers contain the node id's and the data is stored as XML. As such Courier will not process the ID's when it does the deployment process. To fix this a custom PropertyDataResolverProvider is needed. The following code can be included in the App_Code directory to fix this problem.
RotatingImages
Item
ImageSrc(Media Picker)
MobileSrc(Media Picker)
AltText(Text)
LinkTo(Content Picker)
The problem comes in when we publish this item, the content and media pickers contain the node id's and the data is stored as XML. As such Courier will not process the ID's when it does the deployment process. To fix this a custom PropertyDataResolverProvider is needed. The following code can be included in the App_Code directory to fix this problem.
using Umbraco.Courier.Core;
using Umbraco.Courier.Core.Enums;
using Umbraco.Courier.Core.Helpers;
using Umbraco.Courier.DataResolvers;
using Umbraco.Courier.ItemProviders;
using System.Collections.Generic;
using System.Linq;
namespace JSP {
/// <summary>
/// Custm Data Resolver for use with MultiType data objects. Will convers a list of xml nodes to guids for deployment and back again.
/// </summary>
public class MultiType : PropertyDataResolverProvider
{
/// <summary>
/// The datatype guid of the multitype item we are running on.
/// </summary>
public override Guid DataTypeId
{
get { return new Guid("f17bb230-3941-4813-a923-e7c3efd067d8"); }
}
/// <summary>
/// Get the xpath elements from the data types that contain document or media id's.
/// </summary>
/// <param name="propertyData">Property to examin.</param>
/// <param name="documentXPath">XPath string to select all fields with document ID's.</param>
/// <param name="mediaXPath">XPath string to select all fields with media ID's.</param>
private void GetXPath(ContentProperty propertyData, out string documentXPath, out string mediaXPath)
{
// Get the data definition for this item.
var dataDefinition = new umbraco.cms.businesslogic.datatype.DataTypeDefinition(propertyData.DataType);
// Get the item configureation and locate the preValue property.
var preValue = umbraco.library.GetPreValues(dataDefinition.DataType.DataTypeDefinitionId);
preValue.MoveNext();
var preValueIterator = preValue.Current.SelectChildren("preValue", "");
preValueIterator.MoveNext();
// Deserialize the preValue data.
dynamic data = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(preValueIterator.Current.Value);
// Get the MultiType Children properties.
var mprop = ((object[])((Dictionary<string, object>)data)["MultiTypes"]).Cast<Dictionary<string, object>>();
// Get all content picker properties and add the alias to the list. Resutls: //Node1 | //Node2 | ...
documentXPath = String.Join(" | ", mprop.Where(i => Convert.ToInt32(i["Type"]) == (int)_4Ben.DataTypes.MultiType.ControlType.ContentPicker).Select(i => "//" + i["Alias"].ToString()));
// Get all media picker properties and add the alias to the list. Resutls: //Node1 | //Node2 | ...
mediaXPath = String.Join(" | ", mprop.Where(i => Convert.ToInt32(i["Type"]) == (int)_4Ben.DataTypes.MultiType.ControlType.MediaPicker).Select(i => "//" + i["Alias"].ToString()));
}
/// <summary>
/// Run when a property of the specified type is packaged up.
/// </summary>
public override void PackagingProperty(Item item, ContentProperty propertyData)
{
string documentXpath;
string mediaXpath;
// Get the elements from this data type that need to be converted. This could be hard coded but the queries are quick.
GetXPath(propertyData, out documentXpath, out mediaXpath);
// Document References
List<string> replacedIds = new List<string>();
propertyData.Value = XmlDependencies.ReplaceIds(propertyData.Value.ToString(), documentXpath, IdentifierReplaceDirection.FromNodeIdToGuid, out replacedIds);
// List all id's found and make them dependencies.
foreach (string guid in replacedIds)
{
// Add as a dependency. (working?)
item.Dependencies.Add(guid, ProviderIDCollection.documentItemProviderGuid);
}
// Media References
//dataXpath = ConfigurationManager.AppSettings["courierMultiTypeMediaNodes"].ToString();
replacedIds = new List<string>();
propertyData.Value = XmlDependencies.ReplaceIds(propertyData.Value.ToString(), mediaXpath, IdentifierReplaceDirection.FromNodeIdToGuid, out replacedIds);
// List all id's found and make them dependencies.
foreach (string guid in replacedIds)
{
// Add as a dependency. (working?)
item.Dependencies.Add(guid, ProviderIDCollection.mediaItemProviderGuid);
// Could add as a resource but in reality the entire node is needed witch wil transwer the resource so this line should not be run.
//item.Resources.Add(new umbraco.cms.businesslogic.media.Media(new Guid(guid)).getProperty("umbracoFile").Value.ToString());
}
}
/// <summary>
/// Run when a property of the specified type is extracted.
/// </summary>
public override void ExtractingProperty(Item item, ContentProperty propertyData)
{
string documentXpath;
string mediaXpath;
// Get the elements from this data type that need to be converted. This could be hard coded but the queries are quick.
GetXPath(propertyData, out documentXpath, out mediaXpath);
// Document References
List<string> replacedIds = new List<string>();
propertyData.Value = XmlDependencies.ReplaceIds(propertyData.Value.ToString(), documentXpath, IdentifierReplaceDirection.FromGuidToNodeId, out replacedIds);
// Media References
replacedIds = new List<string>();
propertyData.Value = XmlDependencies.ReplaceIds(propertyData.Value.ToString(), mediaXpath, IdentifierReplaceDirection.FromGuidToNodeId, out replacedIds);
}
}
}
Tuesday, July 24, 2012
jQuery Plugin to Scroll an Element with the Page
Updated 11/7/2013: Added support for positioning via padding instead of margins.
This simple javascript plugin is a very simple bit of code that can be attached to any element on a web page. It will make the element work similar of a position:fixed element in that it will cause the element to scroll with the browser window vertically as the user scrolls up and down.
The benefit of this over the css attribute is that this method will retain the items original placement and flow instead simply adjust the margin-top to replicate the scrolling logic. Additional paddingTop and paddingBottom can be specified witch will act as minimum margins between the viewport and the floating item.
Sample Code:
The query Plugin code is available on GitHub here. You will need to include jQuery and then this file in your page header to use it.
This simple javascript plugin is a very simple bit of code that can be attached to any element on a web page. It will make the element work similar of a position:fixed element in that it will cause the element to scroll with the browser window vertically as the user scrolls up and down.
The benefit of this over the css attribute is that this method will retain the items original placement and flow instead simply adjust the margin-top to replicate the scrolling logic. Additional paddingTop and paddingBottom can be specified witch will act as minimum margins between the viewport and the floating item.
Sample Code:
$("#element").autoScroll({ paddingTop: 30 });
The query Plugin code is available on GitHub here. You will need to include jQuery and then this file in your page header to use it.
Friday, July 6, 2012
Web Form Validation the Right/Simple Way.
Another topic that isn't all all new. There are millions of forms out there and they all do user input validation differently. The long and the short of this article is that there are many approaches but we want a best practice that meets a few requirements. It must be quick, efficient, simple to configure, but able to do all the validation logic we may need. There are lots of frameworks or custom code to do this but as I mentioned I am going for the most elegant solution here. So here is goes, here is a sample form with the validation logic.
This might look quite impel but in reality is is doing nearly all the validation we need for this simple form. I am using the jQuery Validation plugin to do all the heavy lifting here. This is also a very elegant solution. You will notice that there is only one javascript call on the page yet all the fields are being validated. How you ask? While the documentation doesn't covert it very well but jquery.validation will acutely use the css class markup to apply validation rules. See the form controls that have the classes required, email, phoneUS, and zip. These are what trigger the validation logic. In essence this is the same to the following script tag but this little know markup is much cleaner.
Now you can see why the css markup trick is a lot cleaner. It also keeps the rules along with the fields they are affecting to it is easier to track down problems with the validation.
On another point you may notice that the first sample I posted is not validating the phone number and zip code properly. That is because I created custom class rules and methods that are not in the validation framework. The following class rule, think alias or marco, and method need to be added to the script tag after the validation include or more simply just added to a site wide script file. The first is a macro that applies multiple rules as a set. This also allows you to apply rules with parameters witch you can't do in the css markup. The second is an entirely new method that does some complex regular expression validation.
This approve can now be used to add as complex of validation logic as needed. The user will automatically see nice callouts when they try to submit the form with errors on it. Also of note this solution will fail gracefully so if there is a script error or javacscript is just unavailable the page will still function and post to the server. Now with that in mind it brings me to my final point. The receiving server side script should always to its own validation to catch not only these rare cases where javacript is disabled or some other error occurred, but also to catch cases there some user is intentionally trying to submit invalid data. And clint side validation like this can easily be disabled but the end user and a invalid form submitted. Thus the onus is always on the server code/database for true validation.
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.2.min.js'></script>
<script type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$("#myForm").validate();
}
</script>
<form action='?' method='post' id='myForm'>
<p>
<label for='firstName'>First Name:</label> <input name='firstName' id='firstName' class='required' type='text'>
</p>
<p>
<label for='lastName'>Last Name:</label> <input name='lastName' id='lastName' class='required' type='text'>
</p>
<p>
<label for="custType">Type:</label> <select name="custType" id="custType" class='required'>
<option value=""></option>
<option value="vendor">Vendor</option>
<option value="salesrep">Sales Rep</option>
<option value="supplier">Supplier</option>
<select>
</p>
<p>
<label for='emailAddress'>Email Address:</label> <input name='emailAddress' id='emailAddress' class='required email' type='text'>
</p>
<p>
<label for='primaryPhone'>Phone Number:</label> <input name='primaryPhone' id='primaryPhone' class='required phoneUS' type='text'>
</p>
<p>
<label for='zipCode'>Zip Code:</label> <input name='zipCode' id='zipCode' class='required zip' type='text'>
</p>
<p>
<input type='submit' name='save' id='save' value='Save'>
</p>
</form>
This might look quite impel but in reality is is doing nearly all the validation we need for this simple form. I am using the jQuery Validation plugin to do all the heavy lifting here. This is also a very elegant solution. You will notice that there is only one javascript call on the page yet all the fields are being validated. How you ask? While the documentation doesn't covert it very well but jquery.validation will acutely use the css class markup to apply validation rules. See the form controls that have the classes required, email, phoneUS, and zip. These are what trigger the validation logic. In essence this is the same to the following script tag but this little know markup is much cleaner.
$("#myForm").validate({
rules: {
firstName: "required",
lastName: "required",
custType: "required",
emailAddress: {
required: true,
email: true
},
primaryPhone: {
required: true,
phoneUS: true
},
zipCode: {
required: true,
digits: true,
minlength: 5,
maxlength: 5
}
}
})
Now you can see why the css markup trick is a lot cleaner. It also keeps the rules along with the fields they are affecting to it is easier to track down problems with the validation.
On another point you may notice that the first sample I posted is not validating the phone number and zip code properly. That is because I created custom class rules and methods that are not in the validation framework. The following class rule, think alias or marco, and method need to be added to the script tag after the validation include or more simply just added to a site wide script file. The first is a macro that applies multiple rules as a set. This also allows you to apply rules with parameters witch you can't do in the css markup. The second is an entirely new method that does some complex regular expression validation.
jQuery.validator.addClassRules({
zip: {
digits: true,
minlength: 5,
maxlength: 5
}
});
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
This approve can now be used to add as complex of validation logic as needed. The user will automatically see nice callouts when they try to submit the form with errors on it. Also of note this solution will fail gracefully so if there is a script error or javacscript is just unavailable the page will still function and post to the server. Now with that in mind it brings me to my final point. The receiving server side script should always to its own validation to catch not only these rare cases where javacript is disabled or some other error occurred, but also to catch cases there some user is intentionally trying to submit invalid data. And clint side validation like this can easily be disabled but the end user and a invalid form submitted. Thus the onus is always on the server code/database for true validation.
Subscribe to:
Posts (Atom)
Project Licenses
These works by Jeremy Pyne are licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License
