Search Results

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

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

  • I want to set the AutoCompleteMode property in ApplyCellStyleToEditingControl subroutine

    - by Ranjan Gupta
    Hi, I am creating a DataGridView Column. and it is working well. now I want to customise this column with AutoCompleteMode, and AutoCompleteSource properties to show the customised data. I made the properties for this columns, and these are also working well. but these properties are not working in the "ApplyCellStyleToEditingControl" subroutine. Please help me to use these column properties in the "ApplyCellStyleToEditingControl" subroutine. Public Class DataGridViewDataValueColumn Inherits DataGridViewColumn Dim m_AutoCompleteMode As AutoCompleteMode, _ m_AutoCompleteSource As AutoCompleteSource, _ m_AutoCompleteStringCollection As AutoCompleteStringCollection Public Sub New() MyBase.New(New DataValueCell()) End Sub Public Overrides Property CellTemplate() As DataGridViewCell Get Return MyBase.CellTemplate End Get Set(ByVal value As DataGridViewCell) ' Ensure that the cell used for the template is a DataValueCell. If (value IsNot Nothing) AndAlso _ Not value.GetType().IsAssignableFrom(GetType(DataValueCell)) _ Then Throw New InvalidCastException("Must be a DataValueCell") End If MyBase.CellTemplate = value End Set End Property Region "User Defined Properties" '&*--------------------------------------*&' <Description("Indicates the text completion behaviour of the combo box."), DefaultValue(AutoCompleteMode.None)> _ Public Property AutoCompleteMode() As AutoCompleteMode Get Return m_AutoCompleteMode End Get Set(ByVal value As AutoCompleteMode) m_AutoCompleteMode = value End Set End Property <Description("The source of complete strings used to automatic completion."), DefaultValue(AutoCompleteSource.None)> _ Public Property AutoCompleteSource() As AutoCompleteSource Get Return m_AutoCompleteSource End Get Set(ByVal value As AutoCompleteSource) m_AutoCompleteSource = value End Set End Property <Description("The autocomplete custom source.")> _ Public Property AutoCompleteCustomSource() As AutoCompleteStringCollection Get Return m_AutoCompleteStringCollection End Get Set(ByVal value As AutoCompleteStringCollection) m_AutoCompleteStringCollection = value End Set End Property End Region End Class '&*--------------------------------------*&' Class DataValueCell Inherits DataGridViewTextBoxCell Public Sub New() ' End Sub Public Overrides ReadOnly Property EditType As Type Get Return GetType(PCLDataGridViewTextBoxEditingControl) End Get End Property End Class '&*--------------------------------------*&' '&* Edit DataGridView Columns *&' '&*--------------------------------------*&' Class PCLDataGridViewTextBoxEditingControl Inherits DataGridViewTextBoxEditingControl Public Overrides Function EditingControlWantsInputKey(ByVal keyData As Keys, ByVal dataGridViewWantsInputKey As Boolean) As Boolean Select Case ((keyData And Keys.KeyCode)) Case Keys.Prior, Keys.Next, Keys.End, Keys.Home, Keys.Left, Keys.Up, Keys.Right, Keys.Down, Keys.Delete Return True End Select Return MyBase.EditingControlWantsInputKey(keyData, dataGridViewWantsInputKey) End Function Public Overrides Sub ApplyCellStyleToEditingControl(ByVal dataGridViewCellStyle As DataGridViewCellStyle) With DirectCast(Me, TextBox) '.AutoCompleteMode = DataGridViewDataValueColumn.AutoCompleteMode_Value '.AutoCompleteSource = DataGridViewDataValueColumn.AutoCompleteSource_Value '.AutoCompleteCustomSource = MyBase.AutoCompleteCustomSource End With End Sub End Class

    Read the article

  • Simplest way to flatten document to a view in RavenDB

    - by degorolls
    Given the following classes: public class Lookup { public string Code { get; set; } public string Name { get; set; } } public class DocA { public string Id { get; set; } public string Name { get; set; } public Lookup Currency { get; set; } } public class ViewA // Simply a flattened version of the doc { public string Id { get; set; } public string Name { get; set; } public string CurrencyName { get; set; } // View just gets the name of the currency } I can create an index that allows client to query the view as follows: public class A_View : AbstractIndexCreationTask<DocA, ViewA> { public A_View() { Map = docs => from doc in docs select new ViewA { Id = doc.Id, Name = doc.Name, CurrencyName = doc.Currency.Name }; Reduce = results => from result in results group on new ViewA { Id = result.Id, Name = result.Name, CurrencyName = result.CurrencyName } into g select new ViewA { Id = g.Key.Id, Name = g.Key.Name, CurrencyName = g.Key.CurrencyName }; } } This certainly works and produces the desired result of a view with the data transformed to the structure required at the client application. However, it is unworkably verbose, will be a maintenance nightmare and is probably fairly inefficient with all the redundant object construction. Is there a simpler way of creating an index with the required structure (ViewA) given a collection of documents (DocA)? FURTHER INFORMATION The issue appears to be that in order to have the index hold the data in the transformed structure (ViewA), we have to do a Reduce. It appears that a Reduce must have both a GROUP ON and a SELECT in order to work as expected so the following are not valid: INVALID REDUCE CLAUSE 1: Reduce = results => from result in results group on new ViewA { Id = result.Id, Name = result.Name, CurrencyName = result.CurrencyName } into g select g.Key; This produces: System.InvalidOperationException: Variable initializer select must have a lambda expression with an object create expression Clearly we need to have the 'select new'. INVALID REDUCE CLAUSE 2: Reduce = results => from result in results select new ViewA { Id = result.Id, Name = result.Name, CurrencyName = result.CurrencyName }; This prduces: System.InvalidCastException: Unable to cast object of type 'ICSharpCode.NRefactory.Ast.IdentifierExpression' to type 'ICSharpCode.NRefactory.Ast.InvocationExpression'. Clearly, we also need to have the 'group on new'. Thanks for any assistance you can provide. (Note: removing the type (ViewA) from the constructor calls has no effect on the above)

    Read the article

  • Should I add try/catch around when casting on an attribute of JSP implicit object?

    - by Michael Mao
    Hi all: Basically what I mean is like this: List<String[]> routes = (List<String[]>)application.getAttribute("routes"); For the above code, it tries to get an attribute named "routes" from the JSP implicit object - application. But as everyone knows, after this line of code, routes may very well contains a null - which means this application hasn't got an attribute named "routes". Is this "casting on null" good programming practice in Java or not? Basically I try to avoid exceptions such as java.io.InvalidCastException I reckon things like this are more as "heritage" of Java 1.4 when generic types were not introduced to this language. So I guess everything stored in application attributes as Objects (Similar to traditional ArrayList). And when you do "downcast", there might be invalid casts. What would you do in this case? Update: Just found that although in the implicit object application I did store a List of String arrays, when I do this : List<double[]> routes = (List<double[]>)application.getAttribute("routes"); It doesn't produce any error... And I felt not comfortable already... And even with this code: out.print(routes.get(0)); It does print out something strange : [Ljava.lang.String;@18b352f Am I printing a "pointer to String"? I can finally get an exception like this: out.print(routes.get(0)[1]); with error : java.lang.ClassCastException: [Ljava.lang.String; Because it was me to add the application attribute, I know which type should it be cast to. I feel this is not "good enough", what if I forget the exact type? I know there are still some cases where this sort of thing would happen, such as in JSP/Servlet when you do casting on session attributes. Is there a better way to do this? Before you say:"OMG, why you don't use Servlets???", I should justify my reason as this: - because my uni sucks, its server can only work with Servlets generated by JSP, and I don't really want to learn how to fix issues like that. look at my previous question on this , and this is uni homework, so I've got no other choice, forget all about war, WEB-INF,etc, but "code everything directly into JSP" - because the professors do that too. :)

    Read the article

  • ASP.NET Repeater and DataBinder.Eval

    - by Fernando
    I've got a <asp:Repeater> in my webpage, which is bound to a programatically created dataset. The purpose of this repeater is to create an index from A-Z, which, when clicked, refreshes the information on the page. The repeater has a link button like so: <asp:LinkButton ID="indexLetter" Text='<%#DataBinder.Eval(Container.DataItem,"letter")%>' runat="server" CssClass='<%#DataBinder.Eval(Container.DataItem, "cssclass")%>' Enabled='<%#DataBinder.Eval(Container.DataItem,"enabled")%>'></asp:LinkButton> The dataset is created the following way: protected DataSet getIndex(String index) { DataSet ds = new DataSet(); ds.Tables.Add("index"); ds.Tables["index"].Columns.Add("letter"); ds.Tables["index"].Columns.Add("cssclass"); ds.Tables["index"].Columns.Add("enabled"); char alphaStart = Char.Parse("A"); char alphaEnd = Char.Parse("Z"); for (char i = alphaStart; i <= alphaEnd; i++) { String cssclass="", enabled="true"; if (index == i.ToString()) { cssclass = "selected"; enabled = "false"; } ds.Tables["index"].Rows.Add(new Object[3] {i.ToString(),cssclass,enabled }); } return ds; } However, when I run the page, a "Specified cast is not valid exception" is thrown in Text='<%#DataBinder.Eval(Container.DataItem,"letter")'. I have no idea why, I have tried manually casting to String with (String), I've tried a ToString() method, I've tried everything. Also, if in the debugger I add a watch for DataBinder.Eval(Container.DataItem,"letter"), the value it returns is "A", which according to me, should be fine for the Text Property. EDIT: Here is the exception: System.InvalidCastException was unhandled by user code Message="Specified cast is not valid." Source="App_Web_cmu9mtyc" StackTrace: at ASP.savecondition_aspx._DataBinding_control7(Object sender, EventArgs e) in e:\Documents and Settings\Fernando\My Documents\Visual Studio 2008\Projects\mediTrack\mediTrack\saveCondition.aspx:line 45 at System.Web.UI.Control.OnDataBinding(EventArgs e) at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) at System.Web.UI.Control.DataBind() at System.Web.UI.Control.DataBindChildren() InnerException: Any advice will be greatly appreciated, thank you EDIT 2: Fixed! The problem was not in the Text or CSS tags, but in the Enabled tag, I had to cast it to a Boolean value. The problem was that the exception was signaled at the Text tag, I don't know why

    Read the article

  • C# Type Casting at Runtimefor Array.SetValue

    - by sprocketonline
    I'm trying to create an array using reflection, and insert values into it. I'm trying to do this for many different types so would like a createAndFillArray function capable of this : Type t1 = typeof(A); Type t2 = typeof(B); double exampleA = 22.5; int exampleB = 43; Array arrA = createAndFillArray(t1, exampleA); Array arrB = createAndFillArray(t2, exampleB); private Array createAndFillArray(Type t, object val){ Array arr = Array.CreateInstance( t, 1); //length 1 in this example only, real-world is of variable length. arr.SetValue( val, 0 ); //this causes the following error: "System.InvalidCastException : Object cannot be stored in an array of this type." return arr; } with the class A being as follows: public class A{ public A(){} private double val; public double Value{ get{ return val; } set{ this.val = value; } } public static implicit operator A(double d){ A a = new A(); a.Value = d; return a; } } and class B being very similar, but with int: public class B{ public B(){} private double val; public double Value{ get{ return val; } set{ this.val = value; } } public static implicit operator B(double d){ B b = new B(); b.Value = d; return b; } } I hoped that the implicit operator would have ensured that the double be converted to class A, or the int to class B, and the error avoided; but this is obviously not so. The above is used in a custom deserialization class, which takes data from a custom data format and fills in the corresponding .Net object properties. I'm doing this via reflection and at runtime, so I think both are unavoidable. I'm targeting the C# 2.0 framework. I've dozens, if not hundreds, of classes similar to A and B, so would prefer to find a solution which improved on the createAndFillArray method rather than a solution which altered these classes.

    Read the article

  • C# Extension Methods - To Extend or Not To Extend...

    - by James Michael Hare
    I've been thinking a lot about extension methods lately, and I must admit I both love them and hate them. They are a lot like sugar, they taste so nice and sweet, but they'll rot your teeth if you eat them too much.   I can't deny that they aren't useful and very handy. One of the major components of the Shared Component library where I work is a set of useful extension methods. But, I also can't deny that they tend to be overused and abused to willy-nilly extend every living type.   So what constitutes a good extension method? Obviously, you can write an extension method for nearly anything whether it is a good idea or not. Many times, in fact, an idea seems like a good extension method but in retrospect really doesn't fit.   So what's the litmus test? To me, an extension method should be like in the movies when a person runs into their twin, separated at birth. You just know you're related. Obviously, that's hard to quantify, so let's try to put a few rules-of-thumb around them.   A good extension method should:     Apply to any possible instance of the type it extends.     Simplify logic and improve readability/maintainability.     Apply to the most specific type or interface applicable.     Be isolated in a namespace so that it does not pollute IntelliSense.     So let's look at a few examples in relation to these rules.   The first rule, to me, is the most important of all. Once again, it bears repeating, a good extension method should apply to all possible instances of the type it extends. It should feel like the long lost relative that should have been included in the original class but somehow was missing from the family tree.    Take this nifty little int extension, I saw this once in a blog and at first I really thought it was pretty cool, but then I started noticing a code smell I couldn't quite put my finger on. So let's look:       public static class IntExtensinos     {         public static int Seconds(int num)         {             return num * 1000;         }           public static int Minutes(int num)         {             return num * 60000;         }     }     This is so you could do things like:       ...     Thread.Sleep(5.Seconds());     ...     proxy.Timeout = 1.Minutes();     ...     Awww, you say, that's cute! Well, that's the problem, it's kitschy and it doesn't always apply (and incidentally you could achieve the same thing with TimeStamp.FromSeconds(5)). It's syntactical candy that looks cool, but tends to rot and pollute the code. It would allow things like:       total += numberOfTodaysOrders.Seconds();     which makes no sense and should never be allowed. The problem is you're applying an extension method to a logical domain, not a type domain. That is, the extension method Seconds() doesn't really apply to ALL ints, it applies to ints that are representative of time that you want to convert to milliseconds.    Do you see what I mean? The two problems, in a nutshell, are that a) Seconds() called off a non-time value makes no sense and b) calling Seconds() off something to pass to something that does not take milliseconds will be off by a factor of 1000 or worse.   Thus, in my mind, you should only ever have an extension method that applies to the whole domain of that type.   For example, this is one of my personal favorites:       public static bool IsBetween<T>(this T value, T low, T high)         where T : IComparable<T>     {         return value.CompareTo(low) >= 0 && value.CompareTo(high) <= 0;     }   This allows you to check if any IComparable<T> is within an upper and lower bound. Think of how many times you type something like:       if (response.Employee.Address.YearsAt >= 2         && response.Employee.Address.YearsAt <= 10)     {     ...     }     Now, you can instead type:       if(response.Employee.Address.YearsAt.IsBetween(2, 10))     {     ...     }     Note that this applies to all IComparable<T> -- that's ints, chars, strings, DateTime, etc -- and does not depend on any logical domain. In addition, it satisfies the second point and actually makes the code more readable and maintainable.   Let's look at the third point. In it we said that an extension method should fit the most specific interface or type possible. Now, I'm not saying if you have something that applies to enumerables, you create an extension for List, Array, Dictionary, etc (though you may have reasons for doing so), but that you should beware of making things TOO general.   For example, let's say we had an extension method like this:       public static T ConvertTo<T>(this object value)     {         return (T)Convert.ChangeType(value, typeof(T));     }         This lets you do more fluent conversions like:       double d = "5.0".ConvertTo<double>();     However, if you dig into Reflector (LOVE that tool) you will see that if the type you are calling on does not implement IConvertible, what you convert to MUST be the exact type or it will throw an InvalidCastException. Now this may or may not be what you want in this situation, and I leave that up to you. Things like this would fail:       object value = new Employee();     ...     // class cast exception because typeof(IEmployee) != typeof(Employee)     IEmployee emp = value.ConvertTo<IEmployee>();       Yes, that's a downfall of working with Convertible in general, but if you wanted your fluent interface to be more type-safe so that ConvertTo were only callable on IConvertibles (and let casting be a manual task), you could easily make it:         public static T ConvertTo<T>(this IConvertible value)     {         return (T)Convert.ChangeType(value, typeof(T));     }         This is what I mean by choosing the best type to extend. Consider that if we used the previous (object) version, every time we typed a dot ('.') on an instance we'd pull up ConvertTo() whether it was applicable or not. By filtering our extension method down to only valid types (those that implement IConvertible) we greatly reduce our IntelliSense pollution and apply a good level of compile-time correctness.   Now my fourth rule is just my general rule-of-thumb. Obviously, you can make extension methods as in-your-face as you want. I included all mine in my work libraries in its own sub-namespace, something akin to:       namespace Shared.Core.Extensions { ... }     This is in a library called Shared.Core, so just referencing the Core library doesn't pollute your IntelliSense, you have to actually do a using on Shared.Core.Extensions to bring the methods in. This is very similar to the way Microsoft puts its extension methods in System.Linq. This way, if you want 'em, you use the appropriate namespace. If you don't want 'em, they won't pollute your namespace.   To really make this work, however, that namespace should only include extension methods and subordinate types those extensions themselves may use. If you plant other useful classes in those namespaces, once a user includes it, they get all the extensions too.   Also, just as a personal preference, extension methods that aren't simply syntactical shortcuts, I like to put in a static utility class and then have extension methods for syntactical candy. For instance, I think it imaginable that any object could be converted to XML:       namespace Shared.Core     {         // A collection of XML Utility classes         public static class XmlUtility         {             ...             // Serialize an object into an xml string             public static string ToXml(object input)             {                 var xs = new XmlSerializer(input.GetType());                   // use new UTF8Encoding here, not Encoding.UTF8. The later includes                 // the BOM which screws up subsequent reads, the former does not.                 using (var memoryStream = new MemoryStream())                 using (var xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding()))                 {                     xs.Serialize(xmlTextWriter, input);                     return Encoding.UTF8.GetString(memoryStream.ToArray());                 }             }             ...         }     }   I also wanted to be able to call this from an object like:       value.ToXml();     But here's the problem, if i made this an extension method from the start with that one little keyword "this", it would pop into IntelliSense for all objects which could be very polluting. Instead, I put the logic into a utility class so that users have the choice of whether or not they want to use it as just a class and not pollute IntelliSense, then in my extensions namespace, I add the syntactical candy:       namespace Shared.Core.Extensions     {         public static class XmlExtensions         {             public static string ToXml(this object value)             {                 return XmlUtility.ToXml(value);             }         }     }   So now it's the best of both worlds. On one hand, they can use the utility class if they don't want to pollute IntelliSense, and on the other hand they can include the Extensions namespace and use as an extension if they want. The neat thing is it also adheres to the Single Responsibility Principle. The XmlUtility is responsible for converting objects to XML, and the XmlExtensions is responsible for extending object's interface for ToXml().

    Read the article

  • Why unhandled exceptions are useful

    - by Simon Cooper
    It’s the bane of most programmers’ lives – an unhandled exception causes your application or webapp to crash, an ugly dialog gets displayed to the user, and they come complaining to you. Then, somehow, you need to figure out what went wrong. Hopefully, you’ve got a log file, or some other way of reporting unhandled exceptions (obligatory employer plug: SmartAssembly reports an application’s unhandled exceptions straight to you, along with the entire state of the stack and variables at that point). If not, you have to try and replicate it yourself, or do some psychic debugging to try and figure out what’s wrong. However, it’s good that the program crashed. Or, more precisely, it is correct behaviour. An unhandled exception in your application means that, somewhere in your code, there is an assumption that you made that is actually invalid. Coding assumptions Let me explain a bit more. Every method, every line of code you write, depends on implicit assumptions that you have made. Take this following simple method, that copies a collection to an array and includes an item if it isn’t in the collection already, using a supplied IEqualityComparer: public static T[] ToArrayWithItem( ICollection<T> coll, T obj, IEqualityComparer<T> comparer) { // check if the object is in collection already // using the supplied comparer foreach (var item in coll) { if (comparer.Equals(item, obj)) { // it's in the collection already // simply copy the collection to an array // and return it T[] array = new T[coll.Count]; coll.CopyTo(array, 0); return array; } } // not in the collection // copy coll to an array, and add obj to it // then return it T[] array = new T[coll.Count+1]; coll.CopyTo(array, 0); array[array.Length-1] = obj; return array; } What’s all the assumptions made by this fairly simple bit of code? coll is never null comparer is never null coll.CopyTo(array, 0) will copy all the items in the collection into the array, in the order defined for the collection, starting at the first item in the array. The enumerator for coll returns all the items in the collection, in the order defined for the collection comparer.Equals returns true if the items are equal (for whatever definition of ‘equal’ the comparer uses), false otherwise comparer.Equals, coll.CopyTo, and the coll enumerator will never throw an exception or hang for any possible input and any possible values of T coll will have less than 4 billion items in it (this is a built-in limit of the CLR) array won’t be more than 2GB, both on 32 and 64-bit systems, for any possible values of T (again, a limit of the CLR) There are no threads that will modify coll while this method is running and, more esoterically: The C# compiler will compile this code to IL according to the C# specification The CLR and JIT compiler will produce machine code to execute the IL on the user’s computer The computer will execute the machine code correctly That’s a lot of assumptions. Now, it could be that all these assumptions are valid for the situations this method is called. But if this does crash out with an exception, or crash later on, then that shows one of the assumptions has been invalidated somehow. An unhandled exception shows that your code is running in a situation which you did not anticipate, and there is something about how your code runs that you do not understand. Debugging the problem is the process of learning more about the new situation and how your code interacts with it. When you understand the problem, the solution is (usually) obvious. The solution may be a one-line fix, the rewrite of a method or class, or a large-scale refactoring of the codebase, but whatever it is, the fix for the crash will incorporate the new information you’ve gained about your own code, along with the modified assumptions. When code is running with an assumption or invariant it depended on broken, then the result is ‘undefined behaviour’. Anything can happen, up to and including formatting the entire disk or making the user’s computer sentient and start doing a good impression of Skynet. You might think that those can’t happen, but at Halting problem levels of generality, as soon as an assumption the code depended on is broken, the program can do anything. That is why it’s important to fail-fast and stop the program as soon as an invariant is broken, to minimise the damage that is done. What does this mean in practice? To start with, document and check your assumptions. As with most things, there is a level of judgement required. How you check and document your assumptions depends on how the code is used (that’s some more assumptions you’ve made), how likely it is a method will be passed invalid arguments or called in an invalid state, how likely it is the assumptions will be broken, how expensive it is to check the assumptions, and how bad things are likely to get if the assumptions are broken. Now, some assumptions you can assume unless proven otherwise. You can safely assume the C# compiler, CLR, and computer all run the method correctly, unless you have evidence of a compiler, CLR or processor bug. You can also assume that interface implementations work the way you expect them to; implementing an interface is more than simply declaring methods with certain signatures in your type. The behaviour of those methods, and how they work, is part of the interface contract as well. For example, for members of a public API, it is very important to document your assumptions and check your state before running the bulk of the method, throwing ArgumentException, ArgumentNullException, InvalidOperationException, or another exception type as appropriate if the input or state is wrong. For internal and private methods, it is less important. If a private method expects collection items in a certain order, then you don’t necessarily need to explicitly check it in code, but you can add comments or documentation specifying what state you expect the collection to be in at a certain point. That way, anyone debugging your code can immediately see what’s wrong if this does ever become an issue. You can also use DEBUG preprocessor blocks and Debug.Assert to document and check your assumptions without incurring a performance hit in release builds. On my coding soapbox… A few pet peeves of mine around assumptions. Firstly, catch-all try blocks: try { ... } catch { } A catch-all hides exceptions generated by broken assumptions, and lets the program carry on in an unknown state. Later, an exception is likely to be generated due to further broken assumptions due to the unknown state, causing difficulties when debugging as the catch-all has hidden the original problem. It’s much better to let the program crash straight away, so you know where the problem is. You should only use a catch-all if you are sure that any exception generated in the try block is safe to ignore. That’s a pretty big ask! Secondly, using as when you should be casting. Doing this: (obj as IFoo).Method(); or this: IFoo foo = obj as IFoo; ... foo.Method(); when you should be doing this: ((IFoo)obj).Method(); or this: IFoo foo = (IFoo)obj; ... foo.Method(); There’s an assumption here that obj will always implement IFoo. If it doesn’t, then by using as instead of a cast you’ve turned an obvious InvalidCastException at the point of the cast that will probably tell you what type obj actually is, into a non-obvious NullReferenceException at some later point that gives you no information at all. If you believe obj is always an IFoo, then say so in code! Let it fail-fast if not, then it’s far easier to figure out what’s wrong. Thirdly, document your assumptions. If an algorithm depends on a non-trivial relationship between several objects or variables, then say so. A single-line comment will do. Don’t leave it up to whoever’s debugging your code after you to figure it out. Conclusion It’s better to crash out and fail-fast when an assumption is broken. If it doesn’t, then there’s likely to be further crashes along the way that hide the original problem. Or, even worse, your program will be running in an undefined state, where anything can happen. Unhandled exceptions aren’t good per-se, but they give you some very useful information about your code that you didn’t know before. And that can only be a good thing.

    Read the article

  • NHibernate MySQL Composite-Key

    - by LnDCobra
    I am trying to create a composite key that mimicks the set of PrimaryKeys in the built in MySQL.DB table. The Db primary key is as follows: Field | Type | Null | ---------------------------------- Host | char(60) | No | Db | char(64) | No | User | char(16) | No | This is my DataBasePrivilege.hbm.xml file <?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="TGS.MySQL.DataBaseObjects" namespace="TGS.MySQL.DataBaseObjects"> <class name="TGS.MySQL.DataBaseObjects.DataBasePrivilege,TGS.MySQL.DataBaseObjects" table="db"> <composite-id name="CompositeKey" class="TGS.MySQL.DataBaseObjects.DataBasePrivilegePrimaryKey, TGS.MySQL.DataBaseObjects"> <key-property name="Host" column="Host" type="char" length="60" /> <key-property name="DataBase" column="Db" type="char" length="64" /> <key-property name="User" column="User" type="char" length="16" /> </composite-id> </class> </hibernate-mapping> The following are my 2 classes for my composite key: namespace TGS.MySQL.DataBaseObjects { public class DataBasePrivilege { public virtual DataBasePrivilegePrimaryKey CompositeKey { get; set; } } public class DataBasePrivilegePrimaryKey { public string Host { get; set; } public string DataBase { get; set; } public string User { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (DataBasePrivilegePrimaryKey)) return false; return Equals((DataBasePrivilegePrimaryKey) obj); } public bool Equals(DataBasePrivilegePrimaryKey other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.Host, Host) && Equals(other.DataBase, DataBase) && Equals(other.User, User); } public override int GetHashCode() { unchecked { int result = (Host != null ? Host.GetHashCode() : 0); result = (result*397) ^ (DataBase != null ? DataBase.GetHashCode() : 0); result = (result*397) ^ (User != null ? User.GetHashCode() : 0); return result; } } } } And the following is the exception I am getting: Execute System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'TGS.MySQL.DataBaseObjects.DataBasePrivilegePrimaryKey'. at (Object , GetterCallback ) at NHibernate.Bytecode.Lightweight.AccessOptimizer.GetPropertyValues(Object target) at NHibernate.Tuple.Component.PocoComponentTuplizer.GetPropertyValues(Object component) at NHibernate.Type.ComponentType.GetPropertyValues(Object component, EntityMode entityMode) at NHibernate.Type.ComponentType.GetHashCode(Object x, EntityMode entityMode) at NHibernate.Type.ComponentType.GetHashCode(Object x, EntityMode entityMode, ISessionFactoryImplementor factory) at NHibernate.Engine.EntityKey.GenerateHashCode() at NHibernate.Engine.EntityKey..ctor(Object identifier, String rootEntityName, String entityName, IType identifierType, Boolean batchLoadable, ISessionFactoryImplementor factory, EntityMode entityMode) at NHibernate.Engine.EntityKey..ctor(Object id, IEntityPersister persister, EntityMode entityMode) at NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) at NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) at NHibernate.Impl.SessionImpl.Get(String entityName, Object id) at NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) at NHibernate.Impl.SessionImpl.Get[T](Object id) at TGS.MySQL.DataBase.DataProvider.GetDatabasePrivilegeByHostDbUser(String host, String db, String user) in C:\Documents and Settings\Michal\My Documents\Visual Studio 2008\Projects\TGS\TGS.MySQL.DataBase\DataProvider.cs:line 20 at TGS.UserAccountControl.UserAccountManager.GetDatabasePrivilegeByHostDbUser(String host, String db, String user) in C:\Documents and Settings\Michal\My Documents\Visual Studio 2008\Projects\TGS\TGS.UserAccountControl\UserAccountManager.cs:line 10 at TGS.UserAccountControlTest.UserAccountManagerTest.CanGetDataBasePrivilegeByHostDbUser() in C:\Documents and Settings\Michal\My Documents\Visual Studio 2008\Projects\TGS\TGS.UserAccountControlTest\UserAccountManagerTest.cs:line 12 I am new to NHibernate and any help would be appreciated. I just can't see where it is getting the object[] from? Is the composite key supposed to be object[]?

    Read the article

  • Issue with translating a delegate function from c# to vb.net for use with Google OAuth 2

    - by Jeremy
    I've been trying to translate a Google OAuth 2 example from C# to Vb.net for a co-worker's project. I'm having on end of issues translating the following methods: private OAuth2Authenticator<WebServerClient> CreateAuthenticator() { // Register the authenticator. var provider = new WebServerClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = ClientCredentials.ClientID; provider.ClientSecret = ClientCredentials.ClientSecret; var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true }; return authenticator; } private IAuthorizationState GetAuthorization(WebServerClient client) { // If this user is already authenticated, then just return the auth state. IAuthorizationState state = AuthState; if (state != null) { return state; } // Check if an authorization request already is in progress. state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request)); if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken))) { // Store and return the credentials. HttpContext.Current.Session["AUTH_STATE"] = _state = state; return state; } // Otherwise do a new authorization request. string scope = TasksService.Scopes.TasksReadonly.GetStringValue(); OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope }); response.Send(); // Will throw a ThreadAbortException to prevent sending another response. return null; } The main issue being this line: var authenticator = new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = true }; The Method signature reads as for this particular line reads as follows: Public Sub New(tokenProvider As TClient, authProvider As System.Func(Of TClient, DotNetOpenAuth.OAuth2.IAuthorizationState)) My understanding of Delegate functions in VB.net isn't the greatest. However I have read over all of the MSDN documentation and other relevant resources on the web, but I'm still stuck as to how to translate this particular line. So far all of my attempts have resulted in either the a cast error (see below) or no call to GetAuthorization. The Code (vb.net on .net 3.5) Private Function CreateAuthenticator() As OAuth2Authenticator(Of WebServerClient) ' Register the authenticator. Dim client As New WebServerClient(GoogleAuthenticationServer.Description, oauth.ClientID, oauth.ClientSecret) Dim authDelegate As Func(Of WebServerClient, IAuthorizationState) = AddressOf GetAuthorization Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, authDelegate) With {.NoCaching = True} 'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, GetAuthorization(client)) With {.NoCaching = True} 'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, New Func(Of WebServerClient, IAuthorizationState)(Function(c) GetAuthorization(c))) With {.NoCaching = True} 'Dim authenticator = New OAuth2Authenticator(Of WebServerClient)(client, New Func(Of WebServerClient, IAuthorizationState)(AddressOf GetAuthorization)) With {.NoCaching = True} Return authenticator End Function Private Function GetAuthorization(arg As WebServerClient) As IAuthorizationState ' If this user is already authenticated, then just return the auth state. Dim state As IAuthorizationState = AuthState If (Not state Is Nothing) Then Return state End If ' Check if an authorization request already is in progress. state = arg.ProcessUserAuthorization(New HttpRequestInfo(HttpContext.Current.Request)) If (state IsNot Nothing) Then If ((String.IsNullOrEmpty(state.AccessToken) = False Or String.IsNullOrEmpty(state.RefreshToken) = False)) Then ' Store Credentials HttpContext.Current.Session("AUTH_STATE") = state _state = state Return state End If End If ' Otherwise do a new authorization request. Dim scope As String = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue() Dim _response As OutgoingWebResponse = arg.PrepareRequestUserAuthorization(New String() {scope}) ' Add Offline Access and forced Approval _response.Headers("location") += "&access_type=offline&approval_prompt=force" _response.Send() ' Will throw a ThreadAbortException to prevent sending another response. Return Nothing End Function The Cast Error Server Error in '/' Application. Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Unable to cast object of type 'DotNetOpenAuth.OAuth2.AuthorizationState' to type 'System.Func`2[DotNetOpenAuth.OAuth2.WebServerClient,DotNetOpenAuth.OAuth2.IAuthorizationState]'. I've spent the better part of a day on this, and it's starting to drive me nuts. Help is much appreciated.

    Read the article

  • XAML Parsing Exception

    - by e28Makaveli
    I have a simple XAML page that load fine when it is loaded as part of any application within Visual Studio. However, when I deploy this application using ClickOnce, I get the following exception: Type : System.Windows.Markup.XamlParseException, PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 Message : Unable to cast object of type 'System.Windows.Controls.Grid' to type 'EMS.Controls.Dictionary.StatusBarControl'. Error at object 'System.Windows.Controls.Grid' in markup file 'EMS.Controls.Dictionary;component/views/statusbarcontrol.xaml'. Source : PresentationFramework Help link : LineNumber : 0 LinePosition : 0 KeyContext : UidContext : NameContext : BaseUri : pack://application:,,,/EMS.Controls.Dictionary;component/views/statusbarcontrol.xaml Data : System.Collections.ListDictionaryInternal TargetSite : Void ThrowException(System.String, System.Exception, Int32, Int32, System.Uri, System.Windows.Markup.XamlObjectIds, System.Windows.Markup.XamlObjectIds, System.Type) Stack Trace : at System.Windows.Markup.XamlParseException.ThrowException(String message, Exception innerException, Int32 lineNumber, Int32 linePosition, Uri baseUri, XamlObjectIds currentXamlObjectIds, XamlObjectIds contextXamlObjectIds, Type objectType) at System.Windows.Markup.XamlParseException.ThrowException(ParserContext parserContext, Int32 lineNumber, Int32 linePosition, String message, Exception innerException) at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord) at System.Windows.Markup.BamlRecordReader.Read(Boolean singleRecord) at System.Windows.Markup.TreeBuilderBamlTranslator.ParseFragment() at System.Windows.Markup.TreeBuilder.Parse() at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream) at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator) at EMS.Controls.Dictionary.StatusBarControl.InitializeComponent() at EMS.Controls.Dictionary.StatusBarControl..ctor(IDataView content) at OCC600.ReportManager.ReportPresenter.ShowQueryView(Object arg, Boolean bringForward, Type selectedDataType) at OCC600.ReportManager.ReportPresenter..ctor(IUnityContainer container) at OCC600.ReportManager.Module.Initialize() at Microsoft.Practices.Composite.Modularity.ModuleLoader.Initialize(ModuleInfo[] moduleInfos) Inner Exception --------------- Type : System.InvalidCastException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Message : Unable to cast object of type 'System.Windows.Controls.Grid' to type 'EMS.Controls.Dictionary.StatusBarControl'. Source : EMS.Controls.Dictionary Help link : Data : System.Collections.ListDictionaryInternal TargetSite : Void System.Windows.Markup.IComponentConnector.Connect(Int32, System.Object) Stack Trace : at EMS.Controls.Dictionary.StatusBarControl.System.Windows.Markup.IComponentConnector.Connect(Int32 connectionId, Object target) at System.Windows.Markup.BamlRecordReader.ReadConnectionId(BamlConnectionIdRecord bamlConnectionIdRecord) at System.Windows.Markup.BamlRecordReader.ReadRecord(BamlRecord bamlRecord) The XAML page is given below: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:cdic="clr-namespace:EMS.Controls.Dictionary.Primitives" xmlns:dicutil="clr-namespace:OCC600.Infrastructure.Dictionary.Utility;assembly=EMS.Infrastructure.Dictionary" Loaded="ResultSetControl_Loaded" <StatusBarItem Margin="10,0, 10, 0"> <TextBlock Text="{Binding CountText}" Padding="5,0"/> </StatusBarItem> <StatusBarItem Margin="10,0"> <TextBlock Text="{Binding MemoryUsageText}" Padding="5,0"/> </StatusBarItem> <StatusBarItem Margin="10,0" MaxWidth="400"> <TextBlock Text="{Binding StatusReport.Summary}" Padding="5,0" /> </StatusBarItem> <ProgressBar Margin="20,0" Name="progBar" Width="150" Height="13" Visibility="Collapsed" > <ProgressBar.ContextMenu> <ContextMenu Name="ctxMenu" ItemsSource="{Binding ActiveWorkItems}" Visibility="{Binding Path=ActiveWorkItems.HasItems, Converter={StaticResource BooToVisConv}}"> <ContextMenu.ItemContainerStyle> <Style TargetType="{x:Type MenuItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type MenuItem}"> <StackPanel Height="20" Margin="10,0" Orientation="Horizontal" HorizontalAlignment="Left"> <TextBlock Text="{Binding Path=Name, Mode=OneTime}" Foreground="Black" VerticalAlignment="Center" HorizontalAlignment="Left" /> <ToggleButton Style="{StaticResource vistaGoldenToggleButtonStyle}" Padding="5,0" Content="Cancel" IsChecked="{Binding Cancel}" Margin="10,0,0,0" > </ToggleButton> </StackPanel> </ControlTemplate> </Setter.Value> </Setter> </Style> </ContextMenu.ItemContainerStyle> </ContextMenu> </ProgressBar.ContextMenu> </ProgressBar> <StatusBarItem Margin="10,0" MaxWidth="400" HorizontalAlignment="Right"> <StackPanel Orientation="Horizontal"> <TextBlock Text="Last Update:" Padding="5,0" /> <TextBlock Text="{Binding TimeStamp}" Padding="5,0" /> </StackPanel> </StatusBarItem> <!-- TODO: Put checkmark if all is well, or error if connection failed--> <StatusBarItem Style="{DynamicResource {ComponentResourceKey TypeInTargetAssembly=dc:Ribbon, ResourceId=StatusBarItemAlt}}" DockPanel.Dock="Right" Padding="6,0,32,0" > <cdic:SplitButton Margin="5,0" Padding="5,2" Style="{DynamicResource {ComponentResourceKey TypeInTargetAssembly={x:Type cdic:SplitButtonResources}, ResourceId=vistaSplitButtonStyle}}" Mode="Split"> <cdic:SplitButton.ContextMenu> <ContextMenu > <MenuItem Header="Refresh Now" Command="{Binding ToggleConnectivityCmd}" CommandParameter="false"/> <MenuItem IsCheckable="True" IsChecked="{Binding ConnectState, Converter={StaticResource isFailedConverter}}" CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=IsChecked}" Header="Work Offline" Command="{Binding ToggleConnectivityCmd}"/> </ContextMenu> </cdic:SplitButton.ContextMenu> <cdic:SplitButton.Content> <StackPanel Orientation="Horizontal"> <Image x:Name="img" Source="{Binding ConnectState, Converter={StaticResource imageConverter}}" Width="16" Height="16" HorizontalAlignment="Center" VerticalAlignment="Center"/> <TextBlock Text="{Binding ConnectState}" Padding="3,0,0,0"/> </StackPanel> </cdic:SplitButton.Content> </cdic:SplitButton> </StatusBarItem> </StatusBar> </Grid> The error just seems to have come out of no where. Any ideas? TIA.

    Read the article

  • Mixed-mode C++/CLI crashing: heap corruption in atexit (static destructor registration)

    - by thaimin
    I am working on deploying a program and the codebase is a mixture of C++/CLI and C#. The C++/CLI comes in all flavors: native, mixed (/clr), and safe (/clr:safe). In my development environment I create a DLL of all the C++/CLI code and reference that from the C# code (EXE). This method works flawlessly. For my releases that I want to release a single executable (simply stating that "why not just have a DLL and EXE separate?" is not acceptable). So far I have succeeded in compiling the EXE with all the different sources. However, when I run it I get the "XXXX has stopped working" dialog with options to Check online, Close and Debug. The problem details are as follows: Problem Event Name: APPCRASH Fault Module Name: StackHash_8d25 Fault Module Version: 6.1.7600.16559 Fault Module Timestamp: 4ba9b29c Exception Code: c0000374 Exception Offset: 000cdc9b OS Version: 6.1.7600.2.0.0.256.48 Locale ID: 1033 Additional Information 1: 8d25 Additional Information 2: 8d25552d834e8c143c43cf1d7f83abb8 Additional Information 3: 7450 Additional Information 4: 74509ce510cd821216ce477edd86119c If I debug and send it to Visual Studio, it reports: Unhandled exception at 0x77d2dc9b in XXX.exe: A heap has been corrupted Choosing break results in it stopping at ntdll.dll!77d2dc9b() with no additional information. If I tell Visual Studio to continue, the program starts up fine and seems to work without incident, probably since a debugger is now attached. What do you make of this? How do I avoid this heap corruption? The program seems to work fine except for this. My abridged compilation script is as follows (I have omitted my error checking for brevity): @set TARGET=x86 @set TARGETX=x86 @set OUT=%TARGETX% @call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" %TARGET% @set WIMGAPI=C:\Program Files\Windows AIK\SDKs\WIMGAPI\%TARGET% set CL=/Zi /nologo /W4 /O2 /GS /EHa /MD /MP /D NDEBUG /D _UNICODE /D UNICODE /D INTEGRATED /Fd%OUT%\ /Fo%OUT%\ set INCLUDE=%WIMGAPI%;%INCLUDE% set LINK=/nologo /LTCG /CLRIMAGETYPE:IJW /MANIFEST:NO /MACHINE:%TARGETX% /SUBSYSTEM:WINDOWS,6.0 /OPT:REF /OPT:ICF /DEFAULTLIB:msvcmrt.lib set LIB=%WIMGAPI%;%LIB% set CSC=/nologo /w:4 /d:INTEGRATED /o+ /target:module :: Compiling resources omitted @set CL_NATIVE=/c /FI"stdafx-native.h" @set CL_MIXED=/c /clr /LN /FI"stdafx-mixed.h" @set CL_PURE=/c /clr:safe /LN /GL /FI"stdafx-pure.h" @set NATIVE=... @set MIXED=... @set PURE=... cl %CL_NATIVE% %NATIVE% cl %CL_MIXED% %MIXED% cl %CL_PURE% %PURE% link /LTCG /NOASSEMBLY /DLL /OUT:%OUT%\core.netmodule %OUT%\*.obj csc %CSC% /addmodule:%OUT%\core.netmodule /out:%OUT%\GUI.netmodule /recurse:*.cs link /FIXED /ENTRY:GUI.Program.Main /OUT:%OUT%\XXX.exe ^ /ASSEMBLYRESOURCE:%OUT%\core.resources,XXX.resources,PRIVATE /ASSEMBLYRESOURCE:%OUT%\GUI.resources,GUI.resources,PRIVATE ^ /ASSEMBLYMODULE:%OUT%\core.netmodule %OUT%\gui.res %OUT%\*.obj %OUT%\GUI.netmodule Update 1 Upon compiling this with debug symbols and trying again, I do in fact get more information. The call stack is: msvcr90d.dll!_msize_dbg(void * pUserData, int nBlockUse) Line 1511 + 0x30 bytes msvcr90d.dll!_dllonexit_nolock(int (void)* func, void (void)* * * pbegin, void (void)* * * pend) Line 295 + 0xd bytes msvcr90d.dll!__dllonexit(int (void)* func, void (void)* * * pbegin, void (void)* * * pend) Line 273 + 0x11 bytes XXX.exe!_onexit(int (void)* func) Line 110 + 0x1b bytes XXX.exe!atexit(void (void)* func) Line 127 + 0x9 bytes XXX.exe!`dynamic initializer for 'Bytes::Null''() Line 7 + 0xa bytes mscorwks.dll!6cbd1b5c() [Frames below may be incorrect and/or missing, no symbols loaded for mscorwks.dll] ... The line of my code that 'causes' this (dynamic initializer for Bytes::Null) is: Bytes Bytes::Null; In the header that is declared as: class Bytes { public: static Bytes Null; } I also tried doing a global extern in the header like so: extern Bytes Null; // header Bytes Null; // cpp file Which failed in the same way. It seems that the CRT atexit function is responsible, being inadvertently required due to the static initializer. Fix As Ben Voigt pointed out the use of any CRT functions (including native static initializers) requires proper initialization of the CRT (which happens in mainCRTStartup, WinMainCRTStartup, or _DllMainCRTStartup). I have added a mixed C++/CLI file that has a C++ main or WinMain: using namespace System; [STAThread] // required if using an STA COM objects (such as drag-n-drop or file dialogs) int main() { // or "int __stdcall WinMain(void*, void*, wchar_t**, int)" for GUI applications array<String^> ^args_orig = Environment::GetCommandLineArgs(); int l = args_orig->Length - 1; // required to remove first argument (program name) array<String^> ^args = gcnew array<String^>(l); if (l > 0) Array::Copy(args_orig, 1, args, 0, l); return XXX::CUI::Program::Main(args); // return XXX::GUI::Program::Main(args); } After doing this, the program now gets a little further, but still has issues (which will be addressed elsewhere): When the program is solely in C# it works fine, along with whenever it is just calling C++/CLI methods, getting C++/CLI properties, and creating managed C++/CLI objects Events added by C# into the C++/CLI code never fire (even though they should) One other weird error is that an exception happens is a InvalidCastException saying can't cast from X to X (where X is the same as X...) However since the heap corruption is fixed (by getting the CRT initialized) the question is done.

    Read the article

  • AutoMapper is not working for a Container class

    - by rboarman
    Hello, I have an AutoMapper issue that has been driving me crazy for way too long now. A similar question was also posted on the AutoMapper user site but has not gotten much love. The summary is that I have a container class that holds a Dictionary of components. The components are a derived object of a common base class. I also have a parallel structure that I am using as DTO objects to which I want to map. The error that gets generated seems to say that the mapper cannot map between two of the classes that I have included in the CreateMap calls. I think the error has to do with the fact that I have a Dictionary of objects that are not part of the container‘s hierarchy. I apologize in advance for the length of the code below. My simple test cases work. Needless to say, it’s only the more complex case that is failing. Here are the classes: #region Dto objects public class ComponentContainerDTO { public Dictionary<string, ComponentDTO> Components { get; set; } public ComponentContainerDTO() { this.Components = new Dictionary<string, ComponentDTO>(); } } public class EntityDTO : ComponentContainerDTO { public int Id { get; set; } } public class ComponentDTO { public EntityDTO Owner { get; set; } public int Id { get; set; } public string Name { get; set; } public string ComponentType { get; set; } } public class HealthDTO : ComponentDTO { public decimal CurrentHealth { get; set; } } public class PhysicalLocationDTO : ComponentDTO { public Point2D Location { get; set; } } #endregion #region Domain objects public class ComponentContainer { public Dictionary<string, Component> Components { get; set; } public ComponentContainer() { this.Components = new Dictionary<string, Component>(); } } public class Entity : ComponentContainer { public int Id { get; set; } } public class Component { public Entity Owner { get; set; } public int Id { get; set; } public string Name { get; set; } public string ComponentType { get; set; } } public class Health : Component { public decimal CurrentHealth { get; set; } } public struct Point2D { public decimal X; public decimal Y; public Point2D(decimal x, decimal y) { X = x; Y = y; } } public class PhysicalLocation : Component { public Point2D Location { get; set; } } #endregion The code: var entity = new Entity() { Id = 1 }; var healthComponent = new Health() { CurrentHealth = 100, Owner = entity, Name = "Health", Id = 2 }; entity.Components.Add("1", healthComponent); var locationComponent = new PhysicalLocation() { Location = new Point2D() { X = 1, Y = 2 }, Owner = entity, Name = "PhysicalLocation", Id = 3 }; entity.Components.Add("2", locationComponent); Mapper.CreateMap<ComponentContainer, ComponentContainerDTO>() .Include<Entity, EntityDTO>(); Mapper.CreateMap<Entity, EntityDTO>(); Mapper.CreateMap<Component, ComponentDTO>() .Include<Health, HealthDTO>() .Include<PhysicalLocation, PhysicalLocationDTO>(); Mapper.CreateMap<Component, ComponentDTO>(); Mapper.CreateMap<Health, HealthDTO>(); Mapper.CreateMap<PhysicalLocation, PhysicalLocationDTO>(); Mapper.AssertConfigurationIsValid(); var targetEntity = Mapper.Map<Entity, EntityDTO>(entity); The error when I call Map() (abbreviated stack crawls): AutoMapper.AutoMapperMappingException was unhandled Message=Trying to map MapperTest1.Entity to MapperTest1.EntityDTO. Using mapping configuration for MapperTest1.Entity to MapperTest1.EntityDTO Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. Source=AutoMapper StackTrace: at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) . . . InnerException: AutoMapper.AutoMapperMappingException Message=Trying to map System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MapperTest1.Component, ElasticTest1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] to System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MapperTest1.ComponentDTO, ElasticTest1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]. Using mapping configuration for MapperTest1.Entity to MapperTest1.EntityDTO Destination property: Components Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. Source=AutoMapper StackTrace: at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap) . . InnerException: AutoMapper.AutoMapperMappingException Message=Trying to map System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MapperTest1.Component, ElasticTest1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] to System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MapperTest1.ComponentDTO, ElasticTest1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]. Using mapping configuration for MapperTest1.Entity to MapperTest1.EntityDTO Destination property: Components Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. Source=AutoMapper StackTrace: at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) . InnerException: AutoMapper.AutoMapperMappingException Message=Trying to map MapperTest1.Component to MapperTest1.ComponentDTO. Using mapping configuration for MapperTest1.Health to MapperTest1.HealthDTO Destination property: Components Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. Source=AutoMapper StackTrace: at AutoMapper.MappingEngine.AutoMapper.IMappingEngineRunner.Map(ResolutionContext context) . . InnerException: AutoMapper.AutoMapperMappingException Message=Trying to map System.Decimal to System.Decimal. Using mapping configuration for MapperTest1.Health to MapperTest1.HealthDTO Destination property: CurrentHealth Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. Source=AutoMapper StackTrace: at AutoMapper.Mappers.TypeMapObjectMapperRegistry.PropertyMapMappingStrategy.MapPropertyValue(ResolutionContext context, IMappingEngineRunner mapper, Object mappedObject, PropertyMap propertyMap) . . InnerException: System.InvalidCastException Message=Unable to cast object of type 'MapperTest1.ComponentDTO' to type 'MapperTest1.HealthDTO'. Source=Anonymously Hosted DynamicMethods Assembly StackTrace: at SetCurrentHealth(Object , Object ) . . Thank you in advance. Rick

    Read the article

  • Configuration Error ASP.NET password format specified is invalid

    - by salvationishere
    I am getting the above error in IIS 6.0 now when I browse my C# / SQL web application. This was built in VS 2008 and SS 2008 on a 32-bit XP OS. The application was working before I added Login controls to it. However, this is my first time configuring Login/password controls so I am probably missing something really basic. This error doesn't happen until I try to login. Here are the details of my error from IIS; I get the same error in VS: Parser Error Message: Password format specified is invalid. Source Error: Line 31: <add Line 32: name="SqlProvider" Line 33: type="System.Web.Security.SqlMembershipProvider" Line 34: connectionStringName="AdventureWorksConnectionString2" Line 35: applicationName="AddFileToSQL2" Source File: C:\Inetpub\AddFileToSQL2\web.config Line: 33 And the relevant contents of my web.config are: <connectionStrings> <add name="Master" connectionString="server=MSSQLSERVER;database=Master; Integrated Security=SSPI" providerName="System.Data.SqlClient" /> <add name="AdventureWorksConnectionString" connectionString="Data Source=SIDEKICK;Initial Catalog=AdventureWorks;Integrated Security=True" providerName="System.Data.SqlClient" /> <add name="AdventureWorksConnectionString2" connectionString="Data Source=SIDEKICK;Initial Catalog=AdventureWorks;Integrated Security=True; " providerName="System.Data.SqlClient" /> </connectionStrings> <system.web> <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15"> <providers> <clear /> <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="AdventureWorksConnectionString2" applicationName="AddFileToSQL2" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="false" passwordFormat="encrypted" /> </providers> </membership> <!-- Set compilation debug="true" to insert debugging symbols into the compiled page. Because this affects performance, set this value to true only during development. --> <roleManager enabled="true" /> <compilation debug="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> <!-- The <authentication> section enables configuration of the security authentication mode used by ASP.NET to identify an incoming user. --> <authentication mode="Forms"> <forms loginUrl="Password.aspx" protection="All" timeout="30" name="SqlAuthCookie" path="/FormsAuth" requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx" cookieless="UseCookies" enableCrossAppRedirects="false" /> </authentication> <!--Authorization permits only authenticated users to access the application --> <authorization> <deny users="?" /> <allow users="*" /> </authorization> <!-- The <customErrors> section enables configuration of what to do if/when an unhandled error occurs during the execution of a request. Specifically, it enables developers to configure html error pages to be displayed in place of a error stack trace. <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> --> <pages> <controls> <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </controls> </pages> <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> </httpHandlers> <httpModules> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </httpModules> </system.web> <system.codedom> <compilers> <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <providerOption name="CompilerVersion" value="v3.5"/> <providerOption name="WarnAsError" value="false"/> </compiler> </compilers> </system.codedom> <!-- The system.webServer section is required for running ASP.NET AJAX under Internet Information Services 7.0. It is not necessary for previous version of IIS. --> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <remove name="ScriptModule"/> <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <remove name="ScriptHandlerFactory"/> <remove name="ScriptHandlerFactoryAppServices"/> <remove name="ScriptResource"/> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </handlers> </system.webServer> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/> <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> <system.net> <mailSettings> <smtp from="[email protected]"> <network host="SIDEKICK" password="" userName="" /> </smtp> </mailSettings> </system.net> </configuration> I checked and I do have an aspnetdb database in my SSMS. The Network Service account has SELECT, EXECUTE, INSERT, UPDATE access to this database. But one problem I see is that all of the tables in this database are empty except for aspnet_SchemaVersions, which just has 2 records (common and membership). Is this right? I added users and roles via ASP.NET Configuration wizard, and I believe I set this up correctly since I followed the Microsoft tutorial at http://msdn.microsoft.com/en-us/library/ms998347.aspx. One other problem I see from VS is after adding content to my Page_Load on my initial login Password.aspx.cs file, I'm getting an invalid cast problem below. I googled this problem also but the solutions I saw confused me even more. The Page_Load section I added is: protected void Page_Load(object sender, EventArgs e) { Response.Write("Hello, " + Server.HtmlEncode(User.Identity.Name)); FormsIdentity id = (FormsIdentity)User.Identity; FormsAuthenticationTicket ticket = id.Ticket; Response.Write("<p/>TicketName: " + ticket.Name); Response.Write("<br/>Cookie Path: " + ticket.CookiePath); Response.Write("<br/>Ticket Expiration: " + ticket.Expiration.ToString()); Response.Write("<br/>Expired: " + ticket.Expired.ToString()); Response.Write("<br/>Persistent: " + ticket.IsPersistent.ToString()); Response.Write("<br/>IssueDate: " + ticket.IssueDate.ToString()); Response.Write("<br/>UserData: " + ticket.UserData); Response.Write("<br/>Version: " + ticket.Version.ToString()); } And the VS exception I'm getting: System.InvalidCastException was unhandled by user code Message="Unable to cast object of type 'System.Security.Principal.GenericIdentity' to type 'System.Web.Security.FormsIdentity'." Source="AddFileToSQL" StackTrace: at AddFileToSQL.Password.Page_Load(Object sender, EventArgs e) in C:\Documents and Settings\Admin\My Documents\Visual Studio 2008\Projects\AddFileToSQL2\AddFileToSQL\Password.aspx.cs:line 22 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException:

    Read the article

  • WMI Remote Process Starting

    - by Goober
    Scenario I've written a WMI Wrapper that seems to be quite sufficient, however whenever I run the code to start a remote process on a server, I see the process name appear in the task manager but the process itself does not start like it should (as in, I don't see the command line log window of the process that prints out what it's doing etc.) The process I am trying to start is just a C# application executable that I have written. Below is my WMI Wrapper Code and the code I am using to start running the process. Question Is the process actually running? - Even if it is only displaying the process name in the task manager and not actually launching the application to the users window? Code To Start The Process IPHostEntry hostEntry = Dns.GetHostEntry("InsertServerName"); WMIWrapper wrapper = new WMIWrapper("Insert User Name", "Insert Password", hostEntry.HostName); List<Process> processes = wrapper.GetProcesses(); foreach (Process process in processes) { if (process.Caption.Equals("MyAppName.exe")) { Console.WriteLine(process.Caption); Console.WriteLine(process.CommandLine); int processId; wrapper.StartProcess("E:\\MyData\\Data\\MyAppName.exe", out processId); Console.WriteLine(processId.ToString()); } } Console.ReadLine(); WMI Wrapper Code using System; using System.Collections.Generic; using System.Management; using System.Runtime.InteropServices; using Common.WMI.Objects; using System.Net; namespace Common.WMIWrapper { public class WMIWrapper : IDisposable { #region Constructor /// <summary> /// Creates a new instance of the wrapper /// </summary> /// <param jobName="username"></param> /// <param jobName="password"></param> /// <param jobName="server"></param> public WMIWrapper(string server) { Initialise(server); } /// <summary> /// Creates a new instance of the wrapper /// </summary> /// <param jobName="username"></param> /// <param jobName="password"></param> /// <param jobName="server"></param> public WMIWrapper(string username, string password, string server) { Initialise(username, password, server); } #endregion #region Destructor /// <summary> /// Clean up unmanaged references /// </summary> ~WMIWrapper() { Dispose(false); } #endregion #region Initialise /// <summary> /// Initialise the WMI Connection (local machine) /// </summary> /// <param name="server"></param> private void Initialise(string server) { m_server = server; // set connection options m_connectOptions = new ConnectionOptions(); IPHostEntry host = Dns.GetHostEntry(Environment.MachineName); } /// <summary> /// Initialise the WMI connection /// </summary> /// <param jobName="username">Username to connect to server with</param> /// <param jobName="password">Password to connect to server with</param> /// <param jobName="server">Server to connect to</param> private void Initialise(string username, string password, string server) { m_server = server; // set connection options m_connectOptions = new ConnectionOptions(); IPHostEntry host = Dns.GetHostEntry(Environment.MachineName); if (host.HostName.Equals(server, StringComparison.OrdinalIgnoreCase)) return; m_connectOptions.Username = username; m_connectOptions.Password = password; m_connectOptions.Impersonation = ImpersonationLevel.Impersonate; m_connectOptions.EnablePrivileges = true; } #endregion /// <summary> /// Return a list of available wmi namespaces /// </summary> /// <returns></returns> public List<String> GetWMINamespaces() { ManagementScope wmiScope = new ManagementScope(String.Format("\\\\{0}\\root", this.Server), this.ConnectionOptions); List<String> wmiNamespaceList = new List<String>(); ManagementClass wmiNamespaces = new ManagementClass(wmiScope, new ManagementPath("__namespace"), null); ; foreach (ManagementObject ns in wmiNamespaces.GetInstances()) wmiNamespaceList.Add(ns["Name"].ToString()); return wmiNamespaceList; } /// <summary> /// Return a list of available classes in a namespace /// </summary> /// <param jobName="wmiNameSpace">Namespace to get wmi classes for</param> /// <returns>List of classes in the requested namespace</returns> public List<String> GetWMIClassList(string wmiNameSpace) { ManagementScope wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\{1}", this.Server, wmiNameSpace), this.ConnectionOptions); List<String> wmiClasses = new List<String>(); ManagementObjectSearcher wmiSearcher = new ManagementObjectSearcher(wmiScope, new WqlObjectQuery("SELECT * FROM meta_Class"), null); foreach (ManagementClass wmiClass in wmiSearcher.Get()) wmiClasses.Add(wmiClass["__CLASS"].ToString()); return wmiClasses; } /// <summary> /// Get a list of wmi properties for the specified class /// </summary> /// <param jobName="wmiNameSpace">WMI Namespace</param> /// <param jobName="wmiClass">WMI Class</param> /// <returns>List of properties for the class</returns> public List<String> GetWMIClassPropertyList(string wmiNameSpace, string wmiClass) { List<String> wmiClassProperties = new List<string>(); ManagementClass managementClass = GetWMIClass(wmiNameSpace, wmiClass); foreach (PropertyData property in managementClass.Properties) wmiClassProperties.Add(property.Name); return wmiClassProperties; } /// <summary> /// Returns a list of methods for the class /// </summary> /// <param jobName="wmiNameSpace"></param> /// <param jobName="wmiClass"></param> /// <returns></returns> public List<String> GetWMIClassMethodList(string wmiNameSpace, string wmiClass) { List<String> wmiClassMethods = new List<string>(); ManagementClass managementClass = GetWMIClass(wmiNameSpace, wmiClass); foreach (MethodData method in managementClass.Methods) wmiClassMethods.Add(method.Name); return wmiClassMethods; } /// <summary> /// Retrieve the specified management class /// </summary> /// <param jobName="wmiNameSpace">Namespace of the class</param> /// <param jobName="wmiClass">Type of the class</param> /// <returns></returns> public ManagementClass GetWMIClass(string wmiNameSpace, string wmiClass) { ManagementScope wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\{1}", this.Server, wmiNameSpace), this.ConnectionOptions); ManagementClass managementClass = null; ManagementObjectSearcher wmiSearcher = new ManagementObjectSearcher(wmiScope, new WqlObjectQuery(String.Format("SELECT * FROM meta_Class WHERE __CLASS = '{0}'", wmiClass)), null); foreach (ManagementClass wmiObject in wmiSearcher.Get()) managementClass = wmiObject; return managementClass; } /// <summary> /// Get an instance of the specficied class /// </summary> /// <param jobName="wmiNameSpace">Namespace of the classes</param> /// <param jobName="wmiClass">Type of the classes</param> /// <returns>Array of management classes</returns> public ManagementObject[] GetWMIClassObjects(string wmiNameSpace, string wmiClass) { ManagementScope wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\{1}", this.Server, wmiNameSpace), this.ConnectionOptions); List<ManagementObject> wmiClasses = new List<ManagementObject>(); ManagementObjectSearcher wmiSearcher = new ManagementObjectSearcher(wmiScope, new WqlObjectQuery(String.Format("SELECT * FROM {0}", wmiClass)), null); foreach (ManagementObject wmiObject in wmiSearcher.Get()) wmiClasses.Add(wmiObject); return wmiClasses.ToArray(); } /// <summary> /// Get a full list of services /// </summary> /// <returns></returns> public List<Service> GetServices() { return GetService(null); } /// <summary> /// Get a list of services /// </summary> /// <returns></returns> public List<Service> GetService(string name) { ManagementObject[] services = GetWMIClassObjects("CIMV2", "WIN32_Service"); List<Service> serviceList = new List<Service>(); for (int i = 0; i < services.Length; i++) { ManagementObject managementObject = services[i]; Service service = new Service(managementObject); service.Status = (string)managementObject["Status"]; service.Name = (string)managementObject["Name"]; service.DisplayName = (string)managementObject["DisplayName"]; service.PathName = (string)managementObject["PathName"]; service.ProcessId = (uint)managementObject["ProcessId"]; service.Started = (bool)managementObject["Started"]; service.StartMode = (string)managementObject["StartMode"]; service.ServiceType = (string)managementObject["ServiceType"]; service.InstallDate = (string)managementObject["InstallDate"]; service.Description = (string)managementObject["Description"]; service.Caption = (string)managementObject["Caption"]; if (String.IsNullOrEmpty(name) || name.Equals(service.Name, StringComparison.OrdinalIgnoreCase)) serviceList.Add(service); } return serviceList; } /// <summary> /// Get a list of processes /// </summary> /// <returns></returns> public List<Process> GetProcesses() { return GetProcess(null); } /// <summary> /// Get a list of processes /// </summary> /// <returns></returns> public List<Process> GetProcess(uint? processId) { ManagementObject[] processes = GetWMIClassObjects("CIMV2", "WIN32_Process"); List<Process> processList = new List<Process>(); for (int i = 0; i < processes.Length; i++) { ManagementObject managementObject = processes[i]; Process process = new Process(managementObject); process.Priority = (uint)managementObject["Priority"]; process.ProcessId = (uint)managementObject["ProcessId"]; process.Status = (string)managementObject["Status"]; DateTime createDate; if (ConvertFromWmiDate((string)managementObject["CreationDate"], out createDate)) process.CreationDate = createDate.ToString("dd-MMM-yyyy HH:mm:ss"); process.Caption = (string)managementObject["Caption"]; process.CommandLine = (string)managementObject["CommandLine"]; process.Description = (string)managementObject["Description"]; process.ExecutablePath = (string)managementObject["ExecutablePath"]; process.ExecutionState = (string)managementObject["ExecutionState"]; process.MaximumWorkingSetSize = (UInt32?)managementObject ["MaximumWorkingSetSize"]; process.MinimumWorkingSetSize = (UInt32?)managementObject["MinimumWorkingSetSize"]; process.KernelModeTime = (UInt64)managementObject["KernelModeTime"]; process.ThreadCount = (UInt32)managementObject["ThreadCount"]; process.UserModeTime = (UInt64)managementObject["UserModeTime"]; process.VirtualSize = (UInt64)managementObject["VirtualSize"]; process.WorkingSetSize = (UInt64)managementObject["WorkingSetSize"]; if (processId == null || process.ProcessId == processId.Value) processList.Add(process); } return processList; } /// <summary> /// Start the specified process /// </summary> /// <param jobName="commandLine"></param> /// <returns></returns> public bool StartProcess(string command, out int processId) { processId = int.MaxValue; ManagementClass processClass = GetWMIClass("CIMV2", "WIN32_Process"); object[] objectsIn = new object[4]; objectsIn[0] = command; processClass.InvokeMethod("Create", objectsIn); if (objectsIn[3] == null) return false; processId = int.Parse(objectsIn[3].ToString()); return true; } /// <summary> /// Schedule a process on the remote machine /// </summary> /// <param name="command"></param> /// <param name="scheduleTime"></param> /// <param name="jobName"></param> /// <returns></returns> public bool ScheduleProcess(string command, DateTime scheduleTime, out string jobName) { jobName = String.Empty; ManagementClass scheduleClass = GetWMIClass("CIMV2", "Win32_ScheduledJob"); object[] objectsIn = new object[7]; objectsIn[0] = command; objectsIn[1] = String.Format("********{0:00}{1:00}{2:00}.000000+060", scheduleTime.Hour, scheduleTime.Minute, scheduleTime.Second); objectsIn[5] = true; scheduleClass.InvokeMethod("Create", objectsIn); if (objectsIn[6] == null) return false; UInt32 scheduleid = (uint)objectsIn[6]; jobName = scheduleid.ToString(); return true; } /// <summary> /// Returns the current time on the remote server /// </summary> /// <returns></returns> public DateTime Now() { ManagementScope wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\{1}", this.Server, "CIMV2"), this.ConnectionOptions); ManagementClass managementClass = null; ManagementObjectSearcher wmiSearcher = new ManagementObjectSearcher(wmiScope, new WqlObjectQuery(String.Format("SELECT * FROM Win32_LocalTime")), null); DateTime localTime = DateTime.MinValue; foreach (ManagementObject time in wmiSearcher.Get()) { UInt32 day = (UInt32)time["Day"]; UInt32 month = (UInt32)time["Month"]; UInt32 year = (UInt32)time["Year"]; UInt32 hour = (UInt32)time["Hour"]; UInt32 minute = (UInt32)time["Minute"]; UInt32 second = (UInt32)time["Second"]; localTime = new DateTime((int)year, (int)month, (int)day, (int)hour, (int)minute, (int)second); }; return localTime; } /// <summary> /// Converts a wmi date into a proper date /// </summary> /// <param jobName="wmiDate">Wmi formatted date</param> /// <returns>Date time object</returns> private static bool ConvertFromWmiDate(string wmiDate, out DateTime properDate) { properDate = DateTime.MinValue; string properDateString; // check if string is populated if (String.IsNullOrEmpty(wmiDate)) return false; wmiDate = wmiDate.Trim().ToLower().Replace("*", "0"); string[] months = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; try { properDateString = String.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}", wmiDate.Substring(6, 2), months[int.Parse(wmiDate.Substring(4, 2)) - 1], wmiDate.Substring(0, 4), wmiDate.Substring(8, 2), wmiDate.Substring(10, 2), wmiDate.Substring(12, 2), wmiDate.Substring(15, 6)); } catch (InvalidCastException) { return false; } catch (ArgumentOutOfRangeException) { return false; } // try and parse the new date if (!DateTime.TryParse(properDateString, out properDate)) return false; // true if conversion successful return true; } private bool m_disposed; #region IDisposable Members /// <summary> /// Managed dispose /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose of managed and unmanaged objects /// </summary> /// <param jobName="disposing"></param> public void Dispose(bool disposing) { if (disposing) { m_connectOptions = null; } } #endregion #region Properties private ConnectionOptions m_connectOptions; /// <summary> /// Gets or sets the management scope /// </summary> private ConnectionOptions ConnectionOptions { get { return m_connectOptions; } set { m_connectOptions = value; } } private String m_server; /// <summary> /// Gets or sets the server to connect to /// </summary> public String Server { get { return m_server; } set { m_server = value; } } #endregion } }

    Read the article

< Previous Page | 1 2 3 4 5