Start Migration Tools, More MongoDB stuff

Killed the Redis dep in BuildFeed, started writing a Migration Tool.
This commit is contained in:
Thomas Hounsell 2015-08-05 00:23:20 +01:00
parent bb00573825
commit a22c5cbe3d
21 changed files with 817 additions and 257 deletions

View File

@ -171,7 +171,7 @@
</site>
<site name="BuildFeed(1)" id="3">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="D:\Thomas\My Documents\Visual Studio 2015\Projects\BuildFeed\BuildFeed" />
<virtualDirectory path="/" physicalPath="C:\Users\Thomas\Documents\Visual Studio 14\Projects\BuildFeed\BuildFeed" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:50505:localhost" />

View File

@ -16,6 +16,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoAuth", "MongoAuth\Mong
EndProject
Project("{262852C6-CD72-467D-83FE-5EEB1973A190}") = "BuildFeedApp-Westminster", "BuildFeedApp-Westminster\BuildFeedApp-Westminster.jsproj", "{5CAADB66-1FC2-4492-B766-36354687120D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RedisMongoMigration", "RedisMongoMigration\RedisMongoMigration.csproj", "{CD3C08CC-45BF-484B-A878-69614A4EA098}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -100,6 +102,22 @@ Global
{5CAADB66-1FC2-4492-B766-36354687120D}.Release|x86.ActiveCfg = Release|x86
{5CAADB66-1FC2-4492-B766-36354687120D}.Release|x86.Build.0 = Release|x86
{5CAADB66-1FC2-4492-B766-36354687120D}.Release|x86.Deploy.0 = Release|x86
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Debug|ARM.ActiveCfg = Debug|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Debug|ARM.Build.0 = Debug|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Debug|x64.ActiveCfg = Debug|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Debug|x64.Build.0 = Debug|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Debug|x86.ActiveCfg = Debug|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Debug|x86.Build.0 = Debug|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Release|Any CPU.Build.0 = Release|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Release|ARM.ActiveCfg = Release|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Release|ARM.Build.0 = Release|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Release|x64.ActiveCfg = Release|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Release|x64.Build.0 = Release|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Release|x86.ActiveCfg = Release|Any CPU
{CD3C08CC-45BF-484B-A878-69614A4EA098}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -51,8 +51,8 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Antlr.3.5.0.2\lib\Antlr3.Runtime.dll</HintPath>
</Reference>
<Reference Include="Humanizer, Version=1.37.0.0, Culture=neutral, PublicKeyToken=979442b78dfc278e, processorArchitecture=MSIL">
<HintPath>..\packages\Humanizer.1.37.0\lib\portable-win+net40+sl50+wp8+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Humanizer.dll</HintPath>
<Reference Include="Humanizer, Version=1.37.7.0, Culture=neutral, PublicKeyToken=979442b78dfc278e, processorArchitecture=MSIL">
<HintPath>..\packages\Humanizer.1.37.7\lib\portable-win+net40+sl50+wp8+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Humanizer.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.ApplicationInsights, Version=1.1.0.1899, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
@ -89,25 +89,22 @@
<Reference Include="Microsoft.Threading.Tasks.Extensions.Desktop">
<HintPath>..\packages\Microsoft.Bcl.Async.1.0.168\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll</HintPath>
</Reference>
<Reference Include="MongoDB.Bson, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Bson.2.0.1\lib\net45\MongoDB.Bson.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="MongoDB.Driver, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Driver.2.0.1\lib\net45\MongoDB.Driver.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="MongoDB.Driver.Core, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MongoDB.Driver.Core.2.0.1\lib\net45\MongoDB.Driver.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NServiceKit.Common, Version=1.0.35.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NServiceKit.Common.1.0.35\lib\net35\NServiceKit.Common.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NServiceKit.Interfaces, Version=1.0.35.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NServiceKit.Common.1.0.35\lib\net35\NServiceKit.Interfaces.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NServiceKit.Redis, Version=1.0.16.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NServiceKit.Redis.1.0.16\lib\net35\NServiceKit.Redis.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NServiceKit.Text">
<HintPath>..\packages\NServiceKit.Text.1.0.10\lib\net35\NServiceKit.Text.dll</HintPath>
</Reference>
<Reference Include="RouteDebugger">
<HintPath>..\packages\routedebugger.2.1.4.0\lib\net40\RouteDebugger.dll</HintPath>
</Reference>
@ -279,6 +276,9 @@
<None Include="Scripts\jquery-2.1.4.intellisense.js" />
<Content Include="Scripts\jquery-2.1.4.js" />
<Content Include="Scripts\jquery-2.1.4.min.js" />
<None Include="Scripts\jquery.validate-vsdoc.js" />
<Content Include="Scripts\jquery.validate.js" />
<Content Include="Scripts\jquery.validate.min.js" />
<Content Include="Scripts\jquery.validate.unobtrusive.js" />
<Content Include="Scripts\jquery.validate.unobtrusive.min.js" />
<Content Include="Scripts\trumbowyg\langs\ca.min.js" />
@ -334,9 +334,6 @@
<Content Include="Scripts\excanvas.compiled.js" />
<Content Include="Scripts\excanvas.js" />
<Content Include="Scripts\jquery-2.1.4.min.map" />
<None Include="Scripts\jquery.validate-vsdoc.js" />
<Content Include="Scripts\jquery.validate.js" />
<Content Include="Scripts\jquery.validate.min.js" />
<Content Include="Scripts\jsrender.js" />
<Content Include="Scripts\jsrender.min.js" />
<Content Include="Scripts\_references.js" />

Binary file not shown.

View File

@ -4,7 +4,7 @@
* intended to be used only for design-time IntelliSense. Please use the
* standard jQuery library for all production use.
*
* Comment version: 1.13.1
* Comment version: 1.14.0
*/
/*
@ -15,7 +15,7 @@
* for informational purposes only and are not the license terms under
* which Microsoft distributed this file.
*
* jQuery Validation Plugin - v1.13.1 - 2/4/2013
* jQuery Validation Plugin - v1.14.0 - 2/4/2013
* https://github.com/jzaefferer/jquery-validation
* Copyright (c) 2013 Jörn Zaefferer; Licensed MIT
*

View File

@ -1,9 +1,9 @@
/*!
* jQuery Validation Plugin v1.13.1
* jQuery Validation Plugin v1.14.0
*
* http://jqueryvalidation.org/
*
* Copyright (c) 2014 Jörn Zaefferer
* Copyright (c) 2015 Jörn Zaefferer
* Released under the MIT license
*/
(function( factory ) {
@ -40,23 +40,24 @@ $.extend($.fn, {
if ( validator.settings.onsubmit ) {
this.validateDelegate( ":submit", "click", function( event ) {
this.on( "click.validate", ":submit", function( event ) {
if ( validator.settings.submitHandler ) {
validator.submitButton = event.target;
}
// allow suppressing validation by adding a cancel class to the submit button
if ( $( event.target ).hasClass( "cancel" ) ) {
if ( $( this ).hasClass( "cancel" ) ) {
validator.cancelSubmit = true;
}
// allow suppressing validation by adding the html5 formnovalidate attribute to the submit button
if ( $( event.target ).attr( "formnovalidate" ) !== undefined ) {
if ( $( this ).attr( "formnovalidate" ) !== undefined ) {
validator.cancelSubmit = true;
}
});
// validate the form on submit
this.submit( function( event ) {
this.on( "submit.validate", function( event ) {
if ( validator.settings.debug ) {
// prevent form submit to be able to see console output
event.preventDefault();
@ -106,29 +107,23 @@ $.extend($.fn, {
},
// http://jqueryvalidation.org/valid/
valid: function() {
var valid, validator;
var valid, validator, errorList;
if ( $( this[ 0 ] ).is( "form" ) ) {
valid = this.validate().form();
} else {
errorList = [];
valid = true;
validator = $( this[ 0 ].form ).validate();
this.each( function() {
valid = validator.element( this ) && valid;
errorList = errorList.concat( validator.errorList );
});
validator.errorList = errorList;
}
return valid;
},
// attributes: space separated list of attributes to retrieve and remove
removeAttrs: function( attributes ) {
var result = {},
$element = this;
$.each( attributes.split( /\s/ ), function( index, value ) {
result[ value ] = $element.attr( value );
$element.removeAttr( value );
});
return result;
},
// http://jqueryvalidation.org/rules/
rules: function( command, argument ) {
var element = this[ 0 ],
@ -272,7 +267,26 @@ $.extend( $.validator, {
}
},
onkeyup: function( element, event ) {
if ( event.which === 9 && this.elementValue( element ) === "" ) {
// Avoid revalidate the field when pressing one of the following keys
// Shift => 16
// Ctrl => 17
// Alt => 18
// Caps lock => 20
// End => 35
// Home => 36
// Left arrow => 37
// Up arrow => 38
// Right arrow => 39
// Down arrow => 40
// Insert => 45
// Num lock => 144
// AltGr key => 225
var excludedKeys = [
16, 17, 18, 20, 35, 36, 37,
38, 39, 40, 45, 144, 225
];
if ( event.which === 9 && this.elementValue( element ) === "" || $.inArray( event.keyCode, excludedKeys ) !== -1 ) {
return;
} else if ( element.name in this.submitted || element === this.lastElement ) {
this.element( element );
@ -359,26 +373,26 @@ $.extend( $.validator, {
});
function delegate( event ) {
var validator = $.data( this[ 0 ].form, "validator" ),
var validator = $.data( this.form, "validator" ),
eventType = "on" + event.type.replace( /^validate/, "" ),
settings = validator.settings;
if ( settings[ eventType ] && !this.is( settings.ignore ) ) {
settings[ eventType ].call( validator, this[ 0 ], event );
if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {
settings[ eventType ].call( validator, this, event );
}
}
$( this.currentForm )
.validateDelegate( ":text, [type='password'], [type='file'], select, textarea, " +
"[type='number'], [type='search'] ,[type='tel'], [type='url'], " +
"[type='email'], [type='datetime'], [type='date'], [type='month'], " +
"[type='week'], [type='time'], [type='datetime-local'], " +
"[type='range'], [type='color'], [type='radio'], [type='checkbox']",
"focusin focusout keyup", delegate)
.on( "focusin.validate focusout.validate keyup.validate",
":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " +
"[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " +
"[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " +
"[type='radio'], [type='checkbox']", delegate)
// Support: Chrome, oldIE
// "select" is provided as event.target when clicking a option
.validateDelegate("select, option, [type='radio'], [type='checkbox']", "click", delegate);
.on("click.validate", "select, option, [type='radio'], [type='checkbox']", delegate);
if ( this.settings.invalidHandler ) {
$( this.currentForm ).bind( "invalid-form.validate", this.settings.invalidHandler );
$( this.currentForm ).on( "invalid-form.validate", this.settings.invalidHandler );
}
// Add aria-required to any Static/Data/Class required fields before first validation
@ -471,10 +485,18 @@ $.extend( $.validator, {
this.lastElement = null;
this.prepareForm();
this.hideErrors();
this.elements()
.removeClass( this.settings.errorClass )
.removeData( "previousValue" )
.removeAttr( "aria-invalid" );
var i, elements = this.elements()
.removeData( "previousValue" )
.removeAttr( "aria-invalid" );
if ( this.settings.unhighlight ) {
for ( i = 0; elements[ i ]; i++ ) {
this.settings.unhighlight.call( this, elements[ i ],
this.settings.errorClass, "" );
}
} else {
elements.removeClass( this.settings.errorClass );
}
},
numberOfInvalids: function() {
@ -536,7 +558,7 @@ $.extend( $.validator, {
// select all valid inputs inside the form (no submit or reset buttons)
return $( this.currentForm )
.find( "input, select, textarea" )
.not( ":submit, :reset, :image, [disabled], [readonly]" )
.not( ":submit, :reset, :image, :disabled" )
.not( this.settings.ignore )
.filter( function() {
if ( !this.name && validator.settings.debug && window.console ) {
@ -587,7 +609,7 @@ $.extend( $.validator, {
type = element.type;
if ( type === "radio" || type === "checkbox" ) {
return $( "input[name='" + element.name + "']:checked" ).val();
return this.findByName( element.name ).filter(":checked").val();
} else if ( type === "number" && typeof element.validity !== "undefined" ) {
return element.validity.badInput ? false : $element.val();
}
@ -637,6 +659,10 @@ $.extend( $.validator, {
if ( this.settings.debug && window.console ) {
console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e );
}
if ( e instanceof TypeError ) {
e.message += ". Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.";
}
throw e;
}
}
@ -786,7 +812,7 @@ $.extend( $.validator, {
// If the element is not a child of an associated label, then it's necessary
// to explicitly apply aria-describedby
errorID = error.attr( "id" ).replace( /(:|\.|\[|\])/g, "\\$1");
errorID = error.attr( "id" ).replace( /(:|\.|\[|\]|\$)/g, "\\$1");
// Respect existing non-error aria-describedby
if ( !describedBy ) {
describedBy = errorID;
@ -918,6 +944,15 @@ $.extend( $.validator, {
valid: true,
message: this.defaultMessage( element, "remote" )
});
},
// cleans up all forms and elements, removes validator-specific events
destroy: function() {
this.resetForm();
$( this.currentForm )
.off( ".validate" )
.removeData( "validator" );
}
},
@ -955,6 +990,29 @@ $.extend( $.validator, {
return rules;
},
normalizeAttributeRule: function( rules, type, method, value ) {
// convert the value to a number for number inputs, and for text for backwards compability
// allows type="date" and others to be compared as strings
if ( /min|max/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {
value = Number( value );
// Support Opera Mini, which returns NaN for undefined minlength
if ( isNaN( value ) ) {
value = undefined;
}
}
if ( value || value === 0 ) {
rules[ method ] = value;
} else if ( type === method && type !== "range" ) {
// exception: the jquery validate 'range' method
// does not test for the html5 'range' type
rules[ method ] = true;
}
},
attributeRules: function( element ) {
var rules = {},
$element = $( element ),
@ -966,30 +1024,20 @@ $.extend( $.validator, {
// support for <input required> in both html5 and older browsers
if ( method === "required" ) {
value = element.getAttribute( method );
// Some browsers return an empty string for the required attribute
// and non-HTML5 browsers might have required="" markup
if ( value === "" ) {
value = true;
}
// force non-HTML5 browsers to return bool
value = !!value;
} else {
value = $element.attr( method );
}
// convert the value to a number for number inputs, and for text for backwards compability
// allows type="date" and others to be compared as strings
if ( /min|max/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) {
value = Number( value );
}
if ( value || value === 0 ) {
rules[ method ] = value;
} else if ( type === method && type !== "range" ) {
// exception: the jquery validate 'range' method
// does not test for the html5 'range' type
rules[ method ] = true;
}
this.normalizeAttributeRule( rules, type, method, value );
}
// maxlength may be returned as -1, 2147483647 ( IE ) and 524288 ( safari ) for text inputs
@ -1001,13 +1049,14 @@ $.extend( $.validator, {
},
dataRules: function( element ) {
var method, value,
rules = {}, $element = $( element );
var rules = {},
$element = $( element ),
type = element.getAttribute( "type" ),
method, value;
for ( method in $.validator.methods ) {
value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() );
if ( value !== undefined ) {
rules[ method ] = value;
}
this.normalizeAttributeRule( rules, type, method, value );
}
return rules;
},
@ -1125,12 +1174,12 @@ $.extend( $.validator, {
if ( this.checkable( element ) ) {
return this.getLength( value, element ) > 0;
}
return $.trim( value ).length > 0;
return value.length > 0;
},
// http://jqueryvalidation.org/email-method/
email: function( value, element ) {
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
// From https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
// Retrieved 2014-01-14
// If you have a problem with this implementation, report a bug against the above spec
// Or use custom methods to implement your own email validation
@ -1139,8 +1188,12 @@ $.extend( $.validator, {
// http://jqueryvalidation.org/url-method/
url: function( value, element ) {
// contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
return this.optional( element ) || /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test( value );
// Copyright (c) 2010-2013 Diego Perini, MIT licensed
// https://gist.github.com/dperini/729294
// see also https://mathiasbynens.be/demo/url-regex
// modified to allow protocol-relative URLs
return this.optional( element ) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value );
},
// http://jqueryvalidation.org/date-method/
@ -1155,7 +1208,7 @@ $.extend( $.validator, {
// http://jqueryvalidation.org/number-method/
number: function( value, element ) {
return this.optional( element ) || /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value );
return this.optional( element ) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value );
},
// http://jqueryvalidation.org/digits-method/
@ -1164,7 +1217,7 @@ $.extend( $.validator, {
},
// http://jqueryvalidation.org/creditcard-method/
// based on http://en.wikipedia.org/wiki/Luhn/
// based on http://en.wikipedia.org/wiki/Luhn_algorithm
creditcard: function( value, element ) {
if ( this.optional( element ) ) {
return "dependency-mismatch";
@ -1240,7 +1293,7 @@ $.extend( $.validator, {
// TODO find a way to bind the event just once, avoiding the unbind-rebind overhead
var target = $( param );
if ( this.settings.onfocusout ) {
target.unbind( ".validate-equalTo" ).bind( "blur.validate-equalTo", function() {
target.off( ".validate-equalTo" ).on( "blur.validate-equalTo", function() {
$( element ).valid();
});
}
@ -1274,7 +1327,6 @@ $.extend( $.validator, {
data = {};
data[ element.name ] = value;
$.ajax( $.extend( true, {
url: param,
mode: "abort",
port: "validate" + element.name,
dataType: "json",
@ -1305,15 +1357,10 @@ $.extend( $.validator, {
}, param ) );
return "pending";
}
}
});
$.format = function deprecated() {
throw "$.format has been deprecated. Please use $.validator.format instead.";
};
// ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
@ -1348,18 +1395,4 @@ if ( $.ajaxPrefilter ) {
};
}
// provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
// handler is only called when $(event.target).is(delegate), in the scope of the jquery-object for event.target
$.extend($.fn, {
validateDelegate: function( delegate, type, handler ) {
return this.bind(type, function( event ) {
var target = $(event.target);
if ( target.is(delegate) ) {
return handler.apply(target, arguments);
}
});
}
});
}));

File diff suppressed because one or more lines are too long

View File

@ -2,10 +2,10 @@
<packages>
<package id="Antlr" version="3.5.0.2" targetFramework="net45" />
<package id="Chart.js" version="1.0.2" targetFramework="net45" />
<package id="Humanizer" version="1.37.0" targetFramework="net452" />
<package id="Humanizer" version="1.37.7" targetFramework="net46" />
<package id="jQuery" version="2.1.4" targetFramework="net452" />
<package id="jquery.TypeScript.DefinitelyTyped" version="2.2.6" targetFramework="net46" />
<package id="jQuery.Validation" version="1.13.1" targetFramework="net45" />
<package id="jQuery.Validation" version="1.14.0" targetFramework="net46" />
<package id="jsrender.TypeScript.DefinitelyTyped" version="0.0.3" targetFramework="net45" />
<package id="Microsoft.ApplicationInsights" version="1.1.0" targetFramework="net46" />
<package id="Microsoft.ApplicationInsights.Agent.Intercept" version="1.0.0" targetFramework="net46" />
@ -26,10 +26,10 @@
<package id="Microsoft.Bcl.Build" version="1.0.21" targetFramework="net45" />
<package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.3" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="MongoDB.Bson" version="2.0.1" targetFramework="net46" />
<package id="MongoDB.Driver" version="2.0.1" targetFramework="net46" />
<package id="MongoDB.Driver.Core" version="2.0.1" targetFramework="net46" />
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net452" />
<package id="NServiceKit.Common" version="1.0.35" targetFramework="net452" />
<package id="NServiceKit.Redis" version="1.0.16" targetFramework="net45" />
<package id="NServiceKit.Text" version="1.0.10" targetFramework="net45" />
<package id="routedebugger" version="2.1.4.0" targetFramework="net45" />
<package id="WebGrease" version="1.6.0" targetFramework="net45" />
<package id="xwebrss" version="1.2.1.130" targetFramework="net45" />

View File

@ -9,8 +9,9 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MongoAuth</RootNamespace>
<AssemblyName>MongoAuth</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -58,10 +59,21 @@
<Compile Include="MongoMembershipProvider.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="MongoRoleProvider.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -14,7 +14,7 @@ namespace MongoAuth
{
public class MongoMembershipProvider : MembershipProvider
{
private const string _CollectionName = "members";
private const string _memberCollectionName = "members";
private bool _enablePasswordReset = true;
private int _maxInvalidPasswordAttempts = 5;
@ -24,6 +24,7 @@ public class MongoMembershipProvider : MembershipProvider
private bool _requiresUniqueEmail = true;
private MongoClient _dbClient;
private IMongoCollection<MongoMember> _memberCollection;
public override string ApplicationName { get; set; }
@ -97,6 +98,7 @@ public override void Initialize(string name, NameValueCollection config)
{
Server = new MongoServerAddress(DatabaseConfig.Host, DatabaseConfig.Port)
});
_memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_memberCollectionName);
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
@ -105,11 +107,11 @@ public override bool ChangePassword(string username, string oldPassword, string
if (isAuthenticated)
{
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var mmTask = collection.Find(m => m.UserName.ToLower() == username.ToLower()).SingleOrDefaultAsync();
mmTask.Wait();
var mm = mmTask.Result;
var task = _memberCollection
.Find(m => m.UserName.ToLower() == username.ToLower())
.SingleOrDefaultAsync();
task.Wait();
var mm = task.Result;
if (mm == null)
{
@ -122,7 +124,8 @@ public override bool ChangePassword(string username, string oldPassword, string
mm.PassSalt = salt;
mm.PassHash = hash;
var replaceTask = collection.ReplaceOneAsync(m => m.Id == mm.Id, mm);
var replaceTask = _memberCollection
.ReplaceOneAsync(m => m.Id == mm.Id, mm);
replaceTask.Wait();
if (replaceTask.IsCompleted)
@ -151,11 +154,12 @@ public override MembershipUser CreateUser(string username, string password, stri
MembershipUser mu = null;
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var dupeUsers = collection.Find(m => m.UserName.ToLower() == username.ToLower()).CountAsync();
var dupeEmails = collection.Find(m => m.EmailAddress.ToLower() == email.ToLower()).CountAsync();
var dupeUsers = _memberCollection
.Find(m => m.UserName.ToLower() == username.ToLower())
.CountAsync();
var dupeEmails = _memberCollection
.Find(m => m.EmailAddress.ToLower() == email.ToLower())
.CountAsync();
dupeUsers.Wait();
dupeEmails.Wait();
@ -189,7 +193,8 @@ public override MembershipUser CreateUser(string username, string password, stri
LastLockoutDate = DateTime.MinValue
};
var insertTask = collection.InsertOneAsync(mm);
var insertTask = _memberCollection
.InsertOneAsync(mm);
insertTask.Wait();
if (insertTask.Status == TaskStatus.RanToCompletion)
@ -209,17 +214,11 @@ public override MembershipUser CreateUser(string username, string password, stri
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var task = _memberCollection
.DeleteOneAsync(m => m.UserName.ToLower() == m.UserName.ToLower());
task.Wait();
var deleteTask = collection.DeleteOneAsync(m => m.UserName.ToLower() == m.UserName.ToLower());
deleteTask.Wait();
if (deleteTask.Result.IsAcknowledged && deleteTask.Result.DeletedCount == 1)
{
return true;
}
return false;
return task.Result.IsAcknowledged && task.Result.DeletedCount == 1;
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
@ -236,16 +235,17 @@ public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize
{
MembershipUserCollection muc = new MembershipUserCollection();
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var users = _memberCollection
.Find(new BsonDocument());
var users = collection.Find(new BsonDocument());
var totalRecordsTask = users.CountAsync();
var totalRecordsTask = users
.CountAsync();
totalRecordsTask.Wait();
totalRecords = Convert.ToInt32(totalRecordsTask.Result);
users = users.Skip(pageIndex * pageSize).Limit(pageSize);
users = users
.Skip(pageIndex * pageSize)
.Limit(pageSize);
var pageItemsTask = users.ToListAsync();
pageItemsTask.Wait();
@ -255,7 +255,6 @@ public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize
}
return muc;
}
public override int GetNumberOfUsersOnline()
@ -270,38 +269,36 @@ public override string GetPassword(string username, string answer)
public override MembershipUser GetUser(string username, bool userIsOnline)
{
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var task = _memberCollection
.Find(f => f.UserName.ToLower() == username.ToLower())
.FirstOrDefaultAsync();
task.Wait();
var mmTask = collection.Find(f => f.UserName.ToLower() == username.ToLower()).FirstOrDefaultAsync();
mmTask.Wait();
var mm = mmTask.Result;
var mm = task.Result;
return mm == null ? null : new MembershipUser(this.Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate);
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var task = _memberCollection
.Find(f => f.Id == (Guid)providerUserKey)
.FirstOrDefaultAsync();
task.Wait();
var mmTask = collection.Find(f => f.Id == (Guid)providerUserKey).FirstOrDefaultAsync();
mmTask.Wait();
var mm = mmTask.Result;
var mm = task.Result;
return mm == null ? null : new MembershipUser(this.Name, mm.UserName, mm.Id, mm.EmailAddress, "", "", mm.IsApproved, mm.IsLockedOut, mm.CreationDate, mm.LastLoginDate, mm.LastActivityDate, DateTime.MinValue, mm.LastLockoutDate);
}
public override string GetUserNameByEmail(string email)
{
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var task = _memberCollection
.Find(f => f.EmailAddress.ToLower() == email.ToLower())
.FirstOrDefaultAsync();
task.Wait();
var mmTask = collection.Find(f => f.EmailAddress.ToLower() == email.ToLower()).FirstOrDefaultAsync();
mmTask.Wait();
var mm = mmTask.Result;
return mm.UserName;
return task.Result.UserName;
}
public override string ResetPassword(string username, string answer)
@ -311,19 +308,15 @@ public override string ResetPassword(string username, string answer)
public void ChangeApproval(Guid Id, bool newStatus)
{
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var task = collection.UpdateOneAsync(
Builders<MongoMember>.Filter.Eq(u => u.Id, Id),
Builders<MongoMember>.Update.Set(u => u.IsApproved, newStatus)
);
var task = _memberCollection
.UpdateOneAsync(
Builders<MongoMember>.Filter.Eq(u => u.Id, Id),
Builders<MongoMember>.Update.Set(u => u.IsApproved, newStatus));
task.Wait();
}
public void ChangeLockStatus(Guid Id, bool newStatus)
{
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var updateDefinition = new List<UpdateDefinition<MongoMember>>();
updateDefinition.Add(Builders<MongoMember>.Update.Set(u => u.IsLockedOut, newStatus));
@ -337,21 +330,23 @@ public void ChangeLockStatus(Guid Id, bool newStatus)
updateDefinition.Add(Builders<MongoMember>.Update.Set(u => u.LastLockoutDate, DateTime.MinValue));
}
var task = collection.UpdateOneAsync(
Builders<MongoMember>.Filter.Eq(u => u.Id, Id),
Builders<MongoMember>.Update.Combine(updateDefinition)
);
var task = _memberCollection
.UpdateOneAsync(
Builders<MongoMember>.Filter.Eq(u => u.Id, Id),
Builders<MongoMember>.Update.Combine(updateDefinition));
task.Wait();
}
public override bool UnlockUser(string userName)
{
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var updTask = collection.UpdateOneAsync(Builders<MongoMember>.Filter.Eq(m => m.UserName.ToLower(), userName.ToLower()), Builders<MongoMember>.Update.Set(m => m.IsLockedOut, false));
var task = _memberCollection
.UpdateOneAsync(
Builders<MongoMember>.Filter.Eq(m => m.UserName.ToLower(), userName.ToLower()),
Builders<MongoMember>.Update.Set(m => m.IsLockedOut,
false));
task.Wait();
updTask.Wait();
return updTask.Result.IsAcknowledged && updTask.Result.ModifiedCount == 1;
return task.Result.IsAcknowledged && task.Result.ModifiedCount == 1;
}
public override void UpdateUser(MembershipUser user)
@ -361,13 +356,11 @@ public override void UpdateUser(MembershipUser user)
public override bool ValidateUser(string username, string password)
{
var collection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_CollectionName);
var mmTask = collection.Find(f => f.UserName.ToLower() == username.ToLower()).FirstOrDefaultAsync();
mmTask.Wait();
var mm = mmTask.Result;
var task = _memberCollection
.Find(f => f.UserName.ToLower() == username.ToLower())
.FirstOrDefaultAsync();
task.Wait();
var mm = task.Result;
if (mm == null || !(mm.IsApproved && !mm.IsLockedOut))
{
@ -384,15 +377,46 @@ public override bool ValidateUser(string username, string password)
isFail |= (hash[i] != mm.PassHash[i]);
}
if (isFail)
{
// increment failed counter and lock out if required.
if (mm.LockoutWindowStart == DateTime.MinValue)
{
mm.LockoutWindowStart = DateTime.Now;
mm.LockoutWindowAttempts = 1;
}
else
{
if (mm.LockoutWindowStart.AddMinutes(PasswordAttemptWindow) > DateTime.Now)
{
// still within window
mm.LockoutWindowAttempts++;
if (mm.LockoutWindowAttempts >= MaxInvalidPasswordAttempts)
{
mm.IsLockedOut = true;
}
}
else
{
// outside of window, reset
mm.LockoutWindowStart = DateTime.Now;
mm.LockoutWindowAttempts = 1;
}
}
}
else
{
// reset failed counter
mm.LastLoginDate = DateTime.Now;
mm.LockoutWindowStart = DateTime.MinValue;
mm.LockoutWindowAttempts = 0;
}
var updTask = _memberCollection
.ReplaceOneAsync(
Builders<MongoMember>.Filter.Eq(u => u.Id, mm.Id),
mm);
updTask.Wait();
return !isFail;
}

View File

@ -7,14 +7,17 @@
using System.Linq;
using System.Web.Security;
using System.Collections.Specialized;
using System.Configuration.Provider;
namespace MongoAuth
{
public class MongoRoleProvider : RoleProvider
{
private const string _RoleCollectionName = "roles";
private const string _MemberCollectionName = "members";
private const string _roleCollectionName = "roles";
private const string _memberCollectionName = "members";
private MongoClient _dbClient;
private IMongoCollection<MongoRole> _roleCollection;
private IMongoCollection<MongoMember> _memberCollection;
public override string ApplicationName
{
@ -30,18 +33,22 @@ public override void Initialize(string name, NameValueCollection config)
{
Server = new MongoServerAddress(DatabaseConfig.Host, DatabaseConfig.Port)
});
_roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_roleCollectionName);
_memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_memberCollectionName);
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
var memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_MemberCollectionName);
var roleTask = roleCollection.Find(r => roleNames.Contains(r.RoleName)).ToListAsync();
var roleTask = _roleCollection
.Find(r => roleNames.Contains(r.RoleName))
.ToListAsync();
roleTask.Wait();
List<MongoRole> roles = roleTask.Result;
var userTask = memberCollection.Find(u => usernames.Contains(u.UserName)).ToListAsync();
var userTask = _memberCollection
.Find(u => usernames.Contains(u.UserName))
.ToListAsync();
userTask.Wait();
List<MongoMember> users = userTask.Result;
@ -62,55 +69,59 @@ public override void AddUsersToRoles(string[] usernames, string[] roleNames)
roles[i].Users = newUsers.ToArray();
var update = roleCollection.ReplaceOneAsync(Builders<MongoRole>.Filter.Eq(r => r.Id, roles[i].Id), roles[i]);
var update = _roleCollection
.ReplaceOneAsync(Builders<MongoRole>.Filter.Eq(r => r.Id, roles[i].Id), roles[i]);
update.Wait();
}
}
public override void CreateRole(string roleName)
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
MongoRole r = new MongoRole()
{
Id = Guid.NewGuid(),
RoleName = roleName
};
var task = roleCollection.InsertOneAsync(r);
var task = _roleCollection
.InsertOneAsync(r);
task.Wait();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
var role = roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync();
var role = _roleCollection
.Find(r => r.RoleName == roleName)
.SingleOrDefaultAsync();
role.Wait();
if (role.Result != null && role.Result.Users.Length > 0 && throwOnPopulatedRole)
{
throw new Exception("This role still has users");
throw new ProviderException(Properties.Resources.RoleNotEmpty);
}
roleCollection.DeleteOneAsync(r => r.RoleName == roleName);
var task = _roleCollection
.DeleteOneAsync(r => r.RoleName == roleName);
task.Wait();
return true;
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
var memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_MemberCollectionName);
var role = roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync();
var role = _roleCollection
.Find(r => r.RoleName == roleName)
.SingleOrDefaultAsync();
role.Wait();
if (role == null)
{
throw new Exception("Role does not exist");
return Array.Empty<string>();
}
var users = memberCollection.Find(u => role.Result.Users.Contains(u.Id) && u.UserName.ToLower().Contains(usernameToMatch.ToLower())).ToListAsync();
var users = _memberCollection
.Find(u => role.Result.Users.Contains(u.Id) && u.UserName.ToLower().Contains(usernameToMatch.ToLower()))
.ToListAsync();
users.Wait();
return users.Result
@ -120,9 +131,11 @@ public override string[] FindUsersInRole(string roleName, string usernameToMatch
public override string[] GetAllRoles()
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
var roles = roleCollection.Find(new BsonDocument()).ToListAsync();
var roles = _roleCollection
.Find(new BsonDocument())
.ToListAsync();
roles.Wait();
return roles.Result
.Select(r => r.RoleName)
.ToArray();
@ -130,40 +143,41 @@ public override string[] GetAllRoles()
public override string[] GetRolesForUser(string username)
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
var memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_MemberCollectionName);
var user = memberCollection.Find(u => u.UserName.ToLower() == username.ToLower()).SingleOrDefaultAsync();
var user = _memberCollection
.Find(u => u.UserName.ToLower() == username.ToLower())
.SingleOrDefaultAsync();
user.Wait();
if (user == null)
{
throw new Exception("User does not exist");
return Array.Empty<string>();
}
var role = roleCollection.Find(new BsonDocument()).ToListAsync();
var role = _roleCollection
.Find(r => r.Users != null && r.Users.Contains(user.Result.Id))
.ToListAsync();
role.Wait();
return (from r in role.Result
where r.Users != null
where r.Users.Any(u => u == user.Result.Id)
select r.RoleName).ToArray();
return role.Result
.Select(r => r.RoleName)
.ToArray();
}
public override string[] GetUsersInRole(string roleName)
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
var memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_MemberCollectionName);
var role = roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync();
var role = _roleCollection
.Find(r => r.RoleName == roleName)
.SingleOrDefaultAsync();
role.Wait();
if (role == null)
{
throw new Exception("Role does not exist");
return Array.Empty<string>();
}
var users = memberCollection.Find(u => role.Result.Users.Contains(u.Id)).ToListAsync();
var users = _memberCollection
.Find(u => role.Result.Users.Contains(u.Id))
.ToListAsync();
users.Wait();
return users.Result
@ -173,42 +187,34 @@ public override string[] GetUsersInRole(string roleName)
public override bool IsUserInRole(string username, string roleName)
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
var memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_MemberCollectionName);
var user = memberCollection.Find(u => u.UserName.ToLower() == username.ToLower()).SingleOrDefaultAsync();
var user = _memberCollection
.Find(u => u.UserName.ToLower() == username.ToLower())
.SingleOrDefaultAsync();
var role = _roleCollection
.Find(r => r.RoleName == roleName)
.SingleOrDefaultAsync();
user.Wait();
role.Wait();
if (user.Result == null)
{
throw new Exception("User does not exist");
}
var role = roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync();
if (role.Result == null)
{
throw new Exception("Role does not exist");
}
if (role.Result.Users == null)
if (user.Result == null || role.Result == null || role.Result.Users == null)
{
return false;
}
return role.Result.Users.Any(u => u == user.Result.Id);
return role.Result.Users.Contains(user.Result.Id);
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
var memberCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoMember>(_MemberCollectionName);
var roleTask = roleCollection.Find(r => roleNames.Any(n => n == r.RoleName)).ToListAsync();
var roleTask = _roleCollection
.Find(r => roleNames.Contains(r.RoleName))
.ToListAsync();
roleTask.Wait();
List<MongoRole> roles = roleTask.Result;
var userTask = memberCollection.Find(u => usernames.Any(n => n == u.UserName)).ToListAsync();
var userTask = _memberCollection
.Find(u => usernames.Contains(u.UserName))
.ToListAsync();
userTask.Wait();
List<MongoMember> users = userTask.Result;
@ -218,16 +224,17 @@ public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames
where !users.Any(v => v.Id == u)
select u).ToArray();
var update = roleCollection.ReplaceOneAsync(Builders<MongoRole>.Filter.Eq(r => r.Id, roles[i].Id), roles[i]);
var update = _roleCollection
.ReplaceOneAsync(Builders<MongoRole>.Filter.Eq(r => r.Id, roles[i].Id), roles[i]);
update.Wait();
}
}
public override bool RoleExists(string roleName)
{
var roleCollection = _dbClient.GetDatabase(DatabaseConfig.Database).GetCollection<MongoRole>(_RoleCollectionName);
var role = roleCollection.Find(r => r.RoleName == roleName).SingleOrDefaultAsync();
var role = _roleCollection
.Find(r => r.RoleName == roleName)
.SingleOrDefaultAsync();
role.Wait();
return role.Result != null;

View File

@ -5,12 +5,12 @@
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MongoAuth")]
[assembly: AssemblyTitle("Mongo Authentication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MongoAuth")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyProduct("BuildFeed")]
[assembly: AssemblyCopyright("Copyright © 2015, Thomas Hounsell")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

View File

@ -0,0 +1,72 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MongoAuth.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MongoAuth.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to There are still users within this role..
/// </summary>
public static string RoleNotEmpty {
get {
return ResourceManager.GetString("RoleNotEmpty", resourceCulture);
}
}
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="RoleNotEmpty" xml:space="preserve">
<value>There are still users within this role.</value>
</data>
</root>

View File

@ -3,4 +3,4 @@
BuildFeed is a website for tracking Windows build numbers. The website itself is hosted at [https://buildfeed.net/](https://buildfeed.net/).
It is built using ASP.NET MVC, with a persistent Redis instance used for storing data.
It is built using ASP.NET MVC, with a MongoDB database used for storing data.

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedisMongoMigration
{
class Program
{
static void Main(string[] args)
{
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RedisMongoMigration")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RedisMongoMigration")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cd3c08cc-45bf-484b-a878-69614a4ea098")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,132 @@
using NServiceKit.DataAnnotations;
using NServiceKit.DesignPatterns.Model;
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace RedisMongoMigration.Redis
{
[DataObject]
public class Build : IHasId<long>
{
[Key]
[AutoIncrement]
[Index]
public long Id { get; set; }
public byte MajorVersion { get; set; }
public byte MinorVersion { get; set; }
public ushort Number { get; set; }
public ushort? Revision { get; set; }
public string Lab { get; set; }
public DateTime? BuildTime { get; set; }
public DateTime Added { get; set; }
public DateTime Modified { get; set; }
public TypeOfSource SourceType { get; set; }
public string SourceDetails { get; set; }
public DateTime? LeakDate { get; set; }
public LevelOfFlight FlightLevel { get; set; }
public bool IsLeaked
{
get
{
switch (SourceType)
{
case TypeOfSource.PublicRelease:
case TypeOfSource.InternalLeak:
case TypeOfSource.UpdateGDR:
return true;
default:
return false;
}
}
}
public string FullBuildString
{
get
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}.{1}.{2}", MajorVersion, MinorVersion, Number);
if (Revision.HasValue)
{
sb.AppendFormat(".{0}", Revision);
}
if (!string.IsNullOrWhiteSpace(Lab))
{
sb.AppendFormat(".{0}", Lab);
}
if (BuildTime.HasValue)
{
sb.AppendFormat(".{0:yyMMdd-HHmm}", BuildTime);
}
return sb.ToString();
}
}
}
public enum TypeOfSource
{
PublicRelease,
InternalLeak,
UpdateGDR,
UpdateLDR,
AppPackage,
BuildTools,
Documentation,
Logging,
PrivateLeak
}
public enum LevelOfFlight
{
None = 0,
Low = 1,
Medium = 2,
High = 3
}
public struct BuildVersion
{
public byte Major { get; set; }
public byte Minor { get; set; }
public override string ToString()
{
return $"{Major}.{Minor}";
}
}
public struct BuildGroup
{
public byte Major { get; set; }
public byte Minor { get; set; }
public ushort Build { get; set; }
public ushort? Revision { get; set; }
public override string ToString()
{
return Revision.HasValue ?
$"{Major}.{Minor}.{Build}.{Revision.Value}" :
$"{Major}.{Minor}.{Build}";
}
}
}

View File

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{CD3C08CC-45BF-484B-A878-69614A4EA098}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>RedisMongoMigration</RootNamespace>
<AssemblyName>RedisMongoMigration</AssemblyName>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="NServiceKit.Common, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NServiceKit.Common.1.0.31\lib\net35\NServiceKit.Common.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NServiceKit.Interfaces, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NServiceKit.Common.1.0.31\lib\net35\NServiceKit.Interfaces.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NServiceKit.Redis, Version=1.0.16.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NServiceKit.Redis.1.0.16\lib\net35\NServiceKit.Redis.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NServiceKit.Text, Version=1.0.10.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NServiceKit.Text.1.0.10\lib\net35\NServiceKit.Text.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Redis\Build.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NServiceKit.Common" version="1.0.31" targetFramework="net46" />
<package id="NServiceKit.Redis" version="1.0.16" targetFramework="net46" />
<package id="NServiceKit.Text" version="1.0.10" targetFramework="net46" />
</packages>