Search Results

Search found 121 results on 5 pages for 'addrange'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • List<T>.AddRange is causing a brief Update/Draw delay

    - by Justin Skiles
    I have a list of entities which implement an ICollidable interface. This interface is used to resolve collisions between entities. My entities are thus: Players Enemies Projectiles Items Tiles On each game update (about 60 t/s), I am clearing the list and adding the current entities based on the game state. I am accomplishing this via: collidableEntities.Clear(); collidableEntities.AddRange(players); collidableEntities.AddRange(enemies); collidableEntities.AddRange(projectiles); collidableEntities.AddRange(items); collidableEntities.AddRange(camera.VisibleTiles); Everything works fine until I add the visible tiles to the list. The first ~1-2 seconds of running the game loop causes a visible hiccup that delays drawing (so I can see a jitter in the rendering). I can literally remove/add the line that adds the tiles and see the jitter occur and not occur, so I have narrowed it down to that line. My question is, why? The list of VisibleTiles is about 450-500 tiles, so it's really not that much data. Each tile contains a Texture2D (image) and a Vector2 (position) to determine what is rendered and where. I'm going to keep looking, but from the top of my head, I can't understand why only the first 1-2 seconds hiccups but is then smooth from there on out. Any advice is appreciated.

    Read the article

  • LIST<> AddRange throwing ArgumentException

    - by Tim
    Hi all, I have a particular method that is occasionally crashing with an ArgumentException: Destination array was not long enough. Check destIndex and length, and the array's lower bounds.: at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable) at System.Collections.Generic.List`1.CopyTo(T[] array, Int32 arrayIndex) at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection) The code that is causing this crash looks something like this: List<MyType> objects = new List<MyType>(100); objects = FindObjects(someParam); objects.AddRange(FindObjects(someOtherParam); According to MSDN, List<.AddRange() should automatically resize itself as needed: If the new Count (the current Count plus the size of the collection) will be greater than Capacity, the capacity of the List<(Of <(T)) is increased by automatically reallocating the internal array to accommodate the new elements, and the existing elements are copied to the new array before the new elements are added. Can someone think of a circumstance in which AddRange could throw this type of exception?

    Read the article

  • List.AddRange inline declaration

    - by AJ
    Hello, This may seem an easy question, but not to me, also a search has led to nothing. Up until now the only .net programming I have done is with Delphi Prism. With Prism I can do things like: var l := new List<String>(['A','B','C']); or var l := new List<String>; l.AddRange(['A','B','C']; but can I do a similar thing in C#, or do I have to do it like: var a = new String[] {"A","B","C"}; var l = new List<String>(a); Thanks, AJ

    Read the article

  • Designer throwing up an error!

    - by Luke
    I have a dropdown list that I want to show only certain options when a bool is true of false. if (mainForm.boolEdit == true) { this.cmbStatusBox.Items.AddRange(new object[] { "Cooking", "In-transit", "Delivered"}); } else { this.cmbStatusBox.Items.AddRange(new object[] { "Ordered"}); } I put this code into the saveForm.Designer.cs and got the following error: The designer cannot process the code at line 205: if (mainForm.boolEdit == true) { this.cmbStatusBox.Items.AddRange(new object[] { "Cooking", "In-transit", "Delivered"}); } else { this.cmbStatusBox.Items.AddRange(new object[] { "Ordered"}); } The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again. What are my alternatives?

    Read the article

  • Select rows from table1 and all the children from table2 into an object

    - by Patrick
    I want to pull data from table "Province_Notifiers" and also fetch all corresponding items from table "Province_Notifier_Datas". The table "Province_Notifier" has a guid to identify it (PK), table "Province_Notifier_Datas" has a column called BelongsToProvinceID witch is a foreign key to the "Province_Notifier" tables guid. I tried something like this: var records = from data in ctx.Province_Notifiers where DateTime.Now >= data.SendTime && data.Sent == false join data2 in ctx.Province_Notifier_Datas on data.Province_ID equals data2.BelongsToProvince_ID select new Province_Notifier { Email = data.Email, Province_ID = data.Province_ID, ProvinceName = data.ProvinceName, Sent = data.Sent, UserName = data.UserName, User_ID = data.User_ID, Province_Notifier_Datas = (new List<Province_Notifier_Data>().AddRange(data2)) }; This line is not working and i am trying to figure out how topull the data from table2 into that Province_Notifier_Datas variable. Province_Notifier_Datas = (new List<Province_Notifier_Data>().AddRange(data2)) I can add a record easily by adding the second table row into the Province_Notifier_Datas but i can't fetch it back. Province_Notifier dbNotifier = new Province_Notifier(); // set some values for dbNotifier dbNotifier.Province_Notifier_Datas.Add( new Province_Notifier_Data { BelongsToProvince_ID = userInput.Value.ProvinceId, EventText = GenerateNotificationDetail(notifierDetail) }); This works and inserts the data correctly into both tables. Edit: These error messages is thrown: Cannot convert from 'Province_Notifier_Data' to 'System.Collections.Generic.IEnumerable' If i look in Visual Studio, the variable "Province_Notifier_Datas" is of type System.Data.Linq.EntitySet The best overloaded method match for 'System.Collections.Generic.List.AddRange(System.Collections.Generic.IEnumerable)' has some invalid arguments Edit: var records = from data in ctx.Province_Notifiers where DateTime.Now >= data.SendTime && data.Sent == false join data2 in ctx.Province_Notifier_Datas on data.Province_ID equals data2.BelongsToProvince_ID into data2list select new Province_Notifier { Email = data.Email, Province_ID = data.Province_ID, ProvinceName = data.ProvinceName, Sent = data.Sent, UserName = data.UserName, User_ID = data.User_ID, Province_Notifier_Datas = new EntitySet<Province_Notifier_Data>().AddRange(data2List) }; Error 3 The name 'data2List' does not exist in the current context.

    Read the article

  • Foreach over a collection of IEnumerables

    - by sdr
    I have 3 IEnumerables that I want to iterate over. I want to do something like this: IEnumerable<Car> redCars = GetRedCars(); IEnumerable<Car> greenCars = GetGreenCars(); IEnumerable<Car> blueCars = GetBlueCars(); foreach(Car c in (redCars + greenCars + blueCars)) { c.DoSomething(); } ... The best way I can think of is: ... List<Car> allCars = new List(); allCars.AddRange(redCars); allCars.AddRange(greenCars); allCars.AddRange(blueCars); foreach(car in allCars) { ... } ... Is there a more concise way to do this? Seems like combinding IEnumberables should be trivial.

    Read the article

  • Combobox population problem

    - by Luke
    So I have a combobox - the designer code: this.cmbStatusBox.Items.AddRange(new object[] { "Ordered", "Cooking", "In-transit", "Delivered"}); The formload code: if (mainForm.boolEdit == true) { this.cmbStatusBox.Items.AddRange(new object[] { "Cooking", "In-transit", "Delivered"}); } else { this.cmbStatusBox.Items.AddRange(new object[] { "Ordered"}); } As you can see, I am trying to make the combobox have different values. As things stand, i get both whats in the designer and in formload in the comboboxes. How can i stop this? I also have an edit function, so when i edit a record, i want the combo box to be populated by what is already saved. Just a random question, can you stop the user entering a value that isn't in the combo box? Thankyou

    Read the article

  • How to improve this piece of code

    - by user303518
    Can anyone help me on this. It may be very frustrating for you all. But I want you guys to take a moment to look at the code below and please tell me all the things that are wrong in the below piece of code. You can copy it into your visual studio to analyze this better. You don’t have to make this code compile. My task is to get the following things: Most obvious mistakes with this code All the things that are wrong/bad practices with the code below Modify/Write an optimized version of this code. Keep in mind, the code DOES NOT need to compile. Reduce the number of lines of code You should NEVER try to implement something like below: public List<ValidationErrorDto> ProcessEQuote(string eQuoteXml, long programUniversalID) { // Get Program Info. DataTable programs = GetAllPrograms(); DataRow[] programRows = programs.Select(string.Format("ProgramUniversalID = {0}", programUniversalID)); long programID = (long)programRows[0]["ProgramID"]; string programName = (string)programRows[0]["Description"]; // Get Config file values. string fromEmail = ConfigurationManager.AppSettings["eQuotesFromEmail"]; string technicalSupportPhone = ConfigurationManager.AppSettings["TechnicalSupportPhone"]; string fromEmailDisplayName = string.IsNullOrEmpty(ConfigurationManager.AppSettings["eQuotesFromDisplayName"]) ? null : string.Format(ConfigurationManager.AppSettings["eQuotesFromDisplayName"], programName); string itEmail = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["ITEmail"]) ? ConfigurationManager.AppSettings["ITEmail"] : string.Empty; string itName = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["ITName"]) ? ConfigurationManager.AppSettings["ITName"] : "IT"; try { List<ValidationErrorDto> allValidationErrors = new List<ValidationErrorDto>(); List<ValidationErrorDto> validationErrors = new List<ValidationErrorDto>(); if (validationErrors.Count == 0) { validationErrors.AddRange(ValidateEQuoteXmlAgainstSchema(eQuoteXml)); if (validationErrors.Count == 0) { XmlDocument eQuoteXmlDoc = new XmlDocument(); eQuoteXmlDoc.LoadXml(eQuoteXml); XmlElement rootElement = eQuoteXmlDoc.DocumentElement; XmlNodeList quotesList = rootElement.SelectNodes("Quote"); foreach (XmlNode node in quotesList) { // Each node should be a quote node but to be safe, check if (node.Name == "Quote") { string groupName = node.SelectSingleNode("Group/GroupName").InnerText; string groupCity = node.SelectSingleNode("Group/GroupCity").InnerText; string groupPostalCode = node.SelectSingleNode("Group/GroupZipCode").InnerText; string groupSicCode = node.SelectSingleNode("Group/GroupSIC").InnerText; string generalAgencyLicenseNumber = node.SelectSingleNode("Group/GALicenseNbr").InnerText; string brokerName = node.SelectSingleNode("Group/BrokerName").InnerText; string deliverToEmailAddress = node.SelectSingleNode("Group/ReturnEmailAddress").InnerText; string brokerEmail = node.SelectSingleNode("Group/BrokerEmail").InnerText; string groupEligibleEmployeeCountString = node.SelectSingleNode("Group/GroupNbrEmployees").InnerText; string quoteEffectiveDateString = node.SelectSingleNode("Group/QuoteEffectiveDate").InnerText; string salesRepName = node.SelectSingleNode("Group/SalesRepName").InnerText; string salesRepPhone = node.SelectSingleNode("Group/SalesRepPhone").InnerText; string salesRepEmail = node.SelectSingleNode("Group/SalesRepEmail").InnerText; string brokerLicenseNumber = node.SelectSingleNode("Group/BrokerLicenseNbr").InnerText; DateTime? quoteEffectiveDate = null; int eligibleEmployeeCount = int.Parse(groupEligibleEmployeeCountString); DateTime quoteEffectiveDateOut; if (!DateTime.TryParse(quoteEffectiveDateString, out quoteEffectiveDateOut)) validationErrors.Add(ValidationHelper.CreateValidationError((long)QuoteField.EffectiveDate, "Quote Effective Date", ValidationErrorDto.ValueOutOfRange, false, ValidationHelper.CreateValidationContext(Entity.QuoteDetail, "Quote"))); else quoteEffectiveDate = quoteEffectiveDateOut; Dictionary<string, string> replacementCodeValues = new Dictionary<string, string>(); if (string.IsNullOrEmpty(Resources.ParameterMessageKeys.ResourceManager.GetString("GroupName"))) throw new InvalidOperationException("GroupName key is not configured"); replacementCodeValues.Add(Resources.ParameterMessageKeys.GroupName, groupName); replacementCodeValues.Add(Resources.ParameterMessageKeys.ProgramName, programName); replacementCodeValues.Add(Resources.ParameterMessageKeys.SalesRepName, salesRepName); replacementCodeValues.Add(Resources.ParameterMessageKeys.SalesRepPhone, salesRepPhone); replacementCodeValues.Add(Resources.ParameterMessageKeys.SalesRepEmail, salesRepEmail); replacementCodeValues.Add(Resources.ParameterMessageKeys.TechnicalSupportPhone, technicalSupportPhone); replacementCodeValues.Add(Resources.ParameterMessageKeys.EligibleEmployeCount, eligibleEmployeeCount.ToString()); // Retrieve the CityID and StateID long? cityID = null; long? stateID = null; DataSet citiesAndStates = Addresses.GetCitiesAndStatesFromPostalCode(groupPostalCode); DataTable cities = citiesAndStates.Tables[0]; DataTable states = citiesAndStates.Tables[1]; DataRow[] cityRows = cities.Select(string.Format("Name = '{0}'", groupCity)); if (cityRows.Length > 0) { cityID = (long)cityRows[0]["CityID"]; DataRow[] stateRows = states.Select(string.Format("CityID = {0}", cityID)); if (stateRows.Length > 0) stateID = (long)stateRows[0]["StateID"]; } // If the StateID does not exist, then we cannot get the GeneralAgency, so set a validation error and do not contine. // Else, Continue and look for an General Agency. If a GA was found, look for or create a Broker. Then look for or create a Prospect Group // Then using the info, create a quote. if (!stateID.HasValue) validationErrors.Add(ValidationHelper.CreateValidationError((long)ProspectGroupField.State, "Prospect Group State", ValidationErrorDto.RequiredFieldMissing, false, ValidationHelper.CreateValidationContext(Entity.ProspectGroup, "Prospect Group"))); bool brokerValidationError = false; SalesRepDto salesRep = GetSalesRepByEmail(salesRepEmail, ref validationErrors); if (salesRep == null) { string exceptionMessage = "Sales Rep Not found in Opportunity System. Please make sure Sales Rep is present in the system by adding the sales rep in AWP SR Add Screen." + Environment.NewLine; exceptionMessage = exceptionMessage + " Sales Rep Name: " + salesRepName + Environment.NewLine; exceptionMessage = exceptionMessage + " Sales Rep Email: " + salesRepEmail + Environment.NewLine; exceptionMessage = exceptionMessage + " Module : E-Quote Service" + Environment.NewLine; throw new Exception(exceptionMessage); } if (validationErrors.Count == 0) { // Note that StateID and EffectiveDate should be valid at this point. If it weren't there would be validation errors. // Find General Agency long? generalAgencyID; validationErrors.AddRange(GetEQuoteGeneralAgency(generalAgencyLicenseNumber, stateID.Value, out generalAgencyID)); // If GA was found, check for Broker. if (validationErrors.Count == 0 && generalAgencyID.HasValue) { Dictionary<string, string> brokerNameParts = ContactHelper.GetNamePartsFromFullName(brokerName); long? brokerID; validationErrors.AddRange(CreateEQuoteBroker(brokerNameParts["FirstName"], brokerNameParts["LastName"], brokerEmail, brokerLicenseNumber, stateID.Value, generalAgencyID.Value, salesRep, programID, out brokerID)); // If Broker was found but had validation errors if (validationErrors.Count > 0) { DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteBrokerValidationFailureMessageEmail, replacementCodeValues); brokerValidationError = true; } // If Broker was found, check for Prospect Group if (validationErrors.Count == 0 && brokerID.HasValue) { long? prospectGroupID; validationErrors.AddRange(CreateEQuoteProspectGroup(groupName, cityID, stateID, groupPostalCode, groupSicCode, brokerID.Value, out prospectGroupID)); if (validationErrors.Count == 0 && prospectGroupID.HasValue) { if (validationErrors.Count == 0) { long? quoteID; validationErrors.AddRange(CreateEQuote(programID, prospectGroupID.Value, generalAgencyID.Value, quoteEffectiveDate.Value, eligibleEmployeeCount, deliverToEmailAddress, node.SelectNodes("Employees/Employee"), deliverToEmailAddress, out quoteID)); if (validationErrors.Count == 0 && quoteID.HasValue) { QuoteFromServiceDto quoteFromService = GetQuoteByQuoteID(quoteID.Value); // Generate Pre-Message replacementCodeValues.Add(Resources.ParameterMessageKeys.QuoteNumber, string.Format("{0}.{1}", quoteFromService.QuoteNumber, quoteFromService.QuoteVersion)); replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, brokerName); replacementCodeValues.Add(Resources.ParameterMessageKeys.LicenseNumbers, brokerLicenseNumber); DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, deliverToEmailAddress, DocumentType.EQuotePreMessageEmail, replacementCodeValues); bool quoteGenerated = false; try { quoteGenerated = GenerateAndDeliverInitialQuote(quoteID.Value); } catch (Exception exception) { TraceLogger.LogException(exception, LoggingCategory); if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Name)) replacementCodeValues[Resources.ParameterMessageKeys.Name] = itName; else replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, itName); if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Errors)) replacementCodeValues[Resources.ParameterMessageKeys.Errors] = string.Format("Errors:\r\n:{0}", exception); else replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, string.Format("Errors:\r\n:{0}", exception)); DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteSystemFailureMessageEmail, replacementCodeValues); } if (!quoteGenerated) { // Generate System Failure Message if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Name)) replacementCodeValues[Resources.ParameterMessageKeys.Name] = brokerName; else replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, brokerName); if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Errors)) replacementCodeValues[Resources.ParameterMessageKeys.Errors] = string.Empty; else replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, string.Empty); DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteSystemFailureMessageEmail, replacementCodeValues); } } } } } } } //if (validationErrors.Count > 0) // Per spec, if Broker Validation returned an error we already sent an email, don't send another generic one if (validationErrors.Count > 0 && (!brokerValidationError)) { StringBuilder errorString = new StringBuilder(); foreach (ValidationErrorDto validationError in validationErrors) errorString = errorString.AppendLine(string.Format(" - {0}", ValidationHelper.GetValidationErrorReason(validationError, true))); replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, errorString.ToString()); if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Name)) replacementCodeValues[Resources.ParameterMessageKeys.Name] = brokerName; else replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, brokerName); // HACK: If there is no effective date, then use Today's date. Do we care about the effecitve dat on validation message? if (quoteEffectiveDate.HasValue) DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteValidationFailureMessageEmail, replacementCodeValues); else DeliverEmailMessage(programID, DateTime.Now, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteValidationFailureMessageEmail, replacementCodeValues); } allValidationErrors.AddRange(validationErrors); validationErrors.Clear(); } } } else { // Use todays date as the effective date. Dictionary<string, string> replacementCodeValues = new Dictionary<string, string>(); StringBuilder errorString = new StringBuilder(); foreach (ValidationErrorDto validationError in validationErrors) errorString = errorString.AppendLine(string.Format(" - {0}", ValidationHelper.GetValidationErrorReason(validationError, true))); replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, string.Format("The following validation errors occurred: \r\n{0}", errorString)); replacementCodeValues.Add(Resources.ParameterMessageKeys.ProgramName, programName); replacementCodeValues.Add(Resources.ParameterMessageKeys.GroupName, "Group"); replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, itName); DeliverEmailMessage(programID, DateTime.Now, fromEmail, null, itEmail, DocumentType.EQuoteSystemFailureMessageEmail, replacementCodeValues); allValidationErrors.AddRange(validationErrors); validationErrors.Clear(); } } return allValidationErrors; } catch (Exception exception) { TraceLogger.LogException(exception, LoggingCategory); // Use todays date as the effective date. Dictionary<string, string> replacementCodeValues = new Dictionary<string, string>(); replacementCodeValues.Add(Resources.ParameterMessageKeys.ProgramName, programName); replacementCodeValues.Add(Resources.ParameterMessageKeys.GroupName, "Group"); replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, itName); replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, string.Format("Errors:\r\n:{0}", exception)); DeliverEmailMessage(programID, DateTime.Now, fromEmail, null, itEmail, DocumentType.EQuoteSystemFailureMessageEmail, replacementCodeValues); throw new FaultException(exception.ToString()); } }

    Read the article

  • Jumbled byte array after using TcpClient and TcpListener

    - by Dylan
    I want to use the TcpClient and TcpListener to send an mp3 file over a network. I implemented a solution of this using sockets, but there were some issues so I am investigating a new/better way to send a file. I create a byte array which looks like this: length_of_filename|filename|file This should then be transmitted using the above mentioned classes, yet on the server side the byte array I read is completely messed up and I'm not sure why. The method I use to send: public static void Send(String filePath) { try { IPEndPoint endPoint = new IPEndPoint(Settings.IpAddress, Settings.Port + 1); Byte[] fileData = File.ReadAllBytes(filePath); FileInfo fi = new FileInfo(filePath); List<byte> dataToSend = new List<byte>(); dataToSend.AddRange(BitConverter.GetBytes(Encoding.Unicode.GetByteCount(fi.Name))); // length of filename dataToSend.AddRange(Encoding.Unicode.GetBytes(fi.Name)); // filename dataToSend.AddRange(fileData); // file binary data using (TcpClient client = new TcpClient()) { client.Connect(Settings.IpAddress, Settings.Port + 1); // Get a client stream for reading and writing. using (NetworkStream stream = client.GetStream()) { // server is ready stream.Write(dataToSend.ToArray(), 0, dataToSend.ToArray().Length); } } } catch (ArgumentNullException e) { Debug.WriteLine(e); } catch (SocketException e) { Debug.WriteLine(e); } } } Then on the server side it looks as follows: private void Listen() { TcpListener server = null; try { // Setup the TcpListener Int32 port = Settings.Port + 1; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[1024]; List<byte> data; // Enter the listening loop. while (true) { Debug.WriteLine("Waiting for a connection... "); string filePath = string.Empty; // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. using (TcpClient client = server.AcceptTcpClient()) { Debug.WriteLine("Connected to client!"); data = new List<byte>(); // Get a stream object for reading and writing using (NetworkStream stream = client.GetStream()) { // Loop to receive all the data sent by the client. while ((stream.Read(bytes, 0, bytes.Length)) != 0) { data.AddRange(bytes); } } } int fileNameLength = BitConverter.ToInt32(data.ToArray(), 0); filePath = Encoding.Unicode.GetString(data.ToArray(), 4, fileNameLength); var binary = data.GetRange(4 + fileNameLength, data.Count - 4 - fileNameLength); Debug.WriteLine("File successfully downloaded!"); // write it to disk using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Append))) { writer.Write(binary.ToArray(), 0, binary.Count); } } } catch (Exception ex) { Debug.WriteLine(ex); } finally { // Stop listening for new clients. server.Stop(); } } Can anyone see something that I am missing/doing wrong?

    Read the article

  • Bone creation in XNA Content Pipeline

    - by cod3monk3y
    I'm trying to manually create a ModelContent instance that includes custom Bone data in a custom ContentProcessor in the XNA Content Pipeline. I can't seem to create or assign manually created bone data due to either private constructors or read-only collections (at every turn). The code I have right now that creates a single triangle ModelContent that I'd like to create a bone for is: MeshContent mc = new MeshContent(); mc.Positions.Add(new Vector3(-10, 0, 0)); mc.Positions.Add(new Vector3(0, 10, 0)); mc.Positions.Add(new Vector3(10, 0, 0)); GeometryContent gc = new GeometryContent(); gc.Indices.AddRange(new int[] { 0, 1, 2 }); gc.Vertices.AddRange(new int[] { 0, 1, 2 }); mc.Geometry.Add(gc); // Create normals MeshHelper.CalculateNormals(mc, true); // finally, convert it to a model ModelContent model = context.Convert<MeshContent, ModelContent>(mc, "ModelProcessor"); The documentation on XNA is amazingly sparse. I've been referencing the class diagrams created by DigitalRune and Sean Hargreaves blog, but I haven't found anything on creating bone content. Once the ModelContent is created, it's not possible to add bones because the Bones collection is read-only. And it seems the only way to create the ModelContent instance is to call the standard ModelProcessor via ContentProcessorContext.Convert. So it's a bit of a catch-22. The BoneContent class has a constructor but no methods except those inherited from NodeContent... though now (true to form) maybe I've realized the solution by asking the question. Should I create a root NodeContent with two children: one MeshContent and one BoneContent as the root of my skeleton; then pass the root NodeContent to ContentProcessorContext.Convert? Off to try that now...

    Read the article

  • Value cannot be null, ArgumentNullException

    - by Wooolie
    I am currently trying to return an array which contains information about a seat at a theate such as Seat number, Name, Price and Status. I am using a combobox where I want to list all vacant or reserved seats based upon choice. When I choose reserved seats in my combobox, I call upon a method using AddRange. This method is supposed to loop through an array containing all seats and their information. If a seat is Vacant, I add it to an array. When all is done, I return this array. However, I am dealing with a ArgumentNullException. MainForm namespace Assignment4 { public partial class MainForm : Form { // private const int totNumberOfSeats = 240; private SeatManager seatMngr; private const int columns = 10; private const int rows = 10; public enum DisplayOptions { AllSeats, VacantSeats, ReservedSeats } public MainForm() { InitializeComponent(); seatMngr = new SeatManager(rows, columns); InitializeGUI(); } /// <summary> /// Fill the listbox with information from the beginning, /// let the user be able to choose from vacant seats. /// </summary> private void InitializeGUI() { rbReserve.Checked = true; txtName.Text = string.Empty; txtPrice.Text = string.Empty; lblTotalSeats.Text = seatMngr.GetNumOfSeats().ToString(); cmbOptions.Items.AddRange(Enum.GetNames(typeof(DisplayOptions))); cmbOptions.SelectedIndex = 0; UpdateGUI(); } /// <summary> /// call on methods ValidateName and ValidatePrice with arguments /// </summary> /// <param name="name"></param> /// <param name="price"></param> /// <returns></returns> private bool ValidateInput(out string name, out double price) { bool nameOK = ValidateName(out name); bool priceOK = ValidatePrice(out price); return nameOK && priceOK; } /// <summary> /// Validate name using inputUtility, show error if input is invalid /// </summary> /// <param name="name"></param> /// <returns></returns> private bool ValidateName(out string name) { name = txtName.Text.Trim(); if (!InputUtility.ValidateString(name)) { //inform user MessageBox.Show("Input of name is Invalid. It can not be empty, " + Environment.NewLine + "and must have at least one character.", " Error!"); txtName.Focus(); txtName.Text = " "; txtName.SelectAll(); return false; } return true; } /// <summary> /// Validate price using inputUtility, show error if input is invalid /// </summary> /// <param name="price"></param> /// <returns></returns> private bool ValidatePrice(out double price) { // show error if input is invalid if (!InputUtility.GetDouble(txtPrice.Text.Trim(), out price, 0)) { //inform user MessageBox.Show("Input of price is Invalid. It can not be less than 0, " + Environment.NewLine + "and must not be empty.", " Error!"); txtPrice.Focus(); txtPrice.Text = " "; txtPrice.SelectAll(); return false; } return true; } /// <summary> /// Check if item is selected in listbox /// </summary> /// <returns></returns> private bool CheckSelectedIndex() { int index = lbSeats.SelectedIndex; if (index < 0) { MessageBox.Show("Please select an item in the box"); return false; } else return true; } /// <summary> /// Call method ReserveOrCancelSeat when button OK is clicked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOK_Click(object sender, EventArgs e) { ReserveOrCancelSeat(); } /// <summary> /// Reserve or cancel seat depending on choice the user makes. Update GUI after choice. /// </summary> private void ReserveOrCancelSeat() { if (CheckSelectedIndex() == true) { string name = string.Empty; double price = 0.0; int selectedSeat = lbSeats.SelectedIndex; bool reserve = false; bool cancel = false; if (rbReserve.Checked) { DialogResult result = MessageBox.Show("Do you want to continue?", "Approve", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { if (ValidateInput(out name, out price)) { reserve = seatMngr.ReserveSeat(name, price, selectedSeat); if (reserve == true) { MessageBox.Show("Seat has been reserved"); UpdateGUI(); } else { MessageBox.Show("Seat has already been reserved"); } } } } else { DialogResult result = MessageBox.Show("Do you want to continue?", "Approve", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { cancel = seatMngr.CancelSeat(selectedSeat); if (cancel == true) { MessageBox.Show("Seat has been cancelled"); UpdateGUI(); } else { MessageBox.Show("Seat is already vacant"); } } } UpdateGUI(); } } /// <summary> /// Update GUI with new information. /// </summary> /// <param name="customerName"></param> /// <param name="price"></param> private void UpdateGUI() { lbSeats.Items.Clear(); lbSeats.Items.AddRange(seatMngr.GetSeatInfoString()); lblVacantSeats.Text = seatMngr.GetNumOfVacant().ToString(); lblReservedSeats.Text = seatMngr.GetNumOfReserved().ToString(); if (rbReserve.Checked) { txtName.Text = string.Empty; txtPrice.Text = string.Empty; } } /// <summary> /// set textboxes to false if cancel reservation button is checked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void rbCancel_CheckedChanged_1(object sender, EventArgs e) { txtName.Enabled = false; txtPrice.Enabled = false; } /// <summary> /// set textboxes to true if reserved radiobutton is checked /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void rbReserve_CheckedChanged_1(object sender, EventArgs e) { txtName.Enabled = true; txtPrice.Enabled = true; } /// <summary> /// Make necessary changes on the list depending on what choice the user makes. Show only /// what the user wants to see, whether its all seats, reserved seats or vacant seats only. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmbOptions_SelectedIndexChanged(object sender, EventArgs e) { if (cmbOptions.SelectedIndex == 0 && rbReserve.Checked) //All seats visible. { UpdateGUI(); txtName.Enabled = true; txtPrice.Enabled = true; btnOK.Enabled = true; } else if (cmbOptions.SelectedIndex == 0 && rbCancel.Checked) { UpdateGUI(); txtName.Enabled = false; txtPrice.Enabled = false; btnOK.Enabled = true; } else if (cmbOptions.SelectedIndex == 1) //Only vacant seats visible. { lbSeats.Items.Clear(); lbSeats.Items.AddRange(seatMngr.ReturnVacantSeats()); // Value cannot be null txtName.Enabled = false; txtPrice.Enabled = false; btnOK.Enabled = false; } else if (cmbOptions.SelectedIndex == 2) //Only reserved seats visible. { lbSeats.Items.Clear(); lbSeats.Items.AddRange(seatMngr.ReturnReservedSeats()); // Value cannot be null txtName.Enabled = false; txtPrice.Enabled = false; btnOK.Enabled = false; } } } } SeatManager namespace Assignment4 { class SeatManager { private string[,] nameList = null; private double[,] priceList = null; private string[,] seatList = null; private readonly int totCols; private readonly int totRows; /// <summary> /// Constructor with declarations of size for all arrays. /// </summary> /// <param name="totNumberOfSeats"></param> public SeatManager(int row, int cols) { totCols = cols; totRows = row; nameList = new string[row, cols]; priceList = new double[row, cols]; seatList = new string[row, cols]; for (int rows = 0; rows < row; rows++) { for (int col = 0; col < totCols; col++) { seatList[rows, col] = "Vacant"; } } } /// <summary> /// Check if index is within bounds of the array /// </summary> /// <param name="index"></param> /// <returns></returns> private bool CheckIndex(int index) { if (index >= 0 && index < nameList.Length) return true; else return false; } /// <summary> /// Return total number of seats /// </summary> /// <returns></returns> public int GetNumOfSeats() { int count = 0; for (int rows = 0; rows < totRows; rows++) { for (int cols = 0; cols < totCols; cols++) { count++; } } return count; } /// <summary> /// Calculate and return total number of reserved seats /// </summary> /// <returns></returns> public int GetNumOfReserved() { int totReservedSeats = 0; for (int rows = 0; rows < totRows; rows++) { for (int col = 0; col < totCols; col++) { if (!string.IsNullOrEmpty(nameList[rows, col])) { totReservedSeats++; } } } return totReservedSeats; } /// <summary> /// Calculate and return total number of vacant seats /// </summary> /// <returns></returns> public int GetNumOfVacant() { int totVacantSeats = 0; for (int rows = 0; rows < totRows; rows++) { for (int col = 0; col < totCols; col++) { if (string.IsNullOrEmpty(nameList[rows, col])) { totVacantSeats++; } } } return totVacantSeats; } /// <summary> /// Return formated string with info about the seat, name, price and its status /// </summary> /// <param name="index"></param> /// <returns></returns> public string GetSeatInfoAt(int index) { int cols = ReturnColumn(index); int rows = ReturnRow(index); string strOut = string.Format("{0,2} {1,10} {2,17} {3,20} {4,35:f2}", rows+1, cols+1, seatList[rows, cols], nameList[rows, cols], priceList[rows, cols]); return strOut; } /// <summary> /// Send an array containing all seats in the cinema /// </summary> /// <returns></returns> public string[] GetSeatInfoString() { int count = totRows * totCols; if (count <= 0) return null; string[] strSeatInfoStrings = new string[count]; for (int i = 0; i < totRows * totCols; i++) { strSeatInfoStrings[i] = GetSeatInfoAt(i); } return strSeatInfoStrings; } /// <summary> /// Reserve seat if seat is vacant /// </summary> /// <param name="name"></param> /// <param name="price"></param> /// <param name="index"></param> /// <returns></returns> public bool ReserveSeat(string name, double price, int index) { int cols = ReturnColumn(index); int rows = ReturnRow(index); if (string.IsNullOrEmpty(nameList[rows, cols])) { nameList[rows, cols] = name; priceList[rows, cols] = price; seatList[rows, cols] = "Reserved"; return true; } else return false; } public string[] ReturnVacantSeats() { int totVacantSeats = int.Parse(GetNumOfVacant().ToString()); string[] vacantSeats = new string[totVacantSeats]; for (int i = 0; i < vacantSeats.Length; i++) { if (GetSeatInfoAt(i) == "Vacant") { vacantSeats[i] = GetSeatInfoAt(i); } } return vacantSeats; } public string[] ReturnReservedSeats() { int totReservedSeats = int.Parse(GetNumOfReserved().ToString()); string[] reservedSeats = new string[totReservedSeats]; for (int i = 0; i < reservedSeats.Length; i++) { if (GetSeatInfoAt(i) == "Reserved") { reservedSeats[i] = GetSeatInfoAt(i); } } return reservedSeats; } /// <summary> /// Cancel seat if seat is reserved /// </summary> /// <param name="index"></param> /// <returns></returns> public bool CancelSeat(int index) { int cols = ReturnColumn(index); int rows = ReturnRow(index); if (!string.IsNullOrEmpty(nameList[rows, cols])) { nameList[rows, cols] = ""; priceList[rows, cols] = 0.0; seatList[rows, cols] = "Vacant"; return true; } else { return false; } } /// <summary> /// Convert index to row and return value /// </summary> /// <param name="index"></param> /// <returns></returns> public int ReturnRow(int index) { int vectorRow = index; int row; row = (int)Math.Ceiling((double)(vectorRow / totCols)); return row; } /// <summary> /// Convert index to column and return value /// </summary> /// <param name="index"></param> /// <returns></returns> public int ReturnColumn(int index) { int row = index; int col = row % totCols; return col; } } } In MainForm, this is where I get ArgumentNullException: lbSeats.Items.AddRange(seatMngr.ReturnVacantSeats()); And this is the method where the array is to be returned containing all vacant seats: public string[] ReturnVacantSeats() { int totVacantSeats = int.Parse(GetNumOfVacant().ToString()); string[] vacantSeats = new string[totVacantSeats]; for (int i = 0; i < vacantSeats.Length; i++) { if (GetSeatInfoAt(i) == "Vacant") { vacantSeats[i] = GetSeatInfoAt(i); } } return vacantSeats; }

    Read the article

  • Tree Node Checked behavior on a TreeView in Compact Framework 3.5 running on Windows Mobile 6.5

    - by Hydroslide
    I have been upgrading an existing .NET Windows Mobile application to use the 3.5 version of the compact framework and to run on Windows Mobile 6.5. I have a form with a TreeView. The TreeView.Checkboxes property is set to true so that each node has a check box. This gives no trouble in all previous versions of Windows Mobile. However, in version 6.5 when you click on a check box it appears to check and then uncheck instantaneously. But it only raises the AfterCheck event once. The only way I can get a check to stick is by double clicking it (which is the wrong behavior). Has anyone seen this behavior? Does anyone know of a workaround for it? I have included a simple test form. Dump this form into a Visual Studio 2008 Smart Device application targeted at Windows Mobile 6 to see what I mean. Public Class frmTree Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.new() ' This call is required by the Windows Form Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. End Sub 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) If disposing AndAlso components IsNot Nothing Then components.Dispose() End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer Friend WithEvents TreeView1 As System.Windows.Forms.TreeView Private mainMenu1 As System.Windows.Forms.MainMenu 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Dim TreeNode1 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("Node0") Dim TreeNode2 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("Node2") Dim TreeNode3 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("Node3") Dim TreeNode4 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("Node4") Dim TreeNode5 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("Node1") Dim TreeNode6 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("Node5") Dim TreeNode7 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("Node6") Dim TreeNode8 As System.Windows.Forms.TreeNode = New System.Windows.Forms.TreeNode("Node7") Me.mainMenu1 = New System.Windows.Forms.MainMenu Me.TreeView1 = New System.Windows.Forms.TreeView Me.SuspendLayout() ' 'TreeView1 ' Me.TreeView1.CheckBoxes = True Me.TreeView1.Location = New System.Drawing.Point(37, 41) Me.TreeView1.Name = "TreeView1" TreeNode2.Text = "Node2" TreeNode3.Text = "Node3" TreeNode4.Text = "Node4" TreeNode1.Nodes.AddRange(New System.Windows.Forms.TreeNode() {TreeNode2, TreeNode3, TreeNode4}) TreeNode1.Text = "Node0" TreeNode6.Text = "Node5" TreeNode7.Text = "Node6" TreeNode8.Text = "Node7" TreeNode5.Nodes.AddRange(New System.Windows.Forms.TreeNode() {TreeNode6, TreeNode7, TreeNode8}) TreeNode5.Text = "Node1" Me.TreeView1.Nodes.AddRange(New System.Windows.Forms.TreeNode() {TreeNode1, TreeNode5}) Me.TreeView1.Size = New System.Drawing.Size(171, 179) Me.TreeView1.TabIndex = 0 ' 'frmTree ' Me.AutoScaleDimensions = New System.Drawing.SizeF(96.0!, 96.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi Me.AutoScroll = True Me.ClientSize = New System.Drawing.Size(240, 268) Me.Controls.Add(Me.TreeView1) Me.Menu = Me.mainMenu1 Me.Name = "frmTree" Me.Text = "frmTree" Me.ResumeLayout(False) End Sub #End Region End Class

    Read the article

  • Custom Collection Implementing IEnumerable

    - by Burnzy
    I know that technically, an Interface is used for reading and not writting or editing however, I want to add an add and addrange function to the following class, here is what I currently have which is not working public class HrefCollection : IEnumerable<Href> { private IEnumerable<Href> hrefs; public IEnumerable<Href> Add( Href href ) { yield return href; } public IEnumerable<Href> AddRange( List<Href> hrefs ) { foreach( Href href in hrefs ) { yield return href; } } public IEnumerator<Href> GetEnumerator() { return hrefs.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return hrefs.GetEnumerator(); } } I'm not quite sure how to associate the yield return with the private list. Thanks for your help!

    Read the article

  • C# Property Access vs Interface Implementation

    - by ehdv
    I'm writing a class to represent a Pivot Collection, the root object recognized by Pivot. A Collection has several attributes, a list of facet categories (each represented by a FacetCategory object) and a list of items (each represented by a PivotItem object). Therefore, an extremely simplified Collection reads: public class Collection { private List<FacetCategory> categories; private List<PivotItem> items; // other attributes } What I'm unsure of is how to properly grant access to those two lists. Because declaration order of both facet categories and items is visible to the user, I can't use sets, but the class also shouldn't allow duplicate categories or items. Furthermore, I'd like to make the Collection object as easy to use as possible. So my choices are: Have Collection implement IList<PivotItem> and have accessor methods for FacetCategory: In this case, one would add an item to Collection foo by writing foo.Add(bar). This works, but since a Collection is equally both kinds of list making it only pass as a list for one type (category or item) seems like a subpar solution. Create nested wrapper classes for List (CategoryList and ItemList). This has the advantage of making a consistent interface but the downside is that these properties would no longer be able to serve as lists (because I need to override the non-virtual Add method I have to implement IList rather than subclass List. Implicit casting wouldn't work because that would return the Add method to its normal behavior. Also, for reasons I can't figure out, IList is missing an AddRange method... public class Collection { private class CategoryList: IList<FacetCategory> { // ... } private readonly CategoryList categories = new CategoryList(); private readonly ItemList items = new ItemList(); public CategoryList FacetCategories { get { return categories; } set { categories.Clear(); categories.AddRange(value); } } public ItemList Items { get { return items; } set { items.Clear(); items.AddRange(value); } } } Finally, the third option is to combine options one and two, so that Collection implements IList<PivotItem> and has a property FacetCategories. Question: Which of these three is most appropriate, and why?

    Read the article

  • List.clear() followed by List.add() not working.

    - by Vincent
    I have the following C# Class/Function: class Hand { private List<Card> myCards = new List<Card>(); public void sortBySuitValue() { IEnumerable<Card> query = from s in myCards orderby (int)s.suit, (int)s.value select s; myCards = new List<Card>(); myCards.AddRange(query); } } On a card Game. This works fine, however, I had trouble at first, instead of using myCards = new List(); to 'reset' myCards, I would use myCards.clear(), however, once I called the clear function, I would not be able to call myCards.add() or myCards.addRange(). The count would stay at zero. Is my current approach good? Is using LINQ to sort my cards good/bad?

    Read the article

  • Data extract from website URL

    - by user2522395
    From this below script I am able to extract all links of particular website, But i need to know how I can generate data from extracted links especially like eMail, Phone number if its there Please help how i will modify the existing script and get the result or if you have full sample script please provide me. Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click 'url must be in this format: http://www.example.com/ Dim aList As ArrayList = Spider("http://www.qatarliving.com", 1) For Each url As String In aList lstUrls.Items.Add(url) Next End Sub Private Function Spider(ByVal url As String, ByVal depth As Integer) As ArrayList 'aReturn is used to hold the list of urls Dim aReturn As New ArrayList 'aStart is used to hold the new urls to be checked Dim aStart As ArrayList = GrabUrls(url) 'temp array to hold data being passed to new arrays Dim aTemp As ArrayList 'aNew is used to hold new urls before being passed to aStart Dim aNew As New ArrayList 'add the first batch of urls aReturn.AddRange(aStart) 'if depth is 0 then only return 1 page If depth < 1 Then Return aReturn 'loops through the levels of urls For i = 1 To depth 'grabs the urls from each url in aStart For Each tUrl As String In aStart 'grabs the urls and returns non-duplicates aTemp = GrabUrls(tUrl, aReturn, aNew) 'add the urls to be check to aNew aNew.AddRange(aTemp) Next 'swap urls to aStart to be checked aStart = aNew 'add the urls to the main list aReturn.AddRange(aNew) 'clear the temp array aNew = New ArrayList Next Return aReturn End Function Private Overloads Function GrabUrls(ByVal url As String) As ArrayList 'will hold the urls to be returned Dim aReturn As New ArrayList Try 'regex string used: thanks google Dim strRegex As String = "<a.*?href=""(.*?)"".*?>(.*?)</a>" 'i used a webclient to get the source 'web requests might be faster Dim wc As New WebClient 'put the source into a string Dim strSource As String = wc.DownloadString(url) Dim HrefRegex As New Regex(strRegex, RegexOptions.IgnoreCase Or RegexOptions.Compiled) 'parse the urls from the source Dim HrefMatch As Match = HrefRegex.Match(strSource) 'used later to get the base domain without subdirectories or pages Dim BaseUrl As New Uri(url) 'while there are urls While HrefMatch.Success = True 'loop through the matches Dim sUrl As String = HrefMatch.Groups(1).Value 'if it's a page or sub directory with no base url (domain) If Not sUrl.Contains("http://") AndAlso Not sUrl.Contains("www") Then 'add the domain plus the page Dim tURi As New Uri(BaseUrl, sUrl) sUrl = tURi.ToString End If 'if it's not already in the list then add it If Not aReturn.Contains(sUrl) Then aReturn.Add(sUrl) 'go to the next url HrefMatch = HrefMatch.NextMatch End While Catch ex As Exception 'catch ex here. I left it blank while debugging End Try Return aReturn End Function Private Overloads Function GrabUrls(ByVal url As String, ByRef aReturn As ArrayList, ByRef aNew As ArrayList) As ArrayList 'overloads function to check duplicates in aNew and aReturn 'temp url arraylist Dim tUrls As ArrayList = GrabUrls(url) 'used to return the list Dim tReturn As New ArrayList 'check each item to see if it exists, so not to grab the urls again For Each item As String In tUrls If Not aReturn.Contains(item) AndAlso Not aNew.Contains(item) Then tReturn.Add(item) End If Next Return tReturn End Function

    Read the article

  • Silverlight Cream for March 10, 2010 - 2 -- #811

    - by Dave Campbell
    In this Issue: AfricanGeek, Phil Middlemiss, Damon Payne, David Anson, Jesse Liberty, Jeremy Likness, Jobi Joy(-2-), Fredrik Normén, Bobby Diaz, and Mike Taulty(-2-). Shoutouts: Shawn Wildermuth blogged that they posted My "What's New in Silverlight 3" Video from 0reDev Last Fall Shawn Wildermuth also has a post up for his loyal followers: Where to See Me At MIX10 Jonas Follesø has presentation materials up as well: MVVM presentation from NDC2009 on Vimeo Adam Kinney updated his Favorite Tool and Library Downloads for Silverlight From SilverlightCream.com: Styling Silverlight ListBox with Blend 3 In his latest Video Tutorial, AfricanGeek is animating the ListBox control by way of Expression Blend 3. Animating the Silverlight Opacity Mask Phil Middlemiss has written a Behavior that lets you turn a FrameworkElement into an opacity mask for it's parent container... check out his tutorial and grab the code. AddRange for ObservableCollection in Silverlight 3 Damon Payne has a post up discussing the problem with large amounts of data in an ObservableCollection, and how using AddRange is a performance booster. Easily rotate the axis labels of a Silverlight/WPF Toolkit chart David Anson blogged a solution to rotating the axis labels of a Silverlight and WPF chart. Persisting the Configuration (Updated) Jesse Liberty has a good discussion on the continuation of his HyperVideo Platform talking about what all he is needing from the database in the form of configuration information... including the relationships. Animations and View Models: IAnimationDelegate Check out Jeremy Likness' IAnimationDelegate that lets your ViewModel fire and respond to animations without having to know all about them. Button Style - Silverlight Jobi Joy converted a WPF control template into Silverlight... and you'll want to download the XAML he's got for this :) A Simple Accordion banner using ListBox Jobi Joy also has an Image Accordian created in Expression Blend... and it's a 'drop this XAML in your User Control' kinda thing... again, go grab the XAML :) WCF RIA Services Silverlight Business Application – Using ASP.NET SiteMap for Navigation Fredrik Normén has a code-laden post up on RIA Services and the ASP.NET SiteMap. He is using the Silverlight Business app template that comes with WCF RIA Services. A Simple, Selectable Silverlight TextBlock (sort of)... Bobby Diaz shares with us his solution for a Text control that can be copied from in the same manner 'normal' web controls can be. He also includes a link to another post on the same topic. Silverlight 4 Beta Networking. Part 11 - WCF and TCP Mike Taulty has another pair of video tutorials up in his Networking series. This one is on WCF over TCP Silverlight 4 Beta Networking. Part 12 - WCF and Polling HTTP Mike Taulty's 12th networking video tutorial is on WCF with HTTP polling duplex. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    MIX10

    Read the article

  • Why ComboBox hides cursor when DroppedDown is set?

    - by Ivan Danilov
    Let's create WinForms Application (I have Visual Studio 2008 running on Windows Vista, but it seems that described situation takes place almost everywhere from Win98 to Vista, on native or managed code). Write such code: using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public class Form1 : Form { private readonly Button button1 = new Button(); private readonly ComboBox comboBox1 = new ComboBox(); private readonly TextBox textBox1 = new TextBox(); public Form1() { SuspendLayout(); textBox1.Location = new Point(21, 51); button1.Location = new Point(146, 49); button1.Text = "button1"; button1.Click += button1_Click; comboBox1.Items.AddRange(new[] {"1", "2", "3", "4", "5", "6"}); comboBox1.Location = new Point(21, 93); AcceptButton = button1; Controls.AddRange(new Control[] {textBox1, comboBox1, button1}); Text = "Form1"; ResumeLayout(false); PerformLayout(); } private void button1_Click(object sender, EventArgs e) { comboBox1.DroppedDown = true; } } } Then, run app. Place mouse cursor on the form and don't touch mouse anymore. Start to type something in TextBox - cursor will hide because of it. When you press Enter key - event throws and ComboBox will be dropped down. But now cursor won't appear even if you move it! And appears only when you click somewhere. There I've found discussion of this problem. But there's no good solution... Any thoughts? :)

    Read the article

  • Designer serialization persistence problem in .NET, Windows Forms

    - by Jules
    ETA: I have a similar, smaller, problem here which, I suspect, is related to this problem. I have a class which has a readonly property that holds a collection of components (* not quite, see below). At design time, it's possible to select from the components on the design surface to add to the collection. (Think imagelist, but instead of selecting one, you can select as many as you want.) As a test, I inherit from button and attach my class to it as a property. The persistence problem occurs when I add a component,to the collection, from the design surface after I have added my button to the form. The best way to demonstrate this is to show you the designer generated code: Private Sub InitializeComponent() Dim Provider1 As WindowsApplication1.Provider = New WindowsApplication1.Provider Me.MyComponent2 = New WindowsApplication1.MyComponent Me.MyComponent1 = New WindowsApplication1.MyComponent Me.MyButton1 = New WindowsApplication1.MyButton Me.MyComponent3 = New WindowsApplication1.MyComponent Me.SuspendLayout() ' 'MyButton1 ' Me.MyButton1.ProviderCollection.Add(Me.MyButton1.InternalProvider) Me.MyButton1.ProviderCollection.Add(Me.MyComponent1.Provider) Me.MyButton1.ProviderCollection.Add(Me.MyComponent2.Provider) Me.MyButton1.ProviderCollection.Add(Provider1) //Wrong should be Me.MyComponent3.Provider ' 'Form1 ' Me.Controls.Add(Me.MyButton1) End Sub Friend WithEvents MyComponent1 As WindowsApplication1.MyComponent Friend WithEvents MyComponent2 As WindowsApplication1.MyComponent Friend WithEvents MyButton1 As WindowsApplication1.MyButton Friend WithEvents MyComponent3 As WindowsApplication1.MyComponent End Class As you can see from the code, the collection is not actually a collection of the components, but a collection of a property, 'Provider', from the components. It looks like the problem is occurring because MyComponent3 is created after MyButton. However, in my opinion, this should not make any difference - by the time the serializer comes to add the provider property of MyComponent3, it's already created. Note: You may wonder, why I'm not using AddRange to persist the collection. The reason for this is that if I do, the behaviour changes and none of the items will persist correctly. The designer will create local fields - like Provider1 - for each item in the collection. However if I add another collection to the class which holds the actual MyComponents and persist this, then, somehow, the AddRange method persists correctly in ProviderCollection! There seems to be some kind of quantum double slit experiment going down in code dom. How can I solve this problem?

    Read the article

  • mysql data read returning 0 rows from class

    - by Neo
    I am implementing a database manager class within my app, mainly because there are 3 databases to connect to one being a local one. However the return function isn't working, I know the query brings back rows but when it is returned by the class it has 0. What am I missing? public MySqlDataReader localfetchrows(string query, List<MySqlParameter> dbparams = null) { using (var conn = connectLocal()) { Console.WriteLine("Connecting local : " + conn.ServerVersion); MySqlCommand sql = conn.CreateCommand(); sql.CommandText = query; if (dbparams != null) { if (dbparams.Count > 0) { sql.Parameters.AddRange(dbparams.ToArray()); } } MySqlDataReader reader = sql.ExecuteReader(); Console.WriteLine("Reading data : " + reader.HasRows + reader.FieldCount); return reader; /* using (MySqlCommand sql = conn.CreateCommand()) { sql.CommandText = query; if (dbparams != null) { if (dbparams.Count > 0) { sql.Parameters.AddRange(dbparams.ToArray()); } } MySqlDataReader reader = sql.ExecuteReader(); Console.WriteLine("Reading data : " + reader.HasRows + reader.FieldCount); sql.Parameters.Clear(); return reader; }*/ } } And the code to get the results query = @"SELECT jobtypeid, title FROM jobtypes WHERE active = 'Y' ORDER BY title ASC"; //parentfrm.jobtypes = db.localfetchrows(query); var rows = db.localfetchrows(query); Console.WriteLine("Reading data : " + rows.HasRows + rows.FieldCount); while (rows.Read()){ } These scripts return the following : Connecting local : 5.5.16 Reading data : True2 Reading data : False0

    Read the article

  • Data table columns become out of order after changing data source.

    - by Scott Chamberlain
    This is kind of a oddball problem so I will try to describe the best that I can. I have a DataGridView that shows a list of contracts and various pieces of information about them. There are three view modes: Contract Approval, Pre-Production, and Production. Each mode has it's own set of columns that need to be displayed. What I have been doing is I have three radio buttons one for each contract style. all of them fire their check changed on this function private void rbContracts_CheckedChanged(object sender, EventArgs e) { dgvContracts.Columns.Clear(); if (((RadioButton)sender).Checked == true) { if (sender == rbPreProduction) { dgvContracts.Columns.AddRange(searchSettings.GetPreProductionColumns()); this.contractsBindingSource.DataMember = "Preproduction"; this.preproductionTableAdapter.Fill(this.searchDialogDataSet.Preproduction); } else if (sender == rbProduction) { dgvContracts.Columns.AddRange(searchSettings.GetProductionColumns()); this.contractsBindingSource.DataMember = "Production"; this.productionTableAdapter.Fill(this.searchDialogDataSet.Production); } else if (sender == rbContracts) { dgvContracts.Columns.AddRange(searchSettings.GetContractsColumns()); this.contractsBindingSource.DataMember = "Contracts"; this.contractsTableAdapter.Fill(this.searchDialogDataSet.Contracts); } } } Here is the GetxxxColumns function public DataGridViewColumn[] GetPreProductionColumns() { this.dgvTxtPreAccount.Visible = DgvTxtPreAccountVisable; this.dgvTxtPreImpromedAccNum.Visible = DgvTxtPreImpromedAccNumVisable; this.dgvTxtPreCreateDate.Visible = DgvTxtPreCreateDateVisable; this.dgvTxtPreCurrentSoftware.Visible = DgvTxtPreCurrentSoftwareVisable; this.dgvTxtPreConversionRequired.Visible = DgvTxtPreConversionRequiredVisable; this.dgvTxtPreConversionLevel.Visible = DgvTxtPreConversionLevelVisable; this.dgvTxtPreProgrammer.Visible = DgvTxtPreProgrammerVisable; this.dgvCbxPreEdge.Visible = DgvCbxPreEdgeVisable; this.dgvCbxPreEducationRequired.Visible = DgvCbxPreEducationRequiredVisable; this.dgvTxtPreTargetMonth.Visible = DgvTxtPreTargetMonthVisable; this.dgvCbxPreEdgeDatesDate.Visible = DgvCbxPreEdgeDatesDateVisable; this.dgvTxtPreStartDate.Visible = DgvTxtPreStartDateVisable; this.dgvTxtPreUserName.Visible = DgvTxtPreUserNameVisable; this.dgvCbxPreProductionId.Visible = DgvCbxPreProductionIdVisable; return new System.Windows.Forms.DataGridViewColumn[] { this.dgvTxtPreAccount, this.dgvTxtPreImpromedAccNum, this.dgvTxtPreCreateDate, this.dgvTxtPreCurrentSoftware, this.dgvTxtPreConversionRequired, this.dgvTxtPreConversionLevel, this.dgvTxtPreProgrammer, this.dgvCbxPreEdge, this.dgvCbxPreEducationRequired, this.dgvTxtPreTargetMonth, this.dgvCbxPreEdgeDatesDate, this.dgvTxtPreStartDate, this.dgvTxtPreUserName, this.dgvCbxPreProductionId, this.dgvTxtCmnHold, this.dgvTxtCmnConcern, this.dgvTxtCmnAccuracyStatus, this.dgvTxtCmnEconomicStatus, this.dgvTxtCmnSoftwareStatus, this.dgvTxtCmnServiceStatus, this.dgvTxtCmnHardwareStatus, this.dgvTxtCmnAncillaryStatus, this.dgvTxtCmnFlowStatus, this.dgvTxtCmnImpromedAccountNum, this.dgvTxtCmnOpportunityId}; } public DataGridViewColumn[] GetProductionColumns() { this.dgvcTxtProAccount.Visible = DgvTxtProAccountVisable; this.dgvTxtProImpromedAccNum.Visible = DgvTxtProImpromedAccNumVisable; this.dgvTxtProCreateDate.Visible = DgvTxtProCreateDateVisable; this.dgvTxtProConvRequired.Visible = DgvTxtProConvRequiredVisable; this.dgvTxtProEdgeRequired.Visible = DgvTxtProEdgeRequiredVisable; this.dgvTxtProStartDate.Visible = DgvTxtProStartDateVisable; this.dgvTxtProHardwareRequired.Visible = DgvTxtProHardwareReqiredVisable; this.dgvTxtProStandardDate.Visible = DgvTxtProStandardDateVisable; this.dgvTxtProSystemScheduleDate.Visible = DgvTxtProSystemScheduleDateVisable; this.dgvTxtProHwSystemCompleteDate.Visible = DgvTxtProHwSystemCompleteDateVisable; this.dgvTxtProHardwareTechnician.Visible = DgvTxtProHardwareTechnicianVisable; return new System.Windows.Forms.DataGridViewColumn[] { this.dgvcTxtProAccount, this.dgvTxtProImpromedAccNum, this.dgvTxtProCreateDate, this.dgvTxtProConvRequired, this.dgvTxtProEdgeRequired, this.dgvTxtProStartDate, this.dgvTxtProHardwareRequired, this.dgvTxtProStandardDate, this.dgvTxtProSystemScheduleDate, this.dgvTxtProHwSystemCompleteDate, this.dgvTxtProHardwareTechnician, this.dgvTxtCmnHold, this.dgvTxtCmnConcern, this.dgvTxtCmnAccuracyStatus, this.dgvTxtCmnEconomicStatus, this.dgvTxtCmnSoftwareStatus, this.dgvTxtCmnServiceStatus, this.dgvTxtCmnHardwareStatus, this.dgvTxtCmnAncillaryStatus, this.dgvTxtCmnFlowStatus, this.dgvTxtCmnImpromedAccountNum, this.dgvTxtCmnOpportunityId}; } public DataGridViewColumn[] GetContractsColumns() { this.dgvTxtConAccount.Visible = this.DgvTxtConAccountVisable; this.dgvTxtConAccuracyStatus.Visible = this.DgvTxtConAccuracyStatusVisable; this.dgvTxtConCreateDate.Visible = this.DgvTxtConCreateDateVisable; this.dgvTxtConEconomicStatus.Visible = this.DgvTxtConEconomicStatusVisable; this.dgvTxtConHardwareStatus.Visible = this.DgvTxtConHardwareStatusVisable; this.dgvTxtConImpromedAccNum.Visible = this.DgvTxtConImpromedAccNumVisable; this.dgvTxtConServiceStatus.Visible = this.DgvTxtConServiceStatusVisable; this.dgvTxtConSoftwareStatus.Visible = this.DgvTxtConSoftwareStatusVisable; this.dgvCbxConPreProductionId.Visible = this.DgvCbxConPreProductionIdVisable; this.dgvCbxConProductionId.Visible = this.DgvCbxConProductionVisable; return new System.Windows.Forms.DataGridViewColumn[] { this.dgvTxtConAccount, this.dgvTxtConImpromedAccNum, this.dgvTxtConCreateDate, this.dgvTxtConAccuracyStatus, this.dgvTxtConEconomicStatus, this.dgvTxtConSoftwareStatus, this.dgvTxtConServiceStatus, this.dgvTxtConHardwareStatus, this.dgvCbxConPreProductionId, this.dgvCbxConProductionId, this.dgvTxtCmnHold, this.dgvTxtCmnConcern, this.dgvTxtCmnAccuracyStatus, this.dgvTxtCmnEconomicStatus, this.dgvTxtCmnSoftwareStatus, this.dgvTxtCmnServiceStatus, this.dgvTxtCmnHardwareStatus, this.dgvTxtCmnAncillaryStatus, this.dgvTxtCmnFlowStatus, this.dgvTxtCmnImpromedAccountNum, this.dgvTxtCmnOpportunityId}; } The issue is when I check a button the first time, everything shows up ok. I choose another view, everything is ok. But when I click on the first view the columns are out of order (it is like they are in reverse order but it is not exactly the same). this happens only to the first page you click on, the other two are fine. You can click off and click back on as many times as you want after those initial steps, The first list you selected at the start will be out of order the other two will be correct. Any ideas on what could be causing this?

    Read the article

  • What is the most efficient way to convert to binary and back in C#?

    - by Saad Imran.
    I'm trying to write a general purpose socket server for a game I'm working on. I know I could very well use already built servers like SmartFox and Photon, but I wan't to go through the pain of creating one myself for learning purposes. I've come up with a BSON inspired protocol to convert the the basic data types, their arrays, and a special GSObject to binary and arrange them in a way so that it can be put back together into object form on the client end. At the core, the conversion methods utilize the .Net BitConverter class to convert the basic data types to binary. Anyways, the problem is performance, if I loop 50,000 times and convert my GSObject to binary each time it takes about 5500ms (the resulting byte[] is just 192 bytes per conversion). I think think this would be way too slow for an MMO that sends 5-10 position updates per second with a 1000 concurrent users. Yes, I know it's unlikely that a game will have a 1000 users on at the same time, but like I said earlier this is supposed to be a learning process for me, I want to go out of my way and build something that scales well and can handle at least a few thousand users. So yea, if anyone's aware of other conversion techniques or sees where I'm loosing performance I would appreciate the help. GSBitConverter.cs This is the main conversion class, it adds extension methods to main datatypes to convert to the binary format. It uses the BitConverter class to convert the base types. I've shown only the code to convert integer and integer arrays, but the rest of the method are pretty much replicas of those two, they just overload the type. public static class GSBitConverter { public static byte[] ToGSBinary(this short value) { return BitConverter.GetBytes(value); } public static byte[] ToGSBinary(this IEnumerable<short> value) { List<byte> bytes = new List<byte>(); short length = (short)value.Count(); bytes.AddRange(length.ToGSBinary()); for (int i = 0; i < length; i++) bytes.AddRange(value.ElementAt(i).ToGSBinary()); return bytes.ToArray(); } public static byte[] ToGSBinary(this bool value); public static byte[] ToGSBinary(this IEnumerable<bool> value); public static byte[] ToGSBinary(this IEnumerable<byte> value); public static byte[] ToGSBinary(this int value); public static byte[] ToGSBinary(this IEnumerable<int> value); public static byte[] ToGSBinary(this long value); public static byte[] ToGSBinary(this IEnumerable<long> value); public static byte[] ToGSBinary(this float value); public static byte[] ToGSBinary(this IEnumerable<float> value); public static byte[] ToGSBinary(this double value); public static byte[] ToGSBinary(this IEnumerable<double> value); public static byte[] ToGSBinary(this string value); public static byte[] ToGSBinary(this IEnumerable<string> value); public static string GetHexDump(this IEnumerable<byte> value); } Program.cs Here's the the object that I'm converting to binary in a loop. class Program { static void Main(string[] args) { GSObject obj = new GSObject(); obj.AttachShort("smallInt", 15); obj.AttachInt("medInt", 120700); obj.AttachLong("bigInt", 10900800700); obj.AttachDouble("doubleVal", Math.PI); obj.AttachStringArray("muppetNames", new string[] { "Kermit", "Fozzy", "Piggy", "Animal", "Gonzo" }); GSObject apple = new GSObject(); apple.AttachString("name", "Apple"); apple.AttachString("color", "red"); apple.AttachBool("inStock", true); apple.AttachFloat("price", (float)1.5); GSObject lemon = new GSObject(); apple.AttachString("name", "Lemon"); apple.AttachString("color", "yellow"); apple.AttachBool("inStock", false); apple.AttachFloat("price", (float)0.8); GSObject apricoat = new GSObject(); apple.AttachString("name", "Apricoat"); apple.AttachString("color", "orange"); apple.AttachBool("inStock", true); apple.AttachFloat("price", (float)1.9); GSObject kiwi = new GSObject(); apple.AttachString("name", "Kiwi"); apple.AttachString("color", "green"); apple.AttachBool("inStock", true); apple.AttachFloat("price", (float)2.3); GSArray fruits = new GSArray(); fruits.AddGSObject(apple); fruits.AddGSObject(lemon); fruits.AddGSObject(apricoat); fruits.AddGSObject(kiwi); obj.AttachGSArray("fruits", fruits); Stopwatch w1 = Stopwatch.StartNew(); for (int i = 0; i < 50000; i++) { byte[] b = obj.ToGSBinary(); } w1.Stop(); Console.WriteLine(BitConverter.IsLittleEndian ? "Little Endian" : "Big Endian"); Console.WriteLine(w1.ElapsedMilliseconds + "ms"); } Here's the code for some of my other classes that are used in the code above. Most of it is repetitive. GSObject GSArray GSWrappedObject

    Read the article

  • MySQL Connector/Net 6.8.0 alpha has been released

    - by Roberto Garcia
    Dear MySQL users, MySQL Connector/Net 6.8.0, a new version of the all-managed .NET driver for MySQL has been released. This is an alpha release for 6.8.x and it's not recommended for production environments.It is appropriate for use with MySQL server versions 5.0-5.6 It is now available in source and binary form from http://dev.mysql.com/downloads/connector/net/#downloads and mirror sites (note that not all mirror sites may be up to date at this point-if you can't find this version on some mirror, please try again later or choose another download site.) The 6.8.0 version of MySQL Connector/Net has support for Entity Framework 6.0 including: - Async Query and Save- Code-Based Configuration- Dependency Resolution- DbSet.AddRange/RemoveRange- Code First Mapping to Insert/Update/Delete Stored Procedures - Configurable Migrations History Table- DbContext can now be created with a DbConnection that is already opened- Custom Code First Conventions The release is available to download at http://dev.mysql.com/downloads/connector/net/#downloads Documentation-------------------------------------You can view current Connector/Net documentation at http://dev.mysql.com/doc/refman/5.6/en/connector-net.html You can find our team blog at http://blogs.oracle.com/MySQLOnWindows You can also post questions on our forums at http://forums.mysql.com/ Enjoy and thanks for the support! Connector/NET Team

    Read the article

1 2 3 4 5  | Next Page >