Search Results

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

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

  • c# InvalidCastException

    - by krisox
    Hello. I try to use this code : webBrowser.Document.GetElementById("login").SetAttribute("value", "user"); It work great but not when i use it in a new thread. I get an InvalidCastException. What can I do ?

    Read the article

  • C# : MS Chart : SeriesCollection -> InvalidCastException?

    - by HeinrichStack
    What is the correct way to get the Series of a char in PPT 2010. I tried PowerPoint.SeriesCollection mySeriesCollection = (PowerPoint.SeriesCollection) myChart.SeriesCollection(1); throws the following exception Exception Type: System.InvalidCastException Further, What is the correct call in C# to get the series of a chart ? If I try this way: PowerPoint.Series mySeries = (PowerPoint.Series)myChart.SeriesCollection.Item(1); I get the following compile error : error CS0119: 'Microsoft.Office.Interop.PowerPoint.Chart.SeriesCollection(object)' is a 'method', which is not valid in the given context

    Read the article

  • InvalidCastException in DataGridView

    - by Max Yaffe
    (Using VS 2010 Beta 2 - .Net 4.0 B2 Rel) I have a class, MyTable, derived from BindingList where S is a struct. S is made up of several other structs, for example: public class MyTable<S>:BindingList<S> where S: struct { ... } public struct MyStruct { public MyReal r1; public MyReal r2; public MyReal R1 {get{...} set{...}} public MyReal R2 {get{...} set{...}} ... } public struct MyReal { private Double d; private void InitFromString(string) {this.d = ...;} public MyReal(Double d) { this.d = d;} public MyReal(string val) { this.d = default(Double); InitFromString(val);} public override string ToString() { return this.real.ToString();} public static explicit operator MyReal(string s) { return new MyReal(s);} public static implicit operator String(MyReal r) { return r.ToString();} ... } OK, I use the MyTable as a binding source for a DataGridView. I can load the data grid easily using InitFromString on individual fields in MyStruct. The problem comes when I try to edit a value in a cell of the DataGridView. Going to the first row, first column, I change the value of the existing number. It gives an exception blizzard, the first line of which says: System.FormatException: Invalid cast from 'System.String' to 'MyReal' I've looked at the casting discussions and reference books but don't see any obvious problems. Any ideas?

    Read the article

  • Persisting simple tree with (Fluent-)NHibernate leads to System.InvalidCastException

    - by fudge
    Hi there, there seems to be a problem with recursive data structures and (Fluent-)NHibernate or its just me, being a complete moron... here's the tree: public class SimpleNode { public SimpleNode () { this.Children = new List<SimpleNode> (); } public virtual SimpleNode Parent { get; private set; } public virtual List<SimpleNode> Children { get; private set; } public virtual void setParent (SimpleNode parent) { parent.AddChild (this); Parent = parent; } public virtual void AddChild (SimpleNode child) { this.Children.Add (child); } public virtual void AddChildren (IEnumerable<SimpleNode> children) { foreach (var child in children) { AddChild (child); } } } the mapping: public class SimpleNodeEntity : ClassMap<SimpleNode> { public SimpleNodeEntity () { Id (x => x.Id); References (x => x.Parent).Nullable (); HasMany (x => x.Children).Not.LazyLoad ().Inverse ().Cascade.All ().KeyNullable (); } } now, whenever I try to save a node, I get this: System.InvalidCastException: Cannot cast from source type to destination type. at (wrapper dynamic-method) SimpleNode. (object,object[],NHibernate.Bytecode.Lightweight.SetterCallback) at NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues (object,object[]) at NHibernate.Tuple.Entity.PocoEntityTuplizer.SetPropertyValuesWithOptimizer (object,object[]) My setup: Mono 2.8.1 (on OSX), NHibernate 2.1.2, FluentNHibernate 1.1.0

    Read the article

  • Converting Byte[] to String - Interbase to C# - InvalidCastException

    - by NorthernOutpost
    I'm using OleDbDataReader rdr to read a "Comments" field in BLOB form (sub_type 1 segment size 80) into a string from an Interbase DB, and I keep getting exceptions. Any suggestions? Attempt #1 ls_Chap_Comments.Add((rdr["Comments"]).ToString()); InvalidCastException: The data value could not be converted for reasons other than sign mismatch or data overflow. For example, the data was corrupted in the data store but the row was still retrievable." Attempt #2 byte[] b = new byte[100]; b = (byte[])rdr["Comments"]; string s = System.Text.ASCIIEncoding.ASCII.GetString(b); InvalidCastException: Unable to cast object of type System.String to type System.Byte[] Attempt #3 // 17 is the BLOB column zero-based location for "Comments" retval = rdr.GetBytes(17, startIndex, outbyte, 0, bufferSize); InvalidCastException: Unable to cast object of type System.String to type System.Byte[]. Any suggestions would be really appreciated!

    Read the article

  • ProviderException: InvalidCastException

    - by JS
    Few of our clients are regularly getting invalid cast exception, with variations i.e. InvalidCastException / ProviderException, but both generating from method call: System.Web.Security.SqlRoleProvider.GetRolesForUser(String username) The other variation is: Exception type: InvalidCastException Exception message: Unable to cast object of type System.Int32 to type System.String. I had a look at application event log which shows: Stack trace: at System.Web.Security.SqlRoleProvider.GetRolesForUser(String username) at System.Web.Security.RolePrincipal.IsInRole(String role) at System.Web.Configuration.AuthorizationRule.IsTheUserInAnyRole(StringCollection roles, IPrincipal principal) at System.Web.Configuration.AuthorizationRule.IsUserAllowed(IPrincipal user, String verb) at System.Web.Configuration.AuthorizationRuleCollection.IsUserAllowed(IPrincipal user, String verb) at System.Web.Security.UrlAuthorizationModule.OnEnter(Object source, EventArgs eventArgs) at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)* Has anyone come across this issue, and if so what is the fix? Thanks JS

    Read the article

  • InvalidCastException for two Objects of the same type

    - by LLEA
    hi, I have this weird problem that I cannot handle myself. A class in the model of my mvp-project designed as singleton causes an InvalidCastException. The source of error is found in this code line where the deserialised object is assigned to the instance variable of the class: engineObject = (ENGINE)xSerializer.Deserialize(str); It occurs whenever I try to add one of my UserControls to a Form or to a different UC. All of my UCs have a special presenter that access the above mentioned instance variable of the singleton class. This is what I get when trying to add a UC somewhere: 'System.TypeInitializationException: The type initializer for 'MVP.Model.EngineData' threw an exception. ---- System.InvalidCastException: [A]Engine cannot be cast to [B]Engine. Type A originates from 'MVP.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location '[...]\AppData\Roaming\Microsoft\VisualStudio\9.0\ProjectAssemblies\uankw1hh01\MVP.Model.dll'. Type B originates from 'MVP.Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location '[...]\AppData\Roaming\Microsoft\VisualStudio\9.0\ProjectAssemblies\u_hge2de01\MVP.Model.dll'... So I somehow have two assemblies and they are not accessed from my project folder, but from a VS temp folder? I googled a lot and only found this: IronPython Exception: [A]Person cannot be cast to [B]Person. There is a solution offered, but first it concerns IronPhyton and second I don't know where to use it within my project? It would be just great, if u could help me out here :-) thx

    Read the article

  • Nhibernate 2.1 and mysql 5 - InvalidCastException on Setup

    - by Nash
    Hello there, I am trying to use NHibernate with Spring.Net und mySQL 5. However, when setting up the connection and creating the SessionFactoryObject, I get this InvalidCastException: NHibernate seems to cast MySql.Data.MySqlClient.MySqlConnection to System.Data.Common.DbConnection which causes the exception. System.InvalidCastException wurde nicht behandelt. Message="Das Objekt des Typs \"MySql.Data.MySqlClient.MySqlConnection\" kann nicht in Typ \"System.Data.Common.DbConnection\" umgewandelt werden." Source="NHibernate" StackTrace: bei NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare() in c:\CSharp\NH\nhibernate\src\NHibernate\Tool\hbm2ddl\SuppliedConnectionProviderConnectionHelper.cs:Zeile 25. bei NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect dialect, IConnectionHelper connectionHelper) in c:\CSharp\NH\nhibernate\src\NHibernate\Tool\hbm2ddl\SchemaMetadataUpdater.cs:Zeile 43. bei NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactory sessionFactory) in c:\CSharp\NH\nhibernate\src\NHibernate\Tool\hbm2ddl\SchemaMetadataUpdater.cs:Zeile 17. bei NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners) in c:\CSharp\NH\nhibernate\src\NHibernate\Impl\SessionFactoryImpl.cs:Zeile 169. bei NHibernate.Cfg.Configuration.BuildSessionFactory() in c:\CSharp\NH\nhibernate\src\NHibernate\Cfg\Configuration.cs:Zeile 1090. bei OrmTest.Program.Main(String[] args) in C:\Users\Max\Documents\Visual Studio 2008\Projects\OrmTest\OrmTest\Program.cs:Zeile 24. bei System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) bei System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) bei Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() bei System.Threading.ThreadHelper.ThreadStart_Context(Object state) bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) bei System.Threading.ThreadHelper.ThreadStart() InnerException: I am using the programmatically setup approach in order to get a quick NHibernate Setup. Here is the setup Code: Configuration config = new Configuration(); Dictionary props = new Dictionary(); props.Add("dialect", "NHibernate.Dialect.MySQL5Dialect"); props.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider"); props.Add("connection.driver_class", "NHibernate.Driver.MySqlDataDriver"); props.Add("connection.connection_string", "Server=localhost;Database=orm_test;User ID=root;Password=password"); props.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Spring.ProxyFactoryFactory, NHibernate.ByteCode.Spring"); config.AddProperties(props); config.AddFile("Person.hbm.xml"); ISessionFactory factory = config.BuildSessionFactory(); ISession session = factory.OpenSession(); Is something missing? I downloaded the current mysql Connector from the mysql Website.

    Read the article

  • InvalidCastException when creating an instance using assembly.CreateInstance

    - by Yossi Dahan
    I'm looking for an explanation for the following - I have an assembly I'm loading using Assembly assembly = Assembly.LoadFrom(filename); I then loop on all the types in the assembly, and wish to try and find out if a type implements a particular interface and if so I want an instance of that type, I've tried several things which did not work, but when I fell back to the most basic (and probably inefficient) way, I realised there's something more fundamental I don't understand - foreach (Type t in assembly.GetTypes()) { foreach (Type i in t.GetInterfaces()) { if (i.FullName == pluginInterfaceType.FullName) { object o = assembly.CreateInstance(t.ToString()); IInterface plugin = (IInterface)o; That last line causes an InvalidCastException, despite the fact that the type created definitely implements that interface. Further more - if I use Activator.CreateInstance instead of Assembly.CreateInstance (which I don't want to do), casting to the interface works just fine.

    Read the article

  • InvalidCastException: System.Web.UI.PartialCachingControl -> MyCustomControl when OutputCaching

    - by marcinn
    The problem: I am unable to use OutputCaching with my controls which derives from MyCustomControl. Controls are loaded dynamically using definitions from database with Page.LoadControl method. When I add to ascx <%@ OutputCache VaryByParam="*" Duration="3600"% the "InvalidCastException: System.Web.UI.PartialCachingControl - MyCustomControl" exception is thrown. I am unable to modify assembly witch contains dynamic loading controls logic. Is there any way to fix it in derived controls? The second question is about iis7 and native output caching - is it resolves this problem? (I tried to set up several performance counters and I saw that cache wasn't hit...)

    Read the article

  • C# - InvalidCastException when fetching double from sqlite

    - by Irro
    I keep getting a InvalidCastException when I'm fetching any double from my SQLite database in C#. The exception says "Specified cast is not valid." I am able to see the value in a SQL manager so I know it exists. It is possible to fetch Strings (VARCHARS) and ints from the database. I'm also able to fetch the value as an object but then I get "66.0" when it's suppose to be "66,8558604947586" (latitude coordination). Any one who knows how to solve this? My code: using System.Data.SQLite; ... SQLiteConnection conn = new SQLiteConnection(@"Data Source=C:\\database.sqlite; Version=3;"); conn.Open(); SQLiteDataReader reader = getReader(conn, "SELECT * FROM table"); //These are working String name = reader.GetString(1); Int32 value = reader.GetInt32(2); //This is not working Double latitude = reader.getDouble(3); //This gives me wrong value Object o = reader[3]; //or reader["latitude"] or reader.getValue(3)

    Read the article

  • Using generics in Unity ... InvalidCastException

    - by Sunny D
    Hi, My interface definition is: public interface IInterface where T:UserControl My class definition is: public partial class App1Control : UserControl, IInterface The unity section of my app.config looks as below: <unity> <typeAliases> <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" /> <typeAlias alias="myInterface" type="MyApplication.IInterface`1, MyApplication" /> <typeAlias alias="App1" type="MyApplication.App1Control, MyApplication" /> </typeAliases> <containers> <container> <types> <type type="myInterface" mapTo="App1" name="Application 1"> <lifetime type="singleton"/> </type> </types> </container> </containers> </unity> The app runs fine but, the following code gives a InvalidCastException container.Resolve<IInterface<UserControl>>("Application 1"); The error message is : Unable to cast object of type 'MyApplication.App1Control' to type 'MyApplication.IInterface`1[System.Windows.Forms.UserControl]' I believe there is a minor mistake in my code ... but am not able to figure out what. Any thoughts?

    Read the article

  • InvalidCastException from selecting ListBoxItem's Contents

    - by Dan
    My ListBoxItems contain multiple TextBoxes like this: <ListBox Name="myList" SelectionChanged="myList_SelectionChanged"> <ListBox.ItemTemplate> <DataTemplate> <ListBoxItem> <ListBoxItem.Content> <StackPanel Orientation="Vertical"> <TextBlock Name="nameTextBlock" Text="{Binding Name}" /> <TextBlock Name="ageTextBlock" Text="{Binding Age}" /> <TextBlock Name="genderTextBlock" Text="{Binding Gender}" /> <TextBlock Name="heightTextBlock" Text="{Binding Height}" /> </StackPanel> </ListBoxItem.Content> </ListBoxItem> </DataTemplate> </ListBox.ItemTemplate> </ListBox> When an item is clicked, I would like each TextBlock to be saved to IsolatedStorage under corresponding keys. Right now the closest I've gotten to this method is this: private void mysList_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListBoxItem lbi = (ListBoxItem)myList.SelectedItem; appSettings["name"] = (string)lbi.Content; } But, when clicked I get an InvalidCastException. As I understand it, it's basically due to me trying to convert all four textboxes into a single string (or something like that). So how do I save each TextBox's text field independently within the ListBoxItem to an IsolatedStorage key/value? Thanks again in advance.

    Read the article

  • Help with InvalidCastException

    - by Robert
    I have a gridview and, when a record is double-clicked, I want it to open up a new detail-view form for that particular record. As an example, I have created a Customer class: using System; using System.Data; using System.Configuration; using System.Collections.Generic; using System.ComponentModel; using System.Data.SqlClient; using System.Collections; namespace SyncTest { #region Customer Collection public class CustomerCollection : BindingListView<Customer> { public CustomerCollection() : base() { } public CustomerCollection(List<Customer> customers) : base(customers) { } public CustomerCollection(DataTable dt) { foreach (DataRow oRow in dt.Rows) { Customer c = new Customer(oRow); this.Add(c); } } } #endregion public class Customer : INotifyPropertyChanged, IEditableObject, IDataErrorInfo { private string _CustomerID; private string _CompanyName; private string _ContactName; private string _ContactTitle; private string _OldCustomerID; private string _OldCompanyName; private string _OldContactName; private string _OldContactTitle; private bool _Editing; private string _Error = string.Empty; private EntityStateEnum _EntityState; private Hashtable _PropErrors = new Hashtable(); public event PropertyChangedEventHandler PropertyChanged; private void FirePropertyChangeNotification(string propName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propName)); } } public Customer() { this.EntityState = EntityStateEnum.Unchanged; } public Customer(DataRow dr) { //Populates the business object item from a data row this.CustomerID = dr["CustomerID"].ToString(); this.CompanyName = dr["CompanyName"].ToString(); this.ContactName = dr["ContactName"].ToString(); this.ContactTitle = dr["ContactTitle"].ToString(); this.EntityState = EntityStateEnum.Unchanged; } public string CustomerID { get { return _CustomerID; } set { _CustomerID = value; FirePropertyChangeNotification("CustomerID"); } } public string CompanyName { get { return _CompanyName; } set { _CompanyName = value; FirePropertyChangeNotification("CompanyName"); } } public string ContactName { get { return _ContactName; } set { _ContactName = value; FirePropertyChangeNotification("ContactName"); } } public string ContactTitle { get { return _ContactTitle; } set { _ContactTitle = value; FirePropertyChangeNotification("ContactTitle"); } } public Boolean IsDirty { get { return ((this.EntityState != EntityStateEnum.Unchanged) || (this.EntityState != EntityStateEnum.Deleted)); } } public enum EntityStateEnum { Unchanged, Added, Deleted, Modified } void IEditableObject.BeginEdit() { if (!_Editing) { _OldCustomerID = _CustomerID; _OldCompanyName = _CompanyName; _OldContactName = _ContactName; _OldContactTitle = _ContactTitle; } this.EntityState = EntityStateEnum.Modified; _Editing = true; } void IEditableObject.CancelEdit() { if (_Editing) { _CustomerID = _OldCustomerID; _CompanyName = _OldCompanyName; _ContactName = _OldContactName; _ContactTitle = _OldContactTitle; } this.EntityState = EntityStateEnum.Unchanged; _Editing = false; } void IEditableObject.EndEdit() { _Editing = false; } public EntityStateEnum EntityState { get { return _EntityState; } set { _EntityState = value; } } string IDataErrorInfo.Error { get { return _Error; } } string IDataErrorInfo.this[string columnName] { get { return (string)_PropErrors[columnName]; } } private void DataStateChanged(EntityStateEnum dataState, string propertyName) { //Raise the event if (PropertyChanged != null && propertyName != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } //If the state is deleted, mark it as deleted if (dataState == EntityStateEnum.Deleted) { this.EntityState = dataState; } if (this.EntityState == EntityStateEnum.Unchanged) { this.EntityState = dataState; } } } } Here is my the code for the double-click event: private void customersDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { Customer oCustomer = (Customer)customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position]; CustomerForm oForm = new CustomerForm(); oForm.NewCustomer = oCustomer; oForm.ShowDialog(this); oForm.Dispose(); oForm = null; } Unfortunately, when this code runs, I receive an InvalidCastException error stating "Unable to cast object to type 'System.Data.DataRowView' to type 'SyncTest.Customer'". This error occurs on the very first line of that event: Customer oCustomer = (Customer)customersBindingSource.CurrencyManager.List[customersBindingSource.CurrencyManager.Position]; What am I doing wrong?... and what can I do to fix this? Any help is greatly appreciated. Thanks!

    Read the article

  • Intermittent "Specified cast is invalid" with StructureMap injected data context

    - by FreshCode
    I am intermittently getting an System.InvalidCastException: Specified cast is not valid. error in my repository layer when performing an abstracted SELECT query mapped with LINQ. The error can't be caused by a mismatched database schema since it works intermittently and it's on my local dev machine. Could it be because StructureMap is caching the data context between page requests? If so, how do I tell StructureMap v2.6.1 to inject a new data context argument into my repository for each request? Update: I found this question which correlates my hunch that something was being re-used. Looks like I need to call Dispose on my injected data context. Not sure how I'm going to do this to all my repositories without copypasting a lot of code. Edit: These errors are popping up all over the place whenever I refresh my local machine too quickly. Doesn't look like it's happening on my remote deployment box, but I can't be sure. I changed all my repositories' StructureMap life cycles to HttpContextScoped() and the error persists. Code: public ActionResult Index() { // error happens here, which queries my page repository var page = _branchService.GetPage("welcome"); if (page != null) ViewData["Welcome"] = page.Body; ... } Repository: GetPage boils down to a filtered query mapping in my page repository. public IQueryable<Page> GetPages() { var pages = from p in _db.Pages let categories = GetPageCategories(p.PageId) let revisions = GetRevisions(p.PageId) select new Page { ID = p.PageId, UserID = p.UserId, Slug = p.Slug, Title = p.Title, Description = p.Description, Body = p.Text, Date = p.Date, IsPublished = p.IsPublished, Categories = new LazyList<Category>(categories), Revisions = new LazyList<PageRevision>(revisions) }; return pages; } where _db is an injected data context as an argument, stored in a private variable which I reuse for SELECT queries. Error: Specified cast is not valid. Exception Details: System.InvalidCastException: Specified cast is not valid. Stack Trace: [InvalidCastException: Specified cast is not valid.] System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +4539 System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +207 System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +500 System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +50 System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +383 Manager.Controllers.SiteController.Index() in C:\Projects\Manager\Manager\Controllers\SiteController.cs:68 lambda_method(Closure , ControllerBase , Object[] ) +79 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +258 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39 System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +125 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709 System.Web.Mvc.Controller.ExecuteCore() +162 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +58 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371

    Read the article

  • Windows Service Webbrowser object invalid cast exception error

    - by Sam Youtsey
    Hi all, I'm having a bit of trouble with a Windows Service webbrowser object. It's attempting to load in values of username and password to a site but keeps failing and throwing the following error: System.InvalidCastException: Specified cast is not valid. at System.Windows.Forms.UnsafeNativeMethods.IHTMLDocument2.GetLocation() at System.Windows.Forms.WebBrowser.get_Document() at MyWindowsService.MyDataProcessor.login() The code that I'm using to make this call is: MyWebBrowser.Document.All["Login"].SetAttribute("Value", username); MyWebBrowser.Document.All["Password"].SetAttribute("Value", password); MyWebBrowser.Document.All["submit"].InvokeMember("Click"); Any ideas as to why it keeps failing? Thanks in advance for the help.

    Read the article

  • Windows Service Fails on Launch

    - by Jeff
    I'm trying to write a windows service. It installs fine, but fails when I run it with the following exception. I've searched for the string "MyNewProgramService", but I can't find any conversions that would throw this error. I've also added try/catch blocks to a bunch of code with custom exception handling without finding where this exception is occuring. I'm thinking it's somewhere in the auto-generated configuartion/setup code. Any ideas? Event Type: Error Event Source: MyNewProgram Event Category: None Event ID: 0 Date: 4/15/2010 Time: 12:48:34 PM User: N/A Computer: 20F7KF1 Description: Service cannot be started. System.InvalidCastException: Conversion from string "MyNewProgramService" to type 'Integer' is not valid. ---> System.FormatException: Input string was not in a correct format. at Microsoft.VisualBasic.CompilerServices.Conversions.ParseDouble(String Value, NumberFormatInfo NumberFormat) at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value) --- End of inner exception stack trace --- at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value) at TaskManagerFailureHandlerService.MyNewProgramService.OnStart(String[] args) at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)

    Read the article

  • Cast error on SQLDataReader (entlib 5.0, asp.net 3.5, vb)

    - by Phil
    My site is using enterprise library v 5.0. Mainly the DAAB. Some functions such as executescalar, executedataset are working as expected. The problems appear when I start to use Readers I have this function in my includes class: Public Function AssignedDepartmentDetail(ByVal Did As Integer) As SqlDataReader Dim reader As SqlDataReader Dim Command As SqlCommand = db.GetSqlStringCommand("select seomthing from somewhere where something = @did") db.AddInParameter(Command, "@did", Data.DbType.Int32, Did) reader = db.ExecuteReader(Command) reader.Read() Return reader End Function This is called from my aspx.vb like so: reader = includes.AssignedDepartmentDetail(Did) If reader.HasRows Then TheModule = reader("templatefilename") PageID = reader("id") Else TheModule = "#" End If This gives the following error on db.ExecuteReader line: Unable to cast object of type 'Microsoft.Practices.EnterpriseLibrary.Data.RefCountingDataReader' to type 'System.Data.SqlClient.SqlDataReader'. Can anyone shed any light on how I go about getting this working. Will I always run into problems when dealing with readers via entlib?

    Read the article

  • Invalid Cast Exception ASP.NET C#

    - by Shadow Scorpion
    I have a problem in this code: public static T[] GetExtras <T>(Type[] Types) { List<T> Res = new List<T>(); foreach (object Current in GetExtras(typeof(T), Types)) { Res.Add((T)Current);//this is the error } return Res.ToArray(); } public static object[] GetExtras(Type ExtraType, Type[] Types) { lock (ExtraType) { if (!ExtraType.IsInterface) return new object[] { }; List<object> Res = new List<object>(); bool found = false; found = (ExtraType == typeof(IExtra)); foreach (Type CurInterFace in ExtraType.GetInterfaces()) { if (found = (CurInterFace == typeof(IExtra))) break; } if (!found) return new object[] { }; foreach (Type CurType in Types) { found = false; if (!CurType.IsClass) continue; foreach (Type CurInterface in CurType.GetInterfaces()) { try { if (found = (CurInterface.FullName == ExtraType.FullName)) break; } catch { } } try { if (found) Res.Add(Activator.CreateInstance(CurType)); } catch { } } return Res.ToArray(); } } When I'm using this code in windows application it works! But I cant use it on ASP page. Why?

    Read the article

  • LINQ - Linq to Sql - Specified cast is not valid - Please Help!

    - by thiag0
    I am trying to do the following... Request request = ( from r in db.Requests where r.Status == "Processing" && r.Locked == false select r).SingleOrDefault(); It is throwing the following exception... Message: Specified cast is not valid. StackTrace: at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source) at GDRequestProcessor.Worker.GetNextRequest() The .DBML file schema matches my database table that I am trying to select from so I have no clue why I am having this problem. Can anyone help me? Thanks in advance!

    Read the article

  • WinForms: Why do I get InvalidCastException when showing folder browser dialog?

    - by Marek
    I am randomly getting InvalidCastException when showing FolderBrowserDialog and also many clients have reported this. I have not been able to find anything relevant on the internet. Does anyone know what causes this/how to fix this? My code: using (FolderBrowserDialog fbd = new FolderBrowserDialog()) { fbd.ShowNewFolderButton = false; if (fbd.ShowDialog() == DialogResult.OK) Stack trace: Error: System.InvalidCastException: 'Unable to cast object of type 'System.__ComObject' to type 'IMalloc'.'. Stack trace: at System.Windows.Forms.UnsafeNativeMethods.Shell32.SHGetMalloc(IMalloc[] ppMalloc) at System.Windows.Forms.FolderBrowserDialog.GetSHMalloc() at System.Windows.Forms.FolderBrowserDialog.RunDialog(IntPtr hWndOwner) at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner) at System.Windows.Forms.CommonDialog.ShowDialog() EDIT: Additional information: I have been able to reproduce this only when running in VS2008 debugger. When running out of debugger, it happens only very rarely (happened once or twice in 6 months) on my 64 bit Windows 7 and goes away after restart. The clients are certainly not running the app in debugger so it is surely reproducible out of debugger.

    Read the article

  • LinqKit System.InvalidCastException When Invoking method-provided expression on member property.

    - by mdworkin
    Given a simple parent/child class structure. I want to use linqkit to apply a child lambda expression on the parent. I also want the Lambda expression to be provided by a utility method. public class Foo { public Bar Bar { get; set; } } public class Bar { public string Value { get; set; } public static Expression<Func<Bar, bool>> GetLambdaX() { return c => c.Value == "A"; } } ... Expression<Func<Foo, bool>> lx = c => Bar.GetLambdaX().Invoke(c.Bar); Console.WriteLine(lx.Expand()); The above code throws System.InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.MethodCallExpression' to type 'System.Linq.Expressions.LambdaExpression'. at LinqKit.ExpressionExpander.VisitMethodCall(MethodCallExpression m) at LinqKit.ExpressionVisitor.Visit(Expression exp) at LinqKit.ExpressionVisitor.VisitLambda(LambdaExpression lambda) at LinqKit.ExpressionVisitor.Visit(Expression exp) at LinqKit.Extensions.Expand<TDelegate>(Expression`1 expr) .... Please help!

    Read the article

  • InvalidCastException when getting Text from a Label referenced by dynamicaly built String, Fix?

    - by Chris
    NET Version: 3.5 Ok, I recieve an error (System.InvalidCastException was unhandled. Message="Unable to cast object of type 'System.Windows.Forms.Control[]' to type 'System.Windows.Forms.Label'.") when trying to get Text from a Label referenced by a dynamicly built string. Here's my situation; I have an array of 250 labels named l1 - l250. What I want to do is loop through them using this while statement: int c = 1; while (c < 251) { string k = "l" + c.ToString(); //dynamic name of Control(Label) object ka = Controls.Find(k, true); string ct = ((Label)ka).Text; //<<Error Occurs Here build = build + ct; c++; } and get the text value of each to build a string named build. I don't get any build errors, just this while debuging. While debuging I can go down to view my local variables. When looking through these, I can view the contents of object ka; it does contain the correct Text value of the correct Label I want to "access". I just don't understand how to get there. The text value is listed under "[0]" which is the only subcatagory for "ka".

    Read the article

  • help me "dry" out this .net XML serialization code

    - by Sarah Vessels
    I have a base collection class and a child collection class, each of which are serializable. In a test, I discovered that simply having the child class's ReadXml method call base.ReadXml resulted in an InvalidCastException later on. First, here's the class structure: Base Class // Collection of Row objects [Serializable] [XmlRoot("Rows")] public class Rows : IList<Row>, ICollection<Row>, IEnumerable<Row>, IEquatable<Rows>, IXmlSerializable { public Collection<Row> Collection { get; protected set; } public void ReadXml(XmlReader reader) { reader.ReadToFollowing(XmlNodeName); do { using (XmlReader rowReader = reader.ReadSubtree()) { var row = new Row(); row.ReadXml(rowReader); Collection.Add(row); } } while (reader.ReadToNextSibling(XmlNodeName)); } } Derived Class // Acts as a collection of SpecificRow objects, which inherit from Row. Uses the same // Collection<Row> that Rows defines which is fine since SpecificRow : Row. [Serializable] [XmlRoot("MySpecificRowList")] public class SpecificRows : Rows, IXmlSerializable { public new void ReadXml(XmlReader reader) { // Trying to just do base.ReadXml(reader) causes a cast exception later reader.ReadToFollowing(XmlNodeName); do { using (XmlReader rowReader = reader.ReadSubtree()) { var row = new SpecificRow(); row.ReadXml(rowReader); Collection.Add(row); } } while (reader.ReadToNextSibling(XmlNodeName)); } public new Row this[int index] { // The cast in this getter is what causes InvalidCastException if I try // to call base.ReadXml from this class's ReadXml get { return (Row)Collection[index]; } set { Collection[index] = value; } } } And here's the code that causes a runtime InvalidCastException if I do not use the version of ReadXml shown in SpecificRows above (i.e., I get the exception if I just call base.ReadXml from within SpecificRows.ReadXml): TextReader reader = new StringReader(serializedResultStr); SpecificRows deserializedResults = (SpecificRows)xs.Deserialize(reader); SpecificRow = deserializedResults[0]; // this throws InvalidCastException So, the code above all compiles and runs exception-free, but it bugs me that Rows.ReadXml and SpecificRows.ReadXml are essentially the same code. The value of XmlNodeName and the new Row()/new SpecificRow() are the differences. How would you suggest I extract out all the common functionality of both versions of ReadXml? Would it be silly to create some generic class just for one method? Sorry for the lengthy code samples, I just wanted to provide the reason I can't simply call base.ReadXml from within SpecificRows.

    Read the article

  • IncludeExceptionDetailInFaults not behaving as thought

    - by pdiddy
    I have this simple test project just to test the IncludeExceptionDetailInFaults behavior. public class Service1 : IService1 { public string GetData(int value) { throw new InvalidCastException("test"); return string.Format("You entered: {0}", value); } } [ServiceContract] public interface IService1 { [OperationContract] string GetData(int value); } In the app.config of the service i have it set to true <serviceDebug includeExceptionDetailInFaults="True" /> On the client side: try { using (var proxy = new ServiceReference1.Service1Client()) Console.WriteLine(proxy.GetData(5)); } catch (Exception ex) { Console.WriteLine(ex.Message); } This is what I thought the behavior was: Setting to includeExceptionDetailInFaults=true would propagate the exception detail to the client. But I'm always getting the CommunicationObjectFaultException. I did try having the FaultContract(typeof(InvalidCastException)) on the contract but same behavior, only getting the CommunicationObjectFaultException. The only way to make it work was to throw new FaultException(new InvalidCastException("test")); But I thought with IncludeExceptionDetailInFaults=true the above was done automatically. Am I missing something?

    Read the article

1 2 3 4 5  | Next Page >