How to improve this piece of code

Posted by user303518 on Stack Overflow See other posts from Stack Overflow or by user303518
Published on 2010-03-28T11:21:09Z Indexed on 2010/03/28 11:23 UTC
Read the original article Hit count: 364

Filed under:

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;

} }

© Stack Overflow or respective owner

How to improve this piece of code

Posted by user303518 on Stack Overflow See other posts from Stack Overflow or by user303518
Published on 2010-03-28T10:59:55Z Indexed on 2010/03/28 11:03 UTC
Read the original article Hit count: 364

Filed under:

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());

              }

        }

© Stack Overflow or respective owner

Related posts about c#3.0