Search Results

Search found 785 results on 32 pages for 'gettype'.

Page 9/32 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Converting ANTLR AST to Java bytecode using ASM

    - by Nick
    I am currently trying to write my own compiler, targeting the JVM. I have completed the parsing step using Java classes generated by ANTLR, and have an AST of the source code to work from (An ANTLR "CommonTree", specifically). I am using ASM to simplify the generating of the bytecode. Could anyone give a broad overview of how to convert this AST to bytecode? My current strategy is to explore down the tree, generating different code depending on the current node (using "Tree.getType()"). The problem is that I can only recognise tokens from my lexer this way, rather than more complex patterns from the parser. Is there something I am missing, or am I simply approaching this wrong? Thanks in advance :)

    Read the article

  • Why does Javascript use JSON.stringify instead of JSON.serialize?

    - by Chase Florell
    I'm just wondering about "stringify" vs "serialize". To me they're the same thing (though I could be wrong), but in my past experience (mostly with asp.net) I use Serialize() and never use Stringify(). I know I can create a simple alias in Javascript, // either JSON.serialize = function(input) { return JSON.stringify(input); }; // or JSON.serialize = JSON.stringify; http://jsfiddle.net/HKKUb/ but I'm just wondering about the difference between the two and why stringify was chosen. for comparison purpose, here's how you serialize XML to a String in C# public static string SerializeObject<T>(this T toSerialize) { XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType()); StringWriter textWriter = new StringWriter(); xmlSerializer.Serialize(textWriter, toSerialize); return textWriter.ToString(); }

    Read the article

  • WMemoryProfiler is Released

    - by Alois Kraus
    What is it? WMemoryProfiler is a managed profiling Api to aid integration testing. This free library can get managed heap statistics and memory usage for your own process (remember testing) and other processes as well. The best thing is that it does work from .NET 2.0 up to .NET 4.5 in x86 and x64. To make it more interesting it can attach to any running .NET process. The reason why I do mention this is that commercial profilers do support this functionality only for their professional editions. An normally only since .NET 4.0 since the profiling API only since then does support attaching to a running process. This thing does differ in many aspects from “normal” profilers because while profiling yourself you can get all objects from all managed heaps back as an object array. If you ever wanted to change the state of an object which does only exist a method local in another thread you can get your hands on it now … Enough theory. Show me some code /// <summary> /// Show feature to not only get statisics out of a process but also the newly allocated /// instances since the last call to MarkCurrentObjects. /// GetNewObjects does return the newly allocated objects as object array /// </summary> static void InstanceTracking() { using (var dumper = new MemoryDumper()) // if you have problems use to see the debugger windows true,true)) { dumper.MarkCurrentObjects(); Allocate(); ILookup<Type, object> newObjects = dumper.GetNewObjects() .ToLookup( x => x.GetType() ); Console.WriteLine("New Strings:"); foreach (var newStr in newObjects[typeof(string)] ) { Console.WriteLine("Str: {0}", newStr); } } } … New Strings: Str: qqd Str: String data: Str: String data: 0 Str: String data: 1 … This is really hot stuff. Not only you can get heap statistics but you can directly examine the new objects and make queries upon them. When I do find more time I can reconstruct the object root graph from it from my own process. It this cool or what? You can also peek into the Finalization Queue to check if you did accidentally forget to dispose a whole bunch of objects … /// <summary> /// .NET 4.0 or above only. Get all finalizable objects which are ready for finalization and have no other object roots anymore. /// </summary> static void NotYetFinalizedObjects() { using (var dumper = new MemoryDumper()) { object[] finalizable = dumper.GetObjectsReadyForFinalization(); Console.WriteLine("Currently {0} objects of types {1} are ready for finalization. Consider disposing them before.", finalizable.Length, String.Join(",", finalizable.ToLookup( x=> x.GetType() ) .Select( x=> x.Key.Name)) ); } } How does it work? The W of WMemoryProfiler is a good hint. It does employ Windbg and SOS dll to do the heavy lifting and concentrates on an easy to use Api which does hide completely Windbg. If you do not want to see Windbg you will never see it. In my experience the most complex thing is actually to download Windbg from the Windows 8 Stanalone SDK. This is described in the Readme and the exception you are greeted with if it is missing in much greater detail. So I will not go into this here.   What Next? Depending on the feedback I do get I can imagine some features which might be useful as well Calculate first order GC Roots from the actual object graph Identify global statics in Types in object graph Support read out of finalization queue of .NET 2.0 as well. Support Memory Dump analysis (again a feature only supported by commercial profilers in their professional editions if it is supported at all) Deserialize objects from a memory dump into a live process back (this would need some more investigation but it is doable) The last item needs some explanation. Why on earth would you want to do that? The basic idea is to store in your live process some logging/tracing data which can become quite big but since it is never written to it is very fast to generate. When your process crashes with a memory dump you could transfer this data structure back into a live viewer which can then nicely display your program state at the point it did crash. This is an advanced trouble shooting technique I have not seen anywhere yet but it could be quite useful. You can have here a look at the current feature list of WMemoryProfiler with some examples.   How To Get Started? First I would download the released source package (it is tiny). And compile the complete project. Then you can compile the Example project (it has this name) and uncomment in the main method the scenario you want to check out. If you are greeted with an exception it is time to install the Windows 8 Standalone SDK which is described in great detail in the exception text. Thats it for the first round. I have seen something more limited in the Java world some years ago (now I cannot find the link anymore) but anyway. Now we have something much better.

    Read the article

  • What&rsquo;s Wrong With This Code (#25)

    The goal: create an extension method that will make it easy to create FormCollection objects. The method is a helper for unit testing ASP.NET MVC code. public static FormCollection ToFormCollection(this object data) { var namesAndValues = data.GetType() .GetProperties() .WhereValueIsNotDefaultValue(data) .ToNameValueCollection(data); return new FormCollection(namesAndValues); } The extension method itself relies on a couple private extension...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • ASP.NET MVC 2 InputExtensions different on server than local machine

    - by Mike
    Hi everyone, So this is kind of a crazy problem to me, but I've had no luck Googling it. I have an ASP.NET MVC 2 application (under .NET 4.0) running locally just fine. When I upload it to my production server (under shared hosting) I get Compiler Error Message: CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TextBoxFor' and no extension method 'TextBoxFor' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?) for this code: <%= this.Html.TextBoxFor(person => person.LastName) %> This is one of the new standard extension methods in MVC 2. So I wrote some diagnostic code: System.Reflection.Assembly ass = System.Reflection.Assembly.GetAssembly(typeof(InputExtensions)); Response.Write("From GAC: " + ass.GlobalAssemblyCache.ToString() + "<br/>"); Response.Write("ImageRuntimeVersion: " + ass.ImageRuntimeVersion.ToString() + "<br/>"); Response.Write("Version: " + System.Diagnostics.FileVersionInfo.GetVersionInfo(ass.Location).ToString() + "<br/>"); foreach (var method in typeof(InputExtensions).GetMethods()) { Response.Write(method.Name + "<br/>"); } running locally (where it works fine), I get this as output: From GAC: True ImageRuntimeVersion: v2.0.50727 Version: File: C:\Windows\assembly\GAC_MSIL\System.Web.Mvc\2.0.0.0__31bf3856ad364e35\System.Web.Mvc.dll InternalName: System.Web.Mvc.dll OriginalFilename: System.Web.Mvc.dll FileVersion: 2.0.50217.0 FileDescription: System.Web.Mvc.dll Product: Microsoft® .NET Framework ProductVersion: 2.0.50217.0 Debug: False Patched: False PreRelease: False PrivateBuild: False SpecialBuild: False Language: Language Neutral CheckBox CheckBox CheckBox CheckBox CheckBox CheckBox CheckBoxFor CheckBoxFor CheckBoxFor Hidden Hidden Hidden Hidden HiddenFor HiddenFor HiddenFor Password Password Password Password PasswordFor PasswordFor PasswordFor RadioButton RadioButton RadioButton RadioButton RadioButton RadioButton RadioButtonFor RadioButtonFor RadioButtonFor TextBox TextBox TextBox TextBox TextBoxFor TextBoxFor TextBoxFor ToString Equals GetHashCode GetType and when running on the production server (where it fails), I see: From GAC: True ImageRuntimeVersion: v2.0.50727 Version: File: C:\Windows\assembly\GAC_MSIL\System.Web.Mvc\2.0.0.0__31bf3856ad364e35\System.Web.Mvc.dll InternalName: System.Web.Mvc.dll OriginalFilename: System.Web.Mvc.dll FileVersion: 2.0.41001.0 FileDescription: System.Web.Mvc.dll Product: Microsoft® .NET Framework ProductVersion: 2.0.41001.0 Debug: False Patched: False PreRelease: False PrivateBuild: False SpecialBuild: False Language: Language Neutral CheckBox CheckBox CheckBox CheckBox CheckBox CheckBox Hidden Hidden Hidden Hidden Hidden Hidden Password Password Password Password RadioButton RadioButton RadioButton RadioButton RadioButton RadioButton TextBox TextBox TextBox TextBox ToString Equals GetHashCode GetType note that "TextBoxFor" is not present (hence the error). I have MVC referenced in the csproj: <Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"> <SpecificVersion>True</SpecificVersion> <HintPath>References\System.Web.Mvc.dll</HintPath> <Private>True</Private> </Reference> I just can't figure it what to do next. Thoughts? Thanks! -Mike

    Read the article

  • Asp.net MVC2 Custom jquery validation: client -side

    - by Lullaby
    Hi. I want to create a validation rule for 2 date-pickers (startDate less then endDate). I create a validation attribute: [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public sealed class DateCompareAttribute : ValidationAttribute { private const string _defaultErrorMessage = "'{0}' is less then '{1}'."; public DateCompareAttribute(string startDateProperty, string endDateProperty) : base(_defaultErrorMessage) { StartDateProperty = startDateProperty; EndDateProperty = endDateProperty; } public string StartDateProperty { get; private set; } public string EndDateProperty { get; private set; } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, StartDateProperty, EndDateProperty); } public override bool IsValid(object value) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); object startValue = properties.Find(StartDateProperty, true).GetValue(value); object endValue = properties.Find(EndDateProperty, true).GetValue(value); if (startValue.GetType() == typeof(DateTime?) && endValue.GetType() == typeof(DateTime?)) { var start = ((DateTime?)startValue); var end = ((DateTime?)endValue); return (start.Value < end.Value); } return false; } } and added ti to my Dto: [DateCompare("StartDate", "EndDate")] public class QualificationInput{...} I created a validator: public class DateCompareValidator : DataAnnotationsModelValidator { string startField; private string endField; string _message; public DateCompareValidator(ModelMetadata metadata, ControllerContext context , DateCompareAttribute attribute) : base(metadata, context, attribute) { startField = attribute.StartDateProperty; endField = attribute.EndDateProperty; _message = attribute.ErrorMessage; } public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() { var rule = new ModelClientValidationRule { ErrorMessage = _message, ValidationType = "dateCompare" }; rule.ValidationParameters.Add("startField", startField); rule.ValidationParameters.Add("endField", endField); return new[] { rule }; } } And registered it in Global.asax.cs in Application_Start(): DataAnnotationsModelValidatorProvider .RegisterAdapter(typeof(DateCompareAttribute), typeof(DateCompareValidator)); In MicrosoftMvcJQueryValidation.js I have made this changes: switch (thisRule.ValidationType) { ..... case "dateCompare": __MVC_ApplyValidator_DateCompare(rulesObj, thisRule.ValidationParameters["startField"], thisRule.ValidationParameters["endField"]); break; ..... } .... function __MVC_ApplyValidator_DateCompare(object, startField, endField) { object["startField"] = startField; object["endField"] = endField; } jQuery.validator.addMethod("dateCompare", function(value, element, params) { if ($('#' + params["startField"]).val() < $('#' + params["endField"]).val()) { return true; } return false; }, jQuery.format("Error")); But it doesn't work :( no client side validation on this type of rule (the others type like required works fine) What I'm doing wrong?

    Read the article

  • Playing an InputStream video in Blackberry JDE.

    - by Jenny
    I think I'm using InputStream incorrectly with a Blackberry 9000 simulator: I found some sample code, http://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/1089414/How%5FTo%5F-%5FPlay%5Fvideo%5Fwithin%5Fa%5FBlackBerry%5Fsmartphone%5Fapplication.html?nodeid=1383173&vernum=0 that lets you play video from within a Blackberry App. The code claims it can handle HTTP, but it's taken some fandangling to get it to actually approach doing so: http://pastie.org/609491 Specifically, I'm doing: StreamConnection s = null; s = (StreamConnection)Connector.open("http://10.252.9.15/eggs.3gp"); HttpConnection c = (HttpConnection)s; InputStream i = c.openInputStream(); System.out.println("~~~~~I have a connection?~~~~~~" + c); System.out.println("~~~~~I have a URL?~~~~" + c.getURL()); System.out.println("~~~~~I have a type?~~~~" + c.getType()); System.out.println("~~~~~I have a status?~~~~~~" + c.getResponseCode()); System.out.println("~~~~~I have a stream?~~~~~~" + i); player = Manager.createPlayer(i, c.getType()); I've found that this is the only way I can get an InputStream from an HTTPConnection without causing a: "JUM Error 104: Uncaught NullPointer Exception". (That is, the casting as a StreamConnection, and THEN as an HttpConnection stops it from crashing). However, I'm still not streaming video. Before, a stream wasn't able to be created (it would crash with the null pointer exception). Now, a stream is being made, the debugger claims it's begining to stream video from it...and nothing happens. No video plays. The app doesn't freeze, or crash or anything. I can 'pause' and 'play' freely, and get appropriate debug messages for both. But no video shows up. If I'm playing a video stored locally on the blackberry, everything is fine (it actually plays the video), so I know the Player itself is working fine, I"m just wondering if maybe I have something wrong with my stream? The API says the player can take in an InputStream. Is there a specific kind it needs? How can I query my inputstream to know if it's valid? It existing is further than I've gotten before. -Jenny Edit: I'm on a Blackberry Bold simulator (9000). I've heard that some versions of phones do NOT stream video via HTTP, however, the Bold does. I have yet to see examples of this though. When I go to the internet and point at a blackberry playable video, it attempts to stream, and then asks me to physically download the file (and then plays fine once I download). Edit: Also, I have a physical blackberry Bold, as well, but it can't stream either (I've gone to m.youtube.com, only to get a server/content not found error). Is there something special I need to do to stream RTSP content?

    Read the article

  • Creating C# Type from full name

    - by Adi Barda
    I'm trying to get a Type object from type full name i'm doing the folowing: Assembly asm = Assembly.GetEntryAssembly(); string toNativeTypeName="any type full name"; Type t = asm.GetType(toNativeTypeName); I get null, why? the assembly is my executable (.net executable) and the type name is: System.Xml.XmlNode

    Read the article

  • QueryInterface fails at casting inside COM-interface implementation

    - by brecht
    I am creating a tool in c# to retrieve messages of a CAN-network (network in a car) using an Dll written in C/C++. This dll is usable as a COM-interface. My c#-formclass implements one of these COM-interfaces. And other variables are instantiated using these COM-interfaces (everything works perfect). The problem: The interface my C#-form implements has 3 abstract functions. One of these functions is called -by the dll- and i need to implement it myself. In this function i wish to retrieve a property of a form-wide variable that is of a COM-type. The COM library is CANSUPPORTLib The form-wide variable: private CANSUPPORTLib.ICanIOEx devices = new CANSUPPORTLib.CanIO(); This variable is also form-wide and is retrieved via the devices-variable: canreceiver = (CANSUPPORTLib.IDirectCAN2)devices.get_DirectDispatch(receiverLogicalChannel); The function that is called by the dll and implemented in c# public void Message(double dTimeStamp) { Console.WriteLine("!!! message ontvangen !!!" + Environment.NewLine); try { CANSUPPORTLib.can_msg_tag message = new CANSUPPORTLib.can_msg_tag(); message = (CANSUPPORTLib.can_msg_tag) System.Runtime.InteropServices.Marshal.PtrToStructure(canreceiver.RawMessage, message.GetType()); for (int i = 0; i < message.data.Length; i++) { Console.WriteLine("byte " + i + ": " + message.data[i]); } } catch (Exception e) { Console.WriteLine(e.Message); } } The error rises at this line: message = (CANSUPPORTLib.can_msg_tag)System.Runtime.InteropServices.Marshal.PtrToStructure(canreceiver.RawMessage, message.GetType()); Error: Unable to cast COM object of type 'System.__ComObject' to interface type 'CANSUPPORTLib.IDirectCAN2'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{33373EFC-DB42-48C4-A719-3730B7F228B5}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)). Notes: It is possible to have a timer-clock that checks every 100ms for the message i need. The message is then retrieved in the exact same way as i do now. This timer is started when the form starts. The checking is only done when Message(double) has put a variable to true (a message arrived). When the timer-clock is started in the Message function, i have the same error as above Starting another thread when the form starts, is also not possible. Is there someone with experience with COM-interop ? When this timer

    Read the article

  • Reflection - SetValue of array within class?

    - by Jaymz87
    OK, I've been working on something for a while now, using reflection to accomplish a lot of what I need to do, but I've hit a bit of a stumbling block... I'm trying to use reflection to populate the properties of an array of a child property... not sure that's clear, so it's probably best explained in code: Parent Class: Public Class parent Private _child As childObject() Public Property child As childObject() Get Return _child End Get Set(ByVal value As child()) _child = value End Set End Property End Class Child Class: Public Class childObject Private _name As String Public Property name As String Get Return _name End Get Set(ByVal value As String) _name = value End Set End Property Private _descr As String Public Property descr As String Get Return _descr End Get Set(ByVal value As String) _descr = value End Set End Property End Class So, using reflection, I'm trying to set the values of the array of child objects through the parent object... I've tried several methods... the following is pretty much what I've got at the moment (I've added sample data just to keep things simple): Dim Results(1) As String Results(0) = "1,2" Results(1) = "2,3" Dim parent As New parent Dim child As childObject() = New childObject() {} Dim PropInfo As PropertyInfo() = child.GetType().GetProperties() Dim i As Integer = 0 For Each res As String In Results Dim ResultSet As String() = res.Split(",") ReDim child(i) Dim j As Integer = 0 For Each PropItem As PropertyInfo In PropInfo PropItem.SetValue(child, ResultSet(j), Nothing) j += 1 Next i += 1 Next parent.child = child This fails miserably on PropItem.SetValue with ArgumentException: Property set method not found. Anyone have any ideas? @Jon :- Thanks, I think I've gotten a little further, by creating individual child objects, and then assigning them to an array... The issue is now trying to get that array assigned to the parent object (using reflection). It shouldn't be difficult, but I think the problem comes because I don't necessarily know the parent/child types. I'm using reflection to determine which parent/child is being passed in. The parent always has only one property, which is an array of the child object. When I try assigning the child array to the parent object, I get a invalid cast exception saying it can't convert Object[] to . EDIT: Basically, what I have now is: Dim PropChildInfo As PropertyInfo() = ResponseObject.GetType().GetProperties() For Each PropItem As PropertyInfo In PropChildInfo PropItem.SetValue(ResponseObject, ResponseChildren, Nothing) Next ResponseObject is an instance of the parent Class, and ResponseChildren is an array of the childObject Class. This fails with: Object of type 'System.Object[]' cannot be converted to type 'childObject[]'.

    Read the article

  • How to get actual type of an derived class from its parent interface

    - by Tarik
    Hello people, Lets say we have a code portion like this : IProduct product = ProductCreator.CreateProduct(); //Factory Method we have here SellThisProduct(product); //... private void SellThisProduct(IProduct product) { //..do something here } //... internal class Soda : IProduct {} internal class Book : IProduct {} How can I infer which product is actually passed into SellThisProduct() method in the method? I think if I say GetType() or something it will probably return the IProduct type. Thanks...

    Read the article

  • Change type of control by type

    - by Ruben
    Hi, I'm having following problem. I should convert a control to a certain type, this can be multiple types (for example a custom button or a custom label, ....) Here's an example of what i would like to do: private void ConvertToTypeAndUseCustomProperty(Control c) { Type type = c.getType(); ((type) c).CustomPropertieOfControl = 234567; } Thanks in advance.

    Read the article

  • PowerShell - Shorten namespace names so it's easier to access types

    - by Adam Driscoll
    Is there a method of shortening PowerShell namespace references? Typing [RootNameSpace1.NameSpace2.Namepsace3+SomeEnum]::SomeValue is taxing and not a very good user expierence. I realize that you can reference System level objects without a namespace such that [Type]::GetType(... will work. Is there some manifest I could create or command I could use to shorten lengthy namespaces?

    Read the article

  • Custom validator not invoked when using Validation Application Block through configuration

    - by Chris
    I have set up a ruleset in my configuration file which has two validators, one of which is a built-in NotNullValidator, the other of which is a custom validator. The problem is that I see the NotNullValidator hit, but not my custom validator. The custom validator is being used to validate an Entity Framework entity object. I have used the debugger to confirm the NotNull is hit (I forced a failure condition so I saw it set an invalid result), but it never steps into the custom one. I am using MVC as the web app, so I defined the ruleset in a config file at that layer, but my custom validator is defined in another project. However, I wouldn't have thought that to be a problem because when I use the Enterprise Library Configuration tool inside Visual Studio 2008 it is able to set the type properly for the custom validator. As well, I believe the custom validator is fine as it builds ok, and the config tool can reference it properly. Does anybody have any ideas what the problem could be, or even what to do/try to debug further? Here is a stripped down version of my custom validator: [ConfigurationElementType(typeof(CustomValidatorData))] public sealed class UserAccountValidator : Validator { public UserAccountValidator(NameValueCollection attributes) : base(string.Empty, "User Account") { } protected override string DefaultMessageTemplate { get { throw new NotImplementedException(); } } protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults results) { if (!currentTarget.GetType().Equals(typeof(UserAccount))) { throw new Exception(); } UserAccount userAccountToValidate = (UserAccount)currentTarget; // snipped code ... this.LogValidationResult(results, "The User Account is invalid", currentTarget, key); } } Here is the XML of my ruleset in Validation.config (the NotNull rule is only there to force a failure so I could see it getting hit, and it does): <validation> <type defaultRuleset="default" assemblyName="MyProj.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="MyProj.Entities.UserAccount"> <ruleset name="default"> <properties> <property name="HashedPassword"> <validator negated="true" messageTemplate="" messageTemplateResourceName="" messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Not Null Validator" /> </property> <property name="Property"> <validator messageTemplate="" messageTemplateResourceName="" messageTemplateResourceType="" tag="" type="MyProj.Entities.UserAccountValidator, MyProj.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Custom Validator" /> </property> </properties> </ruleset> </type> </validation> And here is the stripped down version of the way I invoke the validation: var type = entity.GetType() var validator = ValidationFactory.CreateValidator(type, "default", new FileConfigurationSource("Validation.config")) var results = validator.Validate(entity) Any advice would be much appreciated! Thanks, Chris

    Read the article

  • Datagrid using usercontrol

    - by klawusel
    Hello I am fighting with this problem: I have a usercontrol which contains a textbox and a button (the button calls some functions to set the textbox's text), here is the xaml: <UserControl x:Class="UcSelect" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="Control1Name" <Grid x:Name="grid1" MaxHeight="25"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition Width="25"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="25"/> </Grid.RowDefinitions> <TextBox x:Name="txSelect" Text="{Binding UcText, Mode=TwoWay}" /> <Button x:Name="pbSelect" Background="Red" Grid.Column="1" Click="pbSelect_Click">...</Button> </Grid> And here the code behind: Partial Public Class UcSelect Private Shared Sub textChangedCallBack(ByVal [property] As DependencyObject, ByVal args As DependencyPropertyChangedEventArgs) Dim UcSelectBox As UcSelect = DirectCast([property], UcSelect) End Sub Public Property UcText() As String Get Return GetValue(UcTextProperty) End Get Set(ByVal value As String) SetValue(UcTextProperty, value) End Set End Property Public Shared ReadOnly UcTextProperty As DependencyProperty = _ DependencyProperty.Register("UcText", _ GetType(String), GetType(UcSelect), _ New FrameworkPropertyMetadata(String.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, New PropertyChangedCallback(AddressOf textChangedCallBack))) Public Sub New() InitializeComponent() grid1.DataContext = Me End Sub Private Sub pbSelect_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) 'just demo UcText = UcText + "!" End Sub End Class The UserControl works fine when used as a single control in this way: <local:UcSelect Grid.Row="1" x:Name="ucSingle1" UcText="{Binding FirstName, Mode=TwoWay}"/> Now I wanted to use the control in a custom datagrid column. As I like to have binding support I choosed to derive from DataGridtextColumn instead of using a DataGridTemplateColumn, here is the derived column class: Public Class DerivedColumn Inherits DataGridTextColumn Protected Overloads Overrides Function GenerateElement(ByVal oCell As DataGridCell, ByVal oDataItem As Object) As FrameworkElement Dim oElement = MyBase.GenerateElement(oCell, oDataItem) Return oElement End Function Protected Overloads Overrides Function GenerateEditingElement(ByVal oCell As DataGridCell, ByVal oDataItem As Object) As FrameworkElement Dim oUc As New UcSelect Dim oBinding As Binding = CType(Me.Binding, Binding) oUc.SetBinding(UcSelect.UcTextProperty, oBinding) Return oUc End Function End Class The column is used in xaml in the following way: <local:DerivedColumn Header="Usercontrol" Binding="{Binding FirstName, Mode=TwoWay}"></local:DerivedColumn> If I start my program all seems to be fine, but changes I make in the custom column are not reflected in the object (property "FirstName"), the changes are simply rolled back when leaving the cell. I think there must be something wrong with my GenerateEditingElement code, but have no idea ... Any Help would really be appreciated Regards Klaus

    Read the article

  • Get compiler generated delegate for an event

    - by Sandor Davidhazi
    I need to know what handlers are subsribed to the CollectionChanged event of the ObservableCollection class. The only solution I found would be to use Delegate.GetInvocationList() on the delegate of the event. The problem is, I can't get Reflection to find the compiler generated delegate. AFAIK the delegate has the same name as the event. I used the following piece of code: PropertyInfo notifyCollectionChangedDelegate = collection.GetType().GetProperty("CollectionChanged", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);

    Read the article

  • Java: why is declaration not sufficient in interface?

    - by HH
    Big class contains Format-interfcase and Format-class. The Format-class contains the methods and the interface has the values of the fields. I could have the fields in the class Format but the goal is with Interface. So do I just create dummy-vars to get the errors away, design issue or something ELSE? KEY: Declaration VS Initialisation Explain by the terms, why you have to init in interface. What is the logic behind it? To which kind of problems it leads the use of interface? Sample Code having the init-interface-problem import java.util.*; import java.io.*; public class FormatBig { private static class Format implements Format { private static long getSize(File f){return f.length();} private static long getTime(File f){return f.lastModified();} private static boolean isFile(File f){if(f.isFile()){return true;}} private static boolean isBinary(File f){return Match.isBinary(f);} private static char getType(File f){return Match.getTypes(f);} private static String getPath(File f){return getNoErrPath(f);} //Java API: isHidden, --- SYSTEM DEPENDED: toURI, toURL Format(File f) { // PUZZLE 0: would Stack<Object> be easier? size=getSize(f); time=getTime(f); isfile=isFile(f); isBinary=isBinary(f); type=getType(f); path=getPath(f); //PUZZLE 1: how can simplify the assignment? values.push(size); values.push(time); values.push(isfile); values.push(isBinary); values.push(type); values.push(path); } } public static String getNoErrPath(File f) { try{return f.getCanonicalPath(); }catch(Exception e){e.printStackTrace();} } public static final interface Format { //ERR: IT REQUIRES "=" public long size; public long time; public boolean isFile=true; //ERROR goes away if I initialise wit DUMMY public boolean isBinary; public char type; public String path; Stack<Object> values=new Stack<Object>(); } public static void main(String[] args) { Format fm=new Format(new File(".")); for(Object o:values){System.out.println(o);} } }

    Read the article

  • Delphi interface cast using TValue

    - by conciliator
    I've recently experimented extensively with interfaces and D2010 RTTI. I don't know at runtime the actual type of the interface; although I will have access to it's qualified name using a string. Consider the following: program rtti_sb_1; {$APPTYPE CONSOLE} uses SysUtils, Rtti, TypInfo, mynamespace in 'mynamespace.pas'; var ctx: TRttiContext; InterfaceType: TRttiType; Method: TRttiMethod; ActualParentInstance: IParent; ChildInterfaceValue: TValue; ParentInterfaceValue: TValue; begin ctx := TRttiContext.Create; // Instantiation ActualParentInstance := TChild.Create as IParent; {$define WORKAROUND} {$ifdef WORKAROUND} InterfaceType := ctx.GetType(TypeInfo(IParent)); InterfaceType := ctx.GetType(TypeInfo(IChild)); {$endif} // Fetch interface type InterfaceType := ctx.FindType('mynamespace.IParent'); // This cast is OK and ChildMethod is executed (ActualParentInstance as IChild).ChildMethod(100); // Create a TValue holding the interface TValue.Make(@ActualParentInstance, InterfaceType.Handle, ParentInterfaceValue); InterfaceType := ctx.FindType('mynamespace.IChild'); // This cast doesn't work if ParentInterfaceValue.TryCast(InterfaceType.Handle, ChildInterfaceValue) then begin Method := InterfaceType.GetMethod('ChildMethod'); if (Method <> nil) then begin Method.Invoke(ChildInterfaceValue, [100]); end; end; ReadLn; end. The contents of mynamespace.pas is as follows: {$M+} IParent = interface ['{2375F59E-D432-4D7D-8D62-768F4225FFD1}'] procedure ParentMethod(const Id: integer); end; {$M-} IChild = interface(IParent) ['{6F89487E-5BB7-42FC-A760-38DA2329E0C5}'] procedure ChildMethod(const Id: integer); end; TParent = class(TInterfacedObject, IParent) public procedure ParentMethod(const Id: integer); end; TChild = class(TParent, IChild) public procedure ChildMethod(const Id: integer); end; For completeness, the implementation goes as procedure TParent.ParentMethod(const Id: integer); begin WriteLn('ParentMethod executed. Id is ' + IntToStr(Id)); end; procedure TChild.ChildMethod(const Id: integer); begin WriteLn('ChildMethod executed. Id is ' + IntToStr(Id)); end; The reason for {$define WORKAROUND} may be found in this post. Question: is there any way for me to make the desired type cast using RTTI? In other words: is there a way for me to invoke IChild.ChildMethod from knowing 1) the qualified name of IChild as a string, and 2) a reference to the TChild instance as a IParent interface? (After all, the hard-coded cast works fine. Is this even possible?) Thanks!

    Read the article

  • Decompressing a very large serialized object and managing memory

    - by Mike_G
    I have an object that contains tons of data used for reports. In order to get this object from the server to the client I first serialize the object in a memory stream, then compress it using the Gzip stream of .NET. I then send the compressed object as a byte[] to the client. The problem is on some clients, when they get the byte[] and try to decompress and deserialize the object, a System.OutOfMemory exception is thrown. Ive read that this exception can be caused by new() a bunch of objects, or holding on to a bunch of strings. Both of these are happening during the deserialization process. So my question is: How do I prevent the exception (any good strategies)? The client needs all of the data, and ive trimmed down the number of strings as much as i can. edit: here is the code i am using to serialize/compress (implemented as extension methods) public static byte[] SerializeObject<T>(this object obj, T serializer) where T: XmlObjectSerializer { Type t = obj.GetType(); if (!Attribute.IsDefined(t, typeof(DataContractAttribute))) return null; byte[] initialBytes; using (MemoryStream stream = new MemoryStream()) { serializer.WriteObject(stream, obj); initialBytes = stream.ToArray(); } return initialBytes; } public static byte[] CompressObject<T>(this object obj, T serializer) where T : XmlObjectSerializer { Type t = obj.GetType(); if(!Attribute.IsDefined(t, typeof(DataContractAttribute))) return null; byte[] initialBytes = obj.SerializeObject(serializer); byte[] compressedBytes; using (MemoryStream stream = new MemoryStream(initialBytes)) { using (MemoryStream output = new MemoryStream()) { using (GZipStream zipper = new GZipStream(output, CompressionMode.Compress)) { Pump(stream, zipper); } compressedBytes = output.ToArray(); } } return compressedBytes; } internal static void Pump(Stream input, Stream output) { byte[] bytes = new byte[4096]; int n; while ((n = input.Read(bytes, 0, bytes.Length)) != 0) { output.Write(bytes, 0, n); } } And here is my code for decompress/deserialize: public static T DeSerializeObject<T,TU>(this byte[] serializedObject, TU deserializer) where TU: XmlObjectSerializer { using (MemoryStream stream = new MemoryStream(serializedObject)) { return (T)deserializer.ReadObject(stream); } } public static T DecompressObject<T, TU>(this byte[] compressedBytes, TU deserializer) where TU: XmlObjectSerializer { byte[] decompressedBytes; using(MemoryStream stream = new MemoryStream(compressedBytes)) { using(MemoryStream output = new MemoryStream()) { using(GZipStream zipper = new GZipStream(stream, CompressionMode.Decompress)) { ObjectExtensions.Pump(zipper, output); } decompressedBytes = output.ToArray(); } } return decompressedBytes.DeSerializeObject<T, TU>(deserializer); } The object that I am passing is a wrapper object, it just contains all the relevant objects that hold the data. The number of objects can be a lot (depending on the reports date range), but ive seen as many as 25k strings. One thing i did forget to mention is I am using WCF, and since the inner objects are passed individually through other WCF calls, I am using the DataContract serializer, and all my objects are marked with the DataContract attribute.

    Read the article

  • C#: Exception to throw when a certain type was expected

    - by cbp
    I know this sort of code is not best practice, but nevertheless in certain situations I find it is a simpler solution: if (obj.Foo is Xxxx) { // Do something } else if (obj.Foo is Yyyy) { // Do something } else { throw new Exception("Type " + obj.Foo.GetType() + " is not handled."); } Anyone know if there is a built-in exception I can throw in this case?

    Read the article

  • Should Application_End fire on an automatic App Pool Recycle?

    - by Laramie
    I have read this, this, this and this plus a dozen other posts/blogs. I have an ASP.Net app in shared hosting that is frequently recycling. We use NLog and have the following code in global.asax void Application_Start(object sender, EventArgs e) { NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); logger.Debug("\r\n\r\nAPPLICATION STARTING\r\n\r\n"); } protected void Application_OnEnd(Object sender, EventArgs e) { NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); logger.Debug("\r\n\r\nAPPLICATION_OnEnd\r\n\r\n"); } void Application_End(object sender, EventArgs e) { HttpRuntime runtime = (HttpRuntime)typeof(System.Web.HttpRuntime).InvokeMember("_theRuntime", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null); if (runtime == null) return; string shutDownMessage = (string)runtime.GetType().InvokeMember("_shutDownMessage", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null); string shutDownStack = (string)runtime.GetType().InvokeMember("_shutDownStack", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null); ApplicationShutdownReason shutdownReason = System.Web.Hosting.HostingEnvironment.ShutdownReason; NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); logger.Debug(String.Format("\r\n\r\nAPPLICATION END\r\n\r\n_shutDownReason = {2}\r\n\r\n _shutDownMessage = {0}\r\n\r\n_shutDownStack = {1}\r\n\r\n", shutDownMessage, shutDownStack, shutdownReason)); } void Application_Error(object sender, EventArgs e) { NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); logger.Debug("\r\n\r\nApplication_Error\r\n\r\n"); } Our log file is littered with "APPLICATION STARTING" entries, but neither Application_OnEnd, Application_End, nor Application_Error are ever fired during these spontaneous restarts. I know they are working because there are entries for touching the web.config or /bin files. We also ran a memory overload test and can trigger an OutOfMemoryException which is caught in Application_Error. We are trying to determine whether the virtual memory limit is causing the recycling. We have added GC.GetTotalMemory(false) throughout the code, but this is for all of .Net, not just our App´s pool, correct? We've also tried var oPerfCounter = new PerformanceCounter(); oPerfCounter.CategoryName = "Process"; oPerfCounter.CounterName = "Virtual Bytes"; oPerfCounter.InstanceName = "iisExpress"; logger.Debug("Virtual Bytes: " + oPerfCounter.RawValue + " bytes"); but don't have permission in shared hosting. I've monitored the app on a dev server with the same requests that caused the recycles in production with ANTS Memory Profiler attached and can't seem to find a culprit. We have also run it with a debugger attached in dev to check for uncaught exceptions in spawned threads that might cause the app to abort. My questions are these: How can I effectively monitor memory usage in shared hosting to tell how much my application is consuming prior to an application recycle? Why are the Application_[End/OnEnd/Error] handlers in global.asax not being called? How else can I determine what is causing these recycles? Thanks.

    Read the article

  • Select Case on an object's Type in VB.Net

    - by mcjabberz
    I'm not sure if this valid C# but hopefully you get the idea. :) switch (msg.GetType()) { case ClassA: // blah case ClassB: // blah 2 case ClassC: // blah 3 } How would I switch on an object's type but using VB.NET's Select Case? I'm aware that some might suggest using polymorphism but I'm using a hierarchy of small message classes so that really wouldn't work in my csae.

    Read the article

  • What are the benefits of using ORM over XML Serialization/Deserialization?

    - by Tequila Jinx
    I've been reading about NHibernate and Microsoft's Entity Framework to perform Object Relational Mapping against my data access layer. I'm interested in the benefits of having an established framework to perform ORM, but I'm curious as to the performance costs of using it against standard XML Serialization and Deserialization. Right now, I develop stored procedures in Oracle and SQL Server that use XML Types for either input or output parameters and return or shred XML depending on need. I use a custom database command object that uses generics to deserialize the XML results into a specified serializable class. By using a combination of generics, xml (de)serialization and Microsoft's DAAB, I've got a process that's fairly simple to develop against regardless of the data source. Moreover, since I exclusively use Stored Procedures to perform database operations, I'm mostly protected from changes in the data structure. Here's an over-simplified example of what I've been doing. static void main() { testXmlClass test = new test(1); test.Name = "Foo"; test.Save(); } // Example Serializable Class ------------------------------------------------ [XmlRootAttribute("test")] class testXmlClass() { [XmlElement(Name="id")] public int ID {set; get;} [XmlElement(Name="name")] public string Name {set; get;} //create an instance of the class loaded with data. public testXmlClass(int id) { GenericDBProvider db = new GenericDBProvider(); this = db.ExecuteSerializable("myGetByIDProcedure"); } //save the class to the database... public Save() { GenericDBProvider db = new GenericDBProvider(); db.AddInParameter("myInputParameter", DbType.XML, this); db.ExecuteSerializableNonQuery("mySaveProcedure"); } } // Database Handler ---------------------------------------------------------- class GenericDBProvider { public T ExecuteSerializable<T>(string commandText) where T : class { XmlSerializer xml = new XmlSerializer(typeof(T)); // connection and command code is assumed for the purposes of this example. // the final results basically just come down to... return xml.Deserialize(commandResults) as T; } public void ExecuteSerializableNonQuery(string commandText) { // once again, connection and command code is assumed... // basically, just execute the command along with the specified // parameters which have been serialized. } public void AddInParameter(string name, DbType type, object value) { StringWriter w = new StringWriter(); XmlSerializer x = new XmlSerializer(value.GetType()); //handle serialization for serializable classes. if (type == DbType.Xml && (value.GetType() != typeof(System.String))) { x.Serialize(w, value); w.Close(); // store serialized object in a DbParameterCollection accessible // to my other methods. } else { //handle all other parameter types } } } I'm starting a new project which will rely heavily on database operations. I'm very curious to know whether my current practices will be sustainable in a high-traffic situation and whether or not I should consider switching to NHibernate or Microsoft's Entity Framework to perform what essentially seems to boil down to the same thing I'm currently doing. I appreciate any advice you may have.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >