Razor/WebPages: Using AppState and RequestString in classes - asp.net

I have a regular class I've added to a Razor WebPages to handle some extra database work. To use the data classes, I added Imports WebMatrix.Data to the class and all works fine.
I need to access Request.QueryString and the Session and AppState dictionaries in another class. I don't fancy passing in these objects. I've looked around but can't find what classes to import.
Any ideas?

You can always grab it from session, which should still be available even in Razor by doing
var ctx = System.Web.HttpContext.Current;
var qvar = ctx.Request.QueryString.Get("ABC");
var svar = ctx.Session["XYZ"];

Related

CamelCase property names with NJsonSchema C# CodeGeneration

does anybody know a way to configure NJsonSchema to use CamelCase property naming durching code generation? I've a JSON schema with property names like message_id which lead to C# property name 'Message_id' where i.e. 'MessageId' whould be a more C#-like way.
With an attribute like '[JsonProperty("message_id"]' it would be no problem to specified the connection between the different names.
So, you asked about code generation. I was having trouble with the schema it generated not matching what was getting sent to my Angular app. So, while this isn't exactly what you were looking for, perhaps it helps you find an answer (maybe?).
To generate the schema with the camel case property names, I'm setting the Default Property Name Handling to CamelCase, but this is using the deprecated call to set these settings directly. There should be some way to use the SerializerSettings directly, but I wasn't quite able to make that work. This isn't production code for me, so it will do.
internal class SchemaFileBuilder<T>
{
public static void CreateSchemaFile()
{
CreateSchemaFile(typeof(T).Name);
}
public static void CreateSchemaFile(string fileName)
{
JsonSchemaGeneratorSettings settings = new JsonSchemaGeneratorSettings();
settings.DefaultPropertyNameHandling = PropertyNameHandling.CamelCase;
var schema = NJsonSchema.JsonSchema.FromType<T>(settings);
var json = schema.ToJson();
Directory.CreateDirectory("Schemas");
File.WriteAllText($"Schemas\\{fileName}.schema.json", json);
}
}
I set this up as a generic function so I could pass multiple schemas in to either createSchemaFile functions. Here's are some example calls which would generate a Person.schema.json file and a Persons.schema.json file:
SchemaFileBuilder<Person>.CreateSchemaFile();
SchemaFileBuilder<Dictionary<string, Person>>.CreateSchemaFile("Persons");

using export in alloy controller versus attaching functions directly to the '$' scope

here is the code of an alloy controller written in two different ways. Although the both work the same, Which one might be best practice?
example 1 of controller.js:
var currentState = true;
$.getState = function(){
return currentState;
}
example 2 of controller.js:
var currentState = true;
exports.getState = function(){
return currentState;
}
Titanium is based on the CommonJS framework. The exports variable is a special variable used typically to expose a public API in a class object. So when you want to expose a method of doSomething() on the MyModule.js class you would use the exports variable like this:
exports.doSomething() = function(args) {
//Some really cool method here
};
Then reference that class using
var myModule = require('MyModule');
myModule.doSomething();
However when referencing a view object the typical way to reference the is using the $. shortcut. You can see they prefer that method in the official documentation.
http://docs.appcelerator.com/platform/latest/#!/guide/Alloy_XML_Markup
The $ variable holds a reference to your controller instance. It also contains some references to all indexed views (understand, views for which you supplied an index in you xml markup).
Both ways are strictly equivalent as, during the compilation, Alloy will merge the content of the exports with your controller referenced in $. Adding them directly to the instance won't change a thing.
Neverthless, developers are used to see the public API as the set of functions exported via the special variable exports; Thus, I will recommend to keep using it in a clean and clear way (for instance, defining your functions in your module scope, and only expose them at the end or beginning of your controller).
function myFunction1 () { }
function myFunction2 () { }
function myFunction3 () { }
exports.myFunction1 = myFunction1;
exports.myFunction3 = myFunction3;
Thereby, your API is quite clear for people diving into your source code. (A readMe file is also highly recommended :) ).

How do i read embedded bytarray file?

I created a tile map editor for my game and it will generate a file when the user is done with the design. The file will store the assets used and other information.
this is the code on how i generate the file
var ba:ByteArray = new ByteArray();
var masterData:Object = { map:Data.instance.mapLayerArr,
asset:assetCollection,
gridrow:Data.instance.gridRow,
gridColumn: Data.instance.gridColumn,
cellWidth: Data.instance.cellWidth,
cellHeight: Data.instance.cellHeight,
assetCount: Data.instance.assetCount,
layerCount: Data.instance.layerCount,
version: Data.instance.version};
ba.writeObject(masterData);
ba.compress();
file = new FileReference();
file.save(ba, Data.instance.fileName);
problem starts when i want to embed the generated file inside my game.
this is the code in my program.
[Embed(source='../../../../res/tilemapdata/File Name', mimeType='application/octet-stream')]
public static const TileMapFile:Class;
public function TileMapLoader()
{
var byteArray:ByteArray;
byteArray = new TileMapFile();
byteArray.uncompress();
var obj:Object;
obj = byteArray.readObject();
trace(fileReference);
}
whenever i run it ends in "obj = byteArray.readObject();" and will display this error.
[Fault] exception, information=ArgumentError: Error #2173: Unable to read object in stream. The class flex.messaging.io.ArrayCollection does not implement flash.utils.IExternalizable but is aliased to an externalizable class.
You are using a strange class flex.messaging.io.ArrayCollection - try replacing all such imports with mx.collections.ArrayCollection.
Also make sure that all classes that are stored in file has [RemoteClass] metatag or they would be restored as Object instances.
A good read about the situation (adobe's official documentation): (Explicitly mapping ActionScript and Java objects)
I have experianced the same problem. General rules which help me to solve:
better to have explicitly declared metatag [RemoteClass] on your client-side actionscript classes.
collections of server-side classes (lists,arrays,etc.) easier to handle when represented client-side flash by mx.collections.ArrayCollection.
at some point you may need to explicitly declare client-side Flash class with the server-side class relationship by coding before any deserialization occures flash.net.registerClassAlias("net.acme.serverside.Foo", clientside.Foo ); otherwise your objects goes untyped as generic flash.Object after deserialization.
Check, that your ArrayCollection alias registered by this way:
import mx.collections.ArrayCollection;
...
registerClassAlias("flex.messaging.io.ArrayCollection", ArrayCollection);
instead of:
import mx.collections.ArrayCollection;
...
registerClassAlias("mx.collections.ArrayCollection", ArrayCollection);
There explanation:
http://livedocs.adobe.com/blazeds/1/javadoc/flex/messaging/io/ArrayCollection.html

Flex: How to use flashvars from different classes

I am just learning actionscript, so come across the problem
In my application I often call to different web services, and because I don't want to hardcode urls to them in my code, I am passing urls to the services as flashvars.
Currently I am doing it this way:
public var siteUrl:String;
public var gameId:String;
public function main():void
{
siteUrl = Application.application.parameters.siteurl;
gameId = Application.application.parameters.gameid;
Where main is a function, which is called on application's creation complete event.
This way I can call both variables from main file of the application but I want to access them from other files. (other as classes)
So is there a way to create class with constants and init values there with flashvars so I can use them everywhere (after importing of course)
The parameters are just stored in that Application.application.parameters object, and that's static. There's no reason you couldn't access that from other classes in your code.
If you want to write a class that wraps the parameters (maybe validates them or something) you could do that fairly easily. You can use a for each loop to loop over all the parameters. Something like:
var params:Object = Application.application.parameters
for(var name:String in params) {
var value:String = params[name] as String;
/* do something with the param */
}
If you want your class to actually verify things then it could just check for each parameter it expects and store it in a local variable.
It really just depends on your own preferences. Some people are fine with accessing the parameters object when they need it. Some people like having the extra code-completion by having a config class that actually defines all the expected config variables.
Update in response to comment:
Instead of having one module declare the variable and have other modules have to depend on that one to access the property it would be cleaner to have a single config module that everything that needs it would all use.
You could use a static class or singleton or some IoC stuff. Just for simplicity I'll show you a way you can do it with a static class.
class MyConfig {
private static var _infoService:String;
private static var _someOtherParam:int;
public static function get infoService():String { return _infoService; }
public static function get someOtherParam():int { return _someOtherParam; }
public static function initParams():Void {
var params:Object = Application.application.parameters;
_infoService = params.infoservice;
// just assuming you have a method to convert here. don't remember the
// code off the top of my head
_someOtherParam = convertToInt(params.someOtherParam);
}
}
Make sure when your app initializes it calls MyConfig.initParams(). You can have that method actually validate that it gets everything it expects and throw exceptions (or return an error) if there's a failure if you want.
Then wherever you need to use that config within your code you just import your config class and access the param. So getting infoService would just be:
var infoService:String = MyConfig.infoService;
Personally I wouldn't use a static class, but it was the easiest to show.

loading an RSL without using flex?

If I have rolled my own RSL, and I want to use it in my pure as3 apps, is there documentation or an example of how to do this?
Or do I need to traverse the flex source code to figure out what adobe's engineers have done?
This is a very tricky one, with lots to go into I'm afraid. Some pointers:
To get a class from an externally loaded SWF use the getDefinition method on an application domain e.g.
public function loadHandler(evt:Event):void
{
var loaderInfo:LoaderInfo = evt.target as LoaderInfo;
var clazz:Class = loaderInfo.applicationDomain.getDefinition("your.external.class");
}
This will give you the class definition if you know the name of the class you want.
To 'join' class domains into each other (so applications can compile against a swc, but not include the classes and load them externally) you need to specify a loaderContext of the same security domain.
var loader:Loader = new Loader();
var context:LoaderContext = new LoaderContext();
context.applicationDomain = ApplicationDomain.currentDomain;
loader.load(new URLRequest("library.swf"), context);
The third pointer I can give you is the compiler option "-external-library-path", use this to specify a list of swc's to compile time check against, but not include (resulting in a lower filesize).
mxmlc -source-path="dir/src" -external-library-path="dir/lib/framework.swc" --main.swf
Sorry I couldn't elaborate more, it's a very expansive topic, hope this gets you started....

Resources