Search Results

Search found 160 results on 7 pages for 'maxvalue'.

Page 4/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • How do I implement SkyBox in xna 4.0 Reach Profile (for Windows Phone 7)?

    - by Biny
    I'm trying to Implement SkyBox in my phone game. Most of the samples in the web are for HiDef profile, and they are using custom effects (that not supported on Windows Phone). I've tried to follow this guide. But for some reason my SkyBox is not rendered. This is my SkyBox class: using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Rocuna.Core; using Rocuna.GameEngine.Graphics; using Rocuna.GameEngine.Graphics.Components; namespace Rocuna.GameEngine.Extension.WP7.Graphics { /// <summary> /// Sky box element for phone games. /// </summary> public class SkyBox : SkyBoxBase { /// <summary> /// Initializes a new instance of the <see cref="SkyBoxBase"/> class. /// </summary> /// <param name="game">The Game that the game component should be attached to.</param> public SkyBox(TextureCube cube, Game game) : base(game) { Cube = cube; CubeFaces = new Texture2D[6]; PositionOffset = new Vector3(20, 20, 20); CreateGraphic(512); StripTexturesFromCube(); InitializeData(Game.GraphicsDevice); } #region Properties /// <summary> /// Gets or sets the position offset. /// </summary> /// <value> /// The position offset. /// </value> public Vector3 PositionOffset { get; set; } /// <summary> /// Gets or sets the position. /// </summary> /// <value> /// The position. /// </value> public Vector3 Position { get; set; } /// <summary> /// Gets or sets the cube. /// </summary> /// <value> /// The cube. /// </value> public TextureCube Cube { get; set; } /// <summary> /// Gets or sets the pixel array. /// </summary> /// <value> /// The pixel array. /// </value> public Color[] PixelArray { get; set; } /// <summary> /// Gets or sets the cube faces. /// </summary> /// <value> /// The cube faces. /// </value> public Texture2D[] CubeFaces { get; set; } /// <summary> /// Gets or sets the vertex buffer. /// </summary> /// <value> /// The vertex buffer. /// </value> public VertexBuffer VertexBuffer { get; set; } /// <summary> /// Gets or sets the index buffer. /// </summary> /// <value> /// The index buffer. /// </value> public IndexBuffer IndexBuffer { get; set; } /// <summary> /// Gets or sets the effect. /// </summary> /// <value> /// The effect. /// </value> public BasicEffect Effect { get; set; } #endregion protected override void LoadContent() { } public override void Update(GameTime gameTime) { var camera = Game.GetService<GraphicManager>().CurrentCamera; this.Position = camera.Position + PositionOffset; base.Update(gameTime); } public override void Draw(GameTime gameTime) { DrawOrder = int.MaxValue; var graphics = Effect.GraphicsDevice; graphics.DepthStencilState = new DepthStencilState() { DepthBufferEnable = false }; graphics.RasterizerState = new RasterizerState() { CullMode = CullMode.None }; graphics.BlendState = new BlendState(); graphics.SamplerStates[0] = SamplerState.AnisotropicClamp; graphics.SetVertexBuffer(VertexBuffer); graphics.Indices = IndexBuffer; Effect.Texture = CubeFaces[0]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 0, 2); Effect.Texture = CubeFaces[1]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 6, 2); Effect.Texture = CubeFaces[2]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 12, 2); Effect.Texture = CubeFaces[3]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 18, 2); Effect.Texture = CubeFaces[4]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 24, 2); Effect.Texture = CubeFaces[5]; Effect.CurrentTechnique.Passes[0].Apply(); graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 30, 2); base.Draw(gameTime); } #region Fields private List<VertexPositionNormalTexture> _vertices = new List<VertexPositionNormalTexture>(); private List<ushort> _indices = new List<ushort>(); #endregion #region Private methods private void InitializeData(GraphicsDevice graphicsDevice) { VertexBuffer = new VertexBuffer(graphicsDevice, typeof(VertexPositionNormalTexture), _vertices.Count, BufferUsage.None); VertexBuffer.SetData<VertexPositionNormalTexture>(_vertices.ToArray()); // Create an index buffer, and copy our index data into it. IndexBuffer = new IndexBuffer(graphicsDevice, typeof(ushort), _indices.Count, BufferUsage.None); IndexBuffer.SetData<ushort>(_indices.ToArray()); // Create a BasicEffect, which will be used to render the primitive. Effect = new BasicEffect(graphicsDevice); Effect.TextureEnabled = true; Effect.EnableDefaultLighting(); } private void CreateGraphic(float size) { Vector3[] normals = { Vector3.Right, Vector3.Left, Vector3.Up, Vector3.Down, Vector3.Backward, Vector3.Forward, }; Vector2[] textureCoordinates = { Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One, }; var index = 0; foreach (var normal in normals) { var side1 = new Vector3(normal.Z, normal.X, normal.Y); var side2 = Vector3.Cross(normal, side1); AddIndex(CurrentVertex + 0); AddIndex(CurrentVertex + 1); AddIndex(CurrentVertex + 2); AddIndex(CurrentVertex + 0); AddIndex(CurrentVertex + 2); AddIndex(CurrentVertex + 3); AddVertex((normal - side1 - side2) * size / 2, normal, textureCoordinates[index++]); AddVertex((normal - side1 + side2) * size / 2, normal, textureCoordinates[index++]); AddVertex((normal + side1 + side2) * size / 2, normal, textureCoordinates[index++]); AddVertex((normal + side1 - side2) * size / 2, normal, textureCoordinates[index++]); } } protected void StripTexturesFromCube() { PixelArray = new Color[Cube.Size * Cube.Size]; for (int s = 0; s < CubeFaces.Length; s++) { CubeFaces[s] = new Texture2D(Game.GraphicsDevice, Cube.Size, Cube.Size, false, SurfaceFormat.Color); switch (s) { case 0: Cube.GetData<Color>(CubeMapFace.PositiveX, PixelArray); CubeFaces[s].SetData<Color>(PixelArray); break; case 1: Cube.GetData(CubeMapFace.NegativeX, PixelArray); CubeFaces[s].SetData(PixelArray); break; case 2: Cube.GetData(CubeMapFace.PositiveY, PixelArray); CubeFaces[s].SetData(PixelArray); break; case 3: Cube.GetData(CubeMapFace.NegativeY, PixelArray); CubeFaces[s].SetData(PixelArray); break; case 4: Cube.GetData(CubeMapFace.PositiveZ, PixelArray); CubeFaces[s].SetData(PixelArray); break; case 5: Cube.GetData(CubeMapFace.NegativeZ, PixelArray); CubeFaces[s].SetData(PixelArray); break; } } } protected void AddVertex(Vector3 position, Vector3 normal, Vector2 textureCoordinates) { _vertices.Add(new VertexPositionNormalTexture(position, normal, textureCoordinates)); } protected void AddIndex(int index) { if (index > ushort.MaxValue) throw new ArgumentOutOfRangeException("index"); _indices.Add((ushort)index); } protected int CurrentVertex { get { return _vertices.Count; } } #endregion } }

    Read the article

  • Interpolation between two 3D points?

    - by meds
    I'm working with some splines which define a path a character follows (you can see a gameplay video here to get a better understanding of what's going on: http://www.youtube.com/watch?v=BndobjOiZ6g). Basically the characters 'forward' look direction is set to the 'forward' direction of the spline and when players tilt their phone left and right the character is strafed along its 'right' coordinate. The issue with this is (rather obviously) in performance, interpolating over a spline to find the nearest position and tangent relative to the player is an incredibly costly operation. To get by this I cache a finite number of positions in what I call 'SplineDetails', the class is as follows: public class SplineDetails { public SplineDetails() { Forward = Vector3.forward; Position = Vector3.one * float.MaxValue; Alpha = -1; } public float Alpha; // [0,1] measured along length of spline where 0 is the initial point and 1 is the end point of the spline public Vector3 Position; // the point of the spline at this alpha public Vector3 Forward; // the forward tangent of the spline at this alpha } I populate this with say 30 coordinates and I can give a rough estimate of a coordinate and 'forward' based on a position past in. It's not as accurate but it's much faster. But now I'd like to make the system work better by estimating positions and 'forward' directions by interpolating between two of the cached points though I'm stuck trying to figure out some logic. My first problem is, how can I determine between which two points the object is? Given each point can be placed at different intervals along the spline it could mean that two points in front or behind the object can be closer to the object. The other problem is to figure out the proportion between the two paths it's between, i.e. if there is a point a at coordinate (0,0,0) and point b at coordinate (1,0,0) if the object is at position (0.5,0,0) then the result it should give is '0.5' (as it is equal distance away from point a and point b). That's a simple example, but what if the object is at coordinate (0.5,3,0) for example?

    Read the article

  • maxItemsInObjectGraph limit required to be changed for server and client

    - by Michael Freidgeim
    We have a wcf service, that expects to return a huge XML data. It worked ok in testing, but in production it failed with error  "Maximum number of items that can be serialized or deserialized in an object graph is '65536'. Change the object graph or increase the MaxItemsInObjectGraph quota."The MSDN article about   dataContractSerializer xml configuration  element  correctly  describes maxItemsInObjectGraph attribute default as 65536, but documentation for of the DataContractSerializer.MaxItemsInObjectGraph property and DataContractJsonSerializer.MaxItemsInObjectGraph Property are talking about Int32.MaxValue, which causes confusion, in particular because Google shows properties articles before configuration articles.When we changed the value in WCF service configuration, it didn't help, because the similar change must be ALSO done on client.There are similar posts:http://stackoverflow.com/questions/6298209/how-to-fix-maxitemsinobjectgraph-error/6298356#6298356You need to set the MaxItemsInObjectGraph on the dataContractSerializer using a behavior on both the client and service. See  for an example.http://devlicio.us/blogs/derik_whittaker/archive/2010/05/04/setting-maxitemsinobjectgraph-for-wcf-there-has-to-be-a-better-way.aspxhttp://stackoverflow.com/questions/2325321/maxitemsinobjectgraph-ignored/4455209#4455209 I had forgot to place this setting in my client app.config file.http://stackoverflow.com/questions/9191167/maximum-number-of-items-that-can-be-serialized-or-deserialized-in-an-object-graphttp://stackoverflow.com/questions/5867304/datacontractjsonserializer-and-maxitemsinobjectgraph?rq=1 -It seems that DataContractJsonSerializer.MaxItemsInObjectGraph has actual default 65536, because there is no configuration for JSON serializer, but  it complains about the limit.I believe that MS should clarify the properties documentation re default limit and make more specific error messages to distinguish server side and client side errors.Note, that as a workaround it's possible to use commonBehaviors section which can be defined only in machine.config:<commonBehaviors> <behaviors> <endpointBehaviors> <dataContractSerializer maxItemsInObjectGraph="..." /> </endpointBehaviors> </behaviors></commonBehaviors>v

    Read the article

  • Fastest way to read data from a lot of ASCII files

    - by Alsenes
    Hi guys, for a college exercise that I've already submitted I needed to read a .txt file wich contained a lot of names of images(1 in each line). Then I needed to open each image as an ascii file, and read their data(images where in ppm format), and do a series of things with them. The things is, I noticed my program was taking 70% of the time in the reading the data from the file part, instead of in the other calculations that I was doing (finding number of repetitions of each pixel with a hash table, finding diferents pixels beetween 2 images etc..), which I found quite odd to say the least. This is how the ppm format looks like: P3 //This value can be ignored when reading the file, because all image will be correctly formatted 4 4 255 //This value can be also ignored, will be always 255. 0 0 0 0 0 0 0 0 0 15 0 15 0 0 0 0 15 7 0 0 0 0 0 0 0 0 0 0 0 0 0 15 7 0 0 0 15 0 15 0 0 0 0 0 0 0 0 0 This is how I was reading the data from the files: ifstream fdatos; fdatos.open(argv[1]); //Open file with the name of all the images const int size = 128; char file[size]; //Where I'll get the image name Image *img; while (fdatos >> file) { //While there's still images anmes left, continue ifstream fimagen; fimagen.open(file); //Open image file img = new Image(fimagen); //Create new image object with it's data file ……… //Rest of the calculations whith that image ……… delete img; //Delete image object after done fimagen.close(); //Close image file after done } fdatos.close(); And inside the image object read the data like this: const int tallafirma = 100; char firma[tallafirma]; fich_in >> std::setw(100) >> firma; // Read the P3 part, can be ignored int maxvalue, numpixels; fich_in >> height >> width >> maxvalue; // Read the next three values numpixels = height*width; datos = new Pixel[numpixels]; int r,g,b; //Don't need to be ints, max value is 256, so an unsigned char would be ok. for (int i=0; i<numpixels; i++) { fich_in >> r >> g >> b; datos[i] = Pixel( r, g ,b); } //This last part is the slow one, //I thing I should be able to read all this data in one single read //to buffer or something which would be stored in an array of unsigned chars, //and then I'd only need to to do: //buffer[0] -> //Pixel 1 - Red data //buffer[1] -> //Pixel 1 - Green data //buffer[2] -> //Pixel 1 - Blue data So, any Ideas? I think I can improve it quite a bit reading all to an array in one single call, I just don't know how that is done. Also, is it posible to know how many images will be in the "index file"? Is it posiible to know the number of lines a file has?(because there's one file name per line..) Thanks!!

    Read the article

  • How to use Primefaces slider component with decimal values?

    - by Ioan
    I am using JSF 2.2, Primefaces 4.0, and I am using slider component from Primefaces. <p:slider displayTemplate="Between {min} and {max}" minValue="20" maxValue="40" step="1"/> I would like to ask you if is possibile to have step as decimal value. E.g. step="0.1", or perhaps some ideas about how to solve this issue. I have tried but I'm getting errors like : javax.el.ELException: Cannot convert 0.1 of type class java.lang.String to int] with root cause Thank you.

    Read the article

  • How To Get all ITEMS from Folders and Sub-folders of PublicFolders

    - by user1891567
    How to retrieve all items from "public folders" and its "sub-folders" in exchange server2010 uisng managed API??? rootfolder = Folder.Bind(service,WellKnownFolderName.PublicFoldersRoot); rootfolder.Load(); foreach (Folder folder in rootfolder.FindFolders(new FolderView(int.MaxValue))) { FindItemsResults<Item> findResults = folder.FindItems(iv); foreach (Item item in findResults) { //get item info; } } "If i do like this i am not getting items present in sub-folders of it..public folders does not support deep traversal queries too..How can i get items from sub-folders of public folders???"

    Read the article

  • Why is my unsafe code block slower than my safe code?

    - by jomtois
    I am attempting to write some code that will expediently process video frames. I am receiving the frames as a System.Windows.Media.Imaging.WriteableBitmap. For testing purposes, I am just applying a simple threshold filter that will process a BGRA format image and assign each pixel to either be black or white based on the average of the BGR pixels. Here is my "Safe" version: public static void ApplyFilter(WriteableBitmap Bitmap, byte Threshold) { // Let's just make this work for this format if (Bitmap.Format != PixelFormats.Bgr24 && Bitmap.Format != PixelFormats.Bgr32) { return; } // Calculate the number of bytes per pixel (should be 4 for this format). var bytesPerPixel = (Bitmap.Format.BitsPerPixel + 7) / 8; // Stride is bytes per pixel times the number of pixels. // Stride is the byte width of a single rectangle row. var stride = Bitmap.PixelWidth * bytesPerPixel; // Create a byte array for a the entire size of bitmap. var arraySize = stride * Bitmap.PixelHeight; var pixelArray = new byte[arraySize]; // Copy all pixels into the array Bitmap.CopyPixels(pixelArray, stride, 0); // Loop through array and change pixels to black or white based on threshold for (int i = 0; i < pixelArray.Length; i += bytesPerPixel) { // i=B, i+1=G, i+2=R, i+3=A var brightness = (byte)((pixelArray[i] + pixelArray[i + 1] + pixelArray[i + 2]) / 3); var toColor = byte.MinValue; // Black if (brightness >= Threshold) { toColor = byte.MaxValue; // White } pixelArray[i] = toColor; pixelArray[i + 1] = toColor; pixelArray[i + 2] = toColor; } Bitmap.WritePixels(new Int32Rect(0, 0, Bitmap.PixelWidth, Bitmap.PixelHeight), pixelArray, stride, 0); } Here is what I think is a direct translation using an unsafe code block and the WriteableBitmap Back Buffer instead of the forebuffer: public static void ApplyFilterUnsafe(WriteableBitmap Bitmap, byte Threshold) { // Let's just make this work for this format if (Bitmap.Format != PixelFormats.Bgr24 && Bitmap.Format != PixelFormats.Bgr32) { return; } var bytesPerPixel = (Bitmap.Format.BitsPerPixel + 7) / 8; Bitmap.Lock(); unsafe { // Get a pointer to the back buffer. byte* pBackBuffer = (byte*)Bitmap.BackBuffer; for (int i = 0; i < Bitmap.BackBufferStride*Bitmap.PixelHeight; i+= bytesPerPixel) { var pCopy = pBackBuffer; var brightness = (byte)((*pBackBuffer + *pBackBuffer++ + *pBackBuffer++) / 3); pBackBuffer++; var toColor = brightness >= Threshold ? byte.MaxValue : byte.MinValue; *pCopy = toColor; *++pCopy = toColor; *++pCopy = toColor; } } // Bitmap.AddDirtyRect(new Int32Rect(0,0, Bitmap.PixelWidth, Bitmap.PixelHeight)); Bitmap.Unlock(); } This is my first foray into unsafe code blocks and pointers, so maybe the logic is not optimal. I have tested both blocks of code on the same WriteableBitmaps using: var threshold = Convert.ToByte(op.Result); var copy2 = copyFrame.Clone(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); BinaryFilter.ApplyFilterUnsafe(copyFrame, threshold); stopWatch.Stop(); var unsafesecs = stopWatch.ElapsedMilliseconds; stopWatch.Reset(); stopWatch.Start(); BinaryFilter.ApplyFilter(copy2, threshold); stopWatch.Stop(); Debug.WriteLine(string.Format("Unsafe: {1}, Safe: {0}", stopWatch.ElapsedMilliseconds, unsafesecs)); So I am analyzing the same image. A test run of an incoming stream of video frames: Unsafe: 110, Safe: 53 Unsafe: 136, Safe: 42 Unsafe: 106, Safe: 36 Unsafe: 95, Safe: 43 Unsafe: 98, Safe: 41 Unsafe: 88, Safe: 36 Unsafe: 129, Safe: 65 Unsafe: 100, Safe: 47 Unsafe: 112, Safe: 50 Unsafe: 91, Safe: 33 Unsafe: 118, Safe: 42 Unsafe: 103, Safe: 80 Unsafe: 104, Safe: 34 Unsafe: 101, Safe: 36 Unsafe: 154, Safe: 83 Unsafe: 134, Safe: 46 Unsafe: 113, Safe: 76 Unsafe: 117, Safe: 57 Unsafe: 90, Safe: 41 Unsafe: 156, Safe: 35 Why is my unsafe version always slower? Is it due to using the back buffer? Or am I doing something wrong? Thanks

    Read the article

  • How to make tooltip move with mouse (winforms)

    - by BlueRaja The Green Unicorn
    I want it to move when the mouse moves, and disappear when the pointer isn't over the label. This doesn't work: private void lblRevisionQuestion_MouseMove(object sender, MouseEventArgs e) { toolTip1.Show("test", this, PointToClient(MousePosition), Int32.MaxValue); } private void lblRevisionQuestion_MouseLeave(object sender, EventArgs e) { toolTip1.Hide(this); } As soon as the tooltip appears, it steals focus away from the form, evoking MouseLeave. Then the tooltip hides, and the pointer is once again over the label, invoking MouseMove. This results in a choppy, flashing tooltip. Is there any way to do this?

    Read the article

  • NetTcpBinding() with TransferMode.Streamed

    - by totem
    Hi, I am getting a timeout exception when trying to use a net tcp endpoint through code that has no security and is streamed like so: NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); binding.TransferMode = TransferMode.Streamed; binding.SendTimeout = TimeSpan.MaxValue; the same code would work if i just leave out the SecurityMode.None or choose SecurityMode.Transport, the exception is on a timeout that is too low, i tired adding all the timeouts for recive, send, open, close and set them all to Max and that didnt work. im using sample code from: http://csharp-codesamples.com/2009/02/data-transfer-using-self-hosted-wcf-service/ Any explenation as to how to use no security in this scenario would be appriciated. Thanks, Totem

    Read the article

  • Zipping Rx IObservable with infinite number set

    - by Toni Kielo
    I have a IObservable [named rows in the sample below] from Reactive extensions framework and I want to add index numbers to each object it observes. I've tried to implement this using Zip function: rows.Zip(Enumerable.Range(1, int.MaxValue), (row, index) => new { Row = row, Index = index }) .Subscribe(a => ProcessRow(a.Row, a.Index), () => Completed()); .. but unfortunately this throws ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: disposables Am I understanding the Zip function wrong or is there a problem with my code? The Range part of the code doesn't seem to be the problem and the IObservable isn't yet receiving any events.

    Read the article

  • Why is FxCop warning about an overflow (CA2233) in this C# code?

    - by matt
    I have the following function to get an int from a high-byte and a low-byte: public static int FromBytes(byte high, byte low) { return high * (byte.MaxValue + 1) + low; } When I analyze the assembly with FxCop, I get the following critical warning: CA2233: OperationsShouldNotOverflow Arithmetic operations should not be done without first validating the operands to prevent overflow. I can't see how this could possibly overflow, so I am just assuming FxCop is being overzealous. Am I missing something? And what steps could be taken to correct what I have (or at least make the FxCop warning go away!)?

    Read the article

  • Rotate Windows.Documents.Table

    - by Neverrav
    I need to rotate a table clockwise up to 90 degrees. It's one of the blocks of a FlowDocument. Is there a way to apply some kind of rotation to a Table? The possible solution of creating TextEffect like this: var table = new Table(); ... // fill the table here var effect = new TextEffect { Transform = new RotationTransform(90), PositionStart = 0, PositionCount = int.MaxValue }; table.TextEffects = new TextEffectCollection(); table.TextEffects.Add(effect); doesn't work.

    Read the article

  • ExpectedException on TestMethod Visual Studio 2010

    - by Joop
    Today I upgraded my solution with all the underlying projects from VS2008 to VS2010. Everything went well except for my unit tests. First of all only the web projects had as target framework .NET 4. All the other projects still had .NET 3.5. I changed them all to .NET 4. Now when I debug my unit tests it breaks on every exception. In 2008 it just wouldn't pass and tell me that an exception occurred. Even when I have the ExpectedException attribute defined it stops debugging on every exception. And example of one of my tests: [TestMethod] [ExpectedException(typeof(EntityDoesNotExistException))] public void ConstructorTest() { AddressType type = new AddressType(int.MaxValue); } The EntityDoesNotExistException is a custom exception and inherits Exception.

    Read the article

  • In C# should I use uint or int for values that are never supposed to be negative?

    - by Hamish Grubijan
    Suppose that the MaxValue of (roughly :) ) 2^31 vs 2^32 does not matter. On one hand, using uint seems nice because it is self-explanatory, it indicates (and promises?) that some value may never be negative. However, int is more common, and a cast is often inconvenient. One can just use int and always supplement it with code contracts (everyone has moved to .Net 4.0 by now, right?) Standard libraries do use int for Length and Size properties, even though those should never be negative. So, is it obvious to you that int is better than uint most of the time, or is it more complicated? Please ask questions if you find that this question is not clearly stated. Thanks.

    Read the article

  • Difference of two 'uint'

    - by vanslly
    When you attempt to declare an unsigned variable in C#.NET with a value outside its value range it is flagged as a compiler error, but if you produce a negative value at runtime and assign it to that variable at runtime the value wraps. uint z = -1; // Will not compile uint a = 5; uint b = 6; uint c = a - b; // Will result in uint.MaxValue Is there a good reason why unsigned variables wrap in such a situation instead of throwing an exception? Thanks.

    Read the article

  • Does DataType DataAnnotation Check the Expression?

    - by Jason
    I am currently using DataAnnotations within my ASP.NET MVC website to ensure data is properly validated. One question I wanted to verify (I think I know the answer, but I can't find verification online) - does the DataType DataAnnotation perform regular expression checks to ensure that you have received a valid e-mail/phone/currency/etc? [Required(ErrorMessage = "Price required")] [DataType(DataType.Currency, ErrorMessage = "Not a valid price")] [Range(0, double.MaxValue, ErrorMessage = "Price must be greater than 0.")] public decimal Price { get; set; } I believe the answer is no (meaning I have to provide my own, custom, RegularExpressionAttribute), but I wanted to double check before I do that for various field types.

    Read the article

  • Jquery post and get data from PHP

    - by Sergio
    Jquery code looks like: $('#gal').rating('gl.php?gal_no=<?=$gal_no;?>&id=<?=$id;?>', {maxvalue:10,increment:.5, curvalue: <?=$cur;?>}); PHP code: $br=mysql_query("SELECT count(gal) as total FROM ...") if ... { echo '0'; } else echo '1'; } Jquery code successfully transmitted data to PHP script and when the PHP done with checking data echo the result ('1' or '0'). How can I get this PHP result back to Jquery and based on them write a message? Some thing like: if(data=="1") { $("#error").show("fast").html('not correct').css({'background-color' : '#F5F5F5','border-color' : '#F69'}); }else{ $("#error").show("fast").html('correct').css({'background-color' : '#FFF','border-color' : '#3b5998'}); }

    Read the article

  • IDispatchMessageInspector to log plain-text soap messages?

    - by Dan Thomas
    I've written a WCF IDispatchMessageInspector, so I can log incomming and outgoing messages. But I'm not sure how to get a nicely-formatted XML string to log. My code looks something like this: public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue); request = buffer.CreateMessage(); Log("Received", request.ToString(); return null; } The result of this logging includes things like "ampersand lt;" and some sort of binary-encoded data. How do I get something that looks like a standard soap XML document? I know this should be obvious, but I'm just too dense to figure it out. Thanks. Dan

    Read the article

  • Clone LINQ To SQL object Extension Method throws object dispose exception....

    - by gtas
    Hello all, I have this extension method for cloning my LINQ To SQL objects: public static T CloneObjectGraph<T>(this T obj) where T : class { var serializer = new DataContractSerializer(typeof(T), null, int.MaxValue, false, true, null); using (var ms = new System.IO.MemoryStream()) { serializer.WriteObject(ms, obj); ms.Position = 0; return (T)serializer.ReadObject(ms); } } But while i carry objects with not all references loaded, while qyuerying with DataLoadOptions, sometimes it throws the object disposed exception, but thing is I don't ask for references that is not loaded (null). e.g. I have Customer with many references and i just need to carry on memory the Address reference EntityRef< and i don't Load anything else. But while i clone the object this exception forces me to load all the EntitySet< references with the Customer object, which might be too much and slow down the application speed. Any suggestions?

    Read the article

  • Oracle sequence but then in MS SQL Server

    - by Raymond
    In Oracle there is a mechanism to generate sequence numbers e.g.; CREATE SEQUENCE supplier_seq MINVALUE 1 MAXVALUE 999999999999999999999999999 START WITH 1 INCREMENT BY 1 CACHE 20; And then execute the statement supplier_seq.nextval to retrieve the next sequence number. How would you create the same functionality in MS SQL Server ? Edit: I'm not looking for ways to automaticly generate keys for table records. I need to generate a unique value that I can use as an (logical) ID for a process. So I need the exact functionality that Oracle provides.

    Read the article

  • Windows installer custome action call WCF to get value from remote failed.(NoEndpoint found exeption

    - by malik
    I am using windows installer to deploy my application. And i have add a custom action to access a WCF service from remote server. While installing application i found endpoind not found exception. ServiceReference.testContractsClient client; var wsBinding = new WSHttpBinding(SecurityMode.None, false); //End point i take from user input EndpointAddress endpointAddress = new EndpointAddress(ctlWebServiceUrl.Text); wsBinding.MaxReceivedMessageSize = int.MaxValue; client = new ServiceReference.testContractsClient(wsBinding, endpointAddress); client.test(); //method call If i connect to LAN (network) it works, same installer work on all machine. Windows XP Professional on only one PC have issue. If anybody can help..

    Read the article

  • defining a simple implicit Arbitary

    - by FredOverflow
    I have a type Foo with a constructor that takes an Int. How do I define an implicit Arbitrary for Foo to be used with scalacheck? implicit def arbFoo: Arbitrary[Foo] = ??? I came up with the following solution, but it's a bit too "manual" and low-level for my taste: val fooGen = for (i <- Gen.choose(Int.MinValue, Int.MaxValue)) yield new Foo(i) implicit def arbFoo: Arbitrary[Foo] = Arbitrary(fooGen) Ideally, I would want a higher-order function where I just have to plug in an Int => Foo function. I managed to cut it down to: implicit def arbFoo = Arbitrary(Gen.resultOf((i: Int) => new Foo(i))) But I still feel like there has got to be a slightly simpler way.

    Read the article

  • Can I load the max value of the range attribute in CFINPUT using and AJAX call?

    - by Eric Belair
    I have a CFINPUT tag in a CFFORM: <cfinput type="text" id="itemInput" name="itemInput" /> I want to set the range dynamically without posting the page. I have several AJAX calls throughout the page to dynamically load form fields on the fly: <cfselect id="this" name="this" bind="cfc:Data.getThis()" bindonload="true" /> <cfselect id="that" name="that" bind="cfc:Data.getThat({p1})" /> <cfselect id="theOther" name="theOther" bind="cfc:Data.getTheOther({p1}, {p2})" /> <cfdiv id="maxQty" bind="cfc:Data.getMaxQty({itemId})" /> <cfinput type="text" id="qty" name="qty" /> <cfdiv id="itemId" bind="cfc:Data.getItemId({this}, {that}, {theOther})" /> In the above CFFORM, I basically want to set the minValue of the range to "1" and the maxValue of the range to the value of cfc:Data.getMaxQty({itemId}). Is this possible? How can I do it?

    Read the article

  • Determine if a decimal can be stored as int32

    - by anchandra
    I am doing some custom serializing, and in order to save some space, i want to serialize the decimals as int, if possible value wise. Performance is a concern, since i am dealing with a high volume of data. The current method i use is: if ((value > Int32.MinValue) && (value < Int32.MaxValue) && ((valueAsInt = Decimal.ToInt32(value)) == value)) { return true; } Can this be improved?

    Read the article

  • Update JSON file C# W8 development

    - by AndrewB
    At the moment, I've got a JSON file with content looking like this: { "username": "test", "someNumber":100 } I'm using JSON.Net to fetch the .JSON file from a webserver - C#: var http = new HttpClient(); http.MaxResponseContentBufferSize = Int32.MaxValue; var response = await http.GetStringAsync(URI); var result = JsonConvert.DeserializeObject<DatClass.Result>(response); This works great together with the class getting/setting the properties. However, what I would like to know is whether there's a good way for a user to update the .JSON file through a textbox UI? As in: [textbox - update username] [update button] - username sent to server - .JSON file updated - [textblock - showing updated username in UI]. I'm not looking for exact code solutions, I'm rather looking for good solutions on this, and/or if this is a terrible idea of an easy database(?).

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >