I'm have the following URL :
www.example.com?arg1=foobar
I want to get the arg1 value.
I tried to use the following code:
var bm:IBrowserManager;
bm= bm.getInstance();
browserManager.init();
var o:Object = URLUtil.stringToObject(bm.fragment, "&");
Alert.show(o.arg1);
It works with the following URL:
www.example.com#arg1=foobar
So it requires the # instead of the ? .
How can get the parameter "arg1" from Flex (nicely) from URLs such as :
www.example.com?arg1=foobar
Thanks ;)
I answered a similar question a while ago.
I use the class Adobe provided in this article. An updated version of this class can also be found here, although I haven't tried this one.
package
{
import flash.external.*;
import flash.utils.*;
public class QueryString
{
private var _queryString:String;
private var _all:String;
private var _params:Object;
public function get queryString():String
{
return _queryString;
}
public function get url():String
{
return _all;
}
public function get parameters():Object
{
return _params;
}
public function QueryString()
{
readQueryString();
}
private function readQueryString():void
{
_params = {};
try
{
_all =
ExternalInterface.call("window.location.href.toString");
_queryString =
ExternalInterface.call("window.location.search.substring", 1);
if(_queryString)
{
var params:Array = _queryString.split('&');
var length:uint = params.length;
for (var i:uint=0,index:int=-1; i 0)
{
var key:String = kvPair.substring(0,index);
var value:String = kvPair.substring(index+1);
_params[key] = value;
}
}
}
}catch(e:Error) { trace("Some error occured.
ExternalInterface doesn't work in Standalone player."); }
}
}
}
Here's an example on how to use the Querystring class:
public function CheckForIDInQuerystring():void
{
// sample URL: http://www.mysite.com/index.aspx?id=12345
var qs:QueryString = new QueryString;
if (qs.parameters.id != null)
{
// URL contains the "id" parameter
trace(qs.parameters.id);
}
else
{
// URL doesn't contain the "id" parameter
trace("No id found.");
}
}
Related
Can someone explain to me how to create an instance of this component in a Moq TestMethod? Here is the definition of the class. I need to test the ProcessAutomaticFillRequest method.
public class AutomaticDispenserComponent : IAutomaticDispenserComponent
{
private readonly Lazy<IMessageQueueComponent> _messageQueueComponent;
protected IMessageQueueComponent MessageQueueComponent { get { return _messageQueueComponent.Value; } }
public AutomaticDispenserComponent(Func<IMessageQueueComponent> messageQueueComponentFactory)
{
_messageQueueComponent = new Lazy<IMessageQueueComponent>(messageQueueComponentFactory);
}
public void ProcessAutomaticFillRequest(FillRequestParamDataContract fillRequestParam)
{
if (fillRequestParam.PrescriptionServiceUniqueId == Guid.Empty)
throw new InvalidOperationException("No prescription service was specified for processing fill request.");
if (fillRequestParam.Dispenser == null)
throw new InvalidOperationException("No dispenser was specified for processing fill request.");
var userContext = GlobalContext.CurrentUserContext;
var channel = string.Format(Channel.FillRequest, userContext.TenantId,
userContext.PharmacyUid, fillRequestParam.Dispenser.DeviceAgentUniqueId);
NotificationServer.Publish(channel, fillRequestParam);
}
Here is how I started my test, but I don't know how to create an instance of the component:
[TestMethod]
[ExpectedException(typeof (InvalidOperationException))]
public void FillRequestFailsWhenPrescriptionServiceUniqueIdIsEmpty()
{
// How do I create an instance of automatiqueDispenserComponent here
// since there is Func as constructor parameter?
var fillRequestParam = new FillRequestParamDataContract
{
PrescriptionServiceUniqueId = Guid.Empty
};
_automaticDispensercomponent.ProcessAutomaticFillRequest(fillRequestParam);
// ...
}
Updated the answer based on the comments below. You need to mock the Func parameter for the test.
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void FillRequestFailsWhenPrescriptionServiceUniqueIdIsEmpty()
{
var mockMsgQueueComponent = new Mock<Func<IMessageQueueComponent>>();
var _automaticDispensercomponent = new AutomaticDispenserComponent
(mockMsgQueueComponent.Object);
var fillRequestParam = new FillRequestParamDataContract
{
PrescriptionServiceUniqueId = Guid.Empty
};
_automaticDispensercomponent.ProcessAutomaticFillRequest(fillRequestParam);
}
Before I had this code to return an arbitrary json object with just an id property.
How do I convert this to the new RC version of WebApi now that HttpResponseMessage is not supported and it now uses Newtonsofts JSON.NET?
public HttpResponseMessage<JsonValue> Post(MyModel model)
{
var id = _theService.AddEntity(model);
dynamic okResponse = new JsonObject();
okResponse["id"] = id;
return new CreateResponse<JsonValue>(okResponse);
}
And...
public class CreateResponse<T> : ResponseBase<T>
{
public CreateResponse()
: base(HttpStatusCode.Created)
{
}
public CreateResponse(T resource)
: base(resource, HttpStatusCode.Created)
{
}
}
public abstract class ResponseBase<T> : HttpResponseMessage<T>
{
protected ResponseBase(HttpStatusCode httpStatusCode)
: base(httpStatusCode)
{
}
protected ResponseBase(T resource, HttpStatusCode httpStatusCode)
: base(resource, httpStatusCode)
{
if (resource is IApiResource)
{
var apiResource = resource as IApiResource;
var resourceLocation = new ResourceLocation();
apiResource.SetLocation(resourceLocation);
Headers.Location = resourceLocation.Location;
}
}
}
The CreateResponse extention method does not accept dynamic variables.
Please change
dynamic okResponse = new JsonObject();
to something like
var okResponse = new JsonObject();
Please see this link also:
https://aspnetwebstack.codeplex.com/discussions/359242
Use Request.CreateResponse(statuscode, content) inside your controller
Maybe I'm missing something in your question, but you could just do this:
public dynamic Post(MyModel model)
{
var id = _theService.AddEntity(model);
return new { id = id };
}
EDIT: assuming your client sets the Content-type to application/json
If I have an application located at http://sitename.com/myapp/ and i want to pass in a variable via the url (i.e. - http://sitename.com/myapp/?name=Joe), how can I get that name variable into a string var?
I use the class Adobe provided in this article.
package
{
import flash.external.*;
import flash.utils.*;
public class QueryString
{
private var _queryString:String;
private var _all:String;
private var _params:Object;
public function get queryString():String
{
return _queryString;
}
public function get url():String
{
return _all;
}
public function get parameters():Object
{
return _params;
}
public function QueryString()
{
readQueryString();
}
private function readQueryString():void
{
_params = {};
try
{
_all =
ExternalInterface.call("window.location.href.toString");
_queryString =
ExternalInterface.call("window.location.search.substring", 1);
if(_queryString)
{
var params:Array = _queryString.split('&');
var length:uint = params.length;
for (var i:uint=0,index:int=-1; i 0)
{
var key:String = kvPair.substring(0,index);
var value:String = kvPair.substring(index+1);
_params[key] = value;
}
}
}
}catch(e:Error) { trace("Some error occured.
ExternalInterface doesn't work in Standalone player."); }
}
}
}
UPDATE: An updated version of this class can also be found here, although I haven't tried this one.
UPDATE 2:
Here's an example on how to use the Querystring class:
public function CheckForIDInQuerystring():void
{
// sample URL: http://www.mysite.com/index.aspx?id=12345
var qs:QueryString = new QueryString;
if (qs.parameters.id != null)
{
// URL contains the "id" parameter
trace(qs.parameters.id);
}
else
{
// URL doesn't contain the "id" parameter
trace("No id found.");
}
}
Divide 'em with String.split() and conquer:
var url:String = "http://www.xxx.zzz/myapp?arg1=vae&arg2=victus";
var params:String = url.substr(url.lastIndexOf("?") + 1);
if (params.length == url.length) return; //no params
for each (var pair:String in params.split("&"))
{
trace("Got parameter:");
var nameValue:Array = pair.split("=");
trace("name: " + nameValue[0] + ", value: " + nameValue[1]);
}
Output:
Got parameter:
name: arg1, value: vae
Got parameter:
name: arg2, value: victus
I've a tree control with checkboxes that uses the control from http://www.sephiroth.it/file_detail.php?id=151#
Somehow I can't get the control to update when I change the dataProvider (i.e. by clicking a checkbox) the only way I can get it to update is to use the scrollbar. How do I force the update? I've tried all possible methods I can figure out? (see update below)
Also how can I reset the Tree (collpasing all nodes, scroll to the top in a large tree)?
package offerta.monkeywrench.components
{
import offerta.monkeywrench.components.componentClasses.TreeCheckBoxItemRenderer;
import mx.collections.ArrayCollection;
import mx.events.TreeEvent;
public class WatchTree extends TreeCheckBox
{
public var idProperty:String;
public var watchFactory:Function;
private var _wSet:Boolean = false;
/* clientId: */
private var _clientId:String;
[Bindable]
public function get clientId():String
{
return _clientId;
}
public function set clientId(value:String):void
{
this._clientId = value;
}
/* //clientId */
/* watching: */
private var _watching:ArrayCollection;
[Bindable]
public function set watching(value:ArrayCollection):void
{
this._watching = value;
}
public function get watching():ArrayCollection
{
return this._watching;
}
/* //watching */
override public function initialize() :void
{
super.initialize();
addEventListener("itemCheck", onItemCheck, false, 0, true);
}
private function isWatching(id:String):Boolean
{
for each(var w:Object in this._watching)
{
if(w[this.idProperty]==id) return true;
}
return false;
}
private function onItemCheck(event:TreeEvent):void
{
var item:Object = event.item as Object;
var currentValue:uint = (event.itemRenderer as TreeCheckBoxItemRenderer).checkBox.checkState;
if(item.children==null)
{
currentValue==2 ? addWatch(item.Id) : removeWatch(item.Id);
}
else
{
for each(var x:Object in item.children)
{
currentValue==2 ? addWatch(x.Id) : removeWatch(x.Id);
}
}
updateParents(item, currentValue);
updateChilds(item, currentValue);
this.dataProvider.refresh();
super.invalidateProperties();
super.invalidateDisplayList();
super.updateDisplayList(this.unscaledWidth, this.unscaledHeight);
}
private function updateParents(item:Object, value:uint):void
{
var checkValue:String = (value == ( 1 << 1 | 2 << 1 ) ? "2" : value == ( 1 << 1 ) ? "1" : "0");
var parentNode:Object = item.parent;
if(parentNode)
{
for each(var x:Object in parentNode.children)
{
if(x.checked != checkValue)
{
checkValue = "2"
}
}
parentNode.checked = checkValue;
updateParents(parentNode, value);
}
}
private function updateChilds(item:Object, value:uint):void
{
var middle:Boolean = (value&2<<1)==(2<<1);
if(item.children!=null && item.children.length>0&&!middle)
{
for each(var x:Object in item.children)
{
x.checked = value == (1<<1|2<<1) ? "2" : value==(1<<1) ? "1" : "0";
updateChilds(x, value);
}
}
}
private function addWatch(id:String):void
{
if(isWatching(id)) return;
this._watching.addItem(this.watchFactory(id, this.clientId));
}
private function removeWatch(id:String):void
{
for(var i:int=0, n:int=this._watching.length; i<n; ++i)
{
if(this._watching[i][this.idProperty]==id)
{
this._watching.removeItemAt(i);
return;
}
}
}
public function update(__watching:ArrayCollection, __clientId:String):void
{
clientId = __clientId;
watching = __watching;
if(this.dataProvider!=null)
{
var ws:ArrayCollection = ArrayCollection(this.dataProvider);
for each(var group:Object in ws)
{
var count:int = 0;
for each(var child:Object in group.children)
{
if(isWatching(child.Id))
{
child.checked = "1";
count++;
}
}
group.checked = (count==0 ? "0" : (count==group.children.length ? "1" : "2"));
}
this._wSet = false;
var dp:ArrayCollection = ArrayCollection(this.dataProvider);
dp.refresh();
super.invalidateProperties();
super.invalidateDisplayList();
super.updateDisplayList(this.unscaledWidth, this.unscaledHeight);
//scroll up the list???
//collapse? (doesn't work)
this.expandItem(null, false);
}
}
}
}
I've found the Tree control a little touchy in Flex. The way I ended up forcing a redraw was to disconnect the dataProvider and reconnect it, then force validation, something a bit like this :
private function forceRedraw(tree:Tree, dataProvider:Object):void
{
var scrollPosition:Number = tree.verticalScrollPosition;
var openItems:Object = tree.openItems;
tree.dataProvider = dataProvider;
tree.openItems = openItems;
tree.validateNow();
tree.verticalScrollPosition = scrollPosition;
}
I guess this incidentally answers the second part of your question since all you'd have to do is null out the openItems collection and set the verticalScrollPosition to 0.
You might have another problem: whenever you check an item the tree scrolls to the top and this is just annoying. To solve this problem you should update the TreeCheckBox.as file this way:
in function checkHandler:
private function checkHandler( event: TreeEvent ): void;
comment the commitProperties(); call.
Now it should work well.
Cheers.
I've had some minor problem with this solution, var scrollPosition:Number = tree.verticalScrollPosition; is constantly 0??
I want to use a validator to ensure 2 password fields match in Flex. I want the validator to highlight form fields like a normal flex validation control. Thanks.
enter code hereI created my own custom validator (mostly copied from date validator):
package validators
{
import mx.validators.ValidationResult;
import mx.validators.Validator;
public class PasswordValidator extends Validator
{
// Define Array for the return value of doValidation().
private var results:Array;
public function PasswordValidator()
{
super();
}
public var confirmationSource: Object;
public var confirmationProperty: String;
// Define the doValidation() method.
override protected function doValidation(value:Object):Array {
// Call base class doValidation().
var results:Array = super.doValidation(value.password);
if (value.password != value.confirmation) {
results.push(new ValidationResult(true, null, "Mismatch",
"Password Dosen't match Retype!"));
}
return results;
}
/**
* #private
* Grabs the data for the confirmation password from its different sources
* if its there and bundles it to be processed by the doValidation routine.
*/
override protected function getValueFromSource():Object
{
var value:Object = {};
value.password = super.getValueFromSource();
if (confirmationSource && confirmationProperty)
{
value.confirmation = confirmationSource[confirmationProperty];
}
return value;
}
}
}
the example mxml for using:
<validators:PasswordValidator id="pwvPasswords" required="true" source="{txtPassword}" property="text" confirmationSource="{txtPasswordConfirm}" confirmationProperty="text" trigger="{btnStep2Finish}" />
It's pretty basic, but it's mostly what I need. It only highlights the password box though, would like to get it to highlight both.
Here's a better custom validator that's more universal, clean, and works well with the 'required' field.
import mx.validators.ValidationResult;
import mx.validators.Validator;
public class MatchValidator extends Validator{
private var _matchSource: Object = null;
private var _matchProperty: String = null;
private var _noMatchError: String = "Fields did not match";
[Inspectable(category="General", defaultValue="Fields did not match")]
public function set noMatchError( argError:String):void{
_noMatchError = argError;
}
public function get noMatchError():String{
return _noMatchError;
}
[Inspectable(category="General", defaultValue="null")]
public function set matchSource( argObject:Object):void{
_matchSource = argObject;
}
public function get matchSource():Object{
return _matchSource;
}
[Inspectable(category="General", defaultValue="null")]
public function set matchProperty( argProperty:String):void{
_matchProperty = argProperty;
}
public function get matchProperty():String{
return _matchProperty;
}
override protected function doValidation(value:Object):Array {
// Call base class doValidation().
var results:Array = super.doValidation(value.ours);
var val:String = value.ours ? String(value.ours) : "";
if (results.length > 0 || ((val.length == 0) && !required)){
return results;
}else{
if(val != value.toMatch){
results.length = 0;
results.push( new ValidationResult(true,null,"mismatch",_noMatchError));
return results;
}else{
return results;
}
}
}
override protected function getValueFromSource():Object {
var value:Object = {};
value.ours = super.getValueFromSource();
if (_matchSource && _matchProperty){
value.toMatch = _matchSource[_matchProperty];
}else{
value.toMatch = null;
}
return value;
}
}
Here's an example:
<components:MatchValidator source="{passwordCheckField}" property="text" matchSource="{passwordField}" matchProperty="text"
valid="passwordsMatch = true" invalid="passwordsMatch = false" noMatchError="Passwords do not match"/>
I've done this in a different way using custom validation rules.
Check it out:
http://martypitt.wordpress.com/2009/08/26/rule-based-asynchronous-validation-in-flex-forms/
It shows how to do async validation (eg., checking a username is available on the server), and other validation scenario's that don't fit neatly into flex's out-of-the-box framework, including two passwords match.
Eg:
<mx:Button label="Register" enabled="{ validationRules.isValid }" />
<validation:ValidationRuleCollection id="validationRules">
<validation:UsernameIsUniqueValidationRule username="{ txtUsername.text }" targetComponent="{ txtUsername }" />
<validation:EmailIsUniqueValidationRule email="{ txtEmailAddress.text }" targetComponent="{ txtEmailAddress }" />
<validation:PasswordsMustMatchValidationRule password1="{ txtPassword.text }" password2="{ txtPasswordConfirm.text }" targetComponent="{ txtPasswordConfirm }" />
<mx:StringValidator required="true" source="{ txtUsername }" property="text" requiredFieldError="{ ResourceManager.getInstance().getString( ResourceBundles.ERROR_MESSAGES , 'REQUIRED_FIELD_ERROR' )}" />
</validation:ValidationRuleCollection>
I expanded on Daniel's solution, adding the ability to trigger off of the matched source as well.
import flash.events.Event;
import mx.validators.ValidationResult;
import mx.validators.Validator;
public class MatchValidator extends Validator
{
private var _matchSource: Object = null;
private var _matchProperty: String = null;
private var _noMatchError: String = "Fields did not match";
[Inspectable(category="General", defaultValue="Fields did not match")]
public function set noMatchError( argError:String):void{
_noMatchError = argError;
}
public function get noMatchError():String{
return _noMatchError;
}
[Inspectable(category="General", defaultValue="null")]
public function set matchSource( argObject:Object):void{
removeTriggerHandler();
_matchSource = argObject;
addTriggerHandler();
}
public function get matchSource():Object{
return _matchSource;
}
[Inspectable(category="General", defaultValue="null")]
public function set matchProperty( argProperty:String):void{
_matchProperty = argProperty;
}
public function get matchProperty():String{
return _matchProperty;
}
override protected function doValidation(value:Object):Array {
// Call base class doValidation().
var results:Array = super.doValidation(value.ours);
var val:String = value.ours ? String(value.ours) : "";
if (results.length > 0 || ((val.length == 0) && !required)){
return results;
}else{
if(val != value.toMatch){
results.length = 0;
results.push( new ValidationResult(true,null,"mismatch",_noMatchError));
return results;
}else{
return results;
}
}
}
override protected function getValueFromSource():Object {
var value:Object = {};
value.ours = super.getValueFromSource();
if (_matchSource && _matchProperty){
value.toMatch = _matchSource[_matchProperty];
}else{
value.toMatch = null;
}
return value;
}
override public function set triggerEvent(value:String):void
{
removeTriggerHandler();
super.triggerEvent = value;
addTriggerHandler();
}
private function addTriggerHandler():void
{
if (_matchSource)
_matchSource.addEventListener(triggerEvent,triggerHandler);
}
private function removeTriggerHandler():void
{
if (_matchSource)
_matchSource.removeEventListener(triggerEvent,triggerHandler);
}
private function triggerHandler(event:Event):void
{
validate();
}
}
Unless you have to use a validator, you can simply attach a change event handler and set errorString property of the password field when the passwords don't match. It gives the same highlighting as done by validator.