Search Results

Search found 247 results on 10 pages for 'createinstance'.

Page 3/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • how to access(read/write) local file system from webkit/javascript?

    - by ganapati hegde
    Hi, i am using Webkitgtk for rendering my HTML pages.Now,say i am browsing the page, i select some text while reading,i want to save/write down the selected text on my local file say /home/localfile.txt. Is any way to access(read/write) local file system using webkit? In case of firefox, i can do like below. try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("Permission to save file was denied."); } var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath( "/home/localfile.txt" ); if ( file.exists() == false ) { alert( "Creating file... " ); file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 ); } var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"] .createInstance( Components.interfaces.nsIFileOutputStream ); outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 ); var output = "my data to be written to the local file"; var result = outputStream.write( output, output.length ); outputStream.close(); The above code is written in a javascript file and the js file is linked to the html file.When some text is selected,the js function will be called and action will be taken place.How can i achieve the same result using Webkit? Thanks...

    Read the article

  • New to MVVM - Best practices for seperating Data processing thread and UI Thread?

    - by OffApps Cory
    Good day. I have started messing around with the MVVP pattern, and I am having some problems with UI responsiveness versus data processing. I have a program that tracks packages. Shipment and package entities are persisted in SQL database, and are displayed in a WPF view. Upon initial retrieval of the records, there is a noticeable pause before displaying the new shipments view, and I have not even implemented the code that counts shipments that are overdue/active yet (which will necessitate a tracking check via web service, and a lot of time). I have built this with the Ocean framework, and all appears to be doing well, except when I first started my foray into multi-threading. It broke, and it appeared to break something in Ocean... Here is what I did: Private QueryThread As New System.Threading.Thread(AddressOf GetShipments) Public Sub New() ' Insert code required on object creation below this point. Me.New(ViewManagerService.CreateInstance, ViewModelUIService.CreateInstance) 'Perform initial query of shipments 'QueryThread.Start() GetShipments() Console.WriteLine(Me.Shipments.Count) End Sub Public Sub New(ByVal objIViewManagerService As IViewManagerService, ByVal objIViewModelUIService As IViewModelUIService) MyBase.New(objIViewModelUIService) End Sub Public Sub GetShipments() Dim InitialResults = From shipment In db.Shipment.Include("Packages") _ Select shipment Me.Shipments = New ShipmentsCollection(InitialResults, db) End Sub So I declared a new Thread, assigned it the GetShipments method and instanced it in the default constructor. Ocean freaks out at this, so there must be a better way of doing it. I have not had the chance to figure out the usage of the SQL ORM thing in Ocean so I am using Entity Framework (perhaps one of these days i will look at NHibernate or something too). Any information would be greatly appreciated. I have looked at a number of articles and they all have examples of simple uses. Some have mentioned the Dispatcher, but none really go very far into how it is used. Anyone know any good tutorials? Cory

    Read the article

  • Firefox Extension Socket Transport

    - by Nathan
    Hey, I'm making a firefox extension and I'm currently trying to get it to send XML data over a local socket to another application that's listening on that socket. Does anyone know what I'm doing wrong in this? Its probably something simple and I'm just having a monday. Thanks. socketConn: function() { var httpLoc = window.top.getBrowser(). selectedBrowser.contentWindow.location.href; var outputData = '<?xml version="1.0"?>' + '<site_data>' + '<session_id></session_id>' + 'site_url>' + httpLoc + '</site_url>' + '<mime_type></mime_type>' + '<data_file>' + filePath + '</data_file>' + '<capture_mode></capture_mode>' + '</site_data>\n'; var transportService = Cc["@mozilla.org/network/socket-transport-service;1"] .getService(Ci.nsISocketTransportService); var transport = transportService.createTransport(["starttls"], 1,"localhost",currentPort, null); var outstream = transport.openOutputStream(0, 0, 0); outstream.write(outputData, outputData.length); var stream = transport.openInputStream(0, 0, 0); var instream = Cc["@mozilla.org/scriptableinputstream;1"] .createInstance(Ci.nsIScriptableInputStream); instream.init(stream); var dataListener = { data : "", onStartRequest: function(request, context){}, onStopRequest: function(request, context, status){ instream.close(); outstream.close(); }, onDataAvailable: function(request, context, inputStream, offset, count){ this.data += instream.read(count); }, };//end dataListener var pump = Cc["@mozilla.org/network/input-stream-pump;1"] .createInstance(Ci.nsIInputStreamPump); pump.init(stream, -1, -1, 0, 0, false); pump.asyncRead(dataListener, null); }//end socketConn Please ask questions about this if you don't understand what I'm trying to do with this.

    Read the article

  • Accessing Static Methods on a Generic class in c#

    - by mrlane
    Hello, I have the following situation in code, which I suspect may be a bit dodgey: I have a class: abstract class DataAccessBase<T> : IDataAccess where T : AnotherAbstractClass This class DataAccessBase also has a static factory method which creates instances of derived classes of itself using an enum value in a which statement to decide which derived type to create: static IDataAccess CreateInstance(TypeToCreateEnum) Now, the types derived from DataAccessBase<T> are themselves NOT generic, they specify a type for T: class PoLcZoneData : DataAccessBase<PoLcZone> // PoLcZone is derived from AnotherAbstractClass So far I am not sure if this is pushing the limits of good use of generics, but what I am really concerned about is how to access the static CreateInstance() method in the first place: The way I am doing this at the moment is to simply pass any type T where T : AnotherAbstractClass. In particular I am passing AnotherAbstractClass itself. This allows compilation just fine, but it does seem to me that passing any type to a generic class just to get at the statics is a bit dodgey. I have actually simplified the situation somewhat as DataAccessBase<T> is the lower level in the inheritance chain, but the static factory methods exists in a middle tier with classes such as PoLcZoneData being the most derived on the only level that is not generic. What are peoples thoughts on this arrangement?

    Read the article

  • Why doesn't my Unity DependencyResolver work on shared hosting but works locally?

    - by frennky
    I'm trying to deploy ASP.NET MVC 3 application wich uses Unity as a IoC container. Application works fine on local server, but when deployed it throws an exception: No parameterless constructor defined for this object. And this is thrown for a controller that should get some repository injected by my Unity DependencyResolver. I've installed Unity with NuGet so it should be referenced directly, and I've checked that it gets copied to bin folder. Edit: Here's the stack trace: [MissingMethodException: No parameterless constructor defined for this object.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98 System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241 System.Activator.CreateInstance(Type type, Boolean nonPublic) +69 System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67 [InvalidOperationException: An error occurred when trying to create a controller of type 'nBlog.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.] System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182 System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +196 System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49 System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841400 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +18 Anyone have an idea what might be the problem?

    Read the article

  • Write to a textfile using Javascript

    - by karikari
    Under Firefox, I want to do something like this : I have a .htm file, that has a button on it. This button, when I click it, the action will write a text inside a local .txt file. By the way, my .htm file is run locally too. I have tried multiple times using this code, but still cant make my .htm file write to my textfile: function save() { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("Permission to save file was denied."); } var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath( savefile ); if ( file.exists() == false ) { alert( "Creating file... " ); file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 ); } var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"] .createInstance( Components.interfaces.nsIFileOutputStream ); outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 ); var output = 'test test test test'; var result = outputStream.write( output, output.length ); outputStream.close(); } This part is for the button: <input type="button" value="write to file2" onClick="save();">

    Read the article

  • Executing untrusted code

    - by MainMa
    Hi, I'm building a C# application which uses plug-ins. The application must guarantee to the user that plug-ins will not do whatever they want on the user machine, and will have less privileges that the application itself (for example, the application can access its own log files, whereas plug-ins cannot). I considered three alternatives. Using System.AddIn. I tried this alternative first, because it seamed much powerful, but I'm really disappointed by the need of modifying the same code seven times in seven different projects each time I want to modify something. Besides, there is a huge number of problems to solve even for a simple Hello World application. Using System.Activator.CreateInstance(assemblyName, typeName). This is what I used in the preceding version of the application. I can't use it nevermore, because it does not provide a way to restrict permissions. Using System.Activator.CreateInstance(AppDomain domain, [...]). That's what I'm trying to implement now, but it seems that the only way to do that is to pass through ObjectHandle, which requires serialization for every used class. Although plug-ins contain WPF UserControls, which are not serializable. So is there a way to create plug-ins containing UserControls or other non serializable objects and to execute those plug-ins with a custom PermissionSet ?

    Read the article

  • ASP.NEt MVC 2 application error on IIS7 works fine on local machine

    - by aspCoolguy
    My ASP.NET MVC2 application is developed using 1. VS 2010 2. Linq To SQL for Models Here is Call controller code: namespace CallTrackMVC.Controllers { public class CallController : Controller { private CallTrackRepository repository; public CallController():this(new CallTrackRepository()) { } public CallController(CallTrackRepository newRepository) { repository = newRepository; } } } Error on IIS7 when browsing the Call Create page is NullReferenceException: Object reference not set to an instance of an object.] CallTrackMVC.Models.ExecOfficeDataContext..ctor() in C:\ClearCase\rartadi_view\STS_Dev_TEST\CallTrackMVC\Models\ExecOffice.designer.cs:71 CallTrackMVC.Controllers.CallController..ctor() in C:\ClearCase\rartadi_view\STS_Dev_TEST\CallTrackMVC\Controllers\CallController.cs:16 [TargetInvocationException: Exception has been thrown by the target of an invocation.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +117 System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +247 System.Activator.CreateInstance(Type type, Boolean nonPublic) +106 System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +102 [InvalidOperationException: **An error occurred when trying to create a controller of type 'CallTrackMVC.Controllers.CallController'. Make sure that the controller has a parameterless public constructor.**] System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +541 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +85 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +165 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +80 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +389 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371 Code in Global.asax is protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } Any suggestion would be a great help.

    Read the article

  • Dynamically loading Assemblies to reduce Runtime Depencies

    - by Rick Strahl
    I've been working on a request to the West Wind Application Configuration library to add JSON support. The config library is a very easy to use code-first approach to configuration: You create a class that holds the configuration data that inherits from a base configuration class, and then assign a persistence provider at runtime that determines where and how the configuration data is store. Currently the library supports .NET Configuration stores (web.config/app.config), XML files, SQL records and string storage.About once a week somebody asks me about JSON support and I've deflected this question for the longest time because frankly I think that JSON as a configuration store doesn't really buy a heck of a lot over XML. Both formats require the user to perform some fixup of the plain configuration data - in XML into XML tags, with JSON using JSON delimiters for properties and property formatting rules. Sure JSON is a little less verbose and maybe a little easier to read if you have hierarchical data, but overall the differences are pretty minor in my opinion. And yet - the requests keep rolling in.Hard Link Issues in a Component LibraryAnother reason I've been hesitant is that I really didn't want to pull in a dependency on an external JSON library - in this case JSON.NET - into the core library. If you're not using JSON.NET elsewhere I don't want a user to have to require a hard dependency on JSON.NET unless they want to use the JSON feature. JSON.NET is also sensitive to versions and doesn't play nice with multiple versions when hard linked. For example, when you have a reference to V4.4 in your project but the host application has a reference to version 4.5 you can run into assembly load problems. NuGet's Update-Package can solve some of this *if* you can recompile, but that's not ideal for a component that's supposed to be just plug and play. This is no criticism of JSON.NET - this really applies to any dependency that might change.  So hard linking the DLL can be problematic for a number reasons, but the primary reason is to not force loading of JSON.NET unless you actually need it when you use the JSON configuration features of the library.Enter Dynamic LoadingSo rather than adding an assembly reference to the project, I decided that it would be better to dynamically load the DLL at runtime and then use dynamic typing to access various classes. This allows me to run without a hard assembly reference and allows more flexibility with version number differences now and in the future.But there are also a couple of downsides:No assembly reference means only dynamic access - no compiler type checking or IntellisenseRequirement for the host application to have reference to JSON.NET or else get runtime errorsThe former is minor, but the latter can be problematic. Runtime errors are always painful, but in this case I'm willing to live with this. If you want to use JSON configuration settings JSON.NET needs to be loaded in the project. If this is a Web project, it'll likely be there already.So there are a few things that are needed to make this work:Dynamically create an instance and optionally attempt to load an Assembly (if not loaded)Load types into dynamic variablesUse Reflection for a few tasks like statics/enumsThe dynamic keyword in C# makes the formerly most difficult Reflection part - method calls and property assignments - fairly painless. But as cool as dynamic is it doesn't handle all aspects of Reflection. Specifically it doesn't deal with object activation, truly dynamic (string based) member activation or accessing of non instance members, so there's still a little bit of work left to do with Reflection.Dynamic Object InstantiationThe first step in getting the process rolling is to instantiate the type you need to work with. This might be a two step process - loading the instance from a string value, since we don't have a hard type reference and potentially having to load the assembly. Although the host project might have a reference to JSON.NET, that instance might have not been loaded yet since it hasn't been accessed yet. In ASP.NET this won't be a problem, since ASP.NET preloads all referenced assemblies on AppDomain startup, but in other executable project, assemblies are just in time loaded only when they are accessed.Instantiating a type is a two step process: Finding the type reference and then activating it. Here's the generic code out of my ReflectionUtils library I use for this:/// <summary> /// Creates an instance of a type based on a string. Assumes that the type's /// </summary> /// <param name="typeName">Common name of the type</param> /// <param name="args">Any constructor parameters</param> /// <returns></returns> public static object CreateInstanceFromString(string typeName, params object[] args) { object instance = null; Type type = null; try { type = GetTypeFromName(typeName); if (type == null) return null; instance = Activator.CreateInstance(type, args); } catch { return null; } return instance; } /// <summary> /// Helper routine that looks up a type name and tries to retrieve the /// full type reference in the actively executing assemblies. /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static Type GetTypeFromName(string typeName) { Type type = null; // Let default name binding find it type = Type.GetType(typeName, false); if (type != null) return type; // look through assembly list var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // try to find manually foreach (Assembly asm in assemblies) { type = asm.GetType(typeName, false); if (type != null) break; } return type; } To use this for loading JSON.NET I have a small factory function that instantiates JSON.NET and sets a bunch of configuration settings on the generated object. The startup code also looks for failure and tries loading up the assembly when it fails since that's the main reason the load would fail. Finally it also caches the loaded instance for reuse (according to James the JSON.NET instance is thread safe and quite a bit faster when cached). Here's what the factory function looks like in JsonSerializationUtils:/// <summary> /// Dynamically creates an instance of JSON.NET /// </summary> /// <param name="throwExceptions">If true throws exceptions otherwise returns null</param> /// <returns>Dynamic JsonSerializer instance</returns> public static dynamic CreateJsonNet(bool throwExceptions = true) { if (JsonNet != null) return JsonNet; lock (SyncLock) { if (JsonNet != null) return JsonNet; // Try to create instance dynamic json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); if (json == null) { try { var ass = AppDomain.CurrentDomain.Load("Newtonsoft.Json"); json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); } catch (Exception ex) { if (throwExceptions) throw; return null; } } if (json == null) return null; json.ReferenceLoopHandling = (dynamic) ReflectionUtils.GetStaticProperty("Newtonsoft.Json.ReferenceLoopHandling", "Ignore"); // Enums as strings in JSON dynamic enumConverter = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.Converters.StringEnumConverter"); json.Converters.Add(enumConverter); JsonNet = json; } return JsonNet; }This code's purpose is to return a fully configured JsonSerializer instance. As you can see the code tries to create an instance and when it fails tries to load the assembly, and then re-tries loading.Once the instance is loaded some configuration occurs on it. Specifically I set the ReferenceLoopHandling option to not blow up immediately when circular references are encountered. There are a host of other small config setting that might be useful to set, but the default seem to be good enough in recent versions. Note that I'm setting ReferenceLoopHandling which requires an Enum value to be set. There's no real easy way (short of using the cardinal numeric value) to set a property or pass parameters from static values or enums. This means I still need to use Reflection to make this work. I'm using the same ReflectionUtils class I previously used to handle this for me. The function looks up the type and then uses Type.InvokeMember() to read the static property.Another feature I need is have Enum values serialized as strings rather than numeric values which is the default. To do this I can use the StringEnumConverter to convert enums to strings by adding it to the Converters collection.As you can see there's still a bit of Reflection to be done even in C# 4+ with dynamic, but with a few helpers this process is relatively painless.Doing the actual JSON ConversionFinally I need to actually do my JSON conversions. For the Utility class I need serialization that works for both strings and files so I created four methods that handle these tasks two each for serialization and deserialization for string and file.Here's what the File Serialization looks like:/// <summary> /// Serializes an object instance to a JSON file. /// </summary> /// <param name="value">the value to serialize</param> /// <param name="fileName">Full path to the file to write out with JSON.</param> /// <param name="throwExceptions">Determines whether exceptions are thrown or false is returned</param> /// <param name="formatJsonOutput">if true pretty-formats the JSON with line breaks</param> /// <returns>true or false</returns> public static bool SerializeToFile(object value, string fileName, bool throwExceptions = false, bool formatJsonOutput = false) { dynamic writer = null; FileStream fs = null; try { Type type = value.GetType(); var json = CreateJsonNet(throwExceptions); if (json == null) return false; fs = new FileStream(fileName, FileMode.Create); var sw = new StreamWriter(fs, Encoding.UTF8); writer = Activator.CreateInstance(JsonTextWriterType, sw); if (formatJsonOutput) writer.Formatting = (dynamic)Enum.Parse(FormattingType, "Indented"); writer.QuoteChar = '"'; json.Serialize(writer, value); } catch (Exception ex) { Debug.WriteLine("JsonSerializer Serialize error: " + ex.Message); if (throwExceptions) throw; return false; } finally { if (writer != null) writer.Close(); if (fs != null) fs.Close(); } return true; }You can see more of the dynamic invocation in this code. First I grab the dynamic JsonSerializer instance using the CreateJsonNet() method shown earlier which returns a dynamic. I then create a JsonTextWriter and configure a couple of enum settings on it, and then call Serialize() on the serializer instance with the JsonTextWriter that writes the output to disk. Although this code is dynamic it's still fairly short and readable.For full circle operation here's the DeserializeFromFile() version:/// <summary> /// Deserializes an object from file and returns a reference. /// </summary> /// <param name="fileName">name of the file to serialize to</param> /// <param name="objectType">The Type of the object. Use typeof(yourobject class)</param> /// <param name="binarySerialization">determines whether we use Xml or Binary serialization</param> /// <param name="throwExceptions">determines whether failure will throw rather than return null on failure</param> /// <returns>Instance of the deserialized object or null. Must be cast to your object type</returns> public static object DeserializeFromFile(string fileName, Type objectType, bool throwExceptions = false) { dynamic json = CreateJsonNet(throwExceptions); if (json == null) return null; object result = null; dynamic reader = null; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); var sr = new StreamReader(fs, Encoding.UTF8); reader = Activator.CreateInstance(JsonTextReaderType, sr); result = json.Deserialize(reader, objectType); reader.Close(); } catch (Exception ex) { Debug.WriteLine("JsonNetSerialization Deserialization Error: " + ex.Message); if (throwExceptions) throw; return null; } finally { if (reader != null) reader.Close(); if (fs != null) fs.Close(); } return result; }This code is a little more compact since there are no prettifying options to set. Here JsonTextReader is created dynamically and it receives the output from the Deserialize() operation on the serializer.You can take a look at the full JsonSerializationUtils.cs file on GitHub to see the rest of the operations, but the string operations are very similar - the code is fairly repetitive.These generic serialization utilities isolate the dynamic serialization logic that has to deal with the dynamic nature of JSON.NET, and any code that uses these functions is none the wiser that JSON.NET is dynamically loaded.Using the JsonSerializationUtils WrapperThe final consumer of the SerializationUtils wrapper is an actual ConfigurationProvider, that is responsible for handling reading and writing JSON values to and from files. The provider is simple a small wrapper around the SerializationUtils component and there's very little code to make this work now:The whole provider looks like this:/// <summary> /// Reads and Writes configuration settings in .NET config files and /// sections. Allows reading and writing to default or external files /// and specification of the configuration section that settings are /// applied to. /// </summary> public class JsonFileConfigurationProvider<TAppConfiguration> : ConfigurationProviderBase<TAppConfiguration> where TAppConfiguration: AppConfiguration, new() { /// <summary> /// Optional - the Configuration file where configuration settings are /// stored in. If not specified uses the default Configuration Manager /// and its default store. /// </summary> public string JsonConfigurationFile { get { return _JsonConfigurationFile; } set { _JsonConfigurationFile = value; } } private string _JsonConfigurationFile = string.Empty; public override bool Read(AppConfiguration config) { var newConfig = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfiguration)) as TAppConfiguration; if (newConfig == null) { if(Write(config)) return true; return false; } DecryptFields(newConfig); DataUtils.CopyObjectData(newConfig, config, "Provider,ErrorMessage"); return true; } /// <summary> /// Return /// </summary> /// <typeparam name="TAppConfig"></typeparam> /// <returns></returns> public override TAppConfig Read<TAppConfig>() { var result = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfig)) as TAppConfig; if (result != null) DecryptFields(result); return result; } /// <summary> /// Write configuration to XmlConfigurationFile location /// </summary> /// <param name="config"></param> /// <returns></returns> public override bool Write(AppConfiguration config) { EncryptFields(config); bool result = JsonSerializationUtils.SerializeToFile(config, JsonConfigurationFile,false,true); // Have to decrypt again to make sure the properties are readable afterwards DecryptFields(config); return result; } }This incidentally demonstrates how easy it is to create a new provider for the West Wind Application Configuration component. Simply implementing 3 methods will do in most cases.Note this code doesn't have any dynamic dependencies - all that's abstracted away in the JsonSerializationUtils(). From here on, serializing JSON is just a matter of calling the static methods on the SerializationUtils class.Already, there are several other places in some other tools where I use JSON serialization this is coming in very handy. With a couple of lines of code I was able to add JSON.NET support to an older AJAX library that I use replacing quite a bit of code that was previously in use. And for any other manual JSON operations (in a couple of apps I use JSON Serialization for 'blob' like document storage) this is also going to be handy.Performance?Some of you might be thinking that using dynamic and Reflection can't be good for performance. And you'd be right… In performing some informal testing it looks like the performance of the native code is nearly twice as fast as the dynamic code. Most of the slowness is attributable to type lookups. To test I created a native class that uses an actual reference to JSON.NET and performance was consistently around 85-90% faster with the referenced code. That being said though - I serialized 10,000 objects in 80ms vs. 45ms so this isn't hardly slouchy. For the configuration component speed is not that important because both read and write operations typically happen once on first access and then every once in a while. But for other operations - say a serializer trying to handle AJAX requests on a Web Server one would be well served to create a hard dependency.Dynamic Loading - Worth it?On occasion dynamic loading makes sense. But there's a price to be paid in added code complexity and a performance hit. But for some operations that are not pivotal to a component or application and only used under certain circumstances dynamic loading can be beneficial to avoid having to ship extra files and loading down distributions. These days when you create new projects in Visual Studio with 30 assemblies before you even add your own code, trying to keep file counts under control seems a good idea. It's not the kind of thing you do on a regular basis, but when needed it can be a useful tool. Hopefully some of you find this information useful…© Rick Strahl, West Wind Technologies, 2005-2013Posted in .NET  C#   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Dynamically loading Assemblies to reduce Runtime Dependencies

    - by Rick Strahl
    I've been working on a request to the West Wind Application Configuration library to add JSON support. The config library is a very easy to use code-first approach to configuration: You create a class that holds the configuration data that inherits from a base configuration class, and then assign a persistence provider at runtime that determines where and how the configuration data is store. Currently the library supports .NET Configuration stores (web.config/app.config), XML files, SQL records and string storage.About once a week somebody asks me about JSON support and I've deflected this question for the longest time because frankly I think that JSON as a configuration store doesn't really buy a heck of a lot over XML. Both formats require the user to perform some fixup of the plain configuration data - in XML into XML tags, with JSON using JSON delimiters for properties and property formatting rules. Sure JSON is a little less verbose and maybe a little easier to read if you have hierarchical data, but overall the differences are pretty minor in my opinion. And yet - the requests keep rolling in.Hard Link Issues in a Component LibraryAnother reason I've been hesitant is that I really didn't want to pull in a dependency on an external JSON library - in this case JSON.NET - into the core library. If you're not using JSON.NET elsewhere I don't want a user to have to require a hard dependency on JSON.NET unless they want to use the JSON feature. JSON.NET is also sensitive to versions and doesn't play nice with multiple versions when hard linked. For example, when you have a reference to V4.4 in your project but the host application has a reference to version 4.5 you can run into assembly load problems. NuGet's Update-Package can solve some of this *if* you can recompile, but that's not ideal for a component that's supposed to be just plug and play. This is no criticism of JSON.NET - this really applies to any dependency that might change.  So hard linking the DLL can be problematic for a number reasons, but the primary reason is to not force loading of JSON.NET unless you actually need it when you use the JSON configuration features of the library.Enter Dynamic LoadingSo rather than adding an assembly reference to the project, I decided that it would be better to dynamically load the DLL at runtime and then use dynamic typing to access various classes. This allows me to run without a hard assembly reference and allows more flexibility with version number differences now and in the future.But there are also a couple of downsides:No assembly reference means only dynamic access - no compiler type checking or IntellisenseRequirement for the host application to have reference to JSON.NET or else get runtime errorsThe former is minor, but the latter can be problematic. Runtime errors are always painful, but in this case I'm willing to live with this. If you want to use JSON configuration settings JSON.NET needs to be loaded in the project. If this is a Web project, it'll likely be there already.So there are a few things that are needed to make this work:Dynamically create an instance and optionally attempt to load an Assembly (if not loaded)Load types into dynamic variablesUse Reflection for a few tasks like statics/enumsThe dynamic keyword in C# makes the formerly most difficult Reflection part - method calls and property assignments - fairly painless. But as cool as dynamic is it doesn't handle all aspects of Reflection. Specifically it doesn't deal with object activation, truly dynamic (string based) member activation or accessing of non instance members, so there's still a little bit of work left to do with Reflection.Dynamic Object InstantiationThe first step in getting the process rolling is to instantiate the type you need to work with. This might be a two step process - loading the instance from a string value, since we don't have a hard type reference and potentially having to load the assembly. Although the host project might have a reference to JSON.NET, that instance might have not been loaded yet since it hasn't been accessed yet. In ASP.NET this won't be a problem, since ASP.NET preloads all referenced assemblies on AppDomain startup, but in other executable project, assemblies are just in time loaded only when they are accessed.Instantiating a type is a two step process: Finding the type reference and then activating it. Here's the generic code out of my ReflectionUtils library I use for this:/// <summary> /// Creates an instance of a type based on a string. Assumes that the type's /// </summary> /// <param name="typeName">Common name of the type</param> /// <param name="args">Any constructor parameters</param> /// <returns></returns> public static object CreateInstanceFromString(string typeName, params object[] args) { object instance = null; Type type = null; try { type = GetTypeFromName(typeName); if (type == null) return null; instance = Activator.CreateInstance(type, args); } catch { return null; } return instance; } /// <summary> /// Helper routine that looks up a type name and tries to retrieve the /// full type reference in the actively executing assemblies. /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static Type GetTypeFromName(string typeName) { Type type = null; // Let default name binding find it type = Type.GetType(typeName, false); if (type != null) return type; // look through assembly list var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // try to find manually foreach (Assembly asm in assemblies) { type = asm.GetType(typeName, false); if (type != null) break; } return type; } To use this for loading JSON.NET I have a small factory function that instantiates JSON.NET and sets a bunch of configuration settings on the generated object. The startup code also looks for failure and tries loading up the assembly when it fails since that's the main reason the load would fail. Finally it also caches the loaded instance for reuse (according to James the JSON.NET instance is thread safe and quite a bit faster when cached). Here's what the factory function looks like in JsonSerializationUtils:/// <summary> /// Dynamically creates an instance of JSON.NET /// </summary> /// <param name="throwExceptions">If true throws exceptions otherwise returns null</param> /// <returns>Dynamic JsonSerializer instance</returns> public static dynamic CreateJsonNet(bool throwExceptions = true) { if (JsonNet != null) return JsonNet; lock (SyncLock) { if (JsonNet != null) return JsonNet; // Try to create instance dynamic json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); if (json == null) { try { var ass = AppDomain.CurrentDomain.Load("Newtonsoft.Json"); json = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.JsonSerializer"); } catch (Exception ex) { if (throwExceptions) throw; return null; } } if (json == null) return null; json.ReferenceLoopHandling = (dynamic) ReflectionUtils.GetStaticProperty("Newtonsoft.Json.ReferenceLoopHandling", "Ignore"); // Enums as strings in JSON dynamic enumConverter = ReflectionUtils.CreateInstanceFromString("Newtonsoft.Json.Converters.StringEnumConverter"); json.Converters.Add(enumConverter); JsonNet = json; } return JsonNet; }This code's purpose is to return a fully configured JsonSerializer instance. As you can see the code tries to create an instance and when it fails tries to load the assembly, and then re-tries loading.Once the instance is loaded some configuration occurs on it. Specifically I set the ReferenceLoopHandling option to not blow up immediately when circular references are encountered. There are a host of other small config setting that might be useful to set, but the default seem to be good enough in recent versions. Note that I'm setting ReferenceLoopHandling which requires an Enum value to be set. There's no real easy way (short of using the cardinal numeric value) to set a property or pass parameters from static values or enums. This means I still need to use Reflection to make this work. I'm using the same ReflectionUtils class I previously used to handle this for me. The function looks up the type and then uses Type.InvokeMember() to read the static property.Another feature I need is have Enum values serialized as strings rather than numeric values which is the default. To do this I can use the StringEnumConverter to convert enums to strings by adding it to the Converters collection.As you can see there's still a bit of Reflection to be done even in C# 4+ with dynamic, but with a few helpers this process is relatively painless.Doing the actual JSON ConversionFinally I need to actually do my JSON conversions. For the Utility class I need serialization that works for both strings and files so I created four methods that handle these tasks two each for serialization and deserialization for string and file.Here's what the File Serialization looks like:/// <summary> /// Serializes an object instance to a JSON file. /// </summary> /// <param name="value">the value to serialize</param> /// <param name="fileName">Full path to the file to write out with JSON.</param> /// <param name="throwExceptions">Determines whether exceptions are thrown or false is returned</param> /// <param name="formatJsonOutput">if true pretty-formats the JSON with line breaks</param> /// <returns>true or false</returns> public static bool SerializeToFile(object value, string fileName, bool throwExceptions = false, bool formatJsonOutput = false) { dynamic writer = null; FileStream fs = null; try { Type type = value.GetType(); var json = CreateJsonNet(throwExceptions); if (json == null) return false; fs = new FileStream(fileName, FileMode.Create); var sw = new StreamWriter(fs, Encoding.UTF8); writer = Activator.CreateInstance(JsonTextWriterType, sw); if (formatJsonOutput) writer.Formatting = (dynamic)Enum.Parse(FormattingType, "Indented"); writer.QuoteChar = '"'; json.Serialize(writer, value); } catch (Exception ex) { Debug.WriteLine("JsonSerializer Serialize error: " + ex.Message); if (throwExceptions) throw; return false; } finally { if (writer != null) writer.Close(); if (fs != null) fs.Close(); } return true; }You can see more of the dynamic invocation in this code. First I grab the dynamic JsonSerializer instance using the CreateJsonNet() method shown earlier which returns a dynamic. I then create a JsonTextWriter and configure a couple of enum settings on it, and then call Serialize() on the serializer instance with the JsonTextWriter that writes the output to disk. Although this code is dynamic it's still fairly short and readable.For full circle operation here's the DeserializeFromFile() version:/// <summary> /// Deserializes an object from file and returns a reference. /// </summary> /// <param name="fileName">name of the file to serialize to</param> /// <param name="objectType">The Type of the object. Use typeof(yourobject class)</param> /// <param name="binarySerialization">determines whether we use Xml or Binary serialization</param> /// <param name="throwExceptions">determines whether failure will throw rather than return null on failure</param> /// <returns>Instance of the deserialized object or null. Must be cast to your object type</returns> public static object DeserializeFromFile(string fileName, Type objectType, bool throwExceptions = false) { dynamic json = CreateJsonNet(throwExceptions); if (json == null) return null; object result = null; dynamic reader = null; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); var sr = new StreamReader(fs, Encoding.UTF8); reader = Activator.CreateInstance(JsonTextReaderType, sr); result = json.Deserialize(reader, objectType); reader.Close(); } catch (Exception ex) { Debug.WriteLine("JsonNetSerialization Deserialization Error: " + ex.Message); if (throwExceptions) throw; return null; } finally { if (reader != null) reader.Close(); if (fs != null) fs.Close(); } return result; }This code is a little more compact since there are no prettifying options to set. Here JsonTextReader is created dynamically and it receives the output from the Deserialize() operation on the serializer.You can take a look at the full JsonSerializationUtils.cs file on GitHub to see the rest of the operations, but the string operations are very similar - the code is fairly repetitive.These generic serialization utilities isolate the dynamic serialization logic that has to deal with the dynamic nature of JSON.NET, and any code that uses these functions is none the wiser that JSON.NET is dynamically loaded.Using the JsonSerializationUtils WrapperThe final consumer of the SerializationUtils wrapper is an actual ConfigurationProvider, that is responsible for handling reading and writing JSON values to and from files. The provider is simple a small wrapper around the SerializationUtils component and there's very little code to make this work now:The whole provider looks like this:/// <summary> /// Reads and Writes configuration settings in .NET config files and /// sections. Allows reading and writing to default or external files /// and specification of the configuration section that settings are /// applied to. /// </summary> public class JsonFileConfigurationProvider<TAppConfiguration> : ConfigurationProviderBase<TAppConfiguration> where TAppConfiguration: AppConfiguration, new() { /// <summary> /// Optional - the Configuration file where configuration settings are /// stored in. If not specified uses the default Configuration Manager /// and its default store. /// </summary> public string JsonConfigurationFile { get { return _JsonConfigurationFile; } set { _JsonConfigurationFile = value; } } private string _JsonConfigurationFile = string.Empty; public override bool Read(AppConfiguration config) { var newConfig = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfiguration)) as TAppConfiguration; if (newConfig == null) { if(Write(config)) return true; return false; } DecryptFields(newConfig); DataUtils.CopyObjectData(newConfig, config, "Provider,ErrorMessage"); return true; } /// <summary> /// Return /// </summary> /// <typeparam name="TAppConfig"></typeparam> /// <returns></returns> public override TAppConfig Read<TAppConfig>() { var result = JsonSerializationUtils.DeserializeFromFile(JsonConfigurationFile, typeof(TAppConfig)) as TAppConfig; if (result != null) DecryptFields(result); return result; } /// <summary> /// Write configuration to XmlConfigurationFile location /// </summary> /// <param name="config"></param> /// <returns></returns> public override bool Write(AppConfiguration config) { EncryptFields(config); bool result = JsonSerializationUtils.SerializeToFile(config, JsonConfigurationFile,false,true); // Have to decrypt again to make sure the properties are readable afterwards DecryptFields(config); return result; } }This incidentally demonstrates how easy it is to create a new provider for the West Wind Application Configuration component. Simply implementing 3 methods will do in most cases.Note this code doesn't have any dynamic dependencies - all that's abstracted away in the JsonSerializationUtils(). From here on, serializing JSON is just a matter of calling the static methods on the SerializationUtils class.Already, there are several other places in some other tools where I use JSON serialization this is coming in very handy. With a couple of lines of code I was able to add JSON.NET support to an older AJAX library that I use replacing quite a bit of code that was previously in use. And for any other manual JSON operations (in a couple of apps I use JSON Serialization for 'blob' like document storage) this is also going to be handy.Performance?Some of you might be thinking that using dynamic and Reflection can't be good for performance. And you'd be right… In performing some informal testing it looks like the performance of the native code is nearly twice as fast as the dynamic code. Most of the slowness is attributable to type lookups. To test I created a native class that uses an actual reference to JSON.NET and performance was consistently around 85-90% faster with the referenced code. This will change though depending on the size of objects serialized - the larger the object the more processing time is spent inside the actual dynamically activated components and the less difference there will be. Dynamic code is always slower, but how much it really affects your application primarily depends on how frequently the dynamic code is called in relation to the non-dynamic code executing. In most situations where dynamic code is used 'to get the process rolling' as I do here the overhead is small enough to not matter.All that being said though - I serialized 10,000 objects in 80ms vs. 45ms so this is hardly slouchy performance. For the configuration component speed is not that important because both read and write operations typically happen once on first access and then every once in a while. But for other operations - say a serializer trying to handle AJAX requests on a Web Server one would be well served to create a hard dependency.Dynamic Loading - Worth it?Dynamic loading is not something you need to worry about but on occasion dynamic loading makes sense. But there's a price to be paid in added code  and a performance hit which depends on how frequently the dynamic code is accessed. But for some operations that are not pivotal to a component or application and are only used under certain circumstances dynamic loading can be beneficial to avoid having to ship extra files adding dependencies and loading down distributions. These days when you create new projects in Visual Studio with 30 assemblies before you even add your own code, trying to keep file counts under control seems like a good idea. It's not the kind of thing you do on a regular basis, but when needed it can be a useful option in your toolset… © Rick Strahl, West Wind Technologies, 2005-2013Posted in .NET  C#   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • my asp.net mvc 2.0 application fails with error "No parameterless constructor defined for this objec

    - by loviji
    Hello, i'm new in asp.net mvc 2. I'm trying to list all data from one table(ms sql server table). as ORM I use Entity Framework. now, I'm tried to write something to do this: Model: private uqsEntities _uqsEntity; public permissionRepository(uqsEntities uqsEntity) { _uqsEntity = uqsEntity; } public IEnumerable<userPermissions> getAllData() { return _uqsEntity.userPermissions; } controller: private DataManager _dataManager; public ManagePermissionsController(DataManager datamanager) { _dataManager = datamanager; } public ActionResult Index() { return RedirectToAction("List"); } [AcceptVerbs(HttpVerbs.Get)] public ActionResult List() { return List(null); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult List(int? userID) { return View(_dataManager.Permission.getAllData().ToList()); } Route: routes.MapRoute( "ManagePerm", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "ManagePermissions", action = "Index"}, new string[] { "uqs.Controllers" } // Parameter defaults ); and View automatically generated by Visual Studio(in action mouse right-click). when I run app. , my app. fails. No parameterless constructor defined for this object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MissingMethodException: No parameterless constructor defined for this object. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [MissingMethodException: No parameterless constructor defined for this object.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230 System.Activator.CreateInstance(Type type, Boolean nonPublic) +67 System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80 [InvalidOperationException: An error occurred when trying to create a controller of type 'uqs.Controllers.ManagePermissionsController'. Make sure that the controller has a parameterless public constructor.] System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +190 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +68 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +118 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +46 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +63 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +13 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8679186 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 please, somebody, help me to catch problem.

    Read the article

  • override GetControllerInstance in asp.NET MVC 2

    - by loviji
    I have a code in asp.net MVC v.1: protected override IController GetControllerInstance(Type controllerType) { string connectionString = ConfigurationManager.ConnectionStrings["someEntities"].ConnectionString; return Activator.CreateInstance(controllerType, new DataManager(connectionString)) as IController; } now I use asp.net mvc v.2. And I know that, now GetController implemented as public virtual IController CreateController(RequestContext requestContext, string controllerName); How can return old functionality of upper code?

    Read the article

  • How can I load style resources from a dynamically loaded Silverlight application (XAP)?

    - by Tom
    I've followed Tim Heuer's video for dynamically loading other XAP's (into a 'master' Silverlight application), as well as some other links to tweak the loading of resources and am stuck on the particular issue of loading style resources from within the dynamically loaded XAP (i.e. the contents of Assets\Styles.xaml). When I run the master/hosting applcation, it successfully streams the dynamic XAP and I can read the deployment info etc. and load the assembly parts. However, when I actuall try to create an instance of a form from the Dynamic XAP, it fails with Cannot find a Resource with the Name/Key LayoutRootGridStyle which is in it's Assets\Styles.xaml file (it works if I run it directly so I know it's OK). For some reason these don't show up as application resources - not sure if I've totally got the wrong end of the stick, or am just missing something? Code snippet below (apologies it's a bit messy - just trying to get it working first) ... '' # Here's the code that reads the dynamic XAP from the web server ... '' #... wCli = New WebClient AddHandler wCli.OpenReadCompleted, AddressOf OpenXAPCompleted wCli.OpenReadAsync(New Uri("MyTest.xap", UriKind.Relative)) '' #... '' #Here's the sub that's called when openread is completed '' #... Private Sub OpenXAPCompleted(ByVal sender As Object, ByVal e As System.Net.OpenReadCompletedEventArgs) Dim sManifest As String = New StreamReader(Application.GetResourceStream(New StreamResourceInfo(e.Result, Nothing), New Uri("AppManifest.xaml", UriKind.Relative)).Stream).ReadToEnd Dim deploymentRoot As XElement = XDocument.Parse(sManifest).Root Dim deploymentParts As List(Of XElement) = _ (From assemblyParts In deploymentRoot.Elements().Elements() Select assemblyParts).ToList() Dim oAssembly As Assembly = Nothing For Each xElement As XElement In deploymentParts Dim asmPart As AssemblyPart = New AssemblyPart() Dim source As String = xElement.Attribute("Source").Value Dim sInfo As StreamResourceInfo = Application.GetResourceStream(New StreamResourceInfo(e.Result, "application/binary"), New Uri(source, UriKind.Relative)) If source = "MyTest.dll" Then oAssembly = asmPart.Load(sInfo.Stream) Else asmPart.Load(sInfo.Stream) End If Next Dim t As Type() = oAssembly.GetTypes() Dim AppClass = (From parts In t Where parts.FullName.EndsWith(".App") Select parts).SingleOrDefault() Dim mykeys As Array If Not AppClass Is Nothing Then Dim a As Application = DirectCast(oAssembly.CreateInstance(AppClass.FullName), Application) For Each strKey As String In a.Resources.Keys If Not Application.Current.Resources.Contains(strKey) Then Application.Current.Resources.Add(strKey, a.Resources(strKey)) End If Next End If Dim objectType As Type = oAssembly.GetType("MyTest.MainPage") Dim ouiel = Activator.CreateInstance(objectType) Dim myData As UIElement = DirectCast(ouiel, UIElement) Me.splMain.Children.Add(myData) Me.splMain.UpdateLayout() End Sub '' #... '' # And here's the line that fails with "Cannot find a Resource with the Name/Key LayoutRootGridStyle" '' # ... System.Windows.Application.LoadComponent(Me, New System.Uri("/MyTest;component/MainPage.xaml", System.UriKind.Relative)) '' #... any thoughts?

    Read the article

  • Is there any documentation on IdentityUnmarshal interface?

    - by sharptooth
    Whenever I put my component into COM+ and call CoCreateInstance() on the client the following happens: the runtime instantiates the objecs (calls IClassFactory::CreateInstance()) the runtime calls QueryInterface() for the interface specified in teh CoCreateInstance() call the runtime calls QueryInterface() for IdentityUnmarshal interface ({0000001b-0000-0000-c000-000000000046}) The only thing I can find is the declaration in comdef.h that there exists IdentityUnmarshal interface with that interface id. Is there any more information on it?

    Read the article

  • Weird result comparing property values using reflection

    - by Brian
    Can someone explain why this is occurring? The code below was executed in the immediate window in vs2008. The prop is an Int32 property (id column) on an object created by the entity framework. The objects entity and defaultEntity were created using Activator.CreateInstance(); Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) == Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) false

    Read the article

  • Where is this System.MissingMethodException occurring? How can I tell?

    - by Jeremy Holovacs
    I am a newbie to ASP.NET MVC (v2), and I am trying to use a strongly-typed view tied to a model object that contains two optional multi-select listbox objects. Upon clicking the submit button, these objects may have 0 or more values selected for them. My model class looks like this: using System; using System.Web.Mvc; using System.Collections.Generic; namespace ModelClasses.Messages { public class ComposeMessage { public bool is_html { get; set; } public bool is_urgent { get; set; } public string message_subject { get; set; } public string message_text { get; set; } public string action { get; set; } public MultiSelectList recipients { get; set; } public MultiSelectList recipient_roles { get; set; } public ComposeMessage() { this.is_html = false; this.is_urgent = false; this.recipients = new MultiSelectList(new Dictionary<int, string>(), "Key", "Value"); this.recipient_roles = new MultiSelectList(new Dictionary<int, string>(), "Key", "Value"); } } } My view looks like this: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ModelClasses.Messages.ComposeMessage>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Compose A Message </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2> Compose A New Message:</h2> <br /> <span id="navigation_top"> <%= Html.ActionLink("\\Home", "Index", "Home") %><%= Html.ActionLink("\\Messages", "Home") %></span> <% using (Html.BeginForm()) { %> <fieldset> <legend>Message Headers</legend> <label for="message_subject"> Subject:</label> <%= Html.TextBox("message_subject")%> <%= Html.ValidationMessage("message_subject")%> <label for="selected_recipients"> Recipient Users:</label> <%= Html.ListBox("recipients") %> <%= Html.ValidationMessage("selected_recipients")%> <label for="selected_recipient_roles"> Recipient Roles:</label> <%= Html.ListBox("recipient_roles") %> <%= Html.ValidationMessage("selected_recipient_roles")%> <label for="is_urgent"> Urgent?</label> <%= Html.CheckBox("is_urgent") %> <%= Html.ValidationMessage("is_urgent")%> </fieldset> <fieldset> <legend>Message Text</legend> <%= Html.TextArea("message_text") %> <%= Html.ValidationMessage("message_text")%> </fieldset> <input type="reset" name="reset" id="reset" value="Reset" /> <input type="submit" name="action" id="send_message" value="Send" /> <% } %> <span id="navigation_bottom"> <%= Html.ActionLink("\\Home", "Index", "Home") %><%= Html.ActionLink("\\Messages", "Home") %></span> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="Scripts" runat="server"> </asp:Content> I have a parameterless ActionResult in my MessagesController like this: [Authorize] public ActionResult ComposeMessage() { ModelClasses.Messages.ComposeMessage FormData = new ModelClasses.Messages.ComposeMessage(); Common C = (Common)Session["Common"]; FormData.recipients = new MultiSelectList(C.AvailableUsers, "Key", "Value"); FormData.recipient_roles = new MultiSelectList(C.AvailableRoles, "Key", "Value"); return View(FormData); } ...and my model-based controller looks like this: [Authorize, AcceptVerbs(HttpVerbs.Post)] public ActionResult ComposeMessage(DCASS3.Classes.Messages.ComposeMessage FormData) { DCASSUser CurrentUser = (DCASSUser)Session["CurrentUser"]; Common C = (Common)Session["Common"]; //... (business logic) return View(FormData); } Problem is, I can access the page fine before a submit. When I actually make selections and press the submit button, however, I get: Server Error in '/' Application. No parameterless constructor defined for this object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.MissingMethodException: No parameterless constructor defined for this object. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [MissingMethodException: No parameterless constructor defined for this object.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86 System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230 System.Activator.CreateInstance(Type type, Boolean nonPublic) +67 System.Activator.CreateInstance(Type type) +6 System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +307 System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +495 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +473 System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +642 System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +144 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +95 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2386 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +539 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +447 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +173 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +801 System.Web.Mvc.Controller.ExecuteCore() +151 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +105 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +36 System.Web.Mvc.<c_DisplayClass8.b_4() +65 System.Web.Mvc.Async.<c_DisplayClass1.b_0() +44 System.Web.Mvc.Async.<c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +42 System.Web.Mvc.Async.WrappedAsyncResult1.End() +140 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +36 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8677678 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3082 This error shows up before I can trap it. I have no idea where it's choking, or what it's choking on. I don't see any point of this model that cannot be created with a parameterless constructor, and I can't find out where it's dying... Help is appreciated, thanks. -Jeremy

    Read the article

  • override GetControllerInstance in MVC

    - by loviji
    I have a code in asp.net MVC v.1: protected override IController GetControllerInstance(HttpContext null , Type controllerType) { string connectionString = ConfigurationManager.ConnectionStrings["someEntities"].ConnectionString; return Activator.CreateInstance(controllerType, new DataManager(connectionString)) as IController; } now I use asp.net mvc v.2. And I know that, now GetController implemented as public virtual IController CreateController(RequestContext requestContext, string controllerName); How can return old functionality of upper code?

    Read the article

  • How to get MinValue/MaxValue of a certain ValueType via reflection?

    - by marco.ragogna
    I need to this at runtime. I checked using Reflector and value types line like Int16, for example, should contain <Serializable, StructLayout(LayoutKind.Sequential), ComVisible(True)> _ Public Structure Int16 Implements IComparable, IFormattable, IConvertible, IComparable(Of Short), IEquatable(Of Short) Public Const MaxValue As Short = &H7FFF Public Const MinValue As Short = -32768 End Structure But the following code is not working Dim dummyValue = Activator.CreateInstance(GetType(UInt16)) Dim minValue As IComparable = DirectCast(dummyValue.GetType.GetProperty("MinValue").GetValue(dummyValue, Nothing), IComparable) any idea how to solve?

    Read the article

  • Member variable pointers to COM objects

    - by drelihan
    Hi Folks, Is there any problem with keeping member variable pointer refernces to COM objects and reussing the reference through out the class in C++. Is anybody aware of a reason why you would want to call .CreateInstance every time you wanted a to use the COM object i.e. you were getting a fresh instance each time. I cannot see any reason who you would want to do this, Thanks, (No is an acceptable answer!!!)

    Read the article

  • .Net Com Interop Create Instance Slow

    - by B Z
    I have a .net 4 application that uses a Com Dll to send SMS messages. I used TlbImp to create the interop assembly and that is what is referenced in the application. When I try to create an instance of this class, it takes a really long time (2-5 seconds). I ran performance profile in VS 2010 and the call that takes the longest by far is System.Activator.CreateInstance(). I am looking for tips on how to debug or gotchas with using Com Interop.

    Read the article

  • Can I Create A Generic Method of a Type of Interface?

    - by DaveDev
    Is it possible to create a generic method with a signature like public static string MyMethod<IMyTypeOfInterface>(object dataToPassToInterface) { // an instance of IMyTypeOfInterface knows how to handle // the data that is passed in } Would I have to instantiate the Interface with (T)Activator.CreateInstance();?

    Read the article

  • PHP cannot find .net assembly in the .net-4 GAC

    - by stacker
    <?php $console = new DOTNET("ProjectX.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=KeyTokenHere-i used a real value here", "ProjectX.Core.Services.ServicX"); echo '1'; ?> The error message: Fatal error: Uncaught exception 'com_exception' with message 'Failed to instantiate .Net object [CreateInstance] [0x80070002] The system cannot find the file specified. What's the problem can be?

    Read the article

  • C# DLL Deployed in COM+. Error while accessing the methods.

    - by Dakshinamurthy
    I have the C# Dll (ABService) deployed in COM + and my os Is windows 2008. I have given the strong name for this dll and its dependent dll’s When I access the method of this dll through localhost or if I add the reference to the client project the method are executed successfully. Simply if I access the dll from the same machine with the reference it is working. So I think there is no problem with the way I deployed in the COM +. I have the doubt whether I have the problem in OS and Visual Studio 2008 combination. I have built all the dll with the Visual Studio 2008 with Target cpu as x86 and targert framework as 2.0. I have given in below the codes I have tried with and the errors. I need to create the object for the dll in server machine(64 bit) and access its method from the client(32 bit) Code : Type svr = Type.GetTypeFromProgID("ABService.Service", strserver1url[2],false); ABService.Service service1= (ABService.Service)Activator.CreateInstance(svr); strresult = service1.ExecuteService(orequest.xml); Error :{"Retrieving the COM class factory for remote component with CLSID {77BF00E0-41AC-3967-9E72-A4927CC0B880} from machine 10.105.138.64 failed due to the following error: 80040154."} Code Type svr = Type.GetTypeFromProgID("ABService.Service", strserver1url[2],true); object Service1 = null; Service1 = (ABService.Service)Activator.CreateInstance(svr, true); strresult = Convert.ToString(ReflectionHelper.Invoke(Service1, "ExecuteService", new object[] { orequest.xml })); Service1 = null; Error: Retrieving the COM class factory for remote component with CLSID {77BF00E0-41AC-3967-9E72-A4927CC0B880} from machine ftpsite failed due to the following error: 80040154. With the below code instead of C#.Net dll if i have the vb dll in Com + the method is executed successfully. Code ords = new RDS.DataSpace(); ords.InternetTimeout = 600000; object M_Service = null; ABService.Service oabservice = null; M_Service = ords.CreateObject("ABService.Service",url); strresult = Convert.ToString(ReflectionHelper.Invoke(M_Service, "ExecuteService", new object[] { orequest.xml })); Error : {"Object doesn't support this property or method 'ExecuteService'"} Code object obj=Interaction.CreateObject("ABService.Service", "10.105.138.64"); strresult = Convert.ToString(ReflectionHelper.Invoke(obj, "ExecuteService", new object[] { orequest.xml })); Error: {"Cannot create ActiveX component."} Code object obj = Activator.GetObject(typeof(ABService.Service), @"http://10.105.138.64:80/ABANET"); strresult = Convert.ToString(ReflectionHelper.Invoke(obj, "ExecuteService", new object[] { orequest.xml })); Error: InnerException {"The remote server returned an error: (405) Method Not Allowed."} System.Exception {System.Net.WebException} Message "Exception has been thrown by the target of an invocation.”

    Read the article

  • Need to cast to an object without knowing what type the object is

    - by jle
    I am trying to dynamically load my authentication server type based on a setting. I am hung up on how to cast to a type when I don't know the type. Type t = Type.GetType(WebConfigurationManager.AppSettings.Get("AuthenticationSvcImpl")); IAuthenticationService authCli = Activator.CreateInstance(t); return authCli.AuthenticateUser(login); I know there is Convert.ChangeType(), but that just converts to an object...

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >