Search Results

Search found 707 results on 29 pages for 'getvalue'.

Page 1/29 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Alternatives to PropertyInfo.GetValue() for Mono?

    - by Trilok
    I have a method that has the following signature: private object GetNestedObject<y>(y objToAccess, string nestedObjectName) I'm using Reflection to get the nestedObject from the objToAccess and return it. This works well except it's really slow (I have to do this a few hundred thousand times). I came across HyperDescriptor, but since I'm running this on Linux, and Mono doesn't support TypeDescriptionProviders, I can't use it. Are there any alternatives to using getValue in this case? I could always hardcode in overrides for each type, but that is not desirable and would add a lot of maintenance overhead in my case.

    Read the article

  • Reflection PropertyInfo GetValue call errors out for Collection<> type property.

    - by Vinit Sankhe
    Hey Guys, I have a propertyInfo object and I try to do a GetValue using it. object source = mysourceObject //This object has a property "Prop1" of type Collection<>. var propInfo = source.GetType().GetProperty("Prop1"); var propValue = prop.GetValue(this, null); // do whatever with propValue // ... I get error at the GetValue() call as "Value cannot be null.\r\nParameter name: source" "Prop1" is a plain property declared as Collection. prop.PropertyType = {Name = "Collection1" FullName = "System.Collections.ObjectModel.Collection1[[Application1.DummyClass, Application1, Version=1.5.5.5834, Culture=neutral, PublicKeyToken=628b2ce865838339]]"} System.Type {System.RuntimeType}

    Read the article

  • How to propertly reference a namespace for Microsoft.Sdc.Tasks.XmlFile.GetValue

    - by æther
    Hi, i want to use MSBuild to insert a custom xml element into web.config. After looking up online, i found such solution: 1) Store element in the .build file in projectextensions <ProjectExtensions> <CustomElement name="CustomElementName"> ... </CustomElement> </ProjectExtensions> 2) Retrieve the element with GetValue <Target name="ModifyConfig"> <XmlFile.GetValue Path="$(MSBuildProjectFullPath)" XPath="Project/ProjectExtensions/CustomElement[@name='CustomElementName']"> <Output TaskParameter="Value" PropertyName="CustomElementProperty"/> </XmlFile.GetValue> </Target> This will not work as i need to reference a namespace the .build project is using for it to find the needed element (checked the .build file with XPath Visualizer). So, i look up for a further solution and come to this: <ItemGroup> <XmlNamespace Include="MSBuild"> <Prefix>msb</Prefix> <Uri>http://schemas.microsoft.com/developer/msbuild/2003</Uri> </XmlNamespace> </ItemGroup> <Target name="ModifyConfig"> <XmlFile.GetValue Path="$(MSBuildProjectFullPath)" Namespaces="$(XmlNamespace)" XPath="/msb:Project/msb:ProjectExtensions/msb:CustomElement[@name='CustomElementName']" > <Output TaskParameter="Value" PropertyName="CustomElementProperty"/> </XmlFile.GetValue> </Target> But for some reason namespace is not recognized - MSBuild reports the following error: C:...\mybuild.build(53,9): error : A task error has occured. C:...\mybuild.build(53,9): error : Message = Namespace prefix 'msb' is not defined. I tried some variations of referencing it differently but none work, and there is not much about propertly referencing those namespaces online also. Can you tell me what am i doing wrong and how to do it propertly?

    Read the article

  • JSF, writeAttribute("value", str, null) fails with strings obtained through ValueExpression.getValue

    - by Roma
    Hello, I'm having a somewhat weird problem with custom JSF component. Here's my renderer code: public class Test extends Renderer { public void encodeBegin(final FacesContext context, final UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.startElement("textarea", component); String clientId = component.getClientId(context); if (clientId != null) writer.writeAttribute("name", clientId, null); ValueExpression exp = component.getValueExpression("value"); if (exp != null && exp.getValue(context.getELContext()) != null) { String val = (String) exp.getValue(context.getELContext()); System.out.println("Value: " + val); writer.writeAttribute("value", val, null); } writer.endElement("textarea"); writer.flush(); } } The code generates: <textarea name="j_id2:j_id12:j_id19" value=""></textarea> Property binding contains "test" and as it should be, "Value: test" is successfully printed to console. Now, if I change the code to: public void encodeBegin(final FacesContext context, final UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.startElement("textarea", component); String clientId = component.getClientId(context); if (clientId != null) writer.writeAttribute("name", clientId, null); ValueExpression exp = component.getValueExpression("value"); if (exp != null && exp.getValue(context.getELContext()) != null) { String val = (String) exp.getValue(context.getELContext()); String str = "new string"; System.out.println("Value1: " + val + ", Value2: " + str); writer.writeAttribute("value", str, null); } writer.endElement("textarea"); writer.flush(); } generated html is: <textarea name="j_id2:j_id12:j_id19" value="new string"></textarea> and console output is "Value1: test, Value2: new string" What's going on here? This doesn't make sense. Why would writeAttribute differentiate between the two strings? Additional info: The component extends UIComponentBase I am using it with facelets

    Read the article

  • GetValue on static field inside nested classes.

    - by Sir Gallahad
    Hi... I have the following class declared. I need to retreive the class structure and the static values without instanciate it. public MyClass() { public static string field = "Value"; public nestedClass() { public static string nestedField = "NestedValue"; } } I've successfuly used GetFields and GetNestedType to recover the class structure and GetValue(null) works fine on field, but not on nestedField. Let me sample: var fi = typeof(MyClass).GetField("field", BindingFlags.Public | BindingFlags.Static); var nt = typeof(MyClass).GetNestedType("nestedClass", BindingFlags.Public); var nfi = nt.GetField("nestedField", BindingFlags.Public | BindingFlags.Static); // All the above references are detected correctly var value = fi.GetValue(null); // until here everything works fine. value == "Value" var nestedValue = nfi.GetValue(null); // this one does not work!! Anyone knows why the last line does not work and how to work around? Thanks.

    Read the article

  • RadioGroup getValue does not return correct slected value

    - by vagabond
    I'm running into a small issue with RadioGroup. My RadioGroup has possible values, true and false. The Radio types I have in my radiogroup use a Model that stores true or false. On an ajax onchange event I want to do some handling, and to do so I need to know the selected radio in my radiogroup and another identical radiogroup. The problem is getValue() only returns the initial value from my Pojo. Whenver I click on a radio button to change the selected Radio getValue() still returns the initial value. When I save my changes, my Pojo gets the correct value. I am finding this bizarre and have spent hours trying to figure our what I'm missing.

    Read the article

  • IQueryable<> dynamic ordering/filtering with GetValue fails

    - by MyNameIsJob
    I'm attempting to filter results from a database using Entity Framework CTP5. Here is my current method. IQueryable<Form> Forms = DataContext.CreateFormContext().Forms; foreach(string header in Headers) { Forms = Forms.Where(f => f.GetType() .GetProperty(header) .GetValue(f, null) .ToString() .IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) >= 0); } However, I found that GetValue doesn't work using Entity Framework. It does when the type if IEnumerable< but not IQueryable< Is there an alternative I can use to produce the same effect?

    Read the article

  • C# : FieldInfo.GetValue returns null

    - by Florian
    Hi and Happy New year ! I've a problem to retrieve my control f2 in the variable o via Reflection : public partial class Form1 : Form { private Form2 f2; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.Show(); } private void button2_Click(object sender, EventArgs e) { Type controlType = this.GetType(); FieldInfo f = controlType.GetField("f2", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); object o = f.GetValue(this); // o == null; } } Thank you for your help !

    Read the article

  • ValueProvider.GetValue Extension Method

    - by griegs
    I have a model like this; public class QuickQuote { [Required] public Enumerations.AUSTRALIA_STATES state { get; set; } [Required] public Enumerations.FAMILY_TYPE familyType { get; set; } As you can see the two proerties are enumerations. Now I want to employ my own model binder for reasons that I won't bother getting into at the moment. So I have; public class QuickQuoteBinder : DefaultModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { quickQuote = new QuickQuote(); try { quickQuote.state = (Enumerations.AUSTRALIA_STATES) Enum.Parse(typeof(Enumerations.AUSTRALIA_STATES), bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".state").AttemptedValue); } catch { ModelState modelState = new ModelState(); ModelError err = new ModelError("Required"); modelState.Errors.Add(err); bindingContext.ModelState.Add(bindingContext.ModelName + ".state", modelState); } The problem is that for each property, and there are heaps, I need to do the whole try catch block. What I thought I might do is create an extension method which would do the whole block for me and all i'd need to pass in is the model property and the enumeration. So I could do something like; quickQuote.state = bindingContext.ValueProvider.GetModelValue("state", ...) etc. Is this possible?

    Read the article

  • Rtti accessing fields and properties in complex data structures

    - by Coco
    As already discussed in Rtti data manipulation and consistency in Delphi 2010 a consistency between the original data and rtti values can be reached by accessing members by using a pair of TRttiField and an instance pointer. This would be very easy in case of a simple class with only basic member types (like e.g. integers or strings). But what if we have structured field types? Here is an example: TIntArray = array [0..1] of Integer; TPointArray = array [0..1] of Point; TExampleClass = class private FPoint : TPoint; FAnotherClass : TAnotherClass; FIntArray : TIntArray; FPointArray : TPointArray; public property Point : TPoint read FPoint write FPoint; //.... and so on end; For an easy access of Members I want to buil a tree of member-nodes, which provides an interface for getting and setting values, getting attributes, serializing/deserializing values and so on. TMemberNode = class private FMember : TRttiMember; FParent : TMemberNode; FInstance : Pointer; public property Value : TValue read GetValue write SetValue; //uses FInstance end; So the most important thing is getting/setting the values, which is done - as stated before - by using the GetValue and SetValue functions of TRttiField. So what is the Instance for FPoint members? Let's say Parent is the Node for TExample class, where the instance is known and the member is a field, then Instance would be: FInstance := Pointer (Integer (Parent.Instance) + TRttiField (FMember).Offset); But what if I want to know the Instance for a record property? There is no offset in this case. So is there a better solution to get a pointer to the data? For the FAnotherClass member, the Instance would be: FInstance := Parent.Value.AsObject; So far the solution works, and data manipulation can be done by using rtti or the original types, without losing information. But things get harder, when working with arrays. Especially the second array of Points. How can I get the instance for the members of points in this case?

    Read the article

  • More SharePoint 2010 Expression Builders

    - by Ricardo Peres
    Introduction Following my last post, I decided to publish the whole set of expression builders that I use with SharePoint. For all who don’t know about expression builders, they allow us to employ a declarative approach, so that we don’t have to write code for “gluing” things together, like getting a value from the query string, the page’s underlying SPListItem or the current SPContext and assigning it to a control’s property. These expression builders are for some quite common scenarios, I use them quite often, and I hope you find them useful as well. SPContextExpression This expression builder allows us to specify an expression to be processed on the SPContext.Current property object. For example: 1: <asp:Literal runat="server" Text=“<%$ SPContextExpression:Site.RootWeb.Lists[0].Author.LoginName %>”/> It is identical to having the following code: 1: String authorName = SPContext.Current.Site.RootWeb.Lists[0].Author.LoginName; SPFarmProperty Returns a property stored on the farm level: 1: <asp:Literal runat="server" Text="<%$ SPFarmProperty:SomeProperty %>"/> Identical to: 1: Object someProperty = SPFarm.Local.Properties["SomeProperty"]; SPField Returns the value of a selected page’s list item field: 1: <asp:Literal runat="server" Text="<%$ SPField:Title %>"/> Does the same as: 1: String title = SPContext.Current.ListItem["Title"] as String; SPIsInAudience Checks if the current user belongs to an audience: 1: <asp:CheckBox runat="server" Checked="<%$ SPIsInAudience:SomeAudience %>"/> Equivalent to: 1: AudienceManager audienceManager = new AudienceManager(SPServiceContext.Current); 2: Audience audience = audienceManager.Audiences["SomeAudience"]; 3: Boolean isMember = audience.IsMember(SPContext.Current.Web.User.LoginName); SPIsInGroup Checks if the current user belongs to a group: 1: <asp:CheckBox runat="server" Checked="<%$ SPIsInGroup:SomeGroup %>"/> The equivalent C# code is: 1: SPContext.Current.Web.CurrentUser.Groups.OfType<SPGroup>().Any(x => String.Equals(x.Name, “SomeGroup”, StringComparison.OrdinalIgnoreCase)); SPProperty Returns the value of a user profile property for the current user: 1: <asp:Literal runat="server" Text="<%$ SPProperty:LastName %>"/> Where the same code in C# would be: 1: UserProfileManager upm = new UserProfileManager(SPServiceContext.Current); 2: UserProfile u = upm.GetUserProfile(false); 3: Object property = u["LastName"].Value; SPQueryString Returns a value passed on the query string: 1: <asp:GridView runat="server" PageIndex="<%$ SPQueryString:PageIndex %>" /> Is equivalent to (no SharePoint code this time): 1: Int32 pageIndex = Convert.ChangeType(typeof(Int32), HttpContext.Current.Request.QueryString["PageIndex"]); SPWebProperty Returns the value of a property stored at the site level: 1: <asp:Literal runat="server" Text="<%$ SPWebProperty:__ImagesListId %>"/> You can get the same result as: 1: String imagesListId = SPContext.Current.Web.AllProperties["__ImagesListId"] as String; Code OK, let’s move to the code. First, a common abstract base class, mainly for inheriting the conversion method: 1: public abstract class SPBaseExpressionBuilder : ExpressionBuilder 2: { 3: #region Protected static methods 4: protected static Object Convert(Object value, PropertyInfo propertyInfo) 5: { 6: if (value != null) 7: { 8: if (propertyInfo.PropertyType.IsAssignableFrom(value.GetType()) == false) 9: { 10: if (propertyInfo.PropertyType.IsEnum == true) 11: { 12: value = Enum.Parse(propertyInfo.PropertyType, value.ToString(), true); 13: } 14: else if (propertyInfo.PropertyType == typeof(String)) 15: { 16: value = value.ToString(); 17: } 18: else if ((typeof(IConvertible).IsAssignableFrom(propertyInfo.PropertyType) == true) && (typeof(IConvertible).IsAssignableFrom(value.GetType()) == true)) 19: { 20: value = System.Convert.ChangeType(value, propertyInfo.PropertyType); 21: } 22: } 23: } 24:  25: return (value); 26: } 27: #endregion 28:  29: #region Public override methods 30: public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 31: { 32: if (String.IsNullOrEmpty(entry.Expression) == true) 33: { 34: return (new CodePrimitiveExpression(String.Empty)); 35: } 36: else 37: { 38: return (new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(this.GetType()), "GetValue"), new CodePrimitiveExpression(entry.Expression.Trim()), new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("entry"), "PropertyInfo"))); 39: } 40: } 41: #endregion 42:  43: #region Public override properties 44: public override Boolean SupportsEvaluate 45: { 46: get 47: { 48: return (true); 49: } 50: } 51: #endregion 52: } Next, the code for each expression builder: 1: [ExpressionPrefix("SPContext")] 2: public class SPContextExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String expression, PropertyInfo propertyInfo) 6: { 7: SPContext context = SPContext.Current; 8: Object expressionValue = DataBinder.Eval(context, expression.Trim().Replace('\'', '"')); 9:  10: expressionValue = Convert(expressionValue, propertyInfo); 11:  12: return (expressionValue); 13: } 14:  15: #endregion 16:  17: #region Public override methods 18: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 19: { 20: return (GetValue(entry.Expression, entry.PropertyInfo)); 21: } 22: #endregion 23: }   1: [ExpressionPrefix("SPFarmProperty")] 2: public class SPFarmPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, PropertyInfo propertyInfo) 6: { 7: Object propertyValue = SPFarm.Local.Properties[propertyName]; 8:  9: propertyValue = Convert(propertyValue, propertyInfo); 10:  11: return (propertyValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPField")] 2: public class SPFieldExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String fieldName, PropertyInfo propertyInfo) 6: { 7: Object fieldValue = SPContext.Current.ListItem[fieldName]; 8:  9: fieldValue = Convert(fieldValue, propertyInfo); 10:  11: return (fieldValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPIsInAudience")] 2: public class SPIsInAudienceExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String audienceName, PropertyInfo info) 6: { 7: Debugger.Break(); 8: audienceName = audienceName.Trim(); 9:  10: if ((audienceName.StartsWith("'") == true) && (audienceName.EndsWith("'") == true)) 11: { 12: audienceName = audienceName.Substring(1, audienceName.Length - 2); 13: } 14:  15: AudienceManager manager = new AudienceManager(); 16: Object value = manager.IsMemberOfAudience(SPControl.GetContextWeb(HttpContext.Current).CurrentUser.LoginName, audienceName); 17:  18: if (info.PropertyType == typeof(String)) 19: { 20: value = value.ToString(); 21: } 22:  23: return(value); 24: } 25:  26: #endregion 27:  28: #region Public override methods 29: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 30: { 31: return (GetValue(entry.Expression, entry.PropertyInfo)); 32: } 33: #endregion 34: }   1: [ExpressionPrefix("SPIsInGroup")] 2: public class SPIsInGroupExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String groupName, PropertyInfo info) 6: { 7: groupName = groupName.Trim(); 8:  9: if ((groupName.StartsWith("'") == true) && (groupName.EndsWith("'") == true)) 10: { 11: groupName = groupName.Substring(1, groupName.Length - 2); 12: } 13:  14: Object value = SPControl.GetContextWeb(HttpContext.Current).CurrentUser.Groups.OfType<SPGroup>().Any(x => String.Equals(x.Name, groupName, StringComparison.OrdinalIgnoreCase)); 15:  16: if (info.PropertyType == typeof(String)) 17: { 18: value = value.ToString(); 19: } 20:  21: return(value); 22: } 23:  24: #endregion 25:  26: #region Public override methods 27: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 28: { 29: return (GetValue(entry.Expression, entry.PropertyInfo)); 30: } 31: #endregion 32: }   1: [ExpressionPrefix("SPProperty")] 2: public class SPPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, System.Reflection.PropertyInfo propertyInfo) 6: { 7: SPServiceContext serviceContext = SPServiceContext.GetContext(HttpContext.Current); 8: UserProfileManager upm = new UserProfileManager(serviceContext); 9: UserProfile up = upm.GetUserProfile(false); 10: Object propertyValue = (up[propertyName] != null) ? up[propertyName].Value : null; 11:  12: propertyValue = Convert(propertyValue, propertyInfo); 13:  14: return (propertyValue); 15: } 16:  17: #endregion 18:  19: #region Public override methods 20: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 21: { 22: return (GetValue(entry.Expression, entry.PropertyInfo)); 23: } 24: #endregion 25: }   1: [ExpressionPrefix("SPQueryString")] 2: public class SPQueryStringExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String parameterName, PropertyInfo propertyInfo) 6: { 7: Object parameterValue = HttpContext.Current.Request.QueryString[parameterName]; 8:  9: parameterValue = Convert(parameterValue, propertyInfo); 10:  11: return (parameterValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPWebProperty")] 2: public class SPWebPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, PropertyInfo propertyInfo) 6: { 7: Object propertyValue = SPContext.Current.Web.AllProperties[propertyName]; 8:  9: propertyValue = Convert(propertyValue, propertyInfo); 10:  11: return (propertyValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: } Registration You probably know how to register them, but here it goes again: add this following snippet to your Web.config file, inside the configuration/system.web/compilation/expressionBuilders section: 1: <add expressionPrefix="SPContext" type="MyNamespace.SPContextExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 2: <add expressionPrefix="SPFarmProperty" type="MyNamespace.SPFarmPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 3: <add expressionPrefix="SPField" type="MyNamespace.SPFieldExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 4: <add expressionPrefix="SPIsInAudience" type="MyNamespace.SPIsInAudienceExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 5: <add expressionPrefix="SPIsInGroup" type="MyNamespace.SPIsInGroupExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 6: <add expressionPrefix="SPProperty" type="MyNamespace.SPPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 7: <add expressionPrefix="SPQueryString" type="MyNamespace.SPQueryStringExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 8: <add expressionPrefix="SPWebProperty" type="MyNamespace.SPWebPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> I’ll leave it up to you to figure out the best way to deploy this to your server!

    Read the article

  • Voxel terrain rendering with marching cubes

    - by JavaJosh94
    I was working on making procedurally generated terrain using normal cubish voxels (like minecraft) But then I read about marching cubes and decided to convert to using those. I managed to create a working marching cubes class and cycle through the densities and everything in it seemed to be working so I went on to work on actual terrain generation. I'm using XNA (C#) and a ported libnoise library to generate noise for the terrain generator. But instead of rendering smooth terrain I get a 64x64 chunk (I specified 64 but can change it) of seemingly random marching cubes using different triangles. This is the code I'm using to generate a "chunk": public MarchingCube[, ,] getTerrainChunk(int size, float dMultiplyer, int stepsize) { MarchingCube[, ,] temp = new MarchingCube[size / stepsize, size / stepsize, size / stepsize]; for (int x = 0; x < size; x += stepsize) { for (int y = 0; y <size; y += stepsize) { for (int z = 0; z < size; z += stepsize) { float[] densities = {(float)terrain.GetValue(x, y, z)*dMultiplyer, (float)terrain.GetValue(x, y+stepsize, z)*dMultiplyer, (float)terrain.GetValue(x+stepsize, y+stepsize, z)*dMultiplyer, (float)terrain.GetValue(x+stepsize, y, z)*dMultiplyer, (float)terrain.GetValue(x,y,z+stepsize)*dMultiplyer,(float)terrain.GetValue(x,y+stepsize,z+stepsize)*dMultiplyer,(float)terrain.GetValue(x+stepsize,y+stepsize,z+stepsize)*dMultiplyer,(float)terrain.GetValue(x+stepsize,y,z+stepsize)*dMultiplyer }; Vector3[] corners = { new Vector3(x,y,z), new Vector3(x,y+stepsize,z),new Vector3(x+stepsize,y+stepsize,z),new Vector3(x+stepsize,y,z), new Vector3(x,y,z+stepsize), new Vector3(x,y+stepsize,z+stepsize), new Vector3(x+stepsize,y+stepsize,z+stepsize), new Vector3(x+stepsize,y,z+stepsize)}; if (x == 0 && y == 0 && z == 0) { temp[x / stepsize, y / stepsize, z / stepsize] = new MarchingCube(densities, corners, device); } temp[x / stepsize, y / stepsize, z / stepsize] = new MarchingCube(densities, corners); } } } (terrain is a Perlin Noise generated using libnoise) I'm sure there's probably an easy solution to this but I've been drawing a blank for the past hour. I'm just wondering if the problem is how I'm reading in the data from the noise or if I may be generating the noise wrong? Or maybe the noise is just not good for this kind of generation? If I'm reading it wrong does anyone know the right way? the answers on google were somewhat ambiguous but I'm going to keep searching. Thanks in advance!

    Read the article

  • Getting an unexpected "?" at the end of a Registry GetValue in C#

    - by Wilhelm Peraud
    Hi, I use the Registry class to manage values in the Registry on Windows Seven in C#. Registry.GetValue(...); But, I'm facing a curious behavior : Every time, the returned value is the correct one, but sometimes, it is followed by an unexpected "?" When I check the Registry, (regedit), the "?" doesn't exist. I really don't understand from where this question mark come from. Could someone help me please ? Info : - C# - 3.5 framework - windows 7 64 bits (and i want my application to work on both 32 and 64 bits systems) Thank you in advance, Wilhelm

    Read the article

  • PropertyInfo.GetValue() - how do you index into a generic parameter using reflection in C#?

    - by flesh
    This (shortened) code.. for (int i = 0; i < count; i++) { object obj = propertyInfo.GetValue(Tcurrent, new object[] { i }); } .. is throwing a 'TargetParameterCountException : Parameter count mismatch' exception. The underlying type of 'propertyInfo' is a Collection of some T. 'count' is the number of items in the collection. I need to iterate through the collection and perform an operation on obj. Advice appreciated.

    Read the article

  • C# Proposal: Compile Time Static Checking Of Dynamic Objects

    - by Paulo Morgado
    C# 4.0 introduces a new type: dynamic. dynamic is a static type that bypasses static type checking. This new type comes in very handy to work with: The new languages from the dynamic language runtime. HTML Document Object Model (DOM). COM objects. Duck typing … Because static type checking is bypassed, this: dynamic dynamicValue = GetValue(); dynamicValue.Method(); is equivalent to this: object objectValue = GetValue(); objectValue .GetType() .InvokeMember( "Method", BindingFlags.InvokeMethod, null, objectValue, null); Apart from caching the call site behind the scenes and some dynamic resolution, dynamic only looks better. Any typing error will only be caught at run time. In fact, if I’m writing the code, I know the contract of what I’m calling. Wouldn’t it be nice to have the compiler do some static type checking on the interactions with these dynamic objects? Imagine that the dynamic object that I’m retrieving from the GetValue method, besides the parameterless method Method also has a string read-only Property property. This means that, from the point of view of the code I’m writing, the contract that the dynamic object returned by GetValue implements is: string Property { get; } void Method(); Since it’s a well defined contract, I could write an interface to represent it: interface IValue { string Property { get; } void Method(); } If dynamic allowed to specify the contract in the form of dynamic(contract), I could write this: dynamic(IValue) dynamicValue = GetValue(); dynamicValue.Method(); This doesn’t mean that the value returned by GetValue has to implement the IValue interface. It just enables the compiler to verify that dynamicValue.Method() is a valid use of dynamicValue and dynamicValue.OtherMethod() isn’t. If the IValue interface already existed for any other reason, this would be fine. But having a type added to an assembly just for compile time usage doesn’t seem right. So, dynamic could be another type construct. Something like this: dynamic DValue { string Property { get; } void Method(); } The code could now be written like this; DValue dynamicValue = GetValue(); dynamicValue.Method(); The compiler would never generate any IL or metadata for this new type construct. It would only thee used for compile type static checking of dynamic objects. As a consequence, it makes no sense to have public accessibility, so it would not be allowed. Once again, if the IValue interface (or any other type definition) already exists, it can be used in the dynamic type definition: dynamic DValue : IValue, IEnumerable, SomeClass { string Property { get; } void Method(); } Another added benefit would be IntelliSense. I’ve been getting mixed reactions to this proposal. What do you think? Would this be useful?

    Read the article

  • why it throws index out of bounds exception??

    - by Johanna
    Hi I want to use merge sort for sorting my doubly linked list.I have created 3 classes(Node,DoublyLinkedList,MergeSort) but it will throw this exception for these lines: 1.in the getNodes method of DoublyLinkedList---> throw new IndexOutOfBoundsException(); 2.in the add method of DoublyLinkedList-----> Node cursor = getNodes(index); 3.in the sort method of MergeSort class------> listTwo.add(x,localDoublyLinkedList.getValue(x)); 4.in the main method of DoublyLinkedList----->merge.sort(); this is my Merge class:(I put the whole code for this class for beter understanding) public class MergeSort { private DoublyLinkedList localDoublyLinkedList; public MergeSort(DoublyLinkedList list) { localDoublyLinkedList = list; } public void sort() { if (localDoublyLinkedList.size() <= 1) { return; } DoublyLinkedList listOne = new DoublyLinkedList(); DoublyLinkedList listTwo = new DoublyLinkedList(); for (int x = 0; x < (localDoublyLinkedList.size() / 2); x++) { listOne.add(x, localDoublyLinkedList.getValue(x)); } for (int x = (localDoublyLinkedList.size() / 2) + 1; x < localDoublyLinkedList.size(); x++) { listTwo.add(x, localDoublyLinkedList.getValue(x)); } //Split the DoublyLinkedList again MergeSort sort1 = new MergeSort(listOne); MergeSort sort2 = new MergeSort(listTwo); sort1.sort(); sort2.sort(); merge(listOne, listTwo); } public void merge(DoublyLinkedList a, DoublyLinkedList b) { int x = 0; int y = 0; int z = 0; while (x < a.size() && y < b.size()) { if (a.getValue(x) < b.getValue(y)) { localDoublyLinkedList.add(z, a.getValue(x)); x++; } else { localDoublyLinkedList.add(z, b.getValue(y)); y++; } z++; } //copy remaining elements to the tail of a[]; for (int i = x; i < a.size(); i++) { localDoublyLinkedList.add(z, a.getValue(i)); z++; } for (int i = y; i < b.size(); i++) { localDoublyLinkedList.add(z, b.getValue(i)); z++; } } } and just a part of my DoublyLinkedList: private Node getNodes(int index) throws IndexOutOfBoundsException { if (index < 0 || index > length) { throw new IndexOutOfBoundsException(); } else { Node cursor = head; for (int i = 0; i < index; i++) { cursor = cursor.getNext(); } return cursor; } } public void add(int index, int value) throws IndexOutOfBoundsException { Node cursor = getNodes(index); Node temp = new Node(value); temp.setPrev(cursor); temp.setNext(cursor.getNext()); cursor.getNext().setPrev(temp); cursor.setNext(temp); length++; } public static void main(String[] args) { int i = 0; i = getRandomNumber(10, 10000); DoublyLinkedList list = new DoublyLinkedList(); for (int j = 0; j < i; j++) { list.add(j, getRandomNumber(10, 10000)); MergeSort merge = new MergeSort(list); merge.sort(); System.out.println(list.getValue(j)); } } PLEASE help me thanks alot.

    Read the article

  • Java Binary Tree. Priting InOrder traversal

    - by user69514
    I am having some problems printing an inOrder traversal of my binary tree. Even after inserting many items into the tree it's only printing 3 items. public class BinaryTree { private TreeNode root; private int size; public BinaryTree(){ this.size = 0; } public boolean insert(TreeNode node){ if( root == null) root = node; else{ TreeNode parent = null; TreeNode current = root; while( current != null){ if( node.getData().getValue().compareTo(current.getData().getValue()) <0){ parent = current; current = current.getLeft(); } else if( node.getData().getValue().compareTo(current.getData().getValue()) >0){ parent = current; current = current.getRight(); } else return false; if(node.getData().getValue().compareTo(parent.getData().getValue()) < 0) parent.setLeft(node); else parent.setRight(node); } } size++; return true; } /** * */ public void inOrder(){ inOrder(root); } private void inOrder(TreeNode root){ if( root.getLeft() !=null) this.inOrder(root.getLeft()); System.out.println(root.getData().getValue()); if( root.getRight() != null) this.inOrder(root.getRight()); } }

    Read the article

  • Weird result comparing property values using reflection

    - by Brian
    Can someone explain why this is occurring? The code below was executed in the immediate window in vs2008. The prop is an Int32 property (id column) on an object created by the entity framework. The objects entity and defaultEntity were created using Activator.CreateInstance(); Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) 0 Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) == Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType) false

    Read the article

  • How to use method hiding (new) with generic constrained class

    - by ongle
    I have a container class that has a generic parameter which is constrained to some base class. The type supplied to the generic is a sub of the base class constraint. The sub class uses method hiding (new) to change the behavior of a method from the base class (no, I can't make it virtual as it is not my code). My problem is that the 'new' methods do not get called, the compiler seems to consider the supplied type to be the base class, not the sub, as if I had upcast it to the base. Clearly I am misunderstanding something fundamental here. I thought that the generic where T: xxx was a constraint, not an upcast type. This sample code basically demonstrates what I'm talking about. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericPartialTest { class ContextBase { public string GetValue() { return "I am Context Base: " + this.GetType().Name; } public string GetOtherValue() { return "I am Context Base: " + this.GetType().Name; } } partial class ContextSub : ContextBase { public new string GetValue() { return "I am Context Sub: " + this.GetType().Name; } } partial class ContextSub { public new string GetOtherValue() { return "I am Context Sub: " + this.GetType().Name; } } class Container<T> where T: ContextBase, new() { private T _context = new T(); public string GetValue() { return this._context.GetValue(); } public string GetOtherValue() { return this._context.GetOtherValue(); } } class Program { static void Main(string[] args) { Console.WriteLine("Simple"); ContextBase myBase = new ContextBase(); ContextSub mySub = new ContextSub(); Console.WriteLine(myBase.GetValue()); Console.WriteLine(myBase.GetOtherValue()); Console.WriteLine(mySub.GetValue()); Console.WriteLine(mySub.GetOtherValue()); Console.WriteLine("Generic Container"); Container<ContextBase> myContainerBase = new Container<ContextBase>(); Container<ContextSub> myContainerSub = new Container<ContextSub>(); Console.WriteLine(myContainerBase.GetValue()); Console.WriteLine(myContainerBase.GetOtherValue()); Console.WriteLine(myContainerSub.GetValue()); Console.WriteLine(myContainerSub.GetOtherValue()); Console.ReadKey(); } } }

    Read the article

  • Django: Odd mark_safe behaviour?

    - by Mark
    I wrote this little function for writing out HTML tags: def html_tag(tag, content=None, close=True, attrs={}): lst = ['<',tag] for key, val in attrs.iteritems(): lst.append(' %s="%s"' % (key, escape_html(val))) if close: if content is None: lst.append(' />') else: lst.extend(['>', content, '</', tag, '>']) else: lst.append('>') return mark_safe(''.join(lst)) Which worked great, but then I read this article on efficient string concatenation (I know it doesn't really matter for this, but I wanted consistency) and decided to update my script: def html_tag(tag, body=None, close=True, attrs={}): s = StringIO() s.write('<%s'%tag) for key, val in attrs.iteritems(): s.write(' %s="%s"' % (key, escape_html(val))) if close: if body is None: s.write(' />') else: s.write('>%s</%s>' % (body, tag)) else: s.write('>') return mark_safe(s.getvalue()) But now my HTML get escaped when I try to render it from my template. Everything else is exactly the same. It works properly if I replace the last line with return mark_safe(unicode(s.getvalue())). I checked the return type of s.getvalue(). It should be a str, just like the first function, so why is this failing?? Also fails with SafeString(s.getvalue()) but succeeds with SafeUnicode(s.getvalue()). I'd also like to point out that I used return mark_safe(s.getvalue()) in a different function with no odd behavior. The "call stack" looks like this: class Input(Widget): def render(self): return html_tag('input', attrs={'type':self.itype, 'id':self.id, 'name':self.name, 'value':self.value, 'class':self.itype}) class Field: def __unicode__(self): return mark_safe(self.widget.render()) And then {{myfield}} is in the template. So it does get mark_safed'd twice, which I thought might have been the problem, but I tried removing that too..... I really have no idea what's causing this, but it's not too hard to work around, so I guess I won't fret about it.

    Read the article

  • Django stupid mark_safe?

    - by Mark
    I wrote this little function for writing out HTML tags: def html_tag(tag, content=None, close=True, attrs={}): lst = ['<',tag] for key, val in attrs.iteritems(): lst.append(' %s="%s"' % (key, escape_html(val))) if close: if content is None: lst.append(' />') else: lst.extend(['>', content, '</', tag, '>']) else: lst.append('>') return mark_safe(''.join(lst)) Which worked great, but then I read this article on efficient string concatenation (I know it doesn't really matter for this, but I wanted consistency) and decided to update my script: def html_tag(tag, body=None, close=True, attrs={}): s = StringIO() s.write('<%s'%tag) for key, val in attrs.iteritems(): s.write(' %s="%s"' % (key, escape_html(val))) if close: if body is None: s.write(' />') else: s.write('>%s</%s>' % (body, tag)) else: s.write('>') return mark_safe(s.getvalue()) But now my HTML get escaped when I try to render it from my template. Everything else is exactly the same. It works properly if I replace the last line with return mark_safe(unicode(s.getvalue())). I checked the return type of s.getvalue(). It should be a str, just like the first function, so why is this failing?? Also fails with SafeString(s.getvalue()) but succeeds with SafeUnicode(s.getvalue()). I'd also like to point out that I used return mark_safe(s.getvalue()) in a different function with no odd behavior.

    Read the article

  • How can I bind to a helper property in Silverlight

    - by Matt
    For the sake of argument, here's a simple person class public class Person : DependencyObject, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register( "FirstName", typeof ( string ), typeof ( Person ), null ); public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register( "LastName", typeof( string ), typeof( Person ), null ); public string FirstName { get { return ( string ) GetValue( FirstNameProperty ); } set { SetValue( FirstNameProperty, value ); if(PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs( "FirstName" )); } } public string LastName { get { return ( string ) GetValue( LastNameProperty ); } set { SetValue( LastNameProperty, value ); if ( PropertyChanged != null ) PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) ); } } } I want to go about creating a readonly property like this public string FullName { get { return FirstName + " " + LastName; } } How does binding work in this scenario? I've tried adding a DependancyProperty and raised the PropertyChanged event for the fullname. Basically I just want to have a property that I can bind to that returns the fullname of a user whenever the first or last name changes. Here's the final class I'm using with the modifications. public class Person : DependencyObject, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register( "FirstName", typeof ( string ), typeof ( Person ), null ); public static readonly DependencyProperty LastNameProperty = DependencyProperty.Register( "LastName", typeof( string ), typeof( Person ), null ); public static readonly DependencyProperty FullNameProperty = DependencyProperty.Register( "FullName", typeof( string ), typeof( Person ), null ); public string FirstName { get { return ( string ) GetValue( FirstNameProperty ); } set { SetValue( FirstNameProperty, value ); if ( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "FirstName" ) ); PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) ); } } } public string LastName { get { return ( string ) GetValue( LastNameProperty ); } set { SetValue( LastNameProperty, value ); if ( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) ); PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) ); } } } public string FullName { get { return GetValue( FirstNameProperty ) + " " + GetValue( LastNameProperty ); } } }

    Read the article

  • Linked List Inserting strings in alphabetical order

    - by user69514
    I have a linked list where each node contains a string and a count. my insert method needs to inset a new node in alphabetical order based on the string. if there is a node with the same string, then i increment the count. the problem is that my method is not inserting in alphabetical order public Node findIsertionPoint(Node head, Node node){ if( head == null) return null; Node curr = head; while( curr != null){ if( curr.getValue().compareTo(node.getValue()) == 0) return curr; else if( curr.getNext() == null || curr.getNext().getValue().compareTo(node.getValue()) > 0) return curr; else curr = curr.getNext(); } return null; } public void insert(Node node){ Node newNode = node; Node insertPoint = this.findIsertionPoint(this.head, node); if( insertPoint == null) this.head = newNode; else{ if( insertPoint.getValue().compareTo(node.getValue()) == 0) insertPoint.getItem().incrementCount(); else{ newNode.setNext(insertPoint.getNext()); insertPoint.setNext(newNode); } } count++; }

    Read the article

  • Liskov principle: violation by type-hinting

    - by Elias Van Ootegem
    According to the Liskov principle, a construction like the one below is invalid, as it strengthens a pre-condition. I know the example is pointless/nonsense, but when I last asked a question like this, and used a more elaborate code sample, it seemed to distract people too much from the actual question. //Data models abstract class Argument { protected $value = null; public function getValue() { return $this->value; } abstract public function setValue($val); } class Numeric extends Argument { public function setValue($val) { $this->value = $val + 0;//coerce to number return $this; } } //used here: abstract class Output { public function printValue(Argument $arg) { echo $this->format($arg); return $this; } abstract public function format(Argument $arg); } class OutputNumeric extends Output { public function format(Numeric $arg)//<-- VIOLATION! { $format = is_float($arg->getValue()) ? '%.3f' : '%d'; return sprintf($format, $arg->getValue()); } } My question is this: Why would this kind of "violation" be considered harmful? So much so that some languages, like the one I used in this example (PHP), don't even allow this? I'm not allowed to strengthen the type-hint of an abstract method but, by overriding the printValue method, I am allowed to write: class OutputNumeric extends Output { final public function printValue(Numeric $arg) { echo $this->format($arg); } public function format(Argument $arg) { $format = is_float($arg->getValue()) ? '%.3f' : '%d'; return sprintf($format, $arg->getValue()); } } But this would imply repeating myself for each and every child of Output, and makes my objects harder to reuse. I understand why the Liskov principle exists, don't get me wrong, but I find it somewhat difficult to fathom why the signature of an abstract method in an abstract class has to be adhered to so much stricter than a non-abstract method. Could someone explain to me why I'm not allowed to hind at a child class, in a child class? The way I see it, the child class OutputNumeric is a specific use-case of Output, and thus might need a specific instance of Argument, namely Numeric. Is it really so wrong of me to write code like this?

    Read the article

  • Dynamic Linq help, different errors depending on object passed as parameter?

    - by sah302
    I have an entityDao that is inherbited by everyone of my objectDaos. I am using Dynamic Linq and trying to get some generic queries to work. I have the following code in my generic method in my EntityDao : public abstract class EntityDao<ImplementationType> where ImplementationType : Entity { public ImplementationType getOneByValueOfProperty(string getProperty, object getValue){ ImplementationType entity = null; if (getProperty != null && getValue != null) { LCFDataContext lcfdatacontext = new LCFDataContext(); //Generic LINQ Query Here entity = lcfdatacontext.GetTable<ImplementationType>().Where(getProperty + " =@0", getValue).FirstOrDefault(); //.Where(getProperty & "==" & CStr(getValue)) } //lcfdatacontext.SubmitChanges() //lcfdatacontext.Dispose() return entity; } }         Then I do the following method call in a unit test (all my objectDaos inherit entityDao): [Test] public void getOneByValueOfProperty() { Accomplishment result = accomplishmentDao.getOneByValueOfProperty("AccomplishmentType.Name", "Publication"); Assert.IsNotNull(result); } The above passes (AccomplishmentType has a relationship to accomplishment) Accomplishment result = accomplishmentDao.getOneByValueOfProperty("Description", "Can you hear me now?"); Accomplishment result = accomplishmentDao.getOneByValueOfProperty("LocalId", 4); Both of the above work Accomplishment result = accomplishmentDao.getOneByValueOfProperty("Id", New Guid("95457751-97d9-44b5-8f80-59fc2d170a4c"))       Does not work and says the following: Operator '=' incompatible with operand types 'Guid' and 'Guid Why is this happening? Guid's can't be compared? I tried == as well but same error. What's even moreso confusing is that every example of Dynamic Linq I have seen simply usings strings whether using the parameterized where predicate or this one I have commented out: //.Where(getProperty & "==" & CStr(getValue)) With or without the Cstr, many datatypes don't work with this format. I tried setting the getValue to a string instead of an object as well, but then I just get different errors (such as a multiword string would stop comparison after the first word). What am I missing to make this work with GUIDs and/or any data type? Ideally I would like to be able to just pass in a string for getValue (as I have seen for every other dynamic LINQ example) instead of the object and have it work regardless of the data Type of the column.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >