Search Results

Search found 114 results on 5 pages for 'invalidcastexception'.

Page 3/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • ASP.NET Binding integer to CheckBox's Checked field

    - by Sung Meister
    I have a following ListView item template, in which I am trying to bind integer value to Checked property of CheckBox. IsUploaded value contains only 0 and 1... <asp:ListView ID="trustListView" runat="server"> <ItemTemplate> <asp:CheckBox ID="isUploadedCheckBox" runat="server" Checked='<%# Bind("IsUploaded") %>' /> </ItemTemplate> </asp:ListView> But ASP.NET complains that Exception Details: System.InvalidCastException: Sepcified cast is not valid Even though following code using DataBinder.Eval() works, I need to have a 2-way binding, thus need to use Bind(). <asp:CheckBox ID="isUploadedCheckBox2" runat="server" Checked='<%# Convert.ToBoolean( DataBinder.Eval(Container.DataItem, "IsUploaded"))) %>' /> How can I convert 0's and 1's to boolean using Bind()? [ANSWER] I have extended auto-generated type through partial class by adding a new property mentioned in the answer by Justin

    Read the article

  • Casting Error with Reflection

    - by Mitchel Sellers
    I have an application that uses plugins that are managed via an interface I then dynamically load the plugin classes and cast them to the interface to work with them. I have the following line of code, assume that IPlugin is my interface. IPlugin _plugin = (IPlugin)Activator.CreateInstance(oInfo.Assembly, oInfo.FullyQualifiedName) This should be pretty simple, create the instance and cast it to the interface. I know that the assembly and fully qualified name values are correct, but I am getting the following exception. Exception= System.InvalidCastException: Unable to cast object of type ‘System.Runtime.Remoting.ObjectHandle’ to type ‘MyNamespace.Components.Integration.IPlugin’. at MyNamespace.Components.Integration.PluginProxy..ctor(Int32 instanceId) Any ideas what could cause this?

    Read the article

  • Casting a non-generic type to a generic one

    - by John Sheehan
    I've got this class: class Foo { public string Name { get; set; } } And this class class Foo<T> : Foo { public T Data { get; set; } } Here's what I want to do: public Foo<T> GetSome() { Foo foo = GetFoo(); Foo<T> foot = (Foo<T>)foo; foot.Data = GetData<T>(); return foot; } What's the easiest way to convert Foo to Foo<T>? I can't cast directly InvalidCastException) and I don't want to copy each property manually (in my actual use case, there's more than one property) if I don't have to. Is a user-defined type conversion the way to go?

    Read the article

  • What are the essential COM components required for burning DVD in Windows XP using .NET?

    - by shruti
    I'm trying to burn DVD/CD through frontend C# code... i have used IMAPI2 for buring CD/DVD in windows XP..but it is giving me unhandled exception... as:- System.InvalidCastException: Unable to cast COM object of type 'IMAPI2.Interop.MsftFileSystemImageClass' to interface type 'IMAPI2.Interop.MsftFileSystemImage'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{7CFF842C-7E97-4807-8304-910DD8F7C051}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)) can anyone please help me out to solve this problem. I'm not able to solve this error. this project is working fine in Windows7 but unable to work with XP.

    Read the article

  • Cast ASP type object to HtmlControl

    - by Joris
    Hey'all How do I cast a li dom element as HtmlControl from an ASP type object? I tried it like this: var li = (HtmlControl)sender; I get a InvalidCastException... The thing is, I want to make the li (a tab) clickable, and then update an UpdatePanel... But when I start like this <li id="li" runat="server" onclick="tab2_Click"> FooBar </li> I get an error because the object is not defined... how to cast?

    Read the article

  • What are the essential COM componenets required for burning DVD in c#.net in Windows XP?

    - by shruti
    im trying to burn DVD/CD through frontend C#.net code... i have used IMAPI2 for buring CD/DVD in windows XP..but it is giving me unhandeled exception... as:- System.InvalidCastException: Unable to cast COM object of type 'IMAPI2.Interop.MsftFileSystemImageClass' to interface type 'IMAPI2.Interop.MsftFileSystemImage'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{7CFF842C-7E97-4807-8304-910DD8F7C051}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)) can anyone plz help me out to solve this pbm...im not able to solve this error.. this project is working fine in Windows7 but unable to work with XP...???

    Read the article

  • nhibernate fatal error

    - by Afif Lamloumi
    i have an error ( System.InvalidCastException: Unable to cast object of type 'AccountProxy' to type 'System.String'.) when i did this code i mapped the tables( Account,AccountString,EventData,...) of the the database opengts ( open source) i have this error when i called a function from EventData.cs IQuery query = session.CreateQuery("FROM Eventdata"); IList pets = query.List(); return pets; the Stack Trace: [InvalidCastException: Impossible d'effectuer un cast d'un objet de type 'AccountProxy' en type 'System.String'.] (Object , Object[] , SetterCallback ) +431 NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues(Object target, Object[] values) +20 NHibernate.Tuple.Component.PocoComponentTuplizer.SetPropertyValues(Object component, Object[] values) +49 NHibernate.Type.ComponentType.SetPropertyValues(Object component, Object[] values, EntityMode entityMode) +34 NHibernate.Type.ComponentType.ResolveIdentifier(Object value, ISessionImplementor session, Object owner) +150 NHibernate.Type.ComponentType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner) +42 NHibernate.Loader.Loader.GetKeyFromResultSet(Int32 i, IEntityPersister persister, Object id, IDataReader rs, ISessionImplementor session) +93 NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies) +92 NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +675 NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +129 NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +116 [GenericADOException: could not execute query [ select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_ ] [SQL: select eventdata0_.deviceID as deviceID5_, eventdata0_.timestamp as timestamp5_, eventdata0_.statusCode as statusCode5_, eventdata0_.accountID as accountID5_, eventdata0_.latitude as latitude5_, eventdata0_.longitude as longitude5_, eventdata0_.gpsAge as gpsAge5_, eventdata0_.speedKPH as speedKPH5_, eventdata0_.heading as heading5_, eventdata0_.altitude as altitude5_, eventdata0_.transportID as transpo11_5_, eventdata0_.inputMask as inputMask5_, eventdata0_.outputMask as outputMask5_, eventdata0_.address as address5_, eventdata0_.DataSource as DataSource5_, eventdata0_.rawdata as rawdata5_, eventdata0_.distanceKM as distanceKM5_, eventdata0_.odometerKM as odometerKM5_, eventdata0_.geozoneIndex as geozone19_5_, eventdata0_.geozoneID as geozoneID5_, eventdata0_.creationTime as creatio21_5_ from eventdata eventdata0_]] NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +213 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) +18 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet`1 querySpaces, IType[] resultTypes) +79 NHibernate.Hql.Ast.ANTLR.Loader.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters) +51 NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters) +231 NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results) +369 NHibernate.Impl.SessionImpl.List(String query, QueryParameters queryParameters, IList results) +317 NHibernate.Impl.SessionImpl.List(String query, QueryParameters parameters) +282 NHibernate.Impl.QueryImpl.List() +163 DATA1.EventdataExtensions.GetEventdata() in C:\Users\HP\Desktop\our_project\DATA1\Queries\Eventdata.cs:33 MvcApplication7.Controllers.HistoriqueController.Index() in C:\Users\HP\Desktop\our_project\MvcApplication7\Controllers\HistoriqueController.cs:17 lambda_method(Closure , ControllerBase , Object[] ) +62 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27 System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263 System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 System.Web.Mvc.Controller.ExecuteCore() +116 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Any suggestions? how can correct this error Data entity class (outtake from comment): public class MyClass { public virtual string DeviceID { get; set; } public virtual int Timestamp { get; set; } public virtual string Account { get; set; } public virtual int StatusCode { get; set; } public virtual double Latitude { get; set; } public virtual double Longitude { get; set; } public virtual int GpsAge { get; set; } public virtual double SpeedKPH { get; set; } public virtual double Heading { get; set; } public override bool Equals(object obj) { return true; } public override int GetHashCode() { return 0; } }

    Read the article

  • polymorphic hql

    - by Berryl
    I have a base type where "business id" must be unique for a given subclass, but it is possible for there to be different subclasses with the same business id. If there is a base type with a requested id but of the wrong subclass I want to return null, using a named query. The code below does this, but I am wondering if I can avoid the try/catch with a better HQL. Can I? Cheers, Berryl current hql <query name="FindActivitySubjectByBusinessId"> <![CDATA[ from ActivitySubject act where act.BusinessId = :businessId ]]> </query> current fetch code public ActivitySubject FindByBusinessId<T>(string businessId) where T : ActivitySubject { Check.RequireStringValue(businessId, "businessId"); try { return _session.GetNamedQuery("FindActivitySubjectByBusinessId") .SetString("businessId", businessId) .UniqueResult<T>(); } catch (InvalidCastException e) { // an Activity Subject was found with the requested id but the wrong type return null; } }

    Read the article

  • problem burning DVD using IMAPI2 in Windows XP using c#.net..

    - by zoya
    i have used IMAPI2 for buring CD/DVD in windows XP..but it is giving me unhandeled exception...it is written as:- System.InvalidCastException: Unable to cast COM object of type 'IMAPI2.Interop.MsftFileSystemImageClass' to interface type 'IMAPI2.Interop.MsftFileSystemImage'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{7CFF842C-7E97-4807-8304-910DD8F7C051}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)) can anyone plz help me out to solve this pbm.. i have updated the XP storage 1.0 as written in the code project.. but still im not able to solve this error.. this project is working fine in Vista and Windows7 but unable to work with XP.. is there any solution to burn DVD in XP by using IMAPI or any other component..??? i have taken the sample code from http://www.codeproject.com/KB/miscctrl/imapi2.aspx

    Read the article

  • Is it OK to open a DB4o file for query, insert, update multiple times?

    - by Khnle
    This is the way I am thinking of using DB4o. When I need to query, I would open the file, read and close: using (IObjectContainer db = Db4oFactory.OpenFile(Db4oFactory.NewConfiguration(), YapFileName)) { try { List<Pilot> pilots = db.Query<Pilot>().ToList<Pilot>(); } finally { try { db.Close(); } catch (Exception) { }; } } At some later time, when I need to insert, then using (IObjectContainer db = Db4oFactory.OpenFile(Db4oFactory.NewConfiguration(), YapFileName)) { try { Pilot pilot1 = new Pilot("Michael Schumacher", 100); db.Store(pilot1); } finally { try { db.Close(); } catch (Exception) { }; } } In this way, I thought I will keep the file more tidy by only having it open when needed, and have it closed most of the time. But I keep getting InvalidCastException Unable to cast object of type 'Db4objects.Db4o.Reflect.Generic.GenericObject' to type 'Pilot' What's the correct way to use DB4o?

    Read the article

  • How to load COM object in smart device project?

    - by Daan
    I want to create a .NET CF application for Windows Mobile 5. In this application, I want to load a COM object based on the ProgID (or CLSID). How do I load this COM object in such a way that I can access its methods as if it were just another .NET object? In addition: how can I configure the projects / solutions in Visual Studio in such a way, that when I debug the application, I am sure that the COM object that is loaded is the one that is installed on the device, not one that may be accessible through the debugger? I have tried adding the .ocx file as a Reference, but I get an error, and I am not sure about 'question 2'. I have also tried loading the COM object using Type type = Type.GetTypeFromProgID("my.prog.id") MyObject myObject = (MyObject)Activator.CreateInstance(type) ...but this results in an InvalidCastException on the second line.

    Read the article

  • Find selected WPF Listbox entries

    - by wonea
    I've been trying iterate through the selected items of a listbox in WPF, with the following code; try { for (int i = 0; i < mylistbox.SelectedItems.Count; i++) { ListItem li = (ListItem)mylistbox.SelectedItems[i]; string listitemcontents_str = li.ToString(); } } catch(Exception e) { // Error appears here string error = e.ToString(); } However I receive an invalid cast exception; System.InvalidCastException: Unable to cast object of type 'mylist' to type 'System.Windows.Documents.ListItem'. Is there a way around this?

    Read the article

  • PropertyInfo SetValue and nulls

    - by Nelson
    If I have something like: object value = null; Foo foo = new Foo(); PropertyInfo property = Foo.GetProperties().Single(p => p.Name == "IntProperty"); property.SetValue(foo, value, null); Then foo.IntProperty gets set to 0, even though value = null. It appears it's doing somemething like IntProperty = default(typeof(int)). I would like to throw an InvalidCastException if IntProperty is not a "nullable" type (Nullable< or reference). I'm using Reflection, so I don't know the type ahead of time. How would I go about doing this?

    Read the article

  • How can I debug or set a break statement inside an expression tree?

    - by Abel
    When an external library contains a LINQ provider, and it throws an exception when executing a dynamic expression tree, how can I break when that expression is thrown? For example, I use a third party LINQ2CRM provider, which allows me to call the Max<TSource, TResult>() method of IQueryable, but when it throws an InvalidCastException, I fail to break on the spot when the exception is thrown, making it hard to review the stack-trace because it's already unwinded when the debugger breaks it in my code. I've set "break on throw" for the mentioned exception. My debug settings are: Clarification on where exactly I'd want to break. I do not want to break in side the LINQ Expression, but instead, I want to break when the expression tree is executed, or, put in other words, when the IQueryable extension method Max() calls the override provided by the LINQ provider. The top of the stacktrace looks like this, which is where I would like to break inside (or step through, or whatever): at XrmLinq.QueryProviderBase.Execute[T](Expression expression) at System.Linq.Queryable.Max[TSource,TResult](IQueryable`1 source, Expression`1 selector)

    Read the article

  • C5 Generics Collection IntervalHeap<T> -- getting an IPriorityQueueHandle from a T for Replace or De

    - by Jared Updike
    I'm using the Generics Collection library C5 (server down :-( ) and I have an IntervalHeap(T) and I need to Delete or Replace a T that is not the Max or Min. How do I get an IPriorityQueueHandle from my T? The C5 library source code shows that IPriorityQueueHandle(T) has no methods or properties to implement and the compiler thinks my implementation of IPriorityQueueHandle(T) for my T is acceptable. I try to use a T like this: q.Replace(t, t); and the C5 library throws an InvalidCastException because it cannot convert my T to a (Handle).

    Read the article

  • Linq to NHibernate - How to return a parent object with only certain child objects included

    - by vakman
    Given a simplified model like the following: public class Enquiry { public virtual DateTime Created { get; set; } public virtual Sender Sender { get; set; } } public class Sender { public virtual IList<Enquiry> Enquiries { get; set; } } How can you construct a Linq to Nhibernate query such that it gives you back a list of senders and their enquiries where the enquiries meet some criteria. I have tried something like this: return session.Linq<Enquiry>() .Where(enquiry => enquiry.Created < DateTime.Now) .Select(enquiry => enquiry.Sender) In this case I get an InvalidCastException saying you can't cast type Sender to type Enquiry. Any pointers on how I can do this without using HQL?

    Read the article

  • Serializing Request.Form to a Dictionary or something

    - by André Alçada Padez
    Hi i need to pass my Request.Form as a parameter, but first i have to add some key/value pairs to it. I get the exception that the Collection is readonly. I've tried: System.Collections.Specialized.NameValueCollection myform = Request.Form; and i get the same error. and i've tried: foreach(KeyValuePair<string, string> pair in Request.Form) { Response.Write(Convert.ToString(pair.Key) + " - " + Convert.ToString(pair.Value) + "<br />"); } to test if i can pass it one by one to another dictionary, but i get: System.InvalidCastException: Specified cast is not valid. some help, anyone? Thanx

    Read the article

  • Linq to NHibernate - How to include parent object and only certain child objects

    - by vakman
    Given a simplified model like the following: public class Enquiry { public virtual DateTime Created { get; set; } public virtual Sender Sender { get; set; } } public class Sender { public virtual IList<Enquiry> Enquiries { get; set; } } How can you construct a Linq to Nhibernate query such that it gives you back a list of senders and their enquiries where the enquiries meet some criteria. I have tried something like this: return session.Linq<Enquiry>() .Where(enquiry => enquiry.Created < DateTime.Now) .Select(enquiry => enquiry.Sender) In this case I get an InvalidCastException saying you can't cast type Sender to type Enquiry. Any pointers on how I can do this without using HQL?

    Read the article

  • Help understanding this stack trace

    - by user80632
    Hi I have health monitoring turned on, and i have the following error i'm trying to understand: Exception: Exception information: Exception type: System.InvalidCastException Exception message: Specified cast is not valid. Thread information: Thread ID: 5 Thread account name: NT AUTHORITY\NETWORK SERVICE Is impersonating: False Stack trace: at _Default.Repeater1_ItemDataBound(Object sender, RepeaterItemEventArgs e) at System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) at System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) at _Default.up1_Load() at _Default.Timer1_Tick(Object sender, EventArgs e) at System.Web.UI.Timer.OnTick(EventArgs e) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) I'm just trying to figure out exactly where the problem is happening and what it is - is it happening in the Repeater1_ItemDataBound sub routine, or in the Timer1_Tick sub routine? Is the last thing that happened before the error occured at the top or bottom of the trace? any help much appreciated thanks

    Read the article

  • Why does a Linq Cast<T> operation fail when I have an implicit cast defined?

    - by Ryan Versaw
    I've created two classes, with one of them having an implicit cast between them: public class Class1 { public int Test1; } public class Class2 { public int Test2; public static implicit operator Class1(Class2 item) { return new Class1{Test1 = item.Test2}; } } When I create a new list of one type and try to Cast<T> to the other, it fails with an InvalidCastException: List<Class2> items = new List<Class2>{new Class2{Test2 = 9}}; foreach (Class1 item in items.Cast<Class1>()) { Console.WriteLine(item.Test1); } This, however, works fine: foreach (Class1 item in items) { Console.WriteLine(item.Test1); } Why is the implicit cast not called when using Cast<T>?

    Read the article

  • Unboxing object containing a value which is known to be assignable to an integer variable

    - by Wim Coenen
    If I have an object instance and I know it is actually a boxed integer, then I can simply cast it back to int like this: object o = GetSomethingByName("foo"); int i = (int)o; However, I don't actually know that the value is an integer. I only know that it can be assigned to an integer. For example, it could be a byte, and the above code would throw InvalidCastException in that case. Instead I would have to do this: object o = GetSomethingByName("foo"); int i = (int)(byte)o; The value could also be a short, or something else which can be assigned to an int. How do I generalize my code to handle all those cases (without handling each possibility separately)?

    Read the article

  • converting tag number to int

    - by Ehtesham Sajed
    i m using Visual C++2008. i've assigned tag value=2 of all buttons from button property(using drag n drop). now i want to make some math calculation with tag value. need to change it in int. what is the default data type tag? i used this code, //code sample if(((int)this-button1-Tag)((int)this-button2-Tag)((int)this-button3-Tag)==50) { ........ //i.e, if tag value of button1*tag value of button2*tag value of button 3==50 then... ........ } generated following run time error on a messegebox An unhandled exception of type 'System.InvalidCastException' occurred in learncpp1.exe Additional information: Specified cast is not valid.

    Read the article

  • How to cast/convert form Object in an byte[] array

    - by maddash
    I've got a maybe simple problem, but at the moment I am not able to solve it. I have an Object and I need to convert it into a byte[]. public byte[] GetMapiPropertyBytes(string propIdentifier) { return (byte[])this.GetMapiProperty(propIdentifier); //InvalidCastException } Exception: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Byte[]'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface. So far so good - I've tried to serialize it, but I got another exception - NOT serializable Could someone help me? I need a method to convert it...

    Read the article

  • What is the point of Convert.ToDateTime(bool)?

    - by Paul Alan Taylor
    I was doing some type conversion routines last night for a system I am working on. One of the conversions involves turning string values into their DateTime equivalents. While doing this, I noticed that the Convert.ToDateTime() method had an overload which accepted a boolean parameter. First question? Under what circumstances could this ever be useful? I went a little further and tried to execute the method in QuickWatch. Either way ( true or false ), the routine returns an InvalidCastException. Second question? Why is this method even here?

    Read the article

  • NHibernate Session Load vs Get when using Table per Hierarchy. Always use ISession.Get&lt;T&gt; for TPH to work.

    - by Rohit Gupta
    Originally posted on: http://geekswithblogs.net/rgupta/archive/2014/06/01/nhibernate-session-load-vs-get-when-using-table-per-hierarchy.aspxNHibernate ISession has two methods on it : Load and Get. Load allows the entity to be loaded lazily, meaning the actual call to the database is made only when properties on the entity being loaded is first accessed. Additionally, if the entity has already been loaded into NHibernate Cache, then the entity is loaded directly from the cache instead of querying the underlying database. ISession.Get<T> instead makes the call to the database, every time it is invoked. With this background, it is obvious that we would prefer ISession.Load<T> over ISession.Get<T> most of the times for performance reasons to avoid making the expensive call to the database. let us consider the impact of using ISession.Load<T> when we are using the Table per Hierarchy implementation of NHibernate. Thus we have base class/ table Animal, there is a derived class named Snake with the Discriminator column being Type which in this case is “Snake”. If we load This Snake entity using the Repository for Animal, we would have a entity loaded, as shown below: public T GetByKey(object key, bool lazy = false) { if (lazy) return CurrentSession.Load<T>(key); return CurrentSession.Get<T>(key); } var tRepo = new NHibernateReadWriteRepository<TPHAnimal>(); var animal = tRepo.GetByKey(new Guid("602DAB56-D1BD-4ECC-B4BB-1C14BF87F47B"), true); var snake = animal as Snake; snake is null As you can see that the animal entity retrieved from the database cannot be cast to Snake even though the entity is actually a snake. The reason being ISession.Load prevents the entity to be cast to Snake and will throw the following exception: System.InvalidCastException :  Message=Unable to cast object of type 'TPHAnimalProxy' to type 'NHibernateChecker.Model.Snake'. Thus we can see that if we lazy load the entity using ISession.Load<TPHAnimal> then we get a TPHAnimalProxy and not a snake. =============================================================== However if do not lazy load the same cast works perfectly fine, this is since we are loading the entity from database and the entity being loaded is not a proxy. Thus the following code does not throw any exceptions, infact the snake variable is not null: var tRepo = new NHibernateReadWriteRepository<TPHAnimal>(); var animal = tRepo.GetByKey(new Guid("602DAB56-D1BD-4ECC-B4BB-1C14BF87F47B"), false); var snake = animal as Snake; if (snake == null) { var snake22 = (Snake) animal; }

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >