Search Results

Search found 580 results on 24 pages for 'setvalue'.

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

  • UISlider disappearing when calling setValue with 0

    - by Kai
    I have several UISliders in my application which all work fine until I call the following code: ... frame = CGRectMake(43, 210, 201, 23); mySlider = [[UISlider alloc] initWithFrame:frame]; [mySlider addTarget:self action:@selector(sliderUpdate:) forControlEvents:UIControlEventValueChanged]; mySlider.minimumValue = 0.0; mySlider.maximumValue = 1.0; mySlider.continuous = YES; tempNum = [myArray objectAtIndex:2]; mySlider.value = [tempNum floatValue]; // only breaks if value is 0 [self.view addSubview:mySlider]; ... For some reason the slider doesn't show up unless mySlider.value is set to greater than 0. The only workaround I've found so far is to set it to an extremely small value (such as 0.000000001), which makes the slider appear as expected. Does anyone have any idea why this might be happening and how it can be fixed?

    Read the article

  • How to properly set relationships in Core Data when using setValue and data already exists

    - by ern
    Let's say I have two objects: Articles and Categories. For the sake of this example all relevant categories have already been added to the data store. When looping through data that holds edits for articles, there is category relationship information that needs to be saved. I was planning on using the -setValue method in the Article class in order to set the relationships like so: - (void)setValue:(id)value forUndefinedKey:(NSString *)key { if([key isEqualToString:@"categories"]){ NSLog(@"trying to set categories..."); } } The problem is that value isn't a Category, it is just a string (or array of strings) holding the title of a category. I could certainly do a lookup within this method for each category and assign it, but that seems inefficient when processing a whole bunch of articles at once. Another option is to populate an array of all possible categories and just filter, but my question is where to store that array? Should it be a class method on Article? Is there a way to pass in additional data to the -setValue method? Is there another, better option for setting the relationship I'm not thinking of? Thanks for your help.

    Read the article

  • Light on every model and not in the whole scene

    - by alecnash
    I am using a custom shader and try to pass the effect on my Models like that: foreach (ModelMesh mesh in Model.Meshes) { foreach (ModelMeshPart part in mesh.MeshParts) { part.Effect = effect; } mesh.Draw(); } My only issue is that every Model now has its own light source in it. Why is this happening and is this a problem of my shader? Edit: These are the parameters passed to the shader: private void Get_lambertEffect() { if (_lambertEffect == null) _lambertEffect = Engine.LambertEffect; //Lambert technique (LambertWithShadows, LambertWithShadows2x2PCF, LambertWithShadows3x3PCF) _lambertEffect.CurrentTechnique = _lambertEffect.Techniques["LambertWithShadows3x3PCF"]; _lambertEffect.Parameters["texelSize"].SetValue(Engine.ShadowMap.TexelSize); //ShadowMap parameters _lambertEffect.Parameters["lightViewProjection"].SetValue(Engine.ShadowMap.LightViewProjectionMatrix); _lambertEffect.Parameters["textureScaleBias"].SetValue(Engine.ShadowMap.TextureScaleBiasMatrix); _lambertEffect.Parameters["depthBias"].SetValue(Engine.ShadowMap.DepthBias); _lambertEffect.Parameters["shadowMap"].SetValue(Engine.ShadowMap.ShadowMapTexture); //Camera view and projection parameters _lambertEffect.Parameters["view"].SetValue(Engine._camera.ViewMatrix); _lambertEffect.Parameters["projection"].SetValue(Engine._camera.ProjectionMatrix); _lambertEffect.Parameters["world"].SetValue( Matrix.CreateScale(Size) * world ); //Light and color _lambertEffect.Parameters["lightDir"].SetValue(Engine._sourceLight.Direction); _lambertEffect.Parameters["lightColor"].SetValue(Engine._sourceLight.Color); _lambertEffect.Parameters["materialAmbient"].SetValue(Engine.Material.Ambient); _lambertEffect.Parameters["materialDiffuse"].SetValue(Engine.Material.Diffuse); _lambertEffect.Parameters["colorMap"].SetValue(ColorTexture.Create(Engine.GraphicsDevice, Color.Red)); }

    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

  • Workflow Foundation (WF) -- Why does setting a DependencyProperty to a COM object using SetValue() t

    - by stakx
    Assume that I have a .NET Workflow Foundation (WF) SequenceActivity class with the following property: public IWorkspace Workspace { get; set; } // ^^^^^^^^^^ // important: this is a COM interface type! public static DependencyProperty WorkspaceProperty = DependencyProperty.Register( "Workspace", typeof(IWorkspace), typeof(FoobarActivity)); // <-- this activity class This activity executes some code that sets both of the above like this: this.Workspace = ...; // exact code not relevant; property set to a COM object SetValue(WorkspaceProperty, this.Workspace); The last line (which makes the call to SetValue) results in an ArgumentException for the second parameter (having the value of this.Workspace): Type […].IWorkspace of dependency property Workspace does not match the value's type System.__ComObject.                                           (translated from German, the English exception text might differ slightly) As soon as I register the dependency property with typeof(object) instead of typeof(IWorkspace) as the second parameter, the code executes just fine. However, that would result in the possibility to assign just about any value to the dependency property, and I do not want that. It seems to me that WF dependency properties don't work for COM interop objects.Does anyone have a solution to this?

    Read the article

  • Why setValue at not working on Jtable?

    - by Nitz
    Hey Guys I am doing project on java. In one of the class, I am working on jtable. Now what i am doing is, In the table data will be loaded from the database. Now i want to change some value at some exact row and column. so for that i am using jtable's setValue function. which is like this.... grayCardTbl.setValueAt(Float.valueOf(String.valueOf(pdiff)),1,4); I have checked the "pdiff" variable, it is perfect. i had total 5 columns and 10 rows. So now problem with rowindex and column index. and after this i have also refresh the table. but still it is not reflecting on table.

    Read the article

  • PropertyInfo SetValue and nulls

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

    Read the article

  • Entity Framework This property descriptor does not support the SetValue

    - by Gayan
    Hello guys, below are my entities which i have created using entity frame work. retailer id name childs(navigation) generated database schema [Id] [int] IDENTITY(1,1) NOT NULL, [Name] nvarchar NOT NULL childern id name RETAILER(navigation) generated database schema [Id] [int] IDENTITY(1,1) NOT NULL, [name] nvarchar NOT NULL [Retailer_Id] [int] NOT NULL, As you can see in the above model the relationship is 1 retailer can have 0 or 1 child. my problem is when i create a new child and set the retailer navigation property of it to a retailer entity it throws the following exception.how do i solve it Error while setting property 'retailer': 'This property descriptor does not support the SetValue method.'.

    Read the article

  • C# Type Casting at Runtimefor Array.SetValue

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

    Read the article

  • C# - setting a property by reflection with a string value

    - by David Hodgson
    Hi, I'd like to set a property of an object through reflection, with a value of type string. So, for instance, suppose I have a Ship class, with a property of Latitude, which is a double. Here's what I'd like to do: Ship ship = new Ship(); string value = "5.5"; PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude"); propertyInfo.SetValue(ship, value, null); As is, this throws an Argument exception (Object of type 'System.String' cannot be converted to type 'System.Double'). How can I convert value to the proper type, based on propertyInfo?

    Read the article

  • How to create a chart from mysql data?

    - by user187580
    Hello, I have some data and want to create some dynamic charts. I have looked on Google visualisation api .. It looks great but the problem is I am not very familiar with it. Any ideas, how I can set the data.setValue from mysql data. <script type='text/javascript'> google.load('visualization', '1', {'packages': ['geomap']}); google.setOnLoadCallback(drawMap); function drawMap() { var data = new google.visualization.DataTable(); data.addRows(6); data.addColumn('string', 'Country'); data.addColumn('number', 'Popularity'); data.setValue(0, 0, 'Germany'); data.setValue(0, 1, 200); data.setValue(1, 0, 'United States'); data.setValue(1, 1, 300); data.setValue(2, 0, 'Brazil'); data.setValue(2, 1, 400); data.setValue(3, 0, 'Canada'); data.setValue(3, 1, 500); data.setValue(4, 0, 'France'); data.setValue(4, 1, 600); data.setValue(5, 0, 'RU'); data.setValue(5, 1, 700); var options = {}; options['dataMode'] = 'regions'; var container = document.getElementById('map_canvas'); var geomap = new google.visualization.GeoMap(container); geomap.draw(data, options); }; </script> I can create chart using some other methods but just interested in using Google Visualisation API. Thanks.

    Read the article

  • DrawIndexedPrimitives overdraws data in previous buffer if called in loop

    - by Daniel Excinsky
    I doubled the question from stackoverflow here, and will delete the opposite of a question that gave me the answer. I have the Draw method in one of my renderers, that loops through the dictionary and gets precollected and preinitialized buffers. When dictionary has only one element, everything is just fine. But with more elements what I get on the screen is only the data from the last buffer (I suppose, not sure) My Draw method: public void Draw(GameTime gameTime) { if (!_areStaticEffectsSet) { // blockEffect.Parameters["TextureAtlas"].SetValue(textureAtlas); blockEffect.Parameters["HorizonColor"].SetValue(World.HORIZONCOLOR); blockEffect.Parameters["NightColor"].SetValue(World.NIGHTCOLOR); blockEffect.Parameters["MorningTint"].SetValue(World.MORNINGTINT); blockEffect.Parameters["EveningTint"].SetValue(World.EVENINGTINT); blockEffect.Parameters["SunColor"].SetValue(World.SUNCOLOR); _areStaticEffectsSet = true; } blockEffect.Parameters["World"].SetValue(Matrix.Identity); blockEffect.Parameters["View"].SetValue(_player.CameraView); blockEffect.Parameters["Projection"].SetValue(_player.CameraProjection); blockEffect.Parameters["CameraPosition"].SetValue(_player.CameraPosition); blockEffect.Parameters["timeOfDay"].SetValue(_world.TimeOfDay); var viewFrustum = new BoundingFrustum(_player.CameraView * _player.CameraProjection); _graphicsDevice.BlendState = BlendState.Opaque; _graphicsDevice.DepthStencilState = DepthStencilState.Default; foreach (KeyValuePair<int, Texture2D> textureAtlas in textureAtlases) { blockEffect.Parameters["TextureAtlas"].SetValue(textureAtlas.Value); foreach (EffectPass pass in blockEffect.CurrentTechnique.Passes) { pass.Apply(); //TODO: ?????????? ??????????????? ?? ?????? ?? ??????? ??????? VertexBuffer ? IndexBuffer foreach (Chunk chunk in _world.Chunks.Values) { if (chunk == null || chunk.IsDisposed) { continue; } if (chunk.BoundingBox.Intersects(viewFrustum) && chunk.GetBlockIndexBuffer(textureAtlas.Key) != null) { lock (chunk) { if (chunk.GetBlockIndexBuffer(textureAtlas.Key).IndexCount > 0) { VertexBuffer vertexBuffer = chunk.GetBlockVertexBuffer(textureAtlas.Key); IndexBuffer indexBuffer = chunk.GetBlockIndexBuffer(textureAtlas.Key); //if (chunk.DrawIndex == new Vector3i(0, 0, 0)) //{ //if (textureAtlas.Key == -1) //{ //var varray = new [] //{ //new VertexPositionTextureLight(new Vector3(0,68,0), new Vector2(0,1),1,new Vector3(0,0,0), new Vector3(1,1,1)), //new VertexPositionTextureLight(new Vector3(0,68,1), new Vector2(0,1),1,new Vector3(0,0,0), new Vector3(1,1,1)), //new VertexPositionTextureLight(new Vector3(1,68,0), new Vector2(0,1),1,new Vector3(0,0,0), new Vector3(1,1,1)) //}; //var iarray = new short[] {0, 1, 2}; //vertexBuffer = new VertexBuffer(_graphicsDevice, typeof(VertexPositionTextureLight), varray.Length, BufferUsage.WriteOnly); //indexBuffer = new IndexBuffer(_graphicsDevice, IndexElementSize.SixteenBits, iarray.Length, BufferUsage.WriteOnly); //vertexBuffer.SetData(varray); //indexBuffer.SetData(iarray); } } _graphicsDevice.SetVertexBuffer(vertexBuffer); _graphicsDevice.Indices = indexBuffer; _graphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, vertexBuffer.VertexCount, 0, indexBuffer.IndexCount / 3); } } } } } } } Noteworthy things about the code: XNA version is 4.0. I've commented the debugging code in the loop, but left it for it may bring some insight. I try not only to change vertices/indices in the loop, but textureAtlas also. Code in the shader about textureAtlas: Texture TextureAtlas; sampler TextureAtlasSampler = sampler_state { texture = <TextureAtlas>; magfilter = POINT; minfilter = POINT; mipfilter = POINT; AddressU = WRAP; AddressV = WRAP; }; struct VSInput { float4 Position : POSITION0; float2 TexCoords1 : TEXCOORD0; float SunLight : COLOR0; float3 LocalLight : COLOR1; float3 Normal : NORMAL0; }; VertexPositionTextureLight is my own realization of IVertexType. So, do anybody know about this problem, or see the wrongness in my code (that's far more likely)?

    Read the article

  • Greasemonkey failing to GM_setValue()

    - by HonoredMule
    I have a Greasemonkey script that uses a Javascript object to maintain some stored objects. It covers quite a large volume of information, but substantially less than it successfully stored and retrieved prior to encountering my problem. One value refuses to save, and I can not for the life of me determine why. The following problem code: Works for other larger objects being maintained. Is presently handling a smaller total amount of data than previously worked. Is not colliding with any function or other object definitions. Can (optionally) successfully save the problem storage key as "{}" during code startup. this.save = function(table) { var tables = this.tables; if(table) tables = [table]; for(i in tables) { logger.log(this[tables[i]]); logger.log(JSON.stringify(this[tables[i]])); GM_setValue(tables[i] + "_" + this.user, JSON.stringify(this[tables[i]])); logger.log(tables[i] + "_" + this.user + " updated"); logger.log(GM_getValue(tables[i] + "_" + this.user)); } } The problem is consistently reproducible and the logging statments produce the following output in Firebug: Object { 54,10 = Object } // Expansion shows complete contents as expected, but there is one oddity--Firebug highlights the array keys in purple instead of the usual black for anonymous objects. {"54,10":{"x":54,"y":10,"name":"Lucky Pheasant"}} // The correctly parsed string. bookmarks_HonoredMule saved undefined I have tried altering the format of the object keys, to no effect. Further narrowing down the issue is that this particular value is successfully saved as an empty object ("{}") during code initialization, but skipping that also does not help. Reloading the page confirms that saving of the nonempty object truly failed. Any idea what could cause this behavior? I've thoroughly explored the possibility of hitting size constraints, but it doesn't appear that can be the problem--as previously mentioned, I've already reduced storage usage. Other larger objects save still, and the total number of objects, which was not high already, has further been reduced by an amount greater than the quantity of data I'm attempting to store here.

    Read the article

  • Transform.Translation problem on rotation

    - by eco_bach
    I am using the following to scale and reposition a UIView layer when the device rotates to landscape. [containerView.layer setValue:[NSNumber numberWithFloat: 0] forKeyPath: @"transform.translation.x"]; [containerView.layer setValue:[NSNumber numberWithFloat: 0] forKeyPath: @"transform.translation.y"]; [containerView.layer setValue:[NSNumber numberWithFloat: 1] forKeyPath: @"transform.scale.x"]; //[NSNumber numberWithInt:1] [containerView.layer setValue:[NSNumber numberWithFloat: 1] forKeyPath: @"transform.scale.y"]; and then the folowing when rotating back to portrait [containerView.layer setValue:[NSNumber numberWithFloat: -75] forKeyPath: @"transform.translation.x"]; [containerView.layer setValue:[NSNumber numberWithFloat: 0] forKeyPath: @"transform.translation.y"]; [containerView.layer setValue:[NSNumber numberWithFloat: .7] forKeyPath: @"transform.scale.x"]; //[NSNumber numberWithInt:1] [containerView.layer setValue:[NSNumber numberWithFloat: .7] forKeyPath: @"transform.scale.y"]; The problem is that after rotaing back to portrait, the layer is 'travelling' ie the x,y offset are gradually changing(increasing x, decreasing y). Scale seems fine (ie doesn't increment, decrement on repeated rotations) Can anyone suggest a proper solution?

    Read the article

  • How to handle multiple effect files in XNA

    - by Adam 'Pi' Burch
    So I'm using ModelMesh and it's built in Effects parameter to draw a mesh with some shaders I'm playing with. I have a simple GUI that lets me change these parameters to my heart's desire. My question is, how do I handle shaders that have unique parameters? For example, I want a 'shiny' parameter that affects shaders with Phong-type specular components, but for an environment mapping shader such a parameter doesn't make a lot of sense. How I have it right now is that every time I call the ModelMesh's Draw() function, I set all the Effect parameters as so foreach (ModelMesh m in model.Meshes) { if (isDrawBunny == true)//Slightly change the way the world matrix is calculated if using the bunny object, since it is not quite centered in object space { world = boneTransforms[m.ParentBone.Index] * Matrix.CreateScale(scale) * rotation * Matrix.CreateTranslation(position + bunnyPositionTransform); } else //If not rendering the bunny, draw normally { world = boneTransforms[m.ParentBone.Index] * Matrix.CreateScale(scale) * rotation * Matrix.CreateTranslation(position); } foreach (Effect e in m.Effects) { Matrix ViewProjection = camera.ViewMatrix * camera.ProjectionMatrix; e.Parameters["ViewProjection"].SetValue(ViewProjection); e.Parameters["World"].SetValue(world); e.Parameters["diffuseLightPosition"].SetValue(lightPositionW); e.Parameters["CameraPosition"].SetValue(camera.Position); e.Parameters["LightColor"].SetValue(lightColor); e.Parameters["MaterialColor"].SetValue(materialColor); e.Parameters["shininess"].SetValue(shininess); //e.Parameters //e.Parameters["normal"] } m.Draw(); Note the prescience of the example! The solutions I've thought of involve preloading all the shaders, and updating the unique parameters as needed. So my question is, is there a best practice I'm missing here? Is there a way to pull the parameters a given Effect needs from that Effect? Thank you all for your time!

    Read the article

  • Convert from Procedural to Object Oriented Code

    - by Anthony
    I have been reading Working Effectively with Legacy Code and Clean Code with the goal of learning strategies on how to begin cleaning up the existing code-base of a large ASP.NET webforms application. This system has been around since 2005 and since then has undergone a number of enhancements. Originally the code was structured as follows (and is still largely structured this way): ASP.NET (aspx/ascx) Code-behind (c#) Business Logic Layer (c#) Data Access Layer (c#) Database (Oracle) The main issue is that the code is procedural masquerading as object-oriented. It virtually violates all of the guidelines described in both books. This is an example of a typical class in the Business Logic Layer: public class AddressBO { public TransferObject GetAddress(string addressID) { if (StringUtils.IsNull(addressID)) { throw new ValidationException("Address ID must be entered"); } AddressDAO addressDAO = new AddressDAO(); return addressDAO.GetAddress(addressID); } public TransferObject Insert(TransferObject addressDetails) { if (StringUtils.IsNull(addressDetails.GetString("EVENT_ID")) || StringUtils.IsNull(addressDetails.GetString("LOCALITY")) || StringUtils.IsNull(addressDetails.GetString("ADDRESS_TARGET")) || StringUtils.IsNull(addressDetails.GetString("ADDRESS_TYPE_CODE")) || StringUtils.IsNull(addressDetails.GetString("CREATED_BY"))) { throw new ValidationException( "You must enter an Event ID, Locality, Address Target, Address Type Code and Created By."); } string addressID = Sequence.GetNextValue("ADDRESS_ID_SEQ"); addressDetails.SetValue("ADDRESS_ID", addressID); string syncID = Sequence.GetNextValue("SYNC_ID_SEQ"); addressDetails.SetValue("SYNC_ADDRESS_ID", syncID); TransferObject syncDetails = new TransferObject(); Transaction transaction = new Transaction(); try { AddressDAO addressDAO = new AddressDAO(); addressDAO.Insert(addressDetails, transaction); // insert the record for the target TransferObject addressTargetDetails = new TransferObject(); switch (addressDetails.GetString("ADDRESS_TARGET")) { case "PARTY_ADDRESSES": { addressTargetDetails.SetValue("ADDRESS_ID", addressID); addressTargetDetails.SetValue("ADDRESS_TYPE_CODE", addressDetails.GetString("ADDRESS_TYPE_CODE")); addressTargetDetails.SetValue("PARTY_ID", addressDetails.GetString("PARTY_ID")); addressTargetDetails.SetValue("EVENT_ID", addressDetails.GetString("EVENT_ID")); addressTargetDetails.SetValue("CREATED_BY", addressDetails.GetString("CREATED_BY")); addressDAO.InsertPartyAddress(addressTargetDetails, transaction); break; } case "PARTY_CONTACT_ADDRESSES": { addressTargetDetails.SetValue("ADDRESS_ID", addressID); addressTargetDetails.SetValue("ADDRESS_TYPE_CODE", addressDetails.GetString("ADDRESS_TYPE_CODE")); addressTargetDetails.SetValue("PUBLIC_RELEASE_FLAG", addressDetails.GetString("PUBLIC_RELEASE_FLAG")); addressTargetDetails.SetValue("CONTACT_ID", addressDetails.GetString("CONTACT_ID")); addressTargetDetails.SetValue("EVENT_ID", addressDetails.GetString("EVENT_ID")); addressTargetDetails.SetValue("CREATED_BY", addressDetails.GetString("CREATED_BY")); addressDAO.InsertContactAddress(addressTargetDetails, transaction); break; } << many more cases here >> default: { break; } } // synchronise SynchronisationBO synchronisationBO = new SynchronisationBO(); syncDetails = synchronisationBO.Synchronise("I", transaction, "ADDRESSES", addressDetails.GetString("ADDRESS_TARGET"), addressDetails, addressTargetDetails); // commit transaction.Commit(); } catch (Exception) { transaction.Rollback(); throw; } return new TransferObject("ADDRESS_ID", addressID, "SYNC_DETAILS", syncDetails); } << many more methods are here >> } It has a lot of duplication, the class has a number of responsibilities, etc, etc - it is just generally 'un-clean' code. All of the code throughout the system is dependent on concrete implementations. This is an example of a typical class in the Data Access Layer: public class AddressDAO : GenericDAO { public static readonly string BASE_SQL_ADDRESSES = "SELECT " + " a.address_id, " + " a.event_id, " + " a.flat_unit_type_code, " + " fut.description as flat_unit_description, " + " a.flat_unit_num, " + " a.floor_level_code, " + " fl.description as floor_level_description, " + " a.floor_level_num, " + " a.building_name, " + " a.lot_number, " + " a.street_number, " + " a.street_name, " + " a.street_type_code, " + " st.description as street_type_description, " + " a.street_suffix_code, " + " ss.description as street_suffix_description, " + " a.postal_delivery_type_code, " + " pdt.description as postal_delivery_description, " + " a.postal_delivery_num, " + " a.locality, " + " a.state_code, " + " s.description as state_description, " + " a.postcode, " + " a.country, " + " a.lock_num, " + " a.created_by, " + " TO_CHAR(a.created_datetime, '" + SQL_DATETIME_FORMAT + "') as created_datetime, " + " a.last_updated_by, " + " TO_CHAR(a.last_updated_datetime, '" + SQL_DATETIME_FORMAT + "') as last_updated_datetime, " + " a.sync_address_id, " + " a.lat," + " a.lon, " + " a.validation_confidence, " + " a.validation_quality, " + " a.validation_status " + "FROM ADDRESSES a, FLAT_UNIT_TYPES fut, FLOOR_LEVELS fl, STREET_TYPES st, " + " STREET_SUFFIXES ss, POSTAL_DELIVERY_TYPES pdt, STATES s " + "WHERE a.flat_unit_type_code = fut.flat_unit_type_code(+) " + "AND a.floor_level_code = fl.floor_level_code(+) " + "AND a.street_type_code = st.street_type_code(+) " + "AND a.street_suffix_code = ss.street_suffix_code(+) " + "AND a.postal_delivery_type_code = pdt.postal_delivery_type_code(+) " + "AND a.state_code = s.state_code(+) "; public TransferObject GetAddress(string addressID) { //Build the SELECT Statement StringBuilder selectStatement = new StringBuilder(BASE_SQL_ADDRESSES); //Add WHERE condition selectStatement.Append(" AND a.address_id = :addressID"); ArrayList parameters = new ArrayList{DBUtils.CreateOracleParameter("addressID", OracleDbType.Decimal, addressID)}; // Execute the SELECT statement Query query = new Query(); DataSet results = query.Execute(selectStatement.ToString(), parameters); // Check if 0 or more than one rows returned if (results.Tables[0].Rows.Count == 0) { throw new NoDataFoundException(); } if (results.Tables[0].Rows.Count > 1) { throw new TooManyRowsException(); } // Return a TransferObject containing the values return new TransferObject(results); } public void Insert(TransferObject insertValues, Transaction transaction) { // Store Values string addressID = insertValues.GetString("ADDRESS_ID"); string syncAddressID = insertValues.GetString("SYNC_ADDRESS_ID"); string eventID = insertValues.GetString("EVENT_ID"); string createdBy = insertValues.GetString("CREATED_BY"); // postal delivery string postalDeliveryTypeCode = insertValues.GetString("POSTAL_DELIVERY_TYPE_CODE"); string postalDeliveryNum = insertValues.GetString("POSTAL_DELIVERY_NUM"); // unit/building string flatUnitTypeCode = insertValues.GetString("FLAT_UNIT_TYPE_CODE"); string flatUnitNum = insertValues.GetString("FLAT_UNIT_NUM"); string floorLevelCode = insertValues.GetString("FLOOR_LEVEL_CODE"); string floorLevelNum = insertValues.GetString("FLOOR_LEVEL_NUM"); string buildingName = insertValues.GetString("BUILDING_NAME"); // street string lotNumber = insertValues.GetString("LOT_NUMBER"); string streetNumber = insertValues.GetString("STREET_NUMBER"); string streetName = insertValues.GetString("STREET_NAME"); string streetTypeCode = insertValues.GetString("STREET_TYPE_CODE"); string streetSuffixCode = insertValues.GetString("STREET_SUFFIX_CODE"); // locality/state/postcode/country string locality = insertValues.GetString("LOCALITY"); string stateCode = insertValues.GetString("STATE_CODE"); string postcode = insertValues.GetString("POSTCODE"); string country = insertValues.GetString("COUNTRY"); // esms address string esmsAddress = insertValues.GetString("ESMS_ADDRESS"); //address/GPS string lat = insertValues.GetString("LAT"); string lon = insertValues.GetString("LON"); string zoom = insertValues.GetString("ZOOM"); //string validateDate = insertValues.GetString("VALIDATED_DATE"); string validatedBy = insertValues.GetString("VALIDATED_BY"); string confidence = insertValues.GetString("VALIDATION_CONFIDENCE"); string status = insertValues.GetString("VALIDATION_STATUS"); string quality = insertValues.GetString("VALIDATION_QUALITY"); // the insert statement StringBuilder insertStatement = new StringBuilder("INSERT INTO ADDRESSES ("); StringBuilder valuesStatement = new StringBuilder("VALUES ("); ArrayList parameters = new ArrayList(); // build the insert statement insertStatement.Append("ADDRESS_ID, EVENT_ID, CREATED_BY, CREATED_DATETIME, LOCK_NUM "); valuesStatement.Append(":addressID, :eventID, :createdBy, SYSDATE, 1 "); parameters.Add(DBUtils.CreateOracleParameter("addressID", OracleDbType.Decimal, addressID)); parameters.Add(DBUtils.CreateOracleParameter("eventID", OracleDbType.Decimal, eventID)); parameters.Add(DBUtils.CreateOracleParameter("createdBy", OracleDbType.Varchar2, createdBy)); // build the insert statement if (!StringUtils.IsNull(syncAddressID)) { insertStatement.Append(", SYNC_ADDRESS_ID"); valuesStatement.Append(", :syncAddressID"); parameters.Add(DBUtils.CreateOracleParameter("syncAddressID", OracleDbType.Decimal, syncAddressID)); } if (!StringUtils.IsNull(postalDeliveryTypeCode)) { insertStatement.Append(", POSTAL_DELIVERY_TYPE_CODE"); valuesStatement.Append(", :postalDeliveryTypeCode "); parameters.Add(DBUtils.CreateOracleParameter("postalDeliveryTypeCode", OracleDbType.Varchar2, postalDeliveryTypeCode)); } if (!StringUtils.IsNull(postalDeliveryNum)) { insertStatement.Append(", POSTAL_DELIVERY_NUM"); valuesStatement.Append(", :postalDeliveryNum "); parameters.Add(DBUtils.CreateOracleParameter("postalDeliveryNum", OracleDbType.Varchar2, postalDeliveryNum)); } if (!StringUtils.IsNull(flatUnitTypeCode)) { insertStatement.Append(", FLAT_UNIT_TYPE_CODE"); valuesStatement.Append(", :flatUnitTypeCode "); parameters.Add(DBUtils.CreateOracleParameter("flatUnitTypeCode", OracleDbType.Varchar2, flatUnitTypeCode)); } if (!StringUtils.IsNull(lat)) { insertStatement.Append(", LAT"); valuesStatement.Append(", :lat "); parameters.Add(DBUtils.CreateOracleParameter("lat", OracleDbType.Decimal, lat)); } if (!StringUtils.IsNull(lon)) { insertStatement.Append(", LON"); valuesStatement.Append(", :lon "); parameters.Add(DBUtils.CreateOracleParameter("lon", OracleDbType.Decimal, lon)); } if (!StringUtils.IsNull(zoom)) { insertStatement.Append(", ZOOM"); valuesStatement.Append(", :zoom "); parameters.Add(DBUtils.CreateOracleParameter("zoom", OracleDbType.Decimal, zoom)); } if (!StringUtils.IsNull(flatUnitNum)) { insertStatement.Append(", FLAT_UNIT_NUM"); valuesStatement.Append(", :flatUnitNum "); parameters.Add(DBUtils.CreateOracleParameter("flatUnitNum", OracleDbType.Varchar2, flatUnitNum)); } if (!StringUtils.IsNull(floorLevelCode)) { insertStatement.Append(", FLOOR_LEVEL_CODE"); valuesStatement.Append(", :floorLevelCode "); parameters.Add(DBUtils.CreateOracleParameter("floorLevelCode", OracleDbType.Varchar2, floorLevelCode)); } if (!StringUtils.IsNull(floorLevelNum)) { insertStatement.Append(", FLOOR_LEVEL_NUM"); valuesStatement.Append(", :floorLevelNum "); parameters.Add(DBUtils.CreateOracleParameter("floorLevelNum", OracleDbType.Varchar2, floorLevelNum)); } if (!StringUtils.IsNull(buildingName)) { insertStatement.Append(", BUILDING_NAME"); valuesStatement.Append(", :buildingName "); parameters.Add(DBUtils.CreateOracleParameter("buildingName", OracleDbType.Varchar2, buildingName)); } if (!StringUtils.IsNull(lotNumber)) { insertStatement.Append(", LOT_NUMBER"); valuesStatement.Append(", :lotNumber "); parameters.Add(DBUtils.CreateOracleParameter("lotNumber", OracleDbType.Varchar2, lotNumber)); } if (!StringUtils.IsNull(streetNumber)) { insertStatement.Append(", STREET_NUMBER"); valuesStatement.Append(", :streetNumber "); parameters.Add(DBUtils.CreateOracleParameter("streetNumber", OracleDbType.Varchar2, streetNumber)); } if (!StringUtils.IsNull(streetName)) { insertStatement.Append(", STREET_NAME"); valuesStatement.Append(", :streetName "); parameters.Add(DBUtils.CreateOracleParameter("streetName", OracleDbType.Varchar2, streetName)); } if (!StringUtils.IsNull(streetTypeCode)) { insertStatement.Append(", STREET_TYPE_CODE"); valuesStatement.Append(", :streetTypeCode "); parameters.Add(DBUtils.CreateOracleParameter("streetTypeCode", OracleDbType.Varchar2, streetTypeCode)); } if (!StringUtils.IsNull(streetSuffixCode)) { insertStatement.Append(", STREET_SUFFIX_CODE"); valuesStatement.Append(", :streetSuffixCode "); parameters.Add(DBUtils.CreateOracleParameter("streetSuffixCode", OracleDbType.Varchar2, streetSuffixCode)); } if (!StringUtils.IsNull(locality)) { insertStatement.Append(", LOCALITY"); valuesStatement.Append(", :locality"); parameters.Add(DBUtils.CreateOracleParameter("locality", OracleDbType.Varchar2, locality)); } if (!StringUtils.IsNull(stateCode)) { insertStatement.Append(", STATE_CODE"); valuesStatement.Append(", :stateCode"); parameters.Add(DBUtils.CreateOracleParameter("stateCode", OracleDbType.Varchar2, stateCode)); } if (!StringUtils.IsNull(postcode)) { insertStatement.Append(", POSTCODE"); valuesStatement.Append(", :postcode "); parameters.Add(DBUtils.CreateOracleParameter("postcode", OracleDbType.Varchar2, postcode)); } if (!StringUtils.IsNull(country)) { insertStatement.Append(", COUNTRY"); valuesStatement.Append(", :country "); parameters.Add(DBUtils.CreateOracleParameter("country", OracleDbType.Varchar2, country)); } if (!StringUtils.IsNull(esmsAddress)) { insertStatement.Append(", ESMS_ADDRESS"); valuesStatement.Append(", :esmsAddress "); parameters.Add(DBUtils.CreateOracleParameter("esmsAddress", OracleDbType.Varchar2, esmsAddress)); } if (!StringUtils.IsNull(validatedBy)) { insertStatement.Append(", VALIDATED_DATE"); valuesStatement.Append(", SYSDATE "); insertStatement.Append(", VALIDATED_BY"); valuesStatement.Append(", :validatedBy "); parameters.Add(DBUtils.CreateOracleParameter("validatedBy", OracleDbType.Varchar2, validatedBy)); } if (!StringUtils.IsNull(confidence)) { insertStatement.Append(", VALIDATION_CONFIDENCE"); valuesStatement.Append(", :confidence "); parameters.Add(DBUtils.CreateOracleParameter("confidence", OracleDbType.Decimal, confidence)); } if (!StringUtils.IsNull(status)) { insertStatement.Append(", VALIDATION_STATUS"); valuesStatement.Append(", :status "); parameters.Add(DBUtils.CreateOracleParameter("status", OracleDbType.Varchar2, status)); } if (!StringUtils.IsNull(quality)) { insertStatement.Append(", VALIDATION_QUALITY"); valuesStatement.Append(", :quality "); parameters.Add(DBUtils.CreateOracleParameter("quality", OracleDbType.Decimal, quality)); } // finish off the statement insertStatement.Append(") "); valuesStatement.Append(")"); // build the insert statement string sql = insertStatement + valuesStatement.ToString(); // Execute the INSERT Statement Dml dmlDAO = new Dml(); int rowsAffected = dmlDAO.Execute(sql, transaction, parameters); if (rowsAffected == 0) { throw new NoRowsAffectedException(); } } << many more methods go here >> } This system was developed by me and a small team back in 2005 after a 1 week .NET course. Before than my experience was in client-server applications. Over the past 5 years I've come to recognise the benefits of automated unit testing, automated integration testing and automated acceptance testing (using Selenium or equivalent) but the current code-base seems impossible to introduce these concepts. We are now starting to work on a major enhancement project with tight time-frames. The team consists of 5 .NET developers - 2 developers with a few years of .NET experience and 3 others with little or no .NET experience. None of the team (including myself) has experience in using .NET unit testing or mocking frameworks. What strategy would you use to make this code cleaner, more object-oriented, testable and maintainable?

    Read the article

  • Create a grid in WPF as Template programmatically

    - by wickie79
    I want to create a basic user control with a style programmatically. In this style i want to add a Grid (no problem), but i dont can add column definitions to this grid. My example code is ControlTemplate templ = new ControlTemplate(); FrameworkElementFactory mainPanel = new FrameworkElementFactory(typeof(DockPanel)); mainPanel.SetValue(DockPanel.LastChildFillProperty, true); FrameworkElementFactory headerPanel = new FrameworkElementFactory(typeof(StackPanel)); headerPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal); headerPanel.SetValue(DockPanel.DockProperty, Dock.Top); mainPanel.AppendChild(headerPanel); FrameworkElementFactory headerImg = new FrameworkElementFactory(typeof(Image)); headerImg.SetValue(Image.MarginProperty, new Thickness(5)); headerImg.SetValue(Image.HeightProperty, 32d); headerImg.SetBinding(Image.SourceProperty, new Binding("ElementImage") { RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent) }); headerPanel.AppendChild(headerImg); FrameworkElementFactory headerTitle = new FrameworkElementFactory(typeof(TextBlock)); headerTitle.SetValue(TextBlock.FontSizeProperty, 16d); headerTitle.SetValue(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center); headerTitle.SetBinding(TextBlock.TextProperty, new Binding("Title") { RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent) }); headerPanel.AppendChild(headerTitle); FrameworkElementFactory mainGrid = new FrameworkElementFactory(typeof(Grid)); FrameworkElementFactory c1 = new FrameworkElementFactory(typeof(ColumnDefinition)); c1.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Star)); FrameworkElementFactory c2 = new FrameworkElementFactory(typeof(ColumnDefinition)); c2.SetValue(ColumnDefinition.WidthProperty, new GridLength(1, GridUnitType.Auto)); FrameworkElementFactory c3 = new FrameworkElementFactory(typeof(ColumnDefinition)); c3.SetValue(ColumnDefinition.WidthProperty, new GridLength(3, GridUnitType.Star)); FrameworkElementFactory colDefinitions = new FrameworkElementFactory(typeof(ColumnDefinitionCollection)); colDefinitions.AppendChild(c1); colDefinitions.AppendChild(c2); colDefinitions.AppendChild(c3); mainGrid.AppendChild(colDefinitions); mainPanel.AppendChild(mainGrid); FrameworkElementFactory content = new FrameworkElementFactory(typeof(ContentPresenter)); content.SetBinding(ContentPresenter.ContentProperty, new Binding() { RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent), Path = new PropertyPath("Content") }); mainGrid.AppendChild(content); templ.VisualTree = mainPanel; Style mainStyle = new Style(); mainStyle.Setters.Add(new Setter(UserControl.TemplateProperty, templ)); this.Style = mainStyle; But the creation of FrameworkElementFactory with type ColumnDefinitionCollection will throw an exception "'ColumnDefinitionCollection' type must derive from FrameworkElement, FrameworkContentElement, or Visual3D." Who can help me?

    Read the article

  • HLSL/XNA Ambient light texture mixed up with multi pass lighting

    - by Manu-EPITA
    I've been having some troubles lately with lighting. I have found a source on google which is working pretty good on the example. However, when I try to implement it to my current project, I am getting some very weird bugs. The main one is that my textures are "mixed up" when I only activate the ambient light, which means that a model gets the texture of another one . I am using the same effect for every meshes of my models. I guess this could be the problem, but I don't really know how to "reset" an effect for a new model. Is it possible? Here is my shader: float4x4 WVP; float4x4 WVP; float3x3 World; float3 Ke; float3 Ka; float3 Kd; float3 Ks; float specularPower; float3 globalAmbient; float3 lightColor; float3 eyePosition; float3 lightDirection; float3 lightPosition; float spotPower; texture2D Texture; sampler2D texSampler = sampler_state { Texture = <Texture>; MinFilter = anisotropic; MagFilter = anisotropic; MipFilter = linear; MaxAnisotropy = 16; }; struct VertexShaderInput { float4 Position : POSITION0; float2 Texture : TEXCOORD0; float3 Normal : NORMAL0; }; struct VertexShaderOutput { float4 Position : POSITION0; float2 Texture : TEXCOORD0; float3 PositionO: TEXCOORD1; float3 Normal : NORMAL0; }; VertexShaderOutput VertexShaderFunction(VertexShaderInput input) { VertexShaderOutput output; output.Position = mul(input.Position, WVP); output.Normal = input.Normal; output.PositionO = input.Position.xyz; output.Texture = input.Texture; return output; } float4 PSAmbient(VertexShaderOutput input) : COLOR0 { return float4(Ka*globalAmbient + Ke,1) * tex2D(texSampler,input.Texture); } float4 PSDirectionalLight(VertexShaderOutput input) : COLOR0 { //Difuze float3 L = normalize(-lightDirection); float diffuseLight = max(dot(input.Normal,L), 0); float3 diffuse = Kd*lightColor*diffuseLight; //Specular float3 V = normalize(eyePosition - input.PositionO); float3 H = normalize(L + V); float specularLight = pow(max(dot(input.Normal,H),0),specularPower); if(diffuseLight<=0) specularLight=0; float3 specular = Ks * lightColor * specularLight; //sum all light components float3 light = diffuse + specular; return float4(light,1) * tex2D(texSampler,input.Texture); } technique MultiPassLight { pass Ambient { VertexShader = compile vs_3_0 VertexShaderFunction(); PixelShader = compile ps_3_0 PSAmbient(); } pass Directional { PixelShader = compile ps_3_0 PSDirectionalLight(); } } And here is how I actually apply my effects: public void ApplyLights(ModelMesh mesh, Matrix world, Texture2D modelTexture, Camera camera, Effect effect, GraphicsDevice graphicsDevice) { graphicsDevice.BlendState = BlendState.Opaque; effect.CurrentTechnique.Passes["Ambient"].Apply(); foreach (ModelMeshPart part in mesh.MeshParts) { graphicsDevice.SetVertexBuffer(part.VertexBuffer); graphicsDevice.Indices = part.IndexBuffer; // Texturing graphicsDevice.BlendState = BlendState.AlphaBlend; if (modelTexture != null) { effect.Parameters["Texture"].SetValue( modelTexture ); } graphicsDevice.DrawIndexedPrimitives( PrimitiveType.TriangleList, part.VertexOffset, 0, part.NumVertices, part.StartIndex, part.PrimitiveCount ); // Applying our shader to all the mesh parts effect.Parameters["WVP"].SetValue( world * camera.View * camera.Projection ); effect.Parameters["World"].SetValue(world); effect.Parameters["eyePosition"].SetValue( camera.Position ); graphicsDevice.BlendState = BlendState.Additive; // Drawing lights foreach (DirectionalLight light in DirectionalLights) { effect.Parameters["lightColor"].SetValue(light.Color.ToVector3()); effect.Parameters["lightDirection"].SetValue(light.Direction); // Applying changes and drawing them effect.CurrentTechnique.Passes["Directional"].Apply(); graphicsDevice.DrawIndexedPrimitives( PrimitiveType.TriangleList, part.VertexOffset, 0, part.NumVertices, part.StartIndex, part.PrimitiveCount ); } } I am also applying this when loading the effect: effect.Parameters["lightColor"].SetValue(Color.White.ToVector3()); effect.Parameters["globalAmbient"].SetValue(Color.White.ToVector3()); effect.Parameters["Ke"].SetValue(0.0f); effect.Parameters["Ka"].SetValue(0.01f); effect.Parameters["Kd"].SetValue(1.0f); effect.Parameters["Ks"].SetValue(0.3f); effect.Parameters["specularPower"].SetValue(100); Thank you very much UPDATE: I tried to load an effect for each model when drawing, but it doesn't seem to have changed anything. I suppose it is because XNA detects that the effect has already been loaded before and doesn't want to load a new one. Any idea why?

    Read the article

  • Render 2 images that uses different shaders

    - by Code Vader
    Based on the giawa/nehe tutorials, how can I render 2 images with different shaders. I'm pretty new to OpenGl and shaders so I'm not completely sure whats happening in my code, but I think the shaders that is called last overwrites the first one. private static void OnRenderFrame() { // calculate how much time has elapsed since the last frame watch.Stop(); float deltaTime = (float)watch.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency; watch.Restart(); // use the deltaTime to adjust the angle of the cube angle += deltaTime; // set up the OpenGL viewport and clear both the color and depth bits Gl.Viewport(0, 0, width, height); Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); // use our shader program and bind the crate texture Gl.UseProgram(program); //<<<<<<<<<<<< TOP PYRAMID // set the transformation of the top_pyramid program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(top_pyramid, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(top_pyramidNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(top_pyramidUV, program, "vertexUV"); Gl.BindBuffer(top_pyramidTrianlges); // draw the textured top_pyramid Gl.DrawElements(BeginMode.Triangles, top_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<< CUBE // set the transformation of the cube program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(cube, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(cubeNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(cubeUV, program, "vertexUV"); Gl.BindBuffer(cubeQuads); // draw the textured cube Gl.DrawElements(BeginMode.Quads, cubeQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<<<< BOTTOM PYRAMID // set the transformation of the bottom_pyramid program["model_matrix"].SetValue(Matrix4.CreateRotationY(angle * rotate_cube)); program["enable_lighting"].SetValue(lighting); // bind the vertex positions, UV coordinates and element array Gl.BindBufferToShaderAttribute(bottom_pyramid, program, "vertexPosition"); Gl.BindBufferToShaderAttribute(bottom_pyramidNormals, program, "vertexNormal"); Gl.BindBufferToShaderAttribute(bottom_pyramidUV, program, "vertexUV"); Gl.BindBuffer(bottom_pyramidTrianlges); // draw the textured bottom_pyramid Gl.DrawElements(BeginMode.Triangles, bottom_pyramidTrianlges.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); //<<<<<<<<<<<<< STAR Gl.Disable(EnableCap.DepthTest); Gl.Enable(EnableCap.Blend); Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One); Gl.BindTexture(starTexture); //calculate the camera position using some fancy polar co-ordinates Vector3 position = 20 * new Vector3(Math.Cos(phi) * Math.Sin(theta), Math.Cos(theta), Math.Sin(phi) * Math.Sin(theta)); Vector3 upVector = ((theta % (Math.PI * 2)) > Math.PI) ? Vector3.Up : Vector3.Down; program_2["view_matrix"].SetValue(Matrix4.LookAt(position, Vector3.Zero, upVector)); // make sure the shader program and texture are being used Gl.UseProgram(program_2); // loop through the stars, drawing each one for (int i = 0; i < stars.Count; i++) { // set the position and color of this star program_2["model_matrix"].SetValue(Matrix4.CreateTranslation(new Vector3(stars[i].dist, 0, 0)) * Matrix4.CreateRotationZ(stars[i].angle)); program_2["color"].SetValue(stars[i].color); Gl.BindBufferToShaderAttribute(star, program_2, "vertexPosition"); Gl.BindBufferToShaderAttribute(starUV, program_2, "vertexUV"); Gl.BindBuffer(starQuads); Gl.DrawElements(BeginMode.Quads, starQuads.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); // update the position of the star stars[i].angle += (float)i / stars.Count * deltaTime * 2 * rotate_stars; stars[i].dist -= 0.2f * deltaTime * rotate_stars; // if we've reached the center then move this star outwards and give it a new color if (stars[i].dist < 0f) { stars[i].dist += 5f; stars[i].color = new Vector3(generator.NextDouble(), generator.NextDouble(), generator.NextDouble()); } } Glut.glutSwapBuffers(); } The same goes for the textures, whichever one I mention last gets applied to both object?

    Read the article

  • Override java methods without affecting parent behaviour

    - by Timmmm
    suppose I have this classes (sorry it's kind of hard to think of a simple example here; I don't want any "why would you want to do that?" answers!): class Squarer { public void setValue(int v) { mV = v; } public int getValue() { return mV; } private int mV; public void square() { setValue(getValue() * getValue()); } } class OnlyOddInputsSquarer extends Squarer { @Override public void setValue(int v) { if (v % 2 == 0) { print("Sorry, this class only lets you square odd numbers!") return; } super.setValue(v); } } auto s = new OnlyOddInputsSquarer(); s.setValue(3); s.square(); This won't work. When Squarer.square() calls setValue(), it will go to OnlyOddInputsSquarer.setValue() which will reject all its values (since all squares are even). Is there any way I can override setValue() so that all the functions in Squarer still use the method defined there? PS: Sorry, java doesn't have an auto keyword you haven't heard about! Wishful thinking on my part.

    Read the article

  • Asp.net Google Charts SSL handler for GeoMap

    - by Ian
    Hi All, I am trying to view Google charts in a site using SSL. Google Charts do not support SSL so if we use the standard charts, we get warning messages. My plan is to create a ASHX handler that is co9ntained in the secure site that will retrieve the content from Google and serve this to the page the user is viewing. Using VS 2008 SP1 and the included web server, my idea works perfectly for both Firefox and IE 8 & 9(Preview) and I am able to see my geomap displayed on my page as it should be. But my problem is when I publish to IIS7 the page using my handler to generate the geomap works in Firefox but not IE(every version). There are no errors anywhere or in any log files, but when i right click in IE in the area where the map should be displayed, I see the message in the context menu saying "movie not loaded" Below is the code from my handler and the aspx page. I have disabled compression in my web.config. Even in IE I am hitting all my break points and when I use the IE9 Developer tools, the web page is correctly generated with all the correct code, url's and references. If you have any better ways to accomplish this or how i can fix my problem, I will appreciate it. Thanks Ian Handler(ASHX) public void ProcessRequest(HttpContext context) { String url = "http://charts.apis.google.com/jsapi"; string query = context.Request.QueryString.ToString(); if (!string.IsNullOrEmpty(query)) { url = query; } HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(HttpUtility.UrlDecode(url))); request.UserAgent = context.Request.UserAgent; WebResponse response = request.GetResponse(); string PageContent = string.Empty; StreamReader Reader; Stream webStream = response.GetResponseStream(); string contentType = response.ContentType; context.Response.BufferOutput = true; context.Response.ContentType = contentType; context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.Cache.SetNoServerCaching(); context.Response.Cache.SetMaxAge(System.TimeSpan.Zero); string newUrl = IanLearning.Properties.Settings.Default.HandlerURL; //"https://localhost:444/googlesecurecharts.ashx?"; if (response.ContentType.Contains("javascript")) { Reader = new StreamReader(webStream); PageContent = Reader.ReadToEnd(); PageContent = PageContent.Replace("http://", newUrl + "http://"); PageContent = PageContent.Replace("charts.apis.google.com", newUrl + "charts.apis.google.com"); PageContent = PageContent.Replace(newUrl + "http://maps.google.com/maps/api/", "http://maps.google.com/maps/api/"); context.Response.Write(PageContent); } else { { byte[] bytes = ReadFully(webStream); context.Response.BinaryWrite(bytes); } } context.Response.Flush(); response.Close(); webStream.Close(); context.Response.End(); context.ApplicationInstance.CompleteRequest(); } ASPX Page <%@ Page Title="" Language="C#" MasterPageFile="~/Site2.Master" AutoEventWireup="true" CodeBehind="googlechart.aspx.cs" Inherits="IanLearning.googlechart" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> <script type='text/javascript' src='~/googlesecurecharts.ashx?'></script> <script type='text/javascript'> google.load('visualization', '1', { 'packages': ['geomap'] }); google.setOnLoadCallback(drawMap); var geomap; function drawMap() { var data = new google.visualization.DataTable(); data.addRows(6); data.addColumn('string', 'City'); data.addColumn('number', 'Sales'); data.setValue(0, 0, 'ZA'); data.setValue(0, 1, 200); data.setValue(1, 0, 'US'); data.setValue(1, 1, 300); data.setValue(2, 0, 'BR'); data.setValue(2, 1, 400); data.setValue(3, 0, 'CN'); data.setValue(3, 1, 500); data.setValue(4, 0, 'IN'); data.setValue(4, 1, 600); data.setValue(5, 0, 'ZW'); data.setValue(5, 1, 700); var options = {}; options['region'] = 'world'; options['dataMode'] = 'regions'; options['showZoomOut'] = false; var container = document.getElementById('map_canvas'); geomap = new google.visualization.GeoMap(container); google.visualization.events.addListener( geomap, 'regionClick', function(e) { drillDown(e['region']); }); geomap.draw(data, options); }; function drillDown(regionData) { alert(regionData); } </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <div id='map_canvas'> </div> </asp:Content>

    Read the article

  • If array is thread safe, what the issue with this function?

    - by Ajay Sharma
    I am totally lost with the things that is happening with my code.It make me to think & get clear with Array's thread Safe concept. Is NSMutableArray OR NSMutableDictionary Thread Safe ? While my code is under execution, the values for the MainArray get's changes although, that has been added to Array. Please try to execute this code, onyour system its very much easy.I am not able to get out of this Trap. It is the function where it is returning Array. What I am Looking to do is : -(Array) (Main Array) --(Dictionary) with Key Value (Multiple Dictionary in Main Array) ----- Above dictionary has 9 Arrays in it. This is the structure I am developing for Array.But even before #define TILE_ROWS 3 #define TILE_COLUMNS 3 #define TILE_COUNT (TILE_ROWS * TILE_COLUMNS) -(NSArray *)FillDataInArray:(int)counter { NSMutableArray *temprecord = [[NSMutableArray alloc] init]; for(int i = 0; i <counter;i++) { if([temprecord count]<=TILE_COUNT) { NSMutableDictionary *d1 = [[NSMutableDictionary alloc]init]; [d1 setValue:[NSString stringWithFormat:@"%d/2011",i+1] forKey:@"serial_data"]; [d1 setValue:@"Friday 13 Sep 12:00 AM" forKey:@"date_data"]; [d1 setValue:@"Description Details " forKey:@"details_data"]; [d1 setValue:@"Subject Line" forKey:@"subject_data"]; [temprecord addObject:d1]; d1= nil; [d1 release]; if([temprecord count]==TILE_COUNT) { NSMutableDictionary *holderKey = [[NSMutableDictionary alloc]initWithObjectsAndKeys:temprecord,[NSString stringWithFormat:@"%d",[casesListArray count]+1],nil]; [self.casesListArray addObject:holderKey]; [holderKey release]; holderKey =nil; [temprecord removeAllObjects]; } } else { [temprecord removeAllObjects]; NSMutableDictionary *d1 = [[NSMutableDictionary alloc]init]; [d1 setValue:[NSString stringWithFormat:@"%d/2011",i+1] forKey:@"serial_data"]; [d1 setValue:@"Friday 13 Sep 12:00 AM" forKey:@"date_data"]; [d1 setValue:@"Description Details " forKey:@"details_data"]; [d1 setValue:@"Subject Line" forKey:@"subject_data"]; [temprecord addObject:d1]; d1= nil; [d1 release]; } } return temprecord; [temprecord release]; } What is the problem with this Code ? Every time there are 9 records in Array, it just replaces the whole Array value instead of just for specific key Value.

    Read the article

  • iPhone - openAL stops playing if I record with AVAudioRecorder

    - by Oscar Peli
    Hi there, this is an iPhone-related question: I use openAL to play some sound (I have to manage gain, pitch, etc.). I want to record what I'm playing and I use AVAudioRecorder but when I "prepareToRecord" openAL stops to play audio. What's the problem? Here is the record IBAction I use: - (IBAction) record: (id) sender { NSError *error; NSMutableDictionary *settings = [NSMutableDictionary dictionary]; [settings setValue: [NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey]; [settings setValue: [NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey]; [settings setValue: [NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey]; [settings setValue: [NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey]; [settings setValue: [NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey]; NSURL *url = [NSURL fileURLWithPath:FILEPATH]; self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error]; self.recorder.delegate = self; self.recorder.meteringEnabled = YES; [self.recorder prepareToRecord]; [self.recorder record]; } Thanks

    Read the article

  • Associate File Extension with Application

    - by fneep
    I've written a program that edits a specific filetype , and I want to give the user the option to set my application as the default editor for this filetype (since I don't want an installer) on startup. I've tried to write a re-useable method that associates a file for me (preferably on any OS, although I'm running Vista) by adding a key to HKEY_CLASSES_ROOT, and am using it with my application, but it doesn't seem to work. public static void SetAssociation(string Extension, string KeyName, string OpenWith, string FileDescription) { RegistryKey BaseKey; RegistryKey OpenMethod; RegistryKey Shell; RegistryKey CurrentUser; BaseKey = Registry.ClassesRoot.CreateSubKey(Extension); BaseKey.SetValue("", KeyName); OpenMethod = Registry.ClassesRoot.CreateSubKey(KeyName); OpenMethod.SetValue("", FileDescription); OpenMethod.CreateSubKey("DefaultIcon").SetValue("", "\"" + OpenWith + "\",0"); Shell = OpenMethod.CreateSubKey("Shell"); Shell.CreateSubKey("edit").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\""); Shell.CreateSubKey("open").CreateSubKey("command").SetValue("", "\"" + OpenWith + "\"" + " \"%1\""); BaseKey.Close(); OpenMethod.Close(); Shell.Close(); CurrentUser = Registry.CurrentUser.CreateSubKey(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ucs"); CurrentUser = CurrentUser.OpenSubKey("UserChoice", RegistryKeyPermissionCheck.ReadWriteSubTree, System.Security.AccessControl.RegistryRights.FullControl); CurrentUser.SetValue("Progid", KeyName, RegistryValueKind.String); CurrentUser.Close(); }

    Read the article

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