I have a dynamic ActionScript Class that is used to send parameters to a WebService. Some of these parameters are always present, so they are public properties of the Class:
package
{
[Bindable]
public dynamic class WebServiceCriteria
{
public var property1:int;
public var property2:String;
public var property3:String;
public var property4:String;
}
}
But, I am also adding properties at runtime that can change over time:
criteria.runTimeProperty = "1";
I'm not very familiar with using dynamic classes, so I was wondering if it is possible to "remove" the new property. Let's say the next time I call the WebService I don't want that property sent - not even as a null. How can I remove it from the Class instance without creating a new instance each time?
I believe all you'd need to do is this:
delete criteria.runTimeProperty;
or
delete criteria["runTimeProperty"];
Either should do the same thing.
See the delete documentation for specifics.
Related
can someone please explain me the code written below
public IList<GetProductPrice> CurrentPage
{
get { return ViewState["CurrentPage"] as List<GetProductPrice>; }
set { ViewState["CurrentPage"] = value; }
}
It is called a Property. They generate a getter and setter functions when compiled:
List<GetProductPrice> GetCurrentPage(){
return ViewState["CurrentPage"] as List<GetProductPrice>;
}
void SetCurrentPage(List<GetProductPrice> value) {
ViewState["CurrentPage"] = value;
}
//i think its actual get_.. but it doesn't matter for the example
So its generates ease of use getter setters. which you can just call by using:
var test = CurrentPage; //compiled to var test = GetCurrenctPage();
CurrentPage = test; //compiled to SetCurrentPage(test);
If you leave the getter and setter empty like this:
public int CurrentPage
{
get;
set;
}
it will also generate a backing field on the class where it stores the data:
private int _currentPage;
public GetCurrentPage(){ return _currentPage }
public SetCurrentPage(int value) { _currentPage = value }
Why do we do this?
Using getters and setters is a very old best practise from java (where ide's would have an option to generate them). But this would lead to a lot of boilerplate code!
In C# they try to counter this by adding these properties. But why do we need getters and setters? For example if you want to be notified when a value changes (to mark the classes it self as dirty). I think entity framework uses it to track if a model is changed otherwise it wont do a db update call. There are also other usefull tools that inject code in properties on compile time. to add extra functionality.
How not to use it:
using properties to return HttpContext.Current Is a dangerous one because you secretly depend on the HttpContext so try not to do this at any time!
Generally its also bad practise to use it when the code inside the get or set is very heavy (very instensive). Its bad practise because someone else using the code might think he is just setting a property/field while actually some very heavy code is executed. its best practice to make a special function for this instead and private the getter/setter:
public int Property {get; private set; }
public SetProperty(int value){
//intensive code here:
Property = value;
}
This property is letting the consumer of the property to use it like Local collection without referring the ViewState in the code. It will make the code simple and easy to use.
get { return ViewState["CurrentPage"] as List<GetProductPrice>; }
Here the ViewState object ViewState["CurrentPage"] is converted to list of GetProductPrice
set { ViewState["CurrentPage"] = value; }
Here the List is assigned to ViewState["CurrentPage"]
This code will only work in a controller, where ViewState is a property. This CurrentPage property provides a statically-typed way to access a certain ViewState item through that property.
So instead of sprinkling ViewState["CurrentPage"] as List<GetProductPrice> all over your controller code where you want to access the "current page", you can now simply use the CurrentPage property.
Of course "current page" is a term made up by the developer who chose to name things like this, I don't see how a List<GetProductPrice> has a relation to the "current page".
I'm working on a ASP.NET WebApi (Release Candidate) project where I'm consuming several DTOs that are marked with the [Serializable] attribute. These DTOs are outside of my control so I'm not able to modify them in any way. When I return any of these from a get method the resulting JSON contains a bunch of k__BackingFields like this:
<Name>k__BackingField=Bobby
<DateCreated>k__BackingField=2012-06-19T12:35:18.6762652-05:00
Based on the searching I've done this seems like a problem with JSON.NET's IgnoreSerializableAttribute setting and to resolve my issue I just need to set it globally as the article suggests. How do I change this setting globally in a ASP.NET Web api project?
I found easy way to get rid of k__BackingField in the names.
This fragment should be somewhere in the Application_Start() in Global.asax.cs:
JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;
Looks like the default setting takes care of it.
Since the library does not expose a static setter for the DefaultContractResolver, I suggest you create a static wrapper over JsonConvert and it's Serialize*/Deserialize* methods (at least the ones you use).
In your static wrapper you can define a static contract resolver:
private static readonly DefaultContractResolver Resolver = new DefaultContractResolver
{
IgnoreSerializableAttribute = true
};
This you can pass to each serialization method in the JsonSerializerSettings, inside your wrapper.
Then you call your class throughout your project.
The alternative would be to get the JSON.NET source code and adjust it yourself to use that attribute by default.
For me, the following fixed the issue with circular references and k__BackingField.
In your WebApiConfig add the following to the Register() method:
JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings {
ContractResolver = new DefaultContractResolver {
IgnoreSerializableAttribute = true
},
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = jSettings;
Friends, don't declare properties like this:
public String DiscretionCode { get; set; }
But, create auxiliar vars, like old....
private String discretionCode;
public String DiscretionCode
{
get { return discretionCode;}
set { discretionCode = value; }
}
In Flex (Flash Builder 4), I need a way to know if something in an array collection has changed.
I have a custom object:
[Bindable]
public var _myobject:MyObject;
It's basically just a class containing a bunch of different String and Number properties.
I need a reliable way to know if any of the properties have been changed. For example, I am binding the properties to a user interface (fields), but it's also possible for some of the properties to change through code.
Is there a way to do this? I found ChangeWatcher, but that looks like it only looks at a single simple property, such as a String or Number. I need to watch or detect changes in all the properties in my object, hopefully without having to add ChangeWatcher events to every property. Is this possible?
You're probably better off just dispatching binding events on the specific properties you want bindable. Better yet, dispatch a custom binding event, so that all of the things that are bound don't have to filter for "is this the property I care about?" It's really easy with Flash Builder 4.5 to do this, just select your variable name and press Ctrl-1, select "Create getter and setter," select getter and setter and check "Bindable" and "create custom event."
This will create code for you that looks something like this:
private var _yourProperty:String;
[Bindable (event='yourPropertyChange')]
public function get yourProperty():String {
return _yourProperty;
}
public function set yourProperty(value:String):void {
if (value !=== _yourProperty) {
_yourProperty = value;
dispatchEvent(new Event('yourPropertyChange'));
}
}
This will be much less verbose and more performant than the code that Flash Builder generates for you behind the scenes when you just use the Bindable tag on its own.
If you use defined classes as VO/DAO and apply the [Bindable] tag to the class, this will do binding on all properties for you (so long as they are read/write).
Anonymous object detection is difficult at best, let alone adding additional headaches of loosing compiler type checking.
Super basic example: - the key is to tie it to the dispatcher, so internally it can send out the PropertyChangeEvent.
[Bindable]
public class Actor extends EventDispatcher
{
public var fName:String;
public var lName:String;
public var age:uint;
public function get displayName():String
{
return lName +', '+ fName;
}
public function Actor()
{
super();
}
}
public class BindableDictionary extends EventDispatcher {
public function BindableDictionary() {
super();
}
public var dictionary:Dictionary = new Dictionary();
[Bindable("change")]
public function get(key:Object):Object {
return dictionary[key];
}
public function put(key:Object, value:Object):void {
dictionary[key] = value;
dispatchEvent(new Event(Event.CHANGE));
}
}
maybe this class will give you some new idea
How do I create a globally accessible Context object similar to the HttpContext object?
I want to create a custom class library which I want to reference from a website project. In the website project I want to be able to call the following globally:
ClassLibraryName.Context
I cannot create a global property directly in my classlibrary, so how should this be implemented? (I've seen other applications/products use this approach, one of which is Sitecore which has a custom Sitecore.Context object available)
Edit
Might this be a 'valid' solution?
namespace MyLibrary
{
public class Context
{
public static object ContextualObject
{
get;
set;
}
}
}
Yes, this is not hard to implement, if you always run this class in the context of an ASP.NET application, use this approach:
namespace MyLibrary
{
public class Context
{
public static object ContextualObject
{
get
{
var ctx = System.Web.HttpContext.Current.Items[typeof(Context)];
if (ctx == null)
{
ctx = new Context();
System.Web.HttpContext.Current.Items.Add(typeof(Context), ctx);
}
return ctx;
}
set { System.Web.HttpContext.Current.Items[typeof(Context)] = ctx; }
}
}
}
Essentially wrapping the existing HTTP context to provide your own service. This approach also doesn't store the object while the app lives, it only creates it for the current context, and when that response ends, it will die, and be regenerated during the next lifecycle. If that is not OK, store a static reference to context.
I've used this approach similarly in a class library I have at http://nucleo.codeplex.com, it works well.
HTH.
It depends on the lifetime you want the Context object to have. If you want all clients to use the same context, you can go with a singleton implementation.
If you want the context to be unique for each thread or http request you have to use a per request/thread implementation. One way to implement a per http request implementation would be to have a HttpModule create the object at every BeginRequest event and stick it in the HttpContext Items collection.
public static object ContextualObject
{
get { return HttpContext.Current.Items["MyContext"];}
}
You could create an instance of the object on Session_Start in the Global.asax.
I'm new to Flex and BlazeDS and I'm trying to implement a simple application which uses Flex on the front end and a Spring/Hibernate application on the back end, with communication between the two going over a BlazeDS channel.
I'm seeking direction as to the best and/or simplest way to approach this. I have the UI set up in such a way that the user is presented with a file chooser in which they pick the image file they want to upload. When this is chosen and submitted (as a form submission) then the server side should receive the image file data as well as some related metadata such as a description and date, then populate a Hibernate entity/POJO with the image file data and related metadata, and then persist the entity/POJO into the database.
I have found some examples of how you would do a file upload and download using servlets here and the FileReference class (here and here) but these don't appear to address the problem in a way which leverages BlazeDS and/or Spring/Hibernate. I want to put the image file data and related metadata (description, capture date, etc.) into a value object within the Flex application and then send this over BlazeDS to a service provided by my Spring/Hibernate application running on Tomcat. In this service I want to extract the image data (both the actual JPG/PNG/GIF data and the related metadata such as description, etc.) from the value object sent from the Flex app into an entity/POJO which is then persisted via Hibernate in my database.
Can this be done, and if so what's the best way to go about it? Am I mistaken in assuming that if I use BlazeDS then I am somehow bypassing the need to provide HTTP-based services such as servlets on the server side and instead I can use my Java services as "RemoteObjects"? Is there necessarily a one-to-one mapping between Java POJO/entity class and the Flex value object class when making this sort of transfer? If so is there a tool which creates corresponding Flex value objects from Java POJOs or vice versa.
Thanks in advance for your help, comments, suggestions, etc.
--James
Update: Some code to make this more clear:
I have this as my value object in Flex:
package valueobjects
{
import flash.utils.ByteArray;
[Bindable]
[RemoteClass(alias="com.abc.example.persistence.entity.Image")]
public class Image
{
public var id:Number;
public var captureDate:Date;
public var description:String;
public var imageData:ByteArray;
public function Image() {}
}
I am assuming that this can be used as a one-to-one mapping to the POJO class used by my service and DAO classes on the server-side, which looks like this:
package com.abc.example.persistence.entity;
import java.sql.Blob;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
#Entity(name = "IMAGE")
public class Image
extends AbstractBaseEntity<Long>
{
private String description;
private Date captureDate;
private Blob imageData;
#Column(name = "CAPTURE_DATE", nullable = true)
public Date getCaptureDate()
{
return captureDate;
}
#Column(name = "DESCRIPTION", nullable = true)
public String getDescription()
{
return description;
}
#Column(name = "IMAGE_DATA", nullable = true)
public Blob getImageData()
{
return imageData;
}
public void setCaptureDate(final Date captureDate)
{
this.captureDate = captureDate;
}
public void setDescription(final String description)
{
this.description = description;
}
public void setImageData(final Blob imageData)
{
this.imageData = imageData;
}
}
In my Flex application I populate the fields of an Image object with a description string, date, and image file data (based on the user's file selection and text input for the description) and then call a method on the RemoteObject which is mapped to the service running on Tomcat. I make the RemoteObject service call within my Flex code using the Image value object as the argument, but the service method running on the servier side actually expects an argument of the POJO/entity type, and it's here that I am thinking that some sort of conversion/transformation between the Flex value object and the Java POJO will occur (by virtue of the RemoteClass alias setting on the value object's class declaration), but it doesn't seem to be happening that way because when I debug the application the Java service is only getting null values when the service call is made.
In my Flex application I have a FileReference and Image value object as public, bindable variables:
[Bindable]
public var imageToBeArchivedFileReference:FileReference = new FileReference();
[Bindable]
public var imageToBeArchivedValueObject:valueobjects.Image = new valueobjects.Image();
There is also an event handler to browse for a file when the user clicks on a file select button:
protected function imageFileSelectButton_clickHandler(event:MouseEvent):void
{
var imageFileFilter:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png");
var fileTypes:Array = new Array();
fileTypes.push(imageFileFilter);
imageToBeArchivedFileReference.addEventListener(Event.SELECT, imageToBeArchived_fileSelectHandler);
imageToBeArchivedFileReference.browse(fileTypes);
}
There is an event handler which builds the value object when the image file has been selected:
private function imageToBeArchived_fileSelectHandler(event:Event):void
{
imageToBeArchivedFileReference.load();
imageToBeArchivedValueObject = new valueobjects.Image()
imageToBeArchivedValueObject.imageData = imageToBeArchivedFileReference.data;
imageToBeArchivedValueObject.description = imageToBeArchivedDescription.text;
imageToBeArchivedValueObject.captureDate = imageToBeArchivedFileReference.creationDate;
}
and there's an event handler which is invoked when the user clicks on the submit button to perform the image save/upload:
protected function archiveImageButton_clickHandler(event:MouseEvent):void
{
imageArchivalService.archiveImage(imageToBeArchived);
}
On the server side my Java class is doing a simple save of the POJO:
public void archiveImage(final Image image)
{
imageDao.saveOrUpdate(image);
}
When I set a breakpoint in the method above and look at the image variable it looks to be empty, so I'm assuming that the transformation from the Flex value object to the Java POJO did not go as expected and that there's more to it than just adding a RemoteClass alias in the Flex value object class.
Check out this example, it is all there.
http://biemond.blogspot.com/2008/08/flex-upload-and-download-with-blazeds.html
Don't use the loader class, use the readBytes call.
Make sure you go to the comments, there are valuable info there.
Cheers