Unable to set RequestHeaders in HTTPServiceWrapper (actionscript 3) - actionscript

I created an HTTPService using the Data Centric Development feature in Flash Builder 4. For some reason, I'm not able to set the requestheaders for an HTTP GET request. I've tried setting the headers object for the mx.rpc.http.Operation; but, it doesn't seem to work. Packet sniffers show that the requestheader isn't changed.
For example here's part of the gettour service:
public class GetTourService extends _Super_GetTourService
{
/**
* Override super.init() to provide any initialization customization if needed.
*/
protected override function preInitializeService():void
{
super.preInitializeService();
// Initialization customization goes here
var header:URLRequestHeader = new URLRequestHeader( "Accept", "application/json");
var headers:Array = new Array();
headers.push(header);
var o:Object = this._serviceControl.getOperation( "gettour");
var operation:Operation = o as Operation;
operation.headers = headers;
}
}
However, packet sniffers show the Accept header to be "Accept: /\r\n". In AIR I get a similar problem with the long list of default Accept values and can't set the Accept value to "application/json". What am I missing?
Any help is much appreciated. Thanks!
EDITED: I found the answer this morning. Instead of
headers.push( header);
I used
headers[ "Accept"] = "/application/json";
This worked.

Since the documentation for this is a bit vague I'm going to take a guess. According to the docs, headers is an Object of custom headers, so passing it an indexed array is probably not going to work. Try passing a defined Object instead:
operation.headers = {Accept:"application/json"};

Related

Add Authorize Attribute Filter in Swashbuckler Implementation of Swagger

Looking to add the AuthorizeFilterAttribute or AnonymousFilterAttribute to an endpoint in Swashbuckle's implementation of Swagger so I can see which attribute is used on each endpoint in the generated documentation file in a running webapi that ends in /swagger. Is this currenlty possible?
I specifically would like to add a big bold label that says this endpoint is [Anonymous] or that endpoint is using [Authorize] and have them look differently that the summary or remark text.
Also I would like to be able to filter out all the different types of these restriction filter attributes for each endpoint including [NonAction], [Authorize], and [Anonymous] where one of these might be at the top of each controller endpoint. Maybe even eventually add other types of FilterAttributes besides these on each endpoint.
Currently it looks like only the HTTP Methods, the request and response objects can be retrieved in the current implementation so I was not able to find definitive information on this.
Since this is a Swagger implementation do these .NET specific attribute filters not translate to Swashbuckle b/c they only implement what's in the Swagger specification and nothing else?
Finally are their .NET specific extensions to Swashbuckle's implementation that do this?
Thanks!
For the part adding the label to unprotected methods/actions you could use an operation filter like this
public class UnprotectedOperationFilter : IOperationFilter
{
private bool HasAttribute(MethodInfo methodInfo, Type type, bool inherit)
{
// inhertit = true also checks inherited attributes
var actionAttributes = methodInfo.GetCustomAttributes(inherit);
var controllerAttributes = methodInfo.DeclaringType.GetTypeInfo().GetCustomAttributes(inherit);
var actionAndControllerAttributes = actionAttributes.Union(controllerAttributes);
return actionAndControllerAttributes.Any(attr => attr.GetType() == type);
}
public void Apply(Operation operation, OperationFilterContext context)
{
bool hasAuthorizeAttribute = HasAttribute(context.MethodInfo, typeof(AuthorizeAttribute), true);
bool hasAnonymousAttribute = HasAttribute(context.MethodInfo, typeof(AllowAnonymousAttribute), true);
// so far as I understood the action/operation is public/unprotected
// if there is no authorize or an allow anonymous (allow anonymous overrides all authorize)
bool isAuthorized = hasAuthorizeAttribute && !hasAnonymousAttribute;
if (!isAuthorized)
{
operation.Description =
"<p><bold>BIG BOLD LABEL indicating an UPROTECTED PUBLIC method</bold></p>"
+ operation.Description;
}
}
}
and add it with
services.AddSwaggerGen(c => { c.OperationFilter<UnprotectedOperationFilter>();} );
I didn't understand what you mean with filter out different attributes but I hope the code above helps you to check if the attribute is present and do what you desire to do.

Auto Mapping errors to individual properties

If I have an auto mapper such as TinyMapper or ExpressMapper configured to map DTOs to Models, and my DTO has notified me that, for example 'myDto.Email' has failed to update, is there a way to map that property back to the model (specifically in my case for ModelState.AddModelError purposes).
Here's a little pseudo code to hopefully clarify my need:
var mapper = SomeMapper.Register<MyModel, MyDto>();
var myDto = mapper.Map(myModel)
var errors = myDto.Update()
if(errors.Any())
{
var error = errors.First();
var property = memberConfiguration.GetMeTheModelPropertyFor(dto => dto.PropertyName= error.Property)
ModelState.AddModelError(property.Name, error.Message);
}
So basically I'm asking which mapper can I achieve something like GetMeTheModelPropertyFor above and how?

Dart Date String Formatting [duplicate]

Is there a function to do urlencoding in Dart? I am doing a AJAX call using XMLHttpRequest object and I need the url to be url encoded.
I did a search on dartlang.org, but it didn't turn up any results.
var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeFull(uri);
assert(encoded == 'http://example.org/api?foo=some%20message');
var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);
http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-uri
Update: There is now support for encode/decode URI in the Dart Uri class
Dart's URI code is placed in a separate library called dart:uri (so it can be shared between both dart:html and dart:io). It looks like it currently does not include a urlencode function so your best alternative, for now, is probably to use this Dart implementation of JavaScript's encodeUriComponent.
Uri.encodeComponent(url); // To encode url
Uri.decodeComponent(encodedUrl); // To decode url
I wrote this small function to convert a Map into a URL encoded string, which may be what you're looking for.
String encodeMap(Map data) {
return data.keys.map((key) => "${Uri.encodeComponent(key)}=${Uri.encodeComponent(data[key])}").join("&");
}
I dont' think there is yet. Check out http://unpythonic.blogspot.com/2011/11/oauth20-and-jsonp-with-dartin-web.html and the encodeComponent method.
Note, it's lacking some characters too, it needs to be expanded. Dart really should have this built in and easy to get to. It may have it in fact, but I didn't find it.
Safe Url Encoding in flutter
Ex.
String url = 'http://example.org/';
String postDataKey = "requestParam="
String postData = 'hdfhghdf+fdfbjdfjjndf'
In Case of get request :
Uri.encodeComponent(url+postDataKey+postData);
In Case of Post Data Request use flutter_inappwebview library
var data = postDataKey + Uri.encodeComponent(postData);
webViewController.postUrl(url: Uri.parse(url), postData: utf8.encode(data));
Uri.encodeComponent() is correct, Uri.encodeFull() has a bug, see below example:
void main() {
print('$text\n');
var coded = Uri.encodeFull(text);
print(coded);
print('\n');
coded = Uri.encodeComponent(text);
print(coded);
}
var text = '#2020-02-29T142022Z_1523651918_RC2EAF9OOHDB_RT.jpg';

Working with parsed model in Xtend validator

I want to know how I can access the parsed model of my program. I have a validation check written in xtend which accepts a rule A as it parameter. however I want to search the entire parsed tree and make sure that any other reference to this specific instance of A follows certain specifications.
#Check
def checkActionBelongsToAssociatedRole(ActionDsc act){
var pRole = act.parentRole
var rs = new ResourceSetImpl()
//DONT KNOW IF THIS IS RIGHT
var resource = rs.getResource(URI.createURI("./model/generated/Protocol.ecore"), true)
for(r:resource.allContents.toIterable.filter(typeof(RoleDec))){
if(r.name == pRole.name){
//DO SOMETHING
}
}
}
In the generator file that I have I already get the Resource object as a parameter.
override void doGenerate(Resource resource, IFileSystemAccess fsa) {
//Generate code
}
How can I do the same thing for my validator. Thank you in advance!
act.eResource() allows to access the resource that contains the action.

Monotouch - EASession output stream gives null error

Looking for some help over here.
When i run this code (below), it crashes when i process it for the second time.
it crashes with an object reference not set.. on the session.outputstream
var session= new EASession(accessory, "net.gebe");
session.OutputStream.Open();
the second time session.outputstream is null. Even when disposing session.
Richard
public void PrintIt()
{
var _accessoryList = EAAccessoryManager.SharedAccessoryManager.ConnectedAccessories;
accessory = null;
foreach(var obj in _accessoryList)
{
if(obj.ProtocolStrings.Contains("net.gebe"))
{
accessory = obj;
//break;
}
}
if(accessory == null)
{
//tmg.InfoAlert ("No Printer");
return;
}
var session= new EASession(accessory, "net.gebe");
session.OutputStream.Open();
string str2 = "HELLO THERE PRINTER 1 2 3 4 5";
byte[] printdata2;
ASCIIEncoding encoding2 = new ASCIIEncoding();
printdata2 = encoding2.GetBytes(str2);
uint nlen2 = Convert.ToUInt32 (str2.Length+1);
session.OutputStream.Write(printdata2,nlen2 );
session.OutputStream.Close ();
session.Dispose ();
}
I got mine working now. What I did:
Save the session as a variable in the class
Only create the session if session is null
You may not want to call session.OutputStream.Close() after every print. At least it's something to keep in mind while debugging for your situation.
This will allow for multiple print jobs on the same page without blowing up. session.OutputStream was not null in this case.
I also found that the ViewDidLoad/Unload events weren't great for detecting when the device becomes available/unavailable via the EAAccessoryDidConnectNotification and EAAccessory DidDisconnectNotification observers. Instead I used ViewDidAppear/ViewDidDisappear. In those methods, I tear down the session, and when I come back in to print a new job, the session gets created and OutputStream is assigned.
Lastly, I wasn't getting events fired for my device via session.OutputStream.OnEvent. Not sure if it's my device, a MonoTouch bug, or just a generic bug of mine yet.
UPDATE: Check out this nicely wrapped implementation of AccessoryAdapter
You need to list the external accessories you're going to use in your Info.plist.
There is some documentation on this on apple's site:
http://developer.apple.com/library/ios/#featuredarticles/ExternalAccessoryPT/Introduction/Introduction.html#//apple_ref/doc/uid/TP40009502
Here is a screenshot of how to set this value in Info.plist:
http://screencast.com/t/AYmOWjf8wkL
(This is from here: https://bugzilla.xamarin.com/show_bug.cgi?id=1635#c1)

Resources