Search Results

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

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

  • VB .Net - Reflection: Reflected Method from a loaded Assembly executes before calling method. Why?

    - by pu.griffin
    When I am loading an Assembly dynamically, then calling a method from it, I appear to be getting the method from Assembly executing before the code in the method that is calling it. It does not appear to be executing in a Serial manner as I would expect. Can anyone shine some light on why this might be happening. Below is some code to illustrate what I am seeing, the code from the some.dll assembly calls a method named PerformLookup. For testing I put a similar MessageBox type output with "PerformLookup Time: " as the text. What I end up seeing is: First: "PerformLookup Time: 40:842" Second: "initIndex Time: 45:873" Imports System Imports System.Data Imports System.IO Imports Microsoft.VisualBasic.Strings Imports System.Reflection Public Class Class1 Public Function initIndex(indexTable as System.Collections.Hashtable) As System.Data.DataSet Dim writeCode As String MessageBox.Show("initIndex Time: " & Date.Now.Second.ToString() & ":" & Date.Now.Millisecond.ToString()) System.Threading.Thread.Sleep(5000) writeCode = RefreshList() End Function Public Function RefreshList() As String Dim asm As System.Reflection.Assembly Dim t As Type() Dim ty As Type Dim m As MethodInfo() Dim mm As MethodInfo Dim retString as String retString = "" Try asm = System.Reflection.Assembly.LoadFrom("C:\Program Files\some.dll") t = asm.GetTypes() ty = asm.GetType(t(28).FullName) 'known class location m = ty.GetMethods() mm = ty.GetMethod("PerformLookup") Dim o as Object o = Activator.CreateInstance(ty) Dim oo as Object() retString = mm.Invoke(o,Nothing).ToString() Catch Ex As Exception End Try return retString End Function End Class

    Read the article

  • How can I create a WebBrowser control (ActiveX / IWebBrowser2) without a UI?

    - by wangminhere
    I cannot figure out how to use the WebBrowser control without having it create a window in the taskbar. I am using the IWebBrowser2 ActiveX control directly because I need to use some of the advanced features like blocking downloading JAVA/ActiveX/images etc. That apparently is not available in the WPF or winforms WebBrowser wrappers (but these wrappers do have the ability to create the control with no UI) Here is my code for creating the control: Type webbrowsertype = Type.GetTypeFromCLSID(Iid_Clsids.CLSID_WebBrowser, true); m_WBWebBrowser2 = (IWebBrowser2)System.Activator.CreateInstance(webbrowsertype); m_WBWebBrowser2.Visible = false; m_WBOleObject = (IOleObject)m_WBWebBrowser2; int iret = m_WBOleObject.SetClientSite(this); iret = m_WBOleObject.SetHostNames("me", string.Empty); tagRECT rect = new tagRECT(0, 0, 0, 0); tagMSG nullMsg = new tagMSG(); m_WBOleInPlaceObject = (IOleInPlaceObject)m_WBWebBrowser2; //INPLACEACTIVATE the WB iret = m_WBOleObject.DoVerb((int)OLEDOVERB.OLEIVERB_INPLACEACTIVATE, ref nullMsg, this, 0, IntPtr.Zero, ref rect); IConnectionPointContainer cpCont = (IConnectionPointContainer)m_WBWebBrowser2; Guid guid = typeof(DWebBrowserEvents2).GUID; IConnectionPoint m_WBConnectionPoint = null; cpCont.FindConnectionPoint(ref guid, out m_WBConnectionPoint); m_WBConnectionPoint.Advise(this, out m_dwCookie); This code works perfectly but it shows a window in the taskbar. If i omit the DoVerb(OLEDOVERB.OLEIVERB_INPLACEACTIVATE) call, then Navigating to a webpage is not working properly. Navigate() will not download everything on the page and it never fires the DocumentComplete event. If I add a DoVerb(OLEIVERB_HIDE) then I get the same behavior as if I omitted the DoVerb(OLEDOVERB.OLEIVERB_INPLACEACTIVATE) call. This seems like a pretty basic question but I couldn't find any examples anywhere.

    Read the article

  • Using Build Manager Class to Load ASPX Files and Populate its Controls

    - by Sandhurst
    I am using BuildManager Class to Load a dynamically generated ASPX File, please note that it does not have a corresponding .cs file. Using Following code I am able to load the aspx file, I am even able to loop through the control collection of the dynamically created aspx file, but when I am assigning values to controls they are not showing it up. for example if I am binding the value "Dummy" to TextBox control of the aspx page, the textbox remains empty. Here's the code that I am using protected void Page_Load(object sender, EventArgs e) { LoadPage("~/Demo.aspx"); } public static void LoadPage(string pagePath) { // get the compiled type of referenced path Type type = BuildManager.GetCompiledType(pagePath); // if type is null, could not determine page type if (type == null) throw new ApplicationException("Page " + pagePath + " not found"); // cast page object (could also cast an interface instance as well) // in this example, ASP220Page is a custom base page System.Web.UI.Page pageView = (System.Web.UI.Page)Activator.CreateInstance(type); // call page title pageView.Title = "Dynamically loaded page..."; // call custom property of ASP220Page //pageView.InternalControls.Add( // new LiteralControl("Served dynamically...")); // process the request with updated object ((IHttpHandler)pageView).ProcessRequest(HttpContext.Current); LoadDataInDynamicPage(pageView); } private static void LoadDataInDynamicPage(Page prvPage) { foreach (Control ctrl in prvPage.Controls) { //Find Form Control if (ctrl.ID != null) { if (ctrl.ID.Equals("form1")) { AllFormsClass cls = new AllFormsClass(); DataSet ds = cls.GetConditionalData("1"); foreach (Control ctr in ctrl.Controls) { if (ctr is TextBox) { if (ctr.ID.Contains("_M")) { TextBox drpControl = (TextBox)ctr; drpControl.Text = ds.Tables[0].Rows[0][ctr.ID].ToString(); } else if (ctr.ID.Contains("_O")) { TextBox drpControl = (TextBox)ctr; drpControl.Text = ds.Tables[1].Rows[0][ctr.ID].ToString(); } } } } } } }

    Read the article

  • error: expected constructor, destructor, or type conversion before '(' token

    - by jonathanasdf
    include/TestBullet.h:12: error: expected constructor, destructor, or type conver sion before '(' token I hate C++ error messages... lol ^^ Basically, I'm following what was written in this post to try to create a factory class for bullets so they can be instantiated from a string, which will be parsed from an xml file, because I don't want to have a function with a switch for all of the classes because that looks ugly. Here is my TestBullet.h: #pragma once #include "Bullet.h" #include "BulletFactory.h" class TestBullet : public Bullet { public: void init(BulletData& bulletData); void update(); }; REGISTER_BULLET(TestBullet); <-- line 12 And my BulletFactory.h: #pragma once #include <string> #include <map> #include "Bullet.h" #define REGISTER_BULLET(NAME) BulletFactory::reg<NAME>(#NAME) #define REGISTER_BULLET_ALT(NAME, CLASS) BulletFactory::reg<CLASS>(NAME) template<typename T> Bullet * create() { return new T; } struct BulletFactory { typedef std::map<std::string, Bullet*(*)()> bulletMapType; static bulletMapType map; static Bullet * createInstance(char* s) { std::string str(s); bulletMapType::iterator it = map.find(str); if(it == map.end()) return 0; return it->second(); } template<typename T> static void reg(std::string& s) { map.insert(std::make_pair(s, &create<T>)); } }; Thanks in advance.

    Read the article

  • help with Firefox extension

    - by Johnny Grass
    I'm writing a Firefox extension that creates a socket server which will output the active tab's URL when a client makes a connection to it. I have the following code in my javascript file: var serverSocket; function startServer() { var listener = { onSocketAccepted : function(socket, transport) { try { var outputString = gBrowser.currentURI.spec + "\n"; var stream = transport.openOutputStream(0,0,0); stream.write(outputString,outputString.length); stream.close(); } catch(ex2){ dump("::"+ex2); } }, onStopListening : function(socket, status){} }; try { serverSocket = Components.classes["@mozilla.org/network/server-socket;1"] .createInstance(Components.interfaces.nsIServerSocket); serverSocket.init(7055,true,-1); serverSocket.asyncListen(listener); } catch(ex){ dump(ex); } document.getElementById("status").value = "Started"; } startServer(); As it is, it works for multiple tabs in a single window. If I open multiple windows, it ignores the additional windows. I think it is creating a server socket for each window, but since they are using the same port, the additional sockets fail to initialize. I need it to create a server socket when the browser launches and continue running when I close the windows (Mac OS X). As it is, when I close a window but Firefox remains running, the socket closes and I have to restart firefox to get it up an running. How do I go about that?

    Read the article

  • Changing save directory

    - by Nathan
    Disregard my previous pre-edit post. Rethought what I needed to do. This is what I'm currently doing: https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIScriptableIO downloadFile: function(httpLoc) { try { //new obj_URI object var obj_URI = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService). newURI(httpLoc, null, null); //new file object //set file with path obj_TargetFile.initWithPath("C:\\javascript\\cache\\test.pdf"); //if file doesn't exist, create if(!obj_TargetFile.exists()) { obj_TargetFile.create(0x00,0644); } //new persitence object var obj_Persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]. createInstance(Ci.nsIWebBrowserPersist); // with persist flags if desired const nsIWBP = Ci.nsIWebBrowserPersist; const flags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES; obj_Persist.persistFlags = flags | nsIWBP.PERSIST_FLAGS_FROM_CACHE; //save file to target obj_Persist.saveURI(obj_URI,null,null,null,null,obj_TargetFile); return true; } catch (e) { alert(e); } },//end downloadFile As you can see the directory is hardcoded in there, I want to save the pdf file open in the active tab to a relative temporary directory, or anywhere that's out of the way enough that the user won't stumble along and delete it. I'm going to try that using File I/O, I was under the impression that what I was looking for was in scriptable file I/O and thus disabled.

    Read the article

  • C# reflection, cloning

    - by Enriquev
    Say I have this class Myclass that contains this method: public class MyClass { public int MyProperty { get; set; } public int MySecondProperty { get; set; } public MyOtherClass subClass { get; set; } public object clone<T>(object original, T emptyObj) { FieldInfo[] fis = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); object tempMyClass = Activator.CreateInstance(typeof(T)); foreach (FieldInfo fi in fis) { if (fi.FieldType.Namespace != original.GetType().Namespace) fi.SetValue(tempMyClass, fi.GetValue(original)); else fi.SetValue(tempMyClass, this.clone(fi.GetValue(original), fi.GetValue(original))); } return tempMyClass; } } Then this class: public class MyOtherClass { public int MyProperty777 { get; set; } } when I do this: MyClass a = new MyClass { MyProperty = 1, MySecondProperty = 2, subClass = new MyOtherClass() { MyProperty777 = -1 } }; MyClass b = a.clone(a, a) as MyClass; how come on the second call to clone, T is of type object and not of type MyOtherClass

    Read the article

  • WPF XAML references not resolved via myAssembly.GetReferencedAssemblies()

    - by WPF-it
    I have a WPF container application (with ContentControl host) and a containee application (UserControl). Both are oblivious of each other. Only one XML config file holds the string dllpath of the containee's DLL and full namespace name of the ViewModelClass inside the containee. A generic code in container resolves containee's assembly (Assembly.LoadFrom(dllpath)) and creates the viewmodel's instance using Activator.CreateInstance(vmType). when this viewmodel is hosted inside the ContentControl of the container, and relevant vierwmodel specific ResourceDictionary is added to ContentControl.Resources.MergedDictionaries of the content control of container, so the view loads fine. Now my containee has to host the WPF DataGrid using assembly reference of WPFToolkit.dll from my local C:\Lib folder. The Copy Local reference to the WPFToolkit.dll is added to the .csproj file of the containee's project and its only referred in the UserControl.XAML using its XAML namepsace. This way my bin\debug folder in my containee application, gets the WPFToolkit.dll copied. XAML: xmlns:Controls="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" <Controls:DataGrid ItemsSource="{Binding AssetList}" ... /> Issue: The moment the ViewModel (i.e. the containee's usercontrol) tries to load itself I get this error. "Cannot find type 'Microsoft.Windows.Controls.DataGrid'. The assembly used when compiling might be different than that used when loading and the type is missing." Hence I tried to load the referenced assemblies of the containee's assembly (myAssembly.GetReferencedAssemblies()) before the viewmodel is hosted. But WPFToolkit isnt there in that list of assemblies! Strange thing is I have another dll referred called Logger.dll in the containee codebase but this one is implemented using C# code behind. So I get its reference correctly resolved in myAssembly.GetReferencedAssemblies(). So does that mean BAML references of assemblies are never resolvable by GetReferencedAssemblies?

    Read the article

  • FluentValidation + s#arp

    - by csetzkorn
    Hi, Did someone implement something like this: http://www.jeremyskinner.co.uk/2010/02/22/using-fluentvalidation-with-an-ioc-container/ in s#arp? Thanks. Christian PS: Hi, I have made a start in using FluentValidation in S#arp. I have implemented a Validator factory: public class ResolveType { private static IWindsorContainer _windsorContainer; public static void Initialize(IWindsorContainer windsorContainer) { _windsorContainer = windsorContainer; } public static object Of(Type type) { return _windsorContainer.Resolve(type); } } public class CastleWindsorValidatorFactory : ValidatorFactoryBase { public override IValidator CreateInstance(Type validatorType) { return ResolveType.Of(validatorType) as IValidator; } } I think I will use services which can be used by the controllers etc.: public class UserValidator : AbstractValidator { private readonly IUserRepository UserRepository; public UserValidator(IUserRepository UserRepository) { Check.Require(UserRepository != null, "UserRepository may not be null"); this.UserRepository = UserRepository; RuleFor(user => user.Email).NotEmpty(); RuleFor(user => user.FirstName).NotEmpty(); RuleFor(user => user.LastName).NotEmpty(); } } public interface IUserService { User CreateUser(User User); } public class UserService : IUserService { private readonly IUserRepository UserRepository; private readonly UserValidator UserValidator; public UserService ( IUserRepository UserRepository ) { Check.Require(UserRepository != null, "UserRepository may not be null"); this.UserRepository = UserRepository; this.UserValidator = new UserValidator(UserRepository); } public User CreateUser(User User) { UserValidator.Validate(User); ... } } Instead of putting concrete validators in the service, I would like to use the above factory somehow. Where do I register it and how in s#arp (Global.asax)? I believe s#arp is geared towards the nhibernator validator. How do I deregister it? Thanks. Best wishes, Christian

    Read the article

  • JSON Twitter List in C#.net

    - by James
    Hi, My code is below. I am not able to extract the 'name' and 'query' lists from the JSON via a DataContracted Class (below) I have spent a long time trying to work this one out, and could really do with some help... My Json string: {"as_of":1266853488,"trends":{"2010-02-22 15:44:48":[{"name":"#nowplaying","query":"#nowplaying"},{"name":"#musicmonday","query":"#musicmonday"},{"name":"#WeGoTogetherLike","query":"#WeGoTogetherLike"},{"name":"#imcurious","query":"#imcurious"},{"name":"#mm","query":"#mm"},{"name":"#HumanoidCityTour","query":"#HumanoidCityTour"},{"name":"#awesomeindianthings","query":"#awesomeindianthings"},{"name":"#officeformac","query":"#officeformac"},{"name":"Justin Bieber","query":"\"Justin Bieber\""},{"name":"National Margarita","query":"\"National Margarita\""}]}} My code: WebClient wc = new WebClient(); wc.Credentials = new NetworkCredential(this.Auth.UserName, this.Auth.Password); string res = wc.DownloadString(new Uri(link)); //the download string gives me the above JSON string - no problems Trends trends = new Trends(); Trends obj = Deserialise<Trends>(res); private T Deserialise<T>(string json) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json))) { DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType()); obj = (T)serialiser.ReadObject(ms); ms.Close(); return obj; } } [DataContract] public class Trends { [DataMember(Name = "as_of")] public string AsOf { get; set; } //The As_OF value is returned - But how do I get the //multidimensional array of Names and Queries from the JSON here? }

    Read the article

  • Call to undefined function 'Encrypt' - Attempting to Link OMF Lib

    - by Changeling
    I created a DLL using Visual Studio 2005 VC++ and marked a function for export (for testing). I then took the .LIB file created, and ran it through the COFF2OMF converter program bundled with Borland C++ Builder 5 and it returns the following: C:\>coff2omf -v -lib:ms MACEncryption.lib MACEncryption2.lib COFF to OMF Converter Version 1.0.0.74 Copyright (c) 1999, 2000 Inprise Corporat ion Internal name Imported name ------------- ------------- ??0CMACEncryptionApp@@QAE@XZ ?Decrypt@CMACEncryptionApp@@QAEXXZ Encrypt Encrypt@0 I added the MACEncryption2.lib file to my C++ Builder 5 Project by going to Project-Add to Project.. and selecting the library. The application links, but it cannot find the Encrypt function that I am declaring for export as follows in the VC++ code: extern "C" __declspec(dllexport) BSTR* __stdcall Encrypt() { CoInitialize(NULL); EncryptionManager::_EncryptionManagerPtr pDotNetCOMPtr; HRESULT hRes = pDotNetCOMPtr.CreateInstance(EncryptionManager::CLSID_EncryptionManager); if (hRes == S_OK) { BSTR* str = new BSTR; BSTR filePath = (BSTR)"C:\\ICVER001.REQ"; BSTR encrypt = (BSTR)"\"test"; pDotNetCOMPtr->EncryptThirdPartyMessage(filePath, encrypt, str); return str; } return NULL; CoUninitialize (); } C++ Builder Code: __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { Encrypt(); } (Yes I know I am encapsulating another DLL.. I am doing this for a reason since Borland can't 'see' the .NET DLL definitions) Can anyone tell me what I am doing wrong so I can figure out why Builder cannot find the function Encrypt() ?

    Read the article

  • Discover generic types

    - by vittore
    Thanks @dtb for help, he advised really need piece of code for generic service locator static class Locator { private static class LocatorEntry<T> where T : ... { public static IDataManager<T> instance; } public static void Register<T>(IDataManager<T> instance) where T : ... { LocatorEntry<T>.instance = instance; } public static IDataManager<T> GetInstance<T>() where T : ... { return LocatorEntry<T>.instance; } } However in my previous version I used reflection on assembly to discover a hundred of DataManager's I want to write an method discover like the following void Discover() { var pManager = new ProtocolSQLDataManager(); Register(pManager); var rManager = new ResultSQLDataManager(); Register(rManager); var gType = typeof(ISQLDataAccessManager<>); foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { if (type.IsSubclassOf(gType) && !type.IsAbstract)) { var manager = Activator.CreateInstance(type); // put something here in order to make next line of code works Register<T>(manager); } } } How to cast type to appropriate type in order to make Register working( and call appropriate Register ?

    Read the article

  • How to debug/break in codedom compiled code

    - by Jason Coyne
    I have an application which loads up c# source files dynamically and runs them as plugins. When I am running the main application in debug mode, is it possible to debug into the dynamic assembly? Obviously setting breakpoints is problematic, since the source is not part of the original project, but should I be able to step into, or break on exceptions for the code? Is there a way to get codedom to generate PDBs for this or something? Here is the code I am using for dynamic compliation. CSharpCodeProvider codeProvider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }); //codeProvider. ICodeCompiler icc = codeProvider.CreateCompiler(); CompilerParameters parameters = new CompilerParameters(); parameters.GenerateExecutable = false; parameters.GenerateInMemory = true; parameters.CompilerOptions = string.Format("/lib:\"{0}\"", Application.StartupPath); parameters.ReferencedAssemblies.Add("System.dll"); parameters.ReferencedAssemblies.Add("System.Core.dll"); CompilerResults results = icc.CompileAssemblyFromSource(parameters, Source); DLL.CreateInstance(t.FullName, false, BindingFlags.Default, null, new object[] { engine }, null, null);

    Read the article

  • spring.net proxy factory with target type needs property virtual ?

    - by Vince
    Hi all, I'm creating spring.net proxy in code by using ProxyFactory object with ProxyTargetType to true to have a proxy on a non interfaced complex object. Proxying seems ok till i call a method on that object. The method references a public property and if this property is not virtual it's value is null. This doesn't happen if i use Spring.Aop.Framework.AutoProxy.InheritanceBasedAopConfigurer in spring config file but in this case i can't use this because spring context doesn't own this object. Is this normal to have such behavior or is there a tweak to perform what i want (proxying object virtual method without having to change properties virtual)? Note that i tried factory.AutoDetectInterfaces and factory.ProxyTargetAttributes values but doesn't help. My proxy creation code: public static T CreateMethodCallStatProxy<T>() { // Proxy factory ProxyFactory factory = new ProxyFactory(); factory.AddAdvice(new CallMonitorTrackerAdvice()); factory.ProxyTargetType = true; // Create instance factory.Target = Activator.CreateInstance<T>(); // Get proxy T proxiedClass = (T)factory.GetProxy(); return proxiedClass; } Thanks for your help

    Read the article

  • Windows Forms: Unable to Click to Focus a MaskedTextBox in a Non TopLevel Form

    - by Overhed
    Like the title says, I've got a Child form being shown with it's TopLevel property set to False and I am unable to click a MaskedTextBox control that it contains (in order to bring focus to it). I can bring focus to it by using TAB on the keyboard though. The child form contains other regular TextBox controls and these I can click to focus with no problems, although they also exhibit some odd behavior: for example if I've got a value in the Textbox and I try to drag-click from the end of the string to the beginning, nothing happens. In fact I can't use my mouse to move the cursor inside the TextBox's text at all (although they keyboard arrow keys work). I'm not too worried about the odd TextBox behavior, but why can't I activate my MaskedTextBox by clicking on it? Below is the code that shows the form: Dim newReportForm As New Form Dim formName As String Dim FullTypeName As String Dim FormInstanceType As Type formName = TreeView1.SelectedNode.Name FullTypeName = Application.ProductName & "." & formName FormInstanceType = Type.GetType(FullTypeName, True, True) newReportForm = CType(Activator.CreateInstance(FormInstanceType), Form) Try newReportForm.Top = CType(SplitContainer1.Panel2.Controls(0), Form).Top + 25 newReportForm.Left = CType(SplitContainer1.Panel2.Controls(0), Form).Left + 25 Catch End Try newReportForm.TopLevel = False newReportForm.Parent = SplitContainer1.Panel2 newReportForm.BringToFront() newReportForm.Show()

    Read the article

  • Looks like COM object is created, but JScript fails to get a reference

    - by damix911
    I'm using the following code to create a COM component that I have developed and registered. var mycom = new ActiveXObject("Mirabilis.ComponentServices.1"); mycom.SetFirstNumber(5); mycom.SetSecondNumber(3); The first line runs fine, while if I alter the ProgID (that is, the string passed to ActiveXObject) I get the message Automation server can't create object. This suggests that at least the basics of the registration mechanism are working properly. I integrated some logging calls into the DLL. When I run the script I get the proof into the log file that both this call to QueryInterface: STDAPI DllGetClassObject( const CLSID &clsid, const IID &iid, void **ppv) { ... CAddFactory *pAddFact = new CAddFactory; ... HRESULT hr = pAddFact->QueryInterface(iid, ppv); if (hr == S_OK) writeToLogFile("Class QueryInterface returned S_OK"); else writeToLogFile("Class QueryInterface failed"); return hr; ... } and this one: HRESULT __stdcall CAddFactory::CreateInstance( IUnknown *pUnknownOuter, const IID &iid, void **ppv) { ... CAddObj *pObject = new CAddObj; ... HRESULT hr = pObject->QueryInterface(iid, ppv); if (hr == S_OK) writeToLogFile("Object QueryInterface returned S_OK"); else writeToLogFile("Object QueryInterface failed"); return hr; ... } return S_OK. However, when JScript gets to line 3 of the script, I get the following error message: 'mycom' is null or not an object Why is this happening? It looks like JScript should be able to obtain a reference. Some attempts I made I tried to return S_FALSE from DllCanUnloadNow to be sure that the DLL will not be unloaded, just in case, but with no luck.

    Read the article

  • HTML file: add annotations through IHTMLDocument

    - by peterchen
    I need to add "annotations" to existing HTML documents - best in the form of string property values I can read & write by name. Apparently (to me), meta elements in the header seem to be the common way - i.e. adding/modifying elements like <head> <meta name="unique-id_property-name" content="property-value"/> ... </head> Question 1: Ist that "acceptable" / ok, or is there a better way to add meta data? I have a little previous experience with getting/mut(il)ating HTML contents through the document in an web browser control. For this task, I've already loaded the HTML document into a HTMLDocument object, but I'm not sure how to go on: // what I have IHTMLDocument2Ptr doc; doc.CreateInstance(__uuidof(HTMLDocument)); IPersistFile pf = doc; pf->Load(fileName, STGM_READ); // everything ok until here Questions 2: Should I be using anything else than HTMLDocument? Questions 3..N: How do I get the head element? How do I get the value of a meta element with a given name? How do I set the value of a meta element (adding the item if and only if it doesn't exist yet)? doc->all returns a collection of all tags, which I can enumerate even though count returns 0. I could scan that for head, then scan that for all meta where the name starts with a certain string, etc. - but this feels very clumsy.

    Read the article

  • Is a call to the following method considered late binding?

    - by AspOnMyNet
    1) Assume: • B1 defines methods virtualM() and nonvirtualM(), where former method is virtual while the latter is non-virtual • B2 derives from B1 • B2 overrides virtualM() • B2 is defined inside assembly A • Application app doesn’t have a reference to assembly A In the following code application app dynamically loads an assembly A, creates an instance of a type B2 and calls methods virtualM() and nonvirtualM(): Assembly a=Assembly.Load(“A”); Type t= a.GetType(“B2”); B1 a = ( B1 ) Activator.CreateInstance ( “t” ); a.virtualM(); a.nonvirtualM(); a) Is call to a.virtualM() considered early binding or late binding? b) I assume a call to a.nonvirtualM() is resolved during compilation time? 2) Does the term late binding refer only to looking up the target method at run time or does it also refer to creating an instance of given type at runtime? thanx EDIT: 1) A a=new A(); a.M(); As far as I know, it is not known at compile time where on the heap (thus at which memory address ) will instance a be created during runtime. Now, with early binding the function calls are replaced with memory addresses during compilation process. But how can compiler replace function call with memory address, if it doesn’t know where on the heap will object a be created during runtime ( here I’m assuming the address of method a.M will also be at same memory location as a )? 2) The method slot is determined at compile time I assume that by method slot you’re referring to the entry point in V-table?

    Read the article

  • XmlDeserializer to handle inline lists

    - by d1k_is
    Im looking at implementing a fix in an XmlDeserializer to allow for element lists without a specific containing element. The XmlDeserializer im basing off checks for a list object type but then it gets the container element im trying to figure out how to get around this and make it work both ways. enter code here var t = type.GetGenericArguments()[0]; var list = (IList)Activator.CreateInstance(type); var container = GetElementByName(root, prop.Name.AsNamespaced(Namespace)); var first = container.Elements().FirstOrDefault(); var elements = container.Elements().Where(d => d.Name == first.Name); PopulateListFromElements(t, elements, list); prop.SetValue(x, list, null); The XML im working with is from the google weather API (forecast_conditions elements) <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0"> <forecast_information>...</forecast_information> <current_conditions>...</current_conditions> <forecast_conditions>...</forecast_conditions> <forecast_conditions>...</forecast_conditions> <forecast_conditions>...</forecast_conditions> </weather> EDIT: Im looking at this as an update to the RESTsharp open source .net library

    Read the article

  • Execute binary from memory in C# .net with binary protected from a 3rd party software

    - by NoobTom
    i've the following scenario: i've a C# application.exe i pack application.exe inside TheMida, a software anti-piracy/reverse engineering. i encrypt application.exe with aes256. (i wrote my own aes encryption/decryption and it is working) Now, when i want to execute my application i do the following: decrypt application.exe in memory execute the application.exe with the following code: BinaryReader br = new BinaryReader(decOutput); byte[] bin = br.ReadBytes(Convert.ToInt32(decOutput.Length)); decOutput.Close(); br.Close(); // load the bytes into Assembly Assembly a = Assembly.Load(bin); // search for the Entry Point MethodInfo method = a.EntryPoint; if (method != null) { // create an istance of the Startup form Main method object o = a.CreateInstance(method.Name); // invoke the application starting point method.Invoke(o, null); the application does not execute correctly. Now, the problem i think, is that this method is only to execute .NET executable. Since i packed my application.exe inside TheMida this does not work. Is there a workaround to this situation? Any suggestion? Thank you in advance.

    Read the article

  • Do COM Dll References Require Manual Disposal? If so, How?

    - by Drew
    I have written some code in VB that verifies that a particular port in the Windows Firewall is open, and opens one otherwise. The code uses references to three COM DLLs. I wrote a WindowsFirewall class, which Imports the primary namespace defined by the DLLs. Within members of the WindowsFirewall class I construct some of the types defined by the DLLs referenced. The following code isn't the entire class, but demonstrates what I am doing. Imports NetFwTypeLib Public Class WindowsFirewall Public Shared Function IsFirewallEnabled as Boolean Dim icfMgr As INetFwMgr icfMgr = CType(System.Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")), INetFwMgr) Dim profile As INetFwProfile profile = icfMgr.LocalPolicy.CurrentProfile Dim fIsFirewallEnabled as Boolean fIsFirewallEnabled = profile.FirewallEnabled return fIsFirewallEnabled End Function End Class I do not reference COM DLLs very often. I have read that unmanaged code may not be cleaned up by the garbage collector and I would like to know how to make sure that I have not introduced any memory leaks. Please tell me (a) if I have introduced a memory leak, and (b) how I may clean it up. (My theory is that the icfMgr and profile objects do allocate memory that remains unreleased until after the application closes. I am hopeful that setting their references equal to nothing will mark them for garbage collection, since I can find no other way to dispose of them. Neither one implements IDisposable, and neither contains a Finalize method. I suspect they may not even be relevant here, and that both of those methods of releasing memory only apply to .Net types.)

    Read the article

  • How to create an instance of object with RTTI in Delphi 2010?

    - by Paul
    As we all known, when we call a constructor of a class like this: instance := TSomeClass.Create; The Delphi compiler actually do the following things: Call the static NewInstance method to allocate memory and initialize the memory layout. Call the constructor method to perform the initialization of the class Call the AfterConstruction method It's simple and easy to understand. but I'm not very sure how the compiler handle exceptions in the second and the third step. It seems there are no explicit way to create an instance using a RTTI constructor method in D2010. so I wrote a simple function in the Spring Framework for Delphi to reproduce the process of the creation. class function TActivator.CreateInstance(instanceType: TRttiInstanceType; constructorMethod: TRttiMethod; const arguments: array of TValue): TObject; var classType: TClass; begin TArgument.CheckNotNull(instanceType, 'instanceType'); TArgument.CheckNotNull(constructorMethod, 'constructorMethod'); classType := instanceType.MetaclassType; Result := classType.NewInstance; try constructorMethod.Invoke(Result, arguments); except on Exception do begin if Result is TInterfacedObject then begin Dec(TInterfacedObjectHack(Result).FRefCount); end; Result.Free; raise; end; end; try Result.AfterConstruction; except on Exception do begin Result.Free; raise; end; end; end; I feel it maybe not 100% right. so please show me the way. Thanks!

    Read the article

  • Dynamically Run IQueryable Method

    - by Micah
    Hi! I'm trying to run the Count() function of a Linq statement in an overriden Gridview function. Basically, I want to be able to assign a linq query to a gridview, and on the OnDataBound(e) event in my new extended gridview have it retrieve the count, using the IQueryable. This is where I'm at so far: protected override void OnDataBound(EventArgs e) { IEnumerable _data = null; if (this.DataSource is IQueryable) { _data = (IQueryable)this.DataSource; } System.Type dataSourceType = _data.GetType(); System.Type dataItemType = typeof(object); if (dataSourceType.HasElementType) { dataItemType = dataSourceType.GetElementType(); } else if (dataSourceType.IsGenericType) { dataItemType = dataSourceType.GetGenericArguments()[0]; } else if (_data is IEnumerable) { IEnumerator dataEnumerator = _data.GetEnumerator(); if (dataEnumerator.MoveNext() && dataEnumerator.Current != null) { dataItemType = dataEnumerator.Current.GetType(); } } Object o = Activator.CreateInstance(dataItemType); object[] objArray = new object[] { o }; RowCount = (int)dataSourceType.GetMethod("Count").Invoke(_data, objArray); Any ideas? I'm really new with working with IQueryables and Linq so I may be way off. How can I get my _data to allow me to run the Count function?

    Read the article

  • Dynamically cast a control type in runtime

    - by JayT
    Hello, I have an application whereby I dynamically create controls on a form from a database. This works well, but my problem is the following: private Type activeControlType; private void addControl(ContainerControl inputControl, string ControlName, string Namespace, string ControlDisplayText, DataRow drow, string cntrlName) { Assembly assem; Type myType = Type.GetType(ControlName + ", " + Namespace); assem = Assembly.GetAssembly(myType); Type controlType = assem.GetType(ControlName); object obj = Activator.CreateInstance(controlType); Control tb = (Control)obj; tb.Click += new EventHandler(Cntrl_Click); inputControl.Controls.Add(tb); activeControlType = controlType; } private void Cntrl_Click(object sender, EventArgs e) { string test = ((activeControlType)sender).Text; //Problem ??? } How do I dynamically cast the sender object to a class that I can reference the property fields of it. I have googled, and found myself trying everything I have come across..... Now I am extremely confused... and in need of some help Thnx JT

    Read the article

  • Using reflection to find all linq2sql tables and ensure they match the database

    - by Jake Stevenson
    I'm trying to use reflection to automatically test that all my linq2sql entities match the test database. I thought I'd do this by getting all the classes that inherit from DataContext from my assembly: var contexttypes = Assembly.GetAssembly(typeof (BaseRepository<,>)).GetTypes().Where( t => t.IsSubclassOf(typeof(DataContext))); foreach (var contexttype in contexttypes) { var context = Activator.CreateInstance(contexttype); var tableProperties = type.GetProperties().Where(t=> t.PropertyType.Name == typeof(ITable<>).Name); foreach (var propertyInfo in tableProperties) { var table = (propertyInfo.GetValue(context, null)); } } So far so good, this loops through each ITable< in each datacontext in the project. If I debug the code, "table" is properly instantiated, and if I expand the results view in the debugger I can see actual data. BUT, I can't figure out how to get my code to actually query that table. I'd really like to just be able to do table.FirstOrDefault() to get the top row out of each table and make sure the SQL fetch doesn't fail. But I cant cast that table to be anything I can query. Any suggestions on how I can make this queryable? Just the ability to call .Count() would be enough for me to ensure the entities don't have anything that doesn't match the table columns.

    Read the article

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