Search Results

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

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

  • Can't echo jquery (with ajax) variable in php

    - by Lars Kerff
    I'm trying to post a variable through ajax. But it won't echo the variable in php. This are the variables (these are working, seen in the log): $("#slider").bind("valuesChanged", function(e, data){console.log("min: " + data.values.min + " max: " + data.values.max);}); The Ajax part: $("#slider").bind("valuesChanged", function (e, data) { $.ajax({ type: "POST", dataType: "text", url: "../test.php", data: { minValue: data.values.min, maxValue: data.values.max }, async: false, success: function(data){ alert('yeah') }, error: function(xhr) { alert('fail') // if your PHP script return an erroneous header, you'll land here } }); }); </script> And php echo: <?php if ( $_POST ) { echo $_POST[ 'minValue' ]; } ?> Now why does it not echo the post? Thanks!

    Read the article

  • How is this statement making sense? (Sun's naming convention for Java variables)

    - by polygenelubricants
    I've been quoting this segment from Sun's document for the past few days, and only now do I stop and think about what it's saying, and I can't make sense out of it. Please keep in mind that English is not my first language. Naming conventions Variables: Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. How is this making sense? Isn't this saying that class names are in mixed case with a lowercase first letter? Like I should name it class myClass? And class constants are also in mixed case with a lowercase first letter? Like I should name it Integer.maxValue? And is it really saying anything about how variables themselves should be named? Am I not parsing this properly or is this actually a blatant error?

    Read the article

  • SQL SERVER – A Puzzle Part 3 – Fun with SEQUENCE in SQL Server 2012 – Guess the Next Value

    - by pinaldave
    Before continuing this blog post – please read the two part of the SEQUENCE Puzzle here A Puzzle – Fun with SEQUENCE in SQL Server 2012 – Guess the Next Value and A Puzzle Part 2 – Fun with SEQUENCE in SQL Server 2012 – Guess the Next Value Where we played a simple guessing game about predicting next value. The answers the of puzzle is shared on the blog posts as a comment. Now here is the next puzzle based on yesterday’s puzzle. I recently shared the puzzle of the blog post on local user group and it was appreciated by attendees. First execute the script which I have written here. Today’s script is bit different than yesterday’s script as well it will require you to do some service related activities. I suggest you try this on your personal computer’s test environment when no one is working on it. Do not attempt this on production server as it will for sure get you in trouble. The purpose to learn how sequence behave during the unexpected shutdowns and services restarts. Now guess what will be the next value as requested in the query. USE AdventureWorks2012 GO -- Create sequence CREATE SEQUENCE dbo.SequenceID AS BIGINT START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 500 CYCLE CACHE 100; GO -- Following will return 1 SELECT next value FOR dbo.SequenceID; ------------------------------------- -- simulate server crash by restarting service -- do not attempt this on production or any server in use ------------------------------------ -- Following will return ??? SELECT next value FOR dbo.SequenceID; -- Clean up DROP SEQUENCE dbo.SequenceID; GO Once the server is restarted what will be the next value for SequenceID. We can learn interesting trivia’s about this new feature of SQL Server using this puzzle. Hint: Pay special attention to the difference between new number and earlier number. Can you see the same number in the definition of the CREATE SEQUENCE? Bonus Question: How to avoid the behavior demonstrated in above mentioned query. Does it have any effect of performance? I suggest you try to attempt to answer this question without running this code in SQL Server 2012. You can restart SQL Server using command prompt as well. I will follow up of the answer in comments below. Recently my friend Vinod Kumar wrote excellent blog post on SQL Server 2012: Using SEQUENCE, you can head over there for learning sequence in details. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Puzzle, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Silverlight and WCF caching

    - by subodhnpushpak
    There are scenarios where Silverlight client calls WCF (or REST) service for data. Now, if the data is cached on the WCF layer, the calls can take considerable resources at the server if NOT cached. Keeping that in mind along with the fact that cache is an cross-cutting aspect, and therefore it should be as easy as possible to put Cache wherever required. The good thing about the solution is that it caches based on the inputs. The input can be basic type of any complex type. If input changes the data is fetched and then cached for further used. If same input is provided again, data id fetched from the cache. The cache logic itself is implemented as PostSharp aspect, and it is as easy as putting an attribute over service call to switch on cache. Notice how clean the code is:        [OperationContract]       [CacheOnArgs(typeof(int))] // based on actual value of cache        public string DoWork(int value)        {            return string.Format("You entered: {0} @ cached time {1}", value, System.DateTime.Now);        } The cache is implemented as POST Sharp as below 1: public override void OnInvocation(MethodInvocationEventArgs eventArgs) 2: { 3: try 4: { 5: object value = new object(); 6: object[] args = eventArgs.GetArgumentArray(); 7: if (args != null || args.Count() > 0) 8: { 9:   10: string key = string.Format("{0}_{1}", eventArgs.Method.Name, XMLUtility<object>.GetDataContractXml(args[0], null));// Compute the cache key (details omitted). 11:   12: 13: value = GetFromCache(key); 14: if (value == null) 15: { 16: eventArgs.Proceed(); 17: value = XMLUtility<object>.GetDataContractXml(eventArgs.ReturnValue, null); 18: value = eventArgs.ReturnValue; 19: AddToCache(key, value); 20: return; 21: } 22:   23:   24: Log(string.Format("Data returned from Cache {0}",value)); 25: eventArgs.ReturnValue = value; 26: } 27: } 28: catch (Exception ex) 29: { 30: //ApplicationLogger.LogException(ex.Message, Source.UtilityService); 31: } 32: } 33:   34: private object GetFromCache(string inputKey) { if (ServerConfig.CachingEnabled) { return WCFCache.Current[inputKey]; } return null; }private void AddToCache(string inputKey,object outputValue) 35: { 36: if (ServerConfig.CachingEnabled) 37: { 38: if (WCFCache.Current.CachedItemsNumber < ServerConfig.NumberOfCachedItems) 39: { 40: if (ServerConfig.SlidingExpirationTime <= 0 || ServerConfig.SlidingExpirationTime == int.MaxValue) 41: { 42: WCFCache.Current[inputKey] = outputValue; 43: } 44: else 45: { 46: WCFCache.Current.Insert(inputKey, outputValue, new TimeSpan(0, 0, ServerConfig.SlidingExpirationTime), true); 47:   48: // _bw.DoWork += bw_DoWork; 49: //string arg = string.Format("{0}|{1}", inputKey,outputValue); 50: //_bw.RunWorkerAsync(inputKey ); 51: } 52: } 53: } 54: }     The cache class can be extended to support Velocity / memcahe / Nache. the attribute can be used over REST services as well. Hope the above helps. Here is the code base for the same.   Please do provide your inputs / comments.

    Read the article

  • [EF + Oracle] Inserting Data (Sequences) (2/2)

    - by JTorrecilla
    Prologue In the previous chapter we have see how to create DB records with EF, now we are going to Some Questions about Oracle.   ORACLE One characteristic from SQL Server that differs from Oracle is “Identity”. To all that has not worked with SQL Server, this property, that applies to Integer Columns, lets indicate that there is auto increment columns, by that way it will be filled automatically, without writing it on the insert statement. In EF with SQL Server, the properties whose match with Identity columns, will be filled after invoking SaveChanges method. In Oracle DB, there is no Identity Property, but there is something similar. Sequences Sequences are DB objects, that allow to create auto increment, but there are not related directly to a Table. The syntax is as follows: name, min value, max value and begin value. 1: CREATE SEQUENCE nombre_secuencia 2: INCREMENT BY numero_incremento 3: START WITH numero_por_el_que_empezara 4: MAXVALUE valor_maximo | NOMAXVALUE 5: MINVALUE valor_minimo | NOMINVALUE 6: CYCLE | NOCYCLE 7: ORDER | NOORDER 8:    How to get sequence value? To obtain the next val from the sequence: 1: SELECT nb_secuencia.Nextval 2: From Dual Due to there is no direct way to indicate that a column is related to a sequence, there is several ways to imitate the behavior: Use a Trigger (DB), Use Stored Procedures or Functions(…) or my particularly option. EF model, only, imports Table Objects, Stored Procedures or Functions, but not sequences. By that, I decide to create my own extension Method to invoke Next Val from a sequence: 1: public static class EFSequence 2: { 3: public static int GetNextValue(this ObjectContext contexto, string SequenceName) 4: { 5: string Connection = ConfigurationManager.ConnectionStrings["JTorrecillaEntities2"].ConnectionString; 6: Connection=Connection.Substring(Connection.IndexOf(@"connection string=")+19); 7: Connection = Connection.Remove(Connection.Length - 1, 1); 8: using (IDbConnection con = new Oracle.DataAccess.Client.OracleConnection(Connection)) 9: { 10: using (IDbCommand cmd = con.CreateCommand()) 11: { 12: con.Open(); 13: cmd.CommandText = String.Format("Select {0}.nextval from DUAL", SequenceName); 14: return Convert.ToInt32(cmd.ExecuteScalar()); 15: } 16: } 17:  18: } 19: } This Object Context’s extension method are going to invoke a query with the Sequence indicated by parameter. It takes the connection strings from the App settings, removing the meta data, that was created by VS when generated the EF model. And then, returns the next value from the Sequence. The next value of a Sequence is unique, by that, when some concurrent users are going to create records in the DB using the sequence will not get duplicates. This is my own implementation, I know that it could be several ways to do and better ways. If I find any other way, I promise to post it. To use the example is needed to add a reference to the Oracle (ODP.NET) dll.

    Read the article

  • Getting a SecurityToken from a RequestSecurityTokenResponse in WIF

    - by Shawn Cicoria
    When you’re working with WIF and WSTrustChannelFactory when you call the Issue operation, you can also request that a RequestSecurityTokenResponse as an out parameter. However, what can you do with that object?  Well, you could keep it around and use it for subsequent calls with the extension method CreateChannelWithIssuedToken – or can you? public static T CreateChannelWithIssuedToken<T>(this ChannelFactory<T> factory, SecurityToken issuedToken);   As you can see from the method signature it takes a SecurityToken – but that’s not present on the RequestSecurityTokenResponse class. However, you can through a little magic get a GenericXmlSecurityToken by means of the following set of extension methods below – just call rstr.GetSecurityTokenFromResponse() – and you’ll get a GenericXmlSecurityToken as a return. public static class TokenHelper { /// <summary> /// Takes a RequestSecurityTokenResponse, pulls out the GenericXmlSecurityToken usable for further WS-Trust calls /// </summary> /// <param name="rstr"></param> /// <returns></returns> public static GenericXmlSecurityToken GetSecurityTokenFromResponse(this RequestSecurityTokenResponse rstr) { var lifeTime = rstr.Lifetime; var appliesTo = rstr.AppliesTo.Uri; var tokenXml = rstr.GetSerializedTokenFromResponse(); var token = GetTokenFromSerializedToken(tokenXml, appliesTo, lifeTime); return token; } /// <summary> /// Provides a token as an XML string. /// </summary> /// <param name="rstr"></param> /// <returns></returns> public static string GetSerializedTokenFromResponse(this RequestSecurityTokenResponse rstr) { var serializedRst = new WSFederationSerializer().GetResponseAsString(rstr, new WSTrustSerializationContext()); return serializedRst; } /// <summary> /// Turns the XML representation of the token back into a GenericXmlSecurityToken. /// </summary> /// <param name="tokenAsXmlString"></param> /// <param name="appliesTo"></param> /// <param name="lifetime"></param> /// <returns></returns> public static GenericXmlSecurityToken GetTokenFromSerializedToken(this string tokenAsXmlString, Uri appliesTo, Lifetime lifetime) { RequestSecurityTokenResponse rstr2 = new WSFederationSerializer().CreateResponse( new SignInResponseMessage(appliesTo, tokenAsXmlString), new WSTrustSerializationContext()); return new GenericXmlSecurityToken( rstr2.RequestedSecurityToken.SecurityTokenXml, new BinarySecretSecurityToken( rstr2.RequestedProofToken.ProtectedKey.GetKeyBytes()), lifetime.Created.HasValue ? lifetime.Created.Value : DateTime.MinValue, lifetime.Expires.HasValue ? lifetime.Expires.Value : DateTime.MaxValue, rstr2.RequestedAttachedReference, rstr2.RequestedUnattachedReference, null); } }

    Read the article

  • XNA 4.0: 2D Camera Y and X are going in wrong direction

    - by Setheron
    I asked this question on stackoverflow but assumed this might be a better area to ask it as well for a more informed answer. My problem is that I am trying to create a camera class and have it so that my camera follows the proper RHS, however the Y axis seems to be inverted since on the screen the 0 starts at the top. Here is my Camera2D Class: class Camera2D { private Vector2 _position; private float _zoom; private float _rotation; private float _cameraSpeed; private Viewport _viewport; private Matrix _viewMatrix; private Matrix _viewMatrixIverse; public static float MinZoom = float.Epsilon; public static float MaxZoom = float.MaxValue; public Camera2D(Viewport viewport) { _viewMatrix = Matrix.Identity; _viewport = viewport; _cameraSpeed = 4.0f; _zoom = 1.0f; _rotation = 0.0f; _position = Vector2.Zero; } public void Move(Vector2 amount) { _position += amount; } public void Zoom(float amount) { _zoom += amount; _zoom = MathHelper.Clamp(_zoom, MaxZoom, MinZoom); UpdateViewTransform(); } public Vector2 Position { get { return _position; } set { _position = value; UpdateViewTransform(); } } public Matrix ViewMatrix { get { return _viewMatrix; } } private void UpdateViewTransform() { Matrix proj = Matrix.CreateTranslation(new Vector3(_viewport.Width * 0.5f, _viewport.Height * 0.5f, 0)) * Matrix.CreateScale(new Vector3(1f, 1f, 1f)); _viewMatrix = Matrix.CreateRotationZ(_rotation) * Matrix.CreateScale(new Vector3(_zoom, _zoom, 1.0f)) * Matrix.CreateTranslation(_position.X, _position.Y, 0.0f); _viewMatrix = proj * _viewMatrix; } } I test it using SpriteBatch in the following way: protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); Vector2 position = new Vector2(0, 0); // TODO: Add your drawing code here spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, camera.ViewMatrix); Texture2D circle = CreateCircle(100); spriteBatch.Draw(circle, position, Color.Red); spriteBatch.End(); base.Draw(gameTime); }

    Read the article

  • SQL SERVER – A Puzzle Part 4 – Fun with SEQUENCE in SQL Server 2012 – Guess the Next Value

    - by pinaldave
    It seems like every weekend I get a new puzzle in my mind. Before continuing I suggest you read my previous posts here where I have shared earlier puzzles. A Puzzle – Fun with SEQUENCE in SQL Server 2012 – Guess the Next Value  A Puzzle Part 2 – Fun with SEQUENCE in SQL Server 2012 – Guess the Next Value A Puzzle Part 3 – Fun with SEQUENCE in SQL Server 2012 – Guess the Next Value After reading above three posts, I am very confident that you all will be ready for the next set of puzzles now. First execute the script which I have written here. Now guess what will be the next value as requested in the query. USE TempDB GO -- Create sequence CREATE SEQUENCE dbo.SequenceID AS DECIMAL(3,0) START WITH 1 INCREMENT BY -1 MINVALUE 1 MAXVALUE 3 CYCLE NO CACHE; GO SELECT next value FOR dbo.SequenceID; -- Guess the number SELECT next value FOR dbo.SequenceID; -- Clean up DROP SEQUENCE dbo.SequenceID; GO Please note that Starting value is 1, Increment value is the negative value of -1 and Minimum value is 3. Now let us first assume how this will work out. In our example of the sequence starting value is equal to 1 and decrement value is -1, this means the value should decrement from 1 to 0. However, the minimum value is 1. This means the value cannot further decrement at all. What will happen here? The natural assumption is that it should throw an error. How many of you are assuming about query will throw an ERROR? Well, you are WRONG! Do not blame yourself, it is my fault as I have told you only half of the story. Now if you have voted for error, let us continue running above code in SQL Server Management Studio. The above script will give the following output: Isn’t it interesting that instead of error out it is giving us result value 3. To understand the answer about the same, carefully observe the original syntax of creating SEQUENCE – there is a keyword CYCLE. This keyword cycles the values between the minimum and maximum value and when one of the range is exhausted it cycles the values from the other end of the cycle. As we have negative incremental value when query reaches to the minimum value or lower end it will cycle it from the maximum value. Here the maximum value is 3 so the next logical value is 3. If your business requirement is such that if sequence reaches the maximum or minimum value, it should throw an error, you should not use the keyword cycle, and it will behave as discussed. I hope, you are enjoying the puzzles as much as I am enjoying it. If you have any interesting puzzle to share, please do share with me and I will share this on blog with due credit to you. Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: PostADay, SQL, SQL Authority, SQL Puzzle, SQL Query, SQL Server, SQL Tips and Tricks, SQLServer, T SQL, Technology

    Read the article

  • dynamic? I'll never use that ... or then again, maybe it could ...

    - by adweigert
    So, I don't know about you, but I was highly skeptical of the dynamic keywork when it was announced. I thought to myself, oh great, just another move towards VB compliance. Well after seeing it being used in things like DynamicXml (which I use for this example) I then was working with a MVC controller and wanted to move some things like operation timeout of an action to a configuration file. Thinking big picture, it'd be really nice to have configuration for all my controllers like that. Ugh, I don't want to have to create all those ConfigurationElement objects... So, I started thinking self, use what you know and do something cool ... Well after a bit of zoning out, self came up with use a dynamic object duh! I was thinking of a config like this ...<controllers> <add type="MyApp.Web.Areas.ComputerManagement.Controllers.MyController, MyApp.Web"> <detail timeout="00:00:30" /> </add> </controllers> So, I ended up with a couple configuration classes like this ...blic abstract class DynamicConfigurationElement : ConfigurationElement { protected DynamicConfigurationElement() { this.DynamicObject = new DynamicConfiguration(); } public DynamicConfiguration DynamicObject { get; private set; } protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) { this.DynamicObject.Add(name, value); return true; } protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader) { this.DynamicObject.Add(elementName, new DynamicXml((XElement)XElement.ReadFrom(reader))); return true; } } public class ControllerConfigurationElement : DynamicConfigurationElement { [ConfigurationProperty("type", Options = ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey)] public string TypeName { get { return (string)this["type"]; } } public Type Type { get { return Type.GetType(this.TypeName, true); } } } public class ControllerConfigurationElementCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new ControllerConfigurationElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((ControllerConfigurationElement)element).Type; } } And then had to create the meat of the DynamicConfiguration class which looks like this ...public class DynamicConfiguration : DynamicObject { private Dictionary<string, object> properties = new Dictionary<string, object>(StringComparer.CurrentCultureIgnoreCase); internal void Add<T>(string name, T value) { this.properties.Add(name, value); } public override bool TryGetMember(GetMemberBinder binder, out object result) { var propertyName = binder.Name; result = null; if (this.properties.ContainsKey(propertyName)) { result = this.properties[propertyName]; } return true; } } So all being said, I made a base controller class like a good little MVC-itizen ...public abstract class BaseController : Controller { protected BaseController() : base() { var configuration = ManagementConfigurationSection.GetInstance(); var controllerConfiguration = configuration.Controllers.ForType(this.GetType()); if (controllerConfiguration != null) { this.Configuration = controllerConfiguration.DynamicObject; } } public dynamic Configuration { get; private set; } } And used it like this ...public class MyController : BaseController { static readonly string DefaultDetailTimeout = TimeSpan.MaxValue.ToString(); public MyController() { this.DetailTimeout = TimeSpan.Parse(this.Configuration.Detail.Timeout ?? DefaultDetailTimeout); } public TimeSpan DetailTimeout { get; private set; } } And there I have an actual use for the dynamic keyword ... never thoguht I'd see the day when I first heard of it as I don't do much COM work ... oh dont' forget this little helper extension methods to find the controller configuration by the controller type.public static ControllerConfigurationElement ForType<T>(this ControllerConfigurationElementCollection collection) { Contract.Requires(collection != null); return ForType(collection, typeof(T)); } public static ControllerConfigurationElement ForType(this ControllerConfigurationElementCollection collection, Type type) { Contract.Requires(collection != null); Contract.Requires(type != null); return collection.Cast<ControllerConfigurationElement>().Where(element => element.Type == type).SingleOrDefault(); } Sure, it isn't perfect and I'm sure I can tweak it over time, but I thought it was a pretty cool way to take advantage of the dynamic keyword functionality. Just remember, it only validates you did it right at runtime, which isn't that bad ... is it? And yes, I did make it case-insensitive so my code didn't have to look like my XML objects, tweak it to your liking if you dare to use this creation.

    Read the article

  • Taking a look at the Mindscape Phone Elements for WP7.

    - by mbcrump
    I recently heard that Mindscape HQ had released the Windows Phone 7 Controls and had to take a look at them. 100 FREE LICENSE GIVEAWAY! Before we get to the screenshots, you will be pleased to learn that my usergroup called “Allaboutxaml” has partnered with Mindscape HQ and are giving away 100 license. You can check out the site here to get your free controls. But please hurry as after the 100 are gone then I will not have any more to give away! A few links to read first: The official blog post from Mindscape HQ detailing the release. They also have the links to download the trial and get started. The phone elements official forum! So, let’s get started. After you download the controls go ahead and double click the .exe to get started installing them. After everything is installed then you will have the following program group. I’d recommend clicking on the Phone Elements Directory to get started: Let’s go over each element: Bin – Just the .DLL that’s required to use Mindscape HQ WP7 Controls in your project. Documentation – a .CHM File that will show you how to get your project up and running quickly. Resources – Just a few image files Samples – This is a full WP7 project that details every controls. The thing that I was most interested in was how the controls look and is it easy to use. I always believed if your paying for controls then you should hold my hand through using them. You will be pleased to know that Mindscape made it very easy to use. First, the WP7 project in the “Samples” folder just works. Double click on the solution file and you are in an emulator looking at the controls. Since you have the source code for every control, it’s a matter of copying/pasting the code in your project to get it to work. What I did, was play with the controls in the emulator until I found one I could use. Then I looked at the Visual Studio solution and found the Page that contained the control. Mindscape makes this very easy to do with their layout: So, the one that I was interested in was the Looping List Box.  Here is a demo of it: I wanted to see how they were populating the numbers 1-100 so I found the code behind and noticed it was just this one line. LoopingListBox1.DataSource = new NumericDataSource() { MinValue = 1, MaxValue = 100 }; In case you are wondering, the NumericDataSource was created by MindScape and you can view the Declaration to find out more about it:   So, the controls are pretty much that easy to use. Play with the emulator and find the control you want to use. Find the XAML file in the Sample Solution and copy/paste the code. Let’s go ahead and take a look at the controls available: They also have a great variety of Charting controls: Overall it’s a nice set of WP7 controls. Feel free to leave a comment below on anything you would like to see and I will make sure that Mindscape HQ get the message. Don’t forget if you are the first 100 people reading this article then you will get a free license.  Subscribe to my feed CodeProject

    Read the article

  • Serializing object with no namespaces using DataContractSerializer

    - by Yurik
    How do I remove XML namespaces from an object's XML representation serialized using DataContractSerializer? That object needs to be serialized to a very simple output XML. Latest & greatest - using .Net 4 beta 2 The object will never need to be deserialized. XML should not have any xmlns:... namespace refs Any subtypes of Exception and ISubObject need to be supported. It will be very difficult to change the original object. Object: [Serializable] class MyObj { string str; Exception ex; ISubObject subobj; } Need to serialize into: <xml> <str>...</str> <ex i:nil="true" /> <subobj i:type="Abc"> <AbcProp1>...</AbcProp1> <AbcProp2>...</AbcProp2> </subobj> </xml> I used this code: private static string ObjectToXmlString(object obj) { if (obj == null) throw new ArgumentNullException("obj"); var serializer = new DataContractSerializer( obj.GetType(), null, Int32.MaxValue, false, false, null, new AllowAllContractResolver()); var sb = new StringBuilder(); using (var xw = XmlWriter.Create(sb, new XmlWriterSettings { OmitXmlDeclaration = true, NamespaceHandling = NamespaceHandling.OmitDuplicates, Indent = true })) { serializer.WriteObject(xw, obj); xw.Flush(); return sb.ToString(); } } From this article I adopted a DataContractResolver so that no subtypes have to be declared: public class AllowAllContractResolver : DataContractResolver { public override bool TryResolveType(Type dataContractType, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) { if (!knownTypeResolver.TryResolveType(dataContractType, declaredType, null, out typeName, out typeNamespace)) { var dictionary = new XmlDictionary(); typeName = dictionary.Add(dataContractType.FullName); typeNamespace = dictionary.Add(dataContractType.Assembly.FullName); } return true; } public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver) { return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null) ?? Type.GetType(typeName + ", " + typeNamespace); } }

    Read the article

  • WPF TextBox.SelectAll () doesn't work

    - by Zoliq
    Hi! I have used the following template in my project: <DataTemplate x:Key="textBoxDataTemplate"> <TextBox Name="textBox" ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" Tag="{Binding}" PreviewKeyDown="cellValueTextBoxKeyDown"> <TextBox.Text> <MultiBinding Converter="{StaticResource intToStringMultiConverter}"> <Binding Path="CellValue" Mode="TwoWay"> <Binding.ValidationRules> <y:MatrixCellValueRule MaxValue="200" /> </Binding.ValidationRules> </Binding> <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type y:MatrixGrid}}" Path="Tag" Mode="OneWay" /> </MultiBinding> </TextBox.Text> </TextBox> </DataTemplate> I used this template to create an editable matrix for the user. The user is able to navigate from cell to cell within the matrix and I would like to highlight the data in the selected textbox but it doesn't work. I called TextBox.Focus () and TextBox.SelectAll () to achieve the effect but nothing. The Focus () works but the text never gets highlighted. Any help is welcome and appreciated.

    Read the article

  • how to map SubclassMap and HasManyToMany in Fluent NHibernate

    - by Davide Orazio Montersino
    Hi everyone. My problem is fluent nhibernate mapping a many to many relationship, they end up referencing a non existent Id. public UserMap() { Id(x => x.Id); Map(x => x.Name); Map(x => x.Password); Map(x => x.Confirmed); HasMany(x => x.Nodes).Cascade.SaveUpdate(); HasManyToMany<Node>(x => x.Events).Cascade.SaveUpdate().Table("RSVPs"); } public EventMap() { Map(x => x.Starts); Map(x => x.Ends); HasManyToMany<User>(x => x.Rsvps).Cascade.SaveUpdate().Table("RSVPs"); } public NodeMap() { Id(x => x.Id); Map(x => x.Title); Map(x => x.Body).CustomSqlType("text"); Map(x => x.CreationDate); References(x => x.Author).Cascade.SaveUpdate(); Map(x => x.Permalink).Unique().Not.Nullable(); } Those are my classes -notice that Event inherits from Node: public class Event : Node//, IEvent { private DateTime _starts = DateTime.MinValue; private DateTime _ends = DateTime.MaxValue; public virtual IList<User> Rsvps { get; set; } } The problem is, the generated RSVPs table is like that: Event_id User_id Node_id Of course the Event table has no ID - only a Node_id. When trying to save a relationship it will try to save a NULL event_id thus generating an error.

    Read the article

  • DataTable.Select Behaves Strangely Using ISNULL Operator on NULL DateTime Column

    - by Paul Williams
    I have a DataTable with a DateTime column, "DateCol", that can be DBNull. The DataTable has one row in it with a NULL value in this column. I am trying to query rows that have either DBNull value in this column or a date that is greater than today's date. Today's date is 5/11/2010. I built a query to select the rows I want, but it did not work as expected. The query was: string query = "ISNULL(DateCol, '" + DateTime.MaxValue + "'") > "' + DateTime.Today "'" This results in the following query: "ISNULL(DateCol, '12/31/9999 11:59:59 PM') > '5/11/2010'" When I run this query, I get no results. It took me a while to figure out why. What follows is my investigation in the Visual Studio immediate window: > dt.Rows.Count 1 > dt.Rows[0]["DateCol"] {} > dt.Rows[0]["DateCol"] == DBNull.Value true > dt.Select("ISNULL(DateCol,'12/31/9999 11:59:59 PM') > '5/11/2010'").Length 0 <-- I expected 1 Trial and error showed a difference in the date checks at the following boundary: > dt.Select("ISNULL(DateCol, '12/31/9999 11:59:59 PM') > '2/1/2000'").Length 0 > dt.Select("ISNULL(DateCol, '12/31/9999 11:59:59 PM') > '1/31/2000'").Length 1 <-- this was the expected answer The query works fine if I wrap the DateTime field in # instead of quotes. > dt.Select("ISNULL(DateCol, #12/31/9999#) > #5/11/2010#").Length 1 My machine's regional settings is currently set to EN-US, and the short date format is M/d/yyyy. Why did the original query return the wrong results? Why would it work fine if the date was compared against 1/31/2000 but not against 2/1/2000?

    Read the article

  • C# mvc2 client side form validation with xval, prevent post

    - by Rob
    I'm using xval to use client side validation in my asp.net mvc2 webapplication. Despite the errors it's giving when i enter text in a nummeric field it still tries to post the form to the database. The incorrect values are being replaced by 0 and saved to the database. But instead it shouldn't even be possible to try and submit the form. Can anyone help me out here? I've set the attributes as below; [Property] [ShowColumnInCrud(true, label = "FromPriceInCents")] [Required] //[Range(1, Int32.MaxValue)] public virtual Int32 FromPriceInCents{ get; set; } The controller catching the request looks as below; I'm getting no errors in this part. [AcceptVerbs(HttpVerbs.Post)] [Transaction] [ValidateInput(false)] public override ActionResult Create() { //some foo happens } My view looks like below; <div class="label"><label for="Price">FromPrice</label></div> <div class="field"> <%= Html.TextBox("FromPriceInCents")%> <%= Html.ValidationMessage("product.FromPriceInCents")%></div> And at the end of the view i have the following rule which in html code generates the correct validation rules <%= Html.ClientSideValidation<Product>("Product") %> I hope someone can helps me out with this issue, thanks in advance!

    Read the article

  • ActiveMq NMS Disconnects after about 30 seconds

    - by Kelly
    'm trying to do simple pub/sub with ActiveMq. I can get it all working fine, but the subscriber disconnects after about 30 seconds. I've looked for a timeout type of value I can change but nothing seems to be working. Here is the subscriber: using System; using Apache.NMS; using Apache.NMS.ActiveMQ; using Apache.NMS.ActiveMQ.Commands; namespace ActiveMQCatcher { internal class Program { private static void Main(string[] args) { IConnectionFactory factory = new ConnectionFactory("tcp://localhost:61616/"); using (IConnection connection = factory.CreateConnection()) { connection.ClientId = "MYID"; connection.Start(); using (ISession session = connection.CreateSession()) { IMessageConsumer consumer = session.CreateConsumer(new ActiveMQTopic("MYTOPIC"), null, false); consumer.Listener += consumer_Listener; Console.ReadLine(); } connection.Stop(); } } private static void consumer_Listener(IMessage message) { Console.WriteLine("Got: " + ((ITextMessage) message).Text); } } } I tried this: connection.RequestTimeout = TimeSpan.MaxValue; But it didn't seem to change anything. To get the problem just run the program and sit waiting for about 30 seconds. You can see the connection disappear in the ActiveMQ Console (http://localhost:8161/admin/connections.jsp by default) Any ideas?

    Read the article

  • Average function without overflow exception

    - by Ron Klein
    .NET Framework 3.5. I'm trying to calculate the average of some pretty large numbers. For instance: using System; using System.Linq; class Program { static void Main(string[] args) { var items = new long[] { long.MinValue + 100, long.MinValue + 200, long.MinValue + 300 }; try { var avg = items.Average(); Console.WriteLine(avg); } catch (OverflowException ex) { Console.WriteLine("can't calculate that!"); } Console.ReadLine(); } } Obviously, the mathematical result is 9223372036854775607 (long.MaxValue - 200), but I get an exception there. This is because the implementation (on my machine) to the Average extension method, as inspected by .NET Reflector is: public static double Average(this IEnumerable<long> source) { if (source == null) { throw Error.ArgumentNull("source"); } long num = 0L; long num2 = 0L; foreach (long num3 in source) { num += num3; num2 += 1L; } if (num2 <= 0L) { throw Error.NoElements(); } return (((double) num) / ((double) num2)); } I know I can use a BigInt library (yes, I know that it is included in .NET Framework 4.0, but I'm tied to 3.5). But I still wonder if there's a pretty straight forward implementation of calculating the average of integers without an external library. Do you happen to know about such implementation? Thanks!! UPDATE: The previous example, of three large integers, was just an example to illustrate the overflow issue. The question is about calculating an average of any set of numbers which might sum to a large number that exceeds the type's max value. Sorry about this confusion. I also changed the question's title to avoid additional confusion. Thanks all!!

    Read the article

  • C# Win Forms Access Violation Exception

    - by Goober
    I keep getting the following error: System.AccessViolationException was unhandled Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Source="FEDivaNET" StackTrace: at Diva.Handles.FEDivaObject.dropReference() at Diva.Handles.FEDivaObject.!FEDivaObject() at Diva.Handles.FEDivaObject.Dispose(Boolean ) at Diva.Handles.FEDivaObject.Finalize() InnerException: Any ideas what the issue could be? - I'm using a library that is written in C++ and isn't designed for multithreading, yet I'm hammering it about 3000 times with requests every 6 minutes. CODE delegate void SetTextCallback(string mxID, string text); public void UpdateLog(string mxID, string text) { //lock (thisLock) //{ if (listBoxProcessLog.InvokeRequired) { SetTextCallback d = new SetTextCallback(UpdateLog); this.BeginInvoke(d, new object[] { mxID, text }); } else { //Get a reference to the datatable assigned as the datasource. //DataTable logDT = (DataTable)listBoxProcessLog.DataSource; //logDT.Rows.Add(DateTime.Now + " - " + mxID + ": " + text); if (text.Contains("COMPLETE") || (text.Contains("FAILED"))) { if (progressBar1.Value <= progressBar1.MaxValue) { progressBar1.Value += 1; } } } //} } Baring in mind that even when the Lock and the DataTable weren't commented out, the error still occurred!

    Read the article

  • richfaces progressBar polling

    - by John
    Hi, I've got a progressBar component defined as the following on my webpage: <rich:modalPanel id="pb1Panel"> <rich:progressBar id="pb1" oncomplete="javascript:#{myBean.handleProgressEvent()} closeProgressModalPanel()" value="#{pb1Listener.percentageComplete}" label="#{pb1Listener.percentageComplete} %" minValue="1" maxValue="100" limitToList="true" timeout="3200" interval="1400" enabled="false"/> </rich:modalPanel> and a button: <a4j:commandButton id="actButton" value="action" action="#{myBean.performAction}" immediate="true" ajaxSingle="true" onclick="javascript:Richfaces.showModalPanel('pb1Panel');" reRender="pb1Panel"> <a4j:support event="onClick" value="#{rich:component('pb1')}.enable()" reRender="pb1" /> </a4j:commandButton> which doesn't work. However if I take out the .... enabled="false"/> .... from the progress bar, and the element from the button, everything seems to work just fine. Any suggestion why it's not working? I'm setting enabled="false" initially because I do not want the polling to start unless the button was clicked (to reduce unnecessary polling). The system is building on richfaces/seam. Thanks!

    Read the article

  • Duplicate Items Using Join in NHibernate Map

    - by Colin Bowern
    I am trying to retrieve the individual detail rows without having to create an object for the parent. I have a map which joins a parent table with the detail to achieve this: Table("UdfTemplate"); Id(x => x.Id, "Template_Id"); Map(x => x.FieldCode, "Field_Code"); Map(x => x.ClientId, "Client_Id"); Join("UdfFields", join => { join.KeyColumn("Template_Id"); join.Map(x => x.Name, "COLUMN_NAME"); join.Map(x => x.Label, "DISPLAY_NAME"); join.Map(x => x.IsRequired, "MANDATORY_FLAG") .CustomType<YesNoType>(); join.Map(x => x.MaxLength, "DATA_LENGTH"); join.Map(x => x.Scale, "DATA_SCALE"); join.Map(x => x.Precision, "DATA_PRECISION"); join.Map(x => x.MinValue, "MIN_VALUE"); join.Map(x => x.MaxValue, "MAX_VALUE"); }); When I run the query in NH using: Session.CreateCriteria(typeof(UserDefinedField)) .Add(Restrictions.Eq("FieldCode", code)).List<UserDefinedField>(); I get back the first row three times as opposed to the three individual rows it should return. Looking at the SQL trace in NH Profiler the query appears to be correct. The problem feels like it is in the mapping but I am unsure how to troubleshoot that process. I am about to turn on logging to see what I can find but I thought I would post here in case someone with experience mapping joins knows where I am going wrong.

    Read the article

  • How can I get at the raw bytes of the request in WCF?

    - by Gregory Higley
    For logging purposes, I want to get at the raw request sent to my RESTful web service implemented in WCF. I have already implemented IDispatchMessageInspector. In my implementation of AfterReceiveRequest, I want to spit out the raw bytes of the message even (and especially) if the content of the message is invalid. This is for debugging purposes. My service works perfectly already, but it is often helpful when working through problems with clients who are trying to call the service to know what it was they sent, i.e., the raw bytes. For example, let's say that instead of sending a well-formed XML document, they post the string "your mama" to my service endpoint. I want to see that that's what they did. Unfortunately using MessageBuffer::CreateBufferedCopy() won't work unless the contents of the message are already well-formed XML. Here's (roughly) what I already have in my implementation of AfterReceiveRequest: // The immediately following line raises an exception if the message // does not contain valid XML. This is uncool because I want // the raw bytes regardless of whether they are valid or not. using (MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue)) { using (MemoryStream stream = new MemoryStream()) using (StreamReader reader = new StreamReader(stream)) { buffer.WriteMessage(stream); stream.Position = 0; Trace.TraceInformation(reader.ReadToEnd()); } request = buffer.CreateMessage(); } My guess here is that I need to get at the raw request before it becomes a Message. This will most likely have to be done at a lower level in the WCF stack than an IDispatchMessageInspector. Anyone know how to do this?

    Read the article

  • Two different seeds producing the same "random" sequence

    - by Ruud Lenders
    Maybe there is a very logic explanation for this, but I just can't seem to understand why the seeds 0 and 2,147,483,647 produce the same "random" sequence, using .NET's Random Class (System). Quick code example: ushort len = 8; Random r0 = new Random(0), r1 = new Random(1), r2 = new Random(int.MaxValue); //2,147,483,647 byte[] b0 = new byte[len], b1 = new byte[len], b2 = new byte[len]; r0.NextBytes(b0); r1.NextBytes(b1); r2.NextBytes(b2); for (int i = 0; i < len; i++) { System.Diagnostics.Debug.WriteLine("{0}\t\t{1}\t\t{2}", b0[i], b1[i], b2[i]); } Console.ReadLine(); Output: 26 70 26 12 208 12 70 134 76 111 130 111 93 64 93 117 151 115 228 228 228 216 163 216 As you can see, the first and the third sequence are the same. Can someone please explain this to me?

    Read the article

  • UISlider how to set the initial value

    - by slim
    I'm pretty new at this iphone dev stuff and i'm working on some existing code at a company. The uislider i'm trying to set the initial value on is actually in a UITableViewCell and is a custom control. I was thinking in the cell init cell = (QuantitiesCell *)[self loadCellWithNibName:@"QuantitiesCell" forTableView:ltableView withStyle:UITableViewCellStyleDefault]; i could just call something like ((QuantitiesCell *)cell).value = 5; The actual QuantitiesCell class has the member value and the following functions -(void)initCell;{ if (listOfValues == nil) { [self initListOfValues]; } quantitiesSLider.maximumValue = [listOfValues count]-1; quantitiesSLider.minimumValue = 0; quantitiesSLider.value = self.value; } -(void)initListOfValues;{ listOfValues = [[NSMutableArray alloc] initWithCapacity:10]; int j =0; for (float i = minValue; i <= maxValue+increment; i=i+increment) { [listOfValues addObject:[NSNumber numberWithFloat: i]]; if (i == value) { quantitiesSLider.value = j; } j++; } } like i said, i'm pretty new at this so if i need to post more of the code to show whats going to get help, let me know, This slider always is defaulting to 1, the slider ranges usually from 1-10, and i want to set it to a specific value of the item i'm trying to edit.

    Read the article

  • WPF - Why doesn't Microsoft supply a decent set of most-used controls ?

    - by IUsedToBeAPygmy
    I've been playing with WPF for some months now, and I quite like it. But one of the things I don't get is why MS doesn't put a little more effort in helping developers by supplying basic controls, and I need to get this off my chest :) For example, I figure most applications somewhere will need to let you edit some properties - for configuration or whatever. What would be the most used types in a proprety-grid editor ? text numbers (byte, float/double, int, etc) colors ....etc. So why isn't there even something as simple as a control to edit numbers ? Like a generic NumericUpDown control that allows you to type in numbers (no text, no pasting invalid input) or spin them up/down according to some given rules (decimal, floating point, min/maxvalue) ? Why isn't there a generic colorpicker, so people get the same user-experience in every application ? Why isn't there a standard implementation of a SearchTextBox, a BreadCrumb-control, or all these other standard control types users have gotten accustomed to the last 10 years ? (..but at least they DID have the time to implement a generic splashscreen - because everyone knows that greatly increases user-productivity....) The well-known ideal is always to give people the same user-experience over different applications. So even if some of those controls would be easy to make - it would be preferred to have one version over different applications. I see people all over the internet trying to do the same stuff over and over again. Okay, so MS started a WPF Toolkit project on Codeplex that tries to implement some controls, but only did so half-heartedly and is completely dead by now (last update of the roadmap dates back to Mar 21 2009). The result of this is that a lot of people starting a WPF-project end up spending a lot of time on trying to figure out how to create some generic controls and get really frustrated. Wasn't the mantra "Developers, developers, developers!" ..? /Rant

    Read the article

  • Jquery and PHP rating function problem

    - by Sergio
    I know that I was already posted similar question but I just can't find the answer and figure it out how to solve this problem. I'm trying to customize Jquery Star Rating plugin (link text) but I do not know what to do to show the message based on response of PHP script. Jquery script successfully send rating data to PHP scripts that query the database and based on that echo message of proper or improper rating. What should I add to an existing JS code so I can get echo from PHP and base on that write a message on some DIV beside rating star? Jquery: $('#gal').rating('gl.php?gal_no=<?=$gal_no;?>&id=<?=$id;?>', {maxvalue:10,increment:.5, curvalue: <?=$cur;?>}); Simplified 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? Something 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'}); } If someone has an idea...I would appreciate it.

    Read the article

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