<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users1406</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1406" rel="self"/>
  <title>zsysop.myopenid.com</title>
  <updated>Fri Sep 23 22:05:30 -0700 2011</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor577750</id>
    <published>2011-09-23T22:05:30-07:00</published>
    <title>[C#] On Need help drying up my controller</title>
    <content type="html">&lt;p&gt;I can pass data using parameters, but every Step within the wizard would need to have all of the fields of the previous step in the form in order to transfer all of the fields from the previous step(s). Would using params be a cleaner way to approach this?&lt;/p&gt;

&lt;p&gt;The checks within the POSTs are there to handle multiple posts.
&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1823-need-help-drying-up-my-controller/refactors/577750" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor577749</id>
    <published>2011-09-23T22:04:21-07:00</published>
    <title>[C#] On Need help drying up my controller</title>
    <content type="html">

&lt;pre&gt;I can pass data using parameters, but every Step within the wizard would need to have all of the fields of the previous step in the form in order to transfer all of the fields from the previous step(s). Would using params be a cleaner way to approach this?

The checks within the POSTs are there to handle multiple posts.
&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1823-need-help-drying-up-my-controller/refactors/577749" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor577748</id>
    <published>2011-09-23T22:04:17-07:00</published>
    <title>[C#] On Need help drying up my controller</title>
    <content type="html">

&lt;pre&gt;I can pass data using parameters, but every Step within the wizard would need to have all of the fields of the previous step in the form in order to transfer all of the fields from the previous step(s). Would using params be a cleaner way to approach this?

The checks within the POSTs are there to handle multiple posts.
&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1823-need-help-drying-up-my-controller/refactors/577748" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1823</id>
    <published>2011-09-22T11:34:36-07:00</published>
    <updated>2011-11-24T13:08:22-08:00</updated>
    <title>[C#] Need help drying up my controller</title>
    <content type="html">&lt;p&gt;Thanks for any help&lt;/p&gt;

&lt;pre&gt;   [Authorize(Roles=&amp;quot;Administrator,DR&amp;quot;)]
    public class RegistrarController : BaseController
    {
        private readonly IRegistrationService _registrationService;

        public const string WizardKey = &amp;quot;Wizard&amp;quot;;
        public const string ActionKey = &amp;quot;Action&amp;quot;;

        public RegistrarController(IRegistrationService registrationService)
        {
            this._registrationService = registrationService;
        }

      
        public ActionResult Dashboard()
        {
            var model = new RegistrarDashboardModel();
            var user = _membershipService.GetUser(this.User.Identity.Name);

            if (user == null)
            {
                ViewBag.ErrorMessage = &amp;quot;Error: Your username could not be found in our database.&amp;quot;;
                return View(&amp;quot;Error&amp;quot;);
            }

            model.Name = user.UserName;
            model.Email = user.Email;
            model.RegistrarId = user.DeputyRegistrarId;

            if (!string.IsNullOrEmpty(user.DeputyRegistrarId))
            {
                var registrar = _registrationService.GetRegistrarBy(r =&amp;gt; r.ID == user.DeputyRegistrarId).FirstOrDefault();
                if (registrar != null)
                {
                    model.Name = registrar.DR_NAME;
                    model.OrganizationId = registrar.ORG_NUM;
                    if (registrar.Organization != null)
                        model.OrganizationName = registrar.Organization.ORG_NAME;
    
                }
            }

            return View(model);
        }


        [HttpGet]
        public ActionResult Step1()
        {
            if (string.IsNullOrEmpty(this.RegistrarId))
            {
                ViewBag.ErrorMessage = &amp;quot;A valid registrar id is not associated with this account.&amp;quot;;
                return View(&amp;quot;Error&amp;quot;);
            }

            NewRegistrantModel model;

            var wizard = TempData[WizardKey] as PersonRegistrationWizard;
            if (wizard == null || wizard.Step1Model == null)
            {
                wizard = new PersonRegistrationWizard();
                wizard.RegistrarId = this.RegistrarId;
                model = new NewRegistrantModel();
            }
            else
                model = wizard.Step1Model;

            wizard.CurrentStep = 1;
            wizard.Step1Model = model;

            TempData[WizardKey] = wizard;

            return View(model);
        }

        [HttpPost]
        public ActionResult Step1(NewRegistrantModel model) 
        {
            var wizard = TempData[WizardKey] as PersonRegistrationWizard;
            if (wizard == null)
                wizard = new PersonRegistrationWizard();

            if (!ModelState.IsValid)
                return View(&amp;quot;Step1&amp;quot;, model);

            var electionDate = _registrationService.GetUpcomingElectionFor(DateTime.Now);


            if (!electionDate.HasValue)
            {
                wizard.Step1Model = model;
                TempData[WizardKey] = wizard;
                ViewBag.ErrorMessage = &amp;quot;Sorry, no upcoming election was found within our database.&amp;quot;;
                return View(&amp;quot;Error&amp;quot;);
            }

            if (!_registrationService.EligibleToVote(model.Birthdate.Value, electionDate.Value))
            {
                wizard.Step1Model = model;
                TempData[WizardKey] = wizard;
                ModelState.AddModelError(&amp;quot;&amp;quot;, string.Format(&amp;quot;You must be 18 years of age or older by {0} election in order to register to Person.&amp;quot;, electionDate.Value.ToShortDateString()));
                return View(&amp;quot;Step1&amp;quot;, model);
            }


            wizard.Step1Model = model;
            if (wizard.MaxCompletedStep &amp;lt; 1)
                wizard.MaxCompletedStep = 1;

            TempData[WizardKey] = wizard;

            return RedirectToAction(&amp;quot;Step2&amp;quot;);
        }


        [HttpGet]
        public ActionResult Step2()
        {
            PersonInformationModel model;

            var wizard = TempData[WizardKey] as PersonRegistrationWizard;
            if (wizard == null || wizard.MaxCompletedStep &amp;lt; 1)
                return RedirectToAction(&amp;quot;Step1&amp;quot;);

            wizard = MoveDataFromStep1ToStep2(wizard);

            if (wizard.Step2Model == null)
                model = new PersonInformationModel();
            else
                model = wizard.Step2Model;

            wizard.CurrentStep = 2;
            TempData[WizardKey] = wizard;

            return View(model);
        }


        [HttpPost]
        public ActionResult Step2(PersonInformationModel model) 
        {

            var wizard = TempData[WizardKey] as PersonRegistrationWizard;
            if (wizard == null || wizard.Step1Model == null || wizard.MaxCompletedStep &amp;lt; 1)
                return RedirectToAction(&amp;quot;Step1&amp;quot;);

            if (!ModelState.IsValid)
            {
                wizard.Step2Model = model;
                TempData[WizardKey] = wizard;
                return View(&amp;quot;Step2&amp;quot;, model);
            }

            model.Person.NotInStreetIndex = !StreetDataValid(model.Person);

            if (model.Person.NotInStreetIndex &amp;amp;&amp;amp; !model.ConfirmCookResident)
            {
                wizard.Step2Model = model;
                TempData[WizardKey] = wizard;
                 ModelState.AddModelError(&amp;quot;ConfirmCookResident&amp;quot;, &amp;quot;The address entered was not found in our cook database. Please confirm that you a resident of Cook County Illinois in order to proceed&amp;quot;);
                return View(model);
            }

            wizard.Step2Model = model;
            wizard = MoveDataFromStep1ToStep2(wizard);

            if (wizard.MaxCompletedStep &amp;lt; 2) 
                wizard.MaxCompletedStep = 2;
            
            TempData[WizardKey] = wizard;

            return RedirectToAction(&amp;quot;Step3&amp;quot;);
        }




        [HttpGet]
        public ActionResult Step3()
        {
            var wizard = TempData[WizardKey] as PersonRegistrationWizard;
            if (wizard == null || wizard.MaxCompletedStep &amp;lt; 2)
                return RedirectToAction(&amp;quot;Step1&amp;quot;);
            wizard.CurrentStep = 3;
            TempData[WizardKey] = wizard;

            return View(wizard);
        }


        [HttpPost]
        public ActionResult Step3(FormCollection form)
        {
            var wizard = TempData[WizardKey] as PersonRegistrationWizard;
            if (wizard == null ||  wizard.MaxCompletedStep &amp;lt; 2 || wizard.Step1Model == null || wizard.Step2Model == null)
                return RedirectToAction(&amp;quot;Step1&amp;quot;);

            if (!string.IsNullOrEmpty(form[&amp;quot;editStep1&amp;quot;]))
                return RedirectToAction(&amp;quot;Step1&amp;quot;);
            else if (!string.IsNullOrEmpty(form[&amp;quot;editStep2&amp;quot;]))
                return RedirectToAction(&amp;quot;Step2&amp;quot;);
            else
            {
                if (wizard.MaxCompletedStep &amp;lt; 2)
                {
                   // Display Error
                }
                if (ModelState.IsValid)
                {
                   
                    wizard = MoveDataFromStep1ToStep2(wizard);

                    var Person = BuildPersonFromModel(wizard);
                    var registration = new RegistrarPersonRegistration();

                    if (Person.Id &amp;gt; 0)
                    {
                        registration = _registrationService.GetManyRegistrarPersonRegistrationsBy(v =&amp;gt; v.PersonId == Person.Id).FirstOrDefault();

                        if (registration == null || registration.Person == null)
                            throw new InvalidProgramException(&amp;quot;The Person id supplied does not have a Person registration&amp;quot;);

                        Person.LastUpdatedOn = DateTime.Now;
                        registration.Person.Copy(Person);
                        registration = _registrationService.UpdateRegistrarPersonRegistration(registration);

                    }
                    else
                    {

                        Person.CreatedBy = this.User.Identity.Name;
                        Person.CreatedOn = DateTime.Now;
                        Person.RegistrationTypeCode = &amp;quot;DEP&amp;quot;;
                        Person.RegistrationStatusCode = &amp;quot;P&amp;quot;;
                        Person.RegistrationDate = DateTime.Now;

                        registration = _registrationService.RegistrarRegisterPerson(wizard.RegistrarId, Person);
                            
                    }

                    _registrationService.Save();
                    wizard.Step2Model.Person.PersonId = registration.PersonId;
                    if (wizard.MaxCompletedStep &amp;lt; 3)
                        wizard.MaxCompletedStep = 3;

                    TempData[WizardKey] = wizard;
                }
                else
                {
                    return View(wizard);
                }
                return RedirectToAction(&amp;quot;Step4&amp;quot;);
            }

        }


        [HttpGet]
        public ActionResult Step4()
        {
            var wizard = TempData[WizardKey] as PersonRegistrationWizard;
            if (wizard == null || wizard.MaxCompletedStep &amp;lt; 3)
                return RedirectToAction(&amp;quot;Step1&amp;quot;);
            wizard.CurrentStep = 4;
            TempData[WizardKey] = wizard;

            return View(wizard);
        }


        [HttpPost]
        public ActionResult Step4(FormCollection form)
        {
            var wizard = TempData[WizardKey] as PersonRegistrationWizard;
            string action = form[ActionKey] == null ? string.Empty : form[ActionKey].ToString().ToUpper();

            if (wizard == null || wizard.MaxCompletedStep &amp;lt; 3 || 
            wizard.Step2Model == null || 
            wizard.Step2Model.Person == null || 
            !wizard.Step2Model.Person.PersonId.HasValue || 
            wizard.Step2Model.Person.PersonId.Value &amp;lt;= 0)
                return RedirectToAction(&amp;quot;Step1&amp;quot;);

            int PersonId = wizard.Step2Model.Person.PersonId.Value;
            var registration = new RegistrarPersonRegistration();

            switch (action)
            {
                case &amp;quot;PRINT&amp;quot;:
                    registration = _registrationService.GetManyRegistrarPersonRegistrationsBy(rvr =&amp;gt; rvr.PersonId == PersonId).FirstOrDefault();
                    if (registration == null)
                    {
                        ViewBag.ErrorMessage = &amp;quot;No Person id was provided.&amp;quot;;
                        wizard = null;
                        return View(&amp;quot;Error&amp;quot;);
                    }

                     registration.Person.RegistrationStatusCode = &amp;quot;C&amp;quot;;
                    _registrationService.UpdateRegistrarPersonRegistration(registration);
                    _registrationService.Save();
                    TempData[WizardKey] = null;

                    // TO DO: Return Generated PDF

                    break;
                case &amp;quot;ADD&amp;quot;:
                    TempData[WizardKey] = null;
                    return RedirectToAction(&amp;quot;Step1&amp;quot;);
                case &amp;quot;DASHBOARD&amp;quot;:
                    TempData[WizardKey] = null;
                    return RedirectToAction(&amp;quot;Dashboard&amp;quot;);
                default:
                    break;
            }

            return View(wizard);
        }


        private Person BuildPersonFromModel(PersonRegistrationWizard wizard)
        {
            int PersonId = 0;
            var modelPerson = wizard.Step2Model.Person;

            var Person = new Person();
            if (modelPerson.PersonId.HasValue)
            {
                Person = _registrationService.GetPersonBy(v =&amp;gt; v.Id == modelPerson.PersonId.Value);
                if (Person == null)
                    throw new InvalidOperationException(string.Format(&amp;quot;An invalid Person id was supplied {0}&amp;quot;, Person.Id));
                PersonId = Person.Id;
            }

            Person = modelPerson.ToEntity();
            Person.Id = PersonId;

            return Person;
        }

        private PersonRegistrationWizard MoveDataFromStep1ToStep2(PersonRegistrationWizard wizard)
        {
            if (wizard == null || wizard.Step1Model == null)
                return null;
            if (wizard.Step2Model == null)
            {
                wizard.Step2Model = new PersonInformationModel();
            }

            wizard.Step2Model.Person.Identification = wizard.Step1Model.Identification;
            wizard.Step2Model.Person.Birthdate = wizard.Step1Model.Birthdate;
            wizard.Step2Model.Person.SocialSecurityNumber = wizard.Step1Model.SocialSecurityNumber;
            wizard.Step2Model.Person.IdSupplied = wizard.Step1Model.OtherIdProvided;
            return wizard;
        }

        private bool StreetDataValid(PersonData Person)
        {
            return _registrationService.ValidateStreet(Person.AddressNumber.Value, Person.AddressDirection, Person.AddressStreet, Person.AddressStreetType, Person.AddressPostDirection, Person.AddressCity, Person.AddressZip);

        }&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1823-need-help-drying-up-my-controller" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1757</id>
    <published>2011-08-01T12:20:18-07:00</published>
    <updated>2011-08-07T03:10:39-07:00</updated>
    <title>[C#] Refactoring Suggestions</title>
    <content type="html">&lt;p&gt;Was looking for some suggestions for refactoring this&lt;/p&gt;

&lt;pre&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using Data.EntityFramework;

namespace Report
{
    public class ElectedOfficialListingReport
    {
        private readonly float Multiplier = 205;

        private readonly float FirstColumnLLX = 0;
        private readonly float FirstColumnURX = 205;

        private readonly float FirstColumnLLY = PageSize.LETTER.Height - 60;
        private readonly float FirstColumnURY = 10;

        private const float CellPaddingTop = 5f;
        private const float CellPaddingLeft = 15f;
        private const float TableSpacingAfter = 12f;

        private readonly int MaxColumns = 2; // 0 based 
        private int PageCount = 0;

        private float llx = 0;
        private float urx = 205;

        private int currentColumn = 0;
        private float pos;
        private int status = 0;

        private Font TitleFont;
        private Font MainHeaderFont;
        private Font SubHeaderFont;
        private Font DetailFont;
        private Font LabelFontBold;

        private readonly BaseColor PrimaryColor = new BaseColor(152, 184, 203);
        private readonly BaseColor SecondaryColor = new BaseColor(230, 237, 242);

        private readonly string fontPath = @&amp;quot;c:\\windows\\fonts\\MYRIADPRO-REGULAR.OTF&amp;quot;;
        private readonly string boldFontPath = @&amp;quot;c:\\windows\\fonts\\MyriadPro-BlackCond.OTF&amp;quot;;




        private readonly ElectionDataEntities _context = new ElectionDataEntities();

        public ElectedOfficialListingReport()
        {

            TitleFont = FontFactory.GetFont(boldFontPath, BaseFont.CP1252, BaseFont.EMBEDDED, 16);
            MainHeaderFont = FontFactory.GetFont(boldFontPath, BaseFont.CP1252, BaseFont.EMBEDDED, 12);
            SubHeaderFont = FontFactory.GetFont(fontPath, BaseFont.CP1252, BaseFont.EMBEDDED, 10);
            DetailFont = FontFactory.GetFont(fontPath, BaseFont.CP1252, BaseFont.EMBEDDED, 9);
            LabelFontBold = FontFactory.GetFont(boldFontPath, BaseFont.CP1252, BaseFont.EMBEDDED, 8);
        }


        public byte[] GenerateReport()
        {
            using (var stream = new MemoryStream())
            {
                Document document = new Document(PageSize.LETTER);
                try
                {

                    PdfWriter writer = PdfWriter.GetInstance(document, stream);
                    document.Open();

                    ColumnText dataColumns = new ColumnText(writer.DirectContent);
                    dataColumns = InitializeColumn(dataColumns, 0);

                    JurisdictionType previousJurisdictionType = null;
                    Jurisdiction previousJurisdiction = null;

                    

                    IList&amp;lt;PdfPTable&amp;gt; tables = new List&amp;lt;PdfPTable&amp;gt;();
                    bool includeOfficeNameInHeader = false;
                    bool useGroupedTemplate = false;

                    JurisdictionType jt;

                    var jurisdictions = (from jurisdictionType in _context.JurisdictionTypes
                                        join jurisdiction in _context.Jurisdictions on jurisdictionType.JurisdictionTypeId equals jurisdiction.JurisdictionTypeId
                                        orderby jurisdictionType.SortOrder, jurisdiction.SortOrder
                                        select jurisdiction)
                                        .ToList();

                    foreach (var jurisdiction in jurisdictions)
                    {
                        jt = _context.JurisdictionTypes.Where(jurisdictionType =&amp;gt; jurisdictionType.JurisdictionTypeId == jurisdiction.JurisdictionTypeId).FirstOrDefault();

                        useGroupedTemplate = jt.JurisdictionLevel.ToUpper() == &amp;quot;LOCAL&amp;quot;;

                        if (jt.JurisdictionLevel.ToUpper() == &amp;quot;FEDERAL&amp;quot; || jt.JurisdictionLevel.ToUpper() == &amp;quot;COUNTY&amp;quot; || jt.JurisdictionLevel.ToUpper() == &amp;quot;LOCAL&amp;quot; || jt.JurisdictionLevel.ToUpper() == &amp;quot;STATE&amp;quot;)
                            includeOfficeNameInHeader = true;

                        // All Muni Wards  must be grouped together
                        if (previousJurisdiction != null &amp;amp;&amp;amp; jurisdiction.JurisdictionTypeId.ToUpper() == &amp;quot;MUNIW&amp;quot; &amp;amp;&amp;amp; 
                            jurisdiction.TaxCode.StartsWith(&amp;quot;50-&amp;quot;) &amp;amp;&amp;amp; previousJurisdiction.JurisdictionCode.Substring(0, 4) == jurisdiction.JurisdictionCode.Substring(0, 4))
                            continue;

                        var officials = _context
                            .GetElectedOfficialsByTaxCode(jurisdiction.TaxCode)
                            .Select(o =&amp;gt; new ElectedOfficialData { 
                                ElectedOfficialId = o.ElectedOfficialId,
                                FirstName = o.FirstName,
                                MiddleName = o.MiddleName,
                                LastName = o.LastName,
                                JurisdictionType = o.JurisdictionType,
                                JurisdictionName = o.JurisdictionName,
                                OfficeId = o.OfficeId,
                                OfficeName = o.OfficeName,
                                Appointed = o.Appointed,
                                ElectionDate = o.ElectionDate,
                                Term = o.Term,
                            })                                
                            .ToList();

                        officials = officials.Where(o =&amp;gt; !o.OfficeName.ToUpper().Contains(&amp;quot;COMMITTEE&amp;quot;)).ToList();
                        ProcessOfficials(document, writer, ref dataColumns, ref previousJurisdictionType, ref previousJurisdiction, ref tables, jt, jurisdiction, useGroupedTemplate, includeOfficeNameInHeader, officials);
                    }



                    IList&amp;lt;JurisdictionType&amp;gt; jurisdictionTypes = _context.JurisdictionTypes.OrderBy(o =&amp;gt; o.SortOrder).ToList();

                    foreach (var jurisdictionType in jurisdictionTypes)
                    {

                        var committeemen = _context.GetElectedOfficials()
                            .Where(eo =&amp;gt; eo.JurisdictionType == jurisdictionType.ShortDescription &amp;amp;&amp;amp; eo.OfficeName.ToUpper().Contains(&amp;quot;COMMITTEE&amp;quot;))
                            .Select(o =&amp;gt; new ElectedOfficialData
                            {
                                ElectedOfficialId = o.ElectedOfficialId,
                                FirstName = o.FirstName,
                                MiddleName = o.MiddleName,
                                LastName = o.LastName,
                                JurisdictionType = o.JurisdictionType,
                                JurisdictionName = o.JurisdictionName,
                                OfficeId = o.OfficeId,
                                OfficeName = o.OfficeName,
                                Appointed = o.Appointed,
                                ElectionDate = o.ElectionDate,
                                Term = o.Term,
                            })
                            .ToList();

                        if (committeemen != null &amp;amp; committeemen.Count() &amp;gt; 0)
                        {
                            
                            useGroupedTemplate = false;
                            includeOfficeNameInHeader = true;
                            JurisdictionType partyJT = new JurisdictionType
                            {
                                JurisdictionLevel = &amp;quot;Party&amp;quot;,
                                JurisdictionTypeId = jurisdictionType.JurisdictionTypeId
                            };
                            ProcessOfficials(document, writer, ref dataColumns, ref previousJurisdictionType, ref previousJurisdiction, ref tables, partyJT, new Jurisdiction(), useGroupedTemplate, includeOfficeNameInHeader, committeemen);
                        }
                    }

                }
                finally
                {
                    document.Close();
                }

                return stream.ToArray();
            }
        }

        private void ProcessOfficials(Document document, 
            PdfWriter writer, 
            ref ColumnText dataColumns, 
            ref JurisdictionType previousJurisdictionType, 
            ref Jurisdiction previousJurisdiction, 
            ref IList&amp;lt;PdfPTable&amp;gt; tables, 
            JurisdictionType jurisdictionType, 
            Jurisdiction jurisdiction, 
            bool useGroupedTemplate, 
            bool includeOfficeNameInHeader, 
            List&amp;lt;ElectedOfficialData&amp;gt; officials)
        {

            bool specialWardJurisdiction = jurisdictionType.JurisdictionLevel.ToUpper() == &amp;quot;LOCAL&amp;quot; &amp;amp;&amp;amp; jurisdiction.JurisdictionTypeId.ToUpper() == &amp;quot;MUNIW&amp;quot; &amp;amp;&amp;amp; jurisdiction.TaxCode.StartsWith(&amp;quot;50-&amp;quot;);
            
            foreach (var official in officials)
            {
                if (jurisdictionType.JurisdictionLevel.ToUpper() == &amp;quot;LOCAL&amp;quot; &amp;amp;&amp;amp; previousJurisdiction.JurisdictionCode == jurisdiction.JurisdictionCode)
                    continue;

                if (jurisdictionType.JurisdictionLevel.ToUpper() == &amp;quot;LOCAL&amp;quot; &amp;amp;&amp;amp;
                  jurisdiction.JurisdictionTypeId.ToUpper() == &amp;quot;MUNIW&amp;quot; &amp;amp;&amp;amp;
                  previousJurisdiction.JurisdictionCode.Substring(0, 4) == jurisdiction.JurisdictionCode.Substring(0, 4))
                    continue;


                if (previousJurisdictionType == null)
                {
                    dataColumns = PageHeader(dataColumns, jurisdictionType.JurisdictionLevel);
                    dataColumns.Go(false);
                    dataColumns = InitializeColumn(dataColumns, 0);
                }
                else if (previousJurisdictionType != null &amp;amp;&amp;amp; previousJurisdictionType.JurisdictionTypeId != jurisdictionType.JurisdictionTypeId 
                    &amp;amp;&amp;amp; !specialWardJurisdiction
                    &amp;amp;&amp;amp; previousJurisdictionType.JurisdictionTypeId.ToUpper() != &amp;quot;MUNIW&amp;quot; ) 
                {
                    CreateNewPage(document, ref dataColumns);
                    dataColumns = PageHeader(dataColumns, jurisdictionType.JurisdictionLevel);
                    dataColumns.Go(false);
                    dataColumns = InitializeColumn(dataColumns, 0);
                }


                if (useGroupedTemplate)
                    tables = GenerateGroupedOfficeTemplate(document, writer, ref dataColumns, jurisdictionType, jurisdiction, specialWardJurisdiction);
                else
                    tables = GenerateOfficeTemplate(document, writer, ref dataColumns, official, jurisdictionType, true, includeOfficeNameInHeader);


                foreach (var table in tables)
                    AddMainContent(document, writer.DirectContent, ref dataColumns, table, jurisdictionType.JurisdictionLevel);

                previousJurisdiction = jurisdiction;
                previousJurisdictionType = jurisdictionType;
            }
        }



       
        private void AddMainContent(Document document, PdfContentByte pcb, ref ColumnText columns, PdfPTable table, string headerText, int numHeaderColumns = 0)
        {

            // Simulate adding table to column
            columns.AddElement(table);
            pos = columns.YLine;
            status = columns.Go(true);

            // if true than can add to current column
            if (!ColumnText.HasMoreText(status))
            {
                columns.AddElement(table);
                columns.YLine = pos;
                status = columns.Go(false);
            }
            else
            {
                currentColumn++;
                if (currentColumn &amp;lt;= MaxColumns) // Put content in a new column
                {
                    columns = CreateNewColumn(pcb, columns);
                    columns.AddElement(table);
                    status = columns.Go(false);
                }
                else // reset columns, create new page and add content to columns
                {
                    CreateNewPage(document, ref columns);
                    columns.SetText(null);

                    columns = PageHeader(columns, headerText);
                    columns.Go(false);

                    columns = InitializeColumn(columns, 0);
                    columns.AddElement(table);
                    status = columns.Go(false);
                }
            }
   

           
        }


        #region &amp;quot;Page, Column &amp;amp; Cell Methods&amp;quot;
        private ColumnText CreateNewPage(Document document, ref ColumnText columns)
        {
            PageCount++;
            document.NewPage();
            columns = InitializeColumn(columns, 0);
            return columns;
        }

        private ColumnText CreateNewColumn(PdfContentByte pcb, ColumnText columns)
        {
            status = 0;
            columns = new ColumnText(pcb);
            llx += Multiplier;
            urx += Multiplier;

            columns.SetSimpleColumn(llx, FirstColumnLLY, urx, FirstColumnURY);
            return columns;
        }

        private ColumnText InitializeColumn(ColumnText columns, int columnToInitialize)
        {
            currentColumn = columnToInitialize;
            llx = FirstColumnLLX + (Multiplier * columnToInitialize);
            urx = FirstColumnURX + (Multiplier * columnToInitialize);
            columns.SetSimpleColumn(llx, FirstColumnLLY, urx, FirstColumnURY);
            return columns;
        }


        private ColumnText InitializeFakeColumn(ColumnText columns)
        {
            float cLLX = FirstColumnLLX;
            float cURX = FirstColumnURX;
            columns.SetSimpleColumn(cLLX, FirstColumnLLY, cURX, FirstColumnURY);
            return columns;
        }

        private PdfPCell CreateNewCell()
        {
            PdfPCell cell = new PdfPCell();
            cell.Border = Rectangle.NO_BORDER;
            cell.PaddingLeft = CellPaddingLeft;
            return cell;
        }


        private void AddCell(IList&amp;lt;PdfPCell&amp;gt; cells, Phrase phrase, bool addBackgroundColor = false)
        {
            if (phrase == null)
                return;
            var cell = CreateNewCell();
            if (addBackgroundColor)
                cell.BackgroundColor = SecondaryColor;
            cell.AddElement(phrase);
            cells.Add(cell);
        }




        private void AddCell(IList&amp;lt;PdfPCell&amp;gt; cells, string data, Font font, bool capitilize, bool addBackgroundColor = false)
        {
            var cell = CreateNewCell();
            cell = AddDataToCell(cell, data, font, capitilize);

            if (cell != null)
            {
                if (addBackgroundColor)
                    cell.BackgroundColor = SecondaryColor;
                cells.Add(cell);
            }
        }


        private void AddCellPadTop(IList&amp;lt;PdfPCell&amp;gt; cells, string data, Font font, bool capitilize, bool addBackgroundColor = false)
        {
            var cell = CreateNewCell();
            cell = AddDataToCell(cell, data, font, capitilize);
            cell.PaddingTop = CellPaddingTop;

            if (addBackgroundColor)
                cell.BackgroundColor = SecondaryColor;

            if (cell != null)
                cells.Add(cell);
        }


        private void AddCellPadTop(IList&amp;lt;PdfPCell&amp;gt; cells, Phrase phrase, bool addBackgroundColor = false)
        {
            if (phrase == null)
                return;

            var cell = CreateNewCell();

            cell.PaddingTop = CellPaddingTop;

            if (addBackgroundColor)
                cell.BackgroundColor = SecondaryColor;

            cell.AddElement(phrase);
            cells.Add(cell);
        }


        private PdfPCell AddDataToCell(PdfPCell cell, string data, Font font, bool capitilize)
        {
            if (string.IsNullOrEmpty(data) || data.Trim() == string.Empty)
                return null;

            if (font == null)
                font = DetailFont;

            if (capitilize)
                data = data.ToUpper();

            if (cell == null)
                cell = CreateNewCell();
                
            Phrase phrase = new Phrase();
            phrase.Add(new Chunk(data, font));
            cell.AddElement(phrase);
            return cell;
        }

        private void AddLabelTextCell(IList&amp;lt;PdfPCell&amp;gt; cells, string label, string text, bool padTop, bool addBackgroundColor = false)
        {
            var cell = CreateNewCell();
            if (padTop)
                cell.PaddingTop = CellPaddingTop;

            var phrase = CreateLabelTextPhrase(label, text);
            if (phrase == null)
                return;

            cell.AddElement(phrase);

            if (addBackgroundColor)
                cell.BackgroundColor = SecondaryColor;

            cells.Add(cell);
        }

        private Phrase CreateLabelTextPhrase(string label, string text)
        {
            if (string.IsNullOrEmpty(text) || text.Trim() == string.Empty)
                return null;

            Phrase phrase = new Phrase();
            if (!string.IsNullOrEmpty(label) &amp;amp;&amp;amp; label.Trim() != string.Empty)
                phrase.Add(new Chunk(label + &amp;quot; &amp;quot;, LabelFontBold));

            phrase.Add(new Chunk(text, DetailFont));

            return phrase;

        }

        #endregion


        private IList&amp;lt;PdfPTable&amp;gt; GenerateGroupedOfficeTemplate(Document document, PdfWriter writer, ref ColumnText columns, JurisdictionType jurisdictionType, Jurisdiction jurisdiction, bool specialWardJurisdiction = false)
        {
            IList&amp;lt;PdfPTable&amp;gt; tables = new List&amp;lt;PdfPTable&amp;gt;();
            IList&amp;lt;PdfPCell&amp;gt; headerCells = new List&amp;lt;PdfPCell&amp;gt;();
            IList&amp;lt;PdfPCell&amp;gt; detailCells = new List&amp;lt;PdfPCell&amp;gt;();
            PdfPTable tempTable = new PdfPTable(1);
            PdfPTable finalTable = new PdfPTable(1);

            var officials = new List&amp;lt;ElectedOfficialData&amp;gt;();

            if (!specialWardJurisdiction)
            {
                officials = _context.GetElectedOfficialsByTaxCode(jurisdiction.TaxCode)
                    .Select(o =&amp;gt; new ElectedOfficialData
                    {
                        ElectedOfficialId = o.ElectedOfficialId,
                        FirstName = o.FirstName,
                        MiddleName = o.MiddleName,
                        LastName = o.LastName,
                        JurisdictionType = o.JurisdictionType,
                        JurisdictionName = o.JurisdictionName,
                        OfficeId = o.OfficeId,
                        OfficeName = o.OfficeName,
                        Appointed = o.Appointed,
                        ElectionDate = o.ElectionDate,
                        Term = o.Term,
                    }).Where(e =&amp;gt; !e.OfficeName.ToUpper().Contains(&amp;quot;COMMITTEE&amp;quot;)).ToList();
            }
            else
            {
                officials = _context.GetElectedOfficials()
                    .Where(e =&amp;gt; e.JurisdictionLevel.ToUpper() == &amp;quot;LOCAL&amp;quot; &amp;amp;&amp;amp;
                        e.JurisdictionType.ToUpper() == &amp;quot;MUNICIPAL WARDS&amp;quot; &amp;amp;&amp;amp;
                        e.JurisdictionCode.Substring(0, 4) == jurisdiction.JurisdictionCode.Substring(0, 4) &amp;amp;&amp;amp;
                        !e.OfficeName.ToUpper().Contains(&amp;quot;COMMITTEE&amp;quot;))
                    .Select(o =&amp;gt; new ElectedOfficialData
                    {
                        ElectedOfficialId = o.ElectedOfficialId,
                        FirstName = o.FirstName,
                        MiddleName = o.MiddleName,
                        LastName = o.LastName,
                        JurisdictionType = o.JurisdictionType,
                        JurisdictionName = o.JurisdictionName,
                        OfficeId = o.OfficeId,
                        OfficeName = o.OfficeName,
                        Appointed = o.Appointed,
                        ElectionDate = o.ElectionDate,
                        Term = o.Term,
                    }).ToList();
            }

            PdfPCell cell;
            Phrase phrase;
            bool addJurisdictionTypeHeader = true;
            int counter = 0;
            bool addBackgroundColor = false;
            int totalDetailCells = 0;
            

            foreach (var result in officials)
            {
                detailCells = new List&amp;lt;PdfPCell&amp;gt;();
                int wardSplitterIndex = 0;
                string jurisdictionHeader = string.Empty;

                wardSplitterIndex = result.JurisdictionName.IndexOf(&amp;quot;,&amp;quot;);

                if (addJurisdictionTypeHeader)
                {
                    //AddCell(headerCells, string.Format(&amp;quot;{0}&amp;quot;, result.JurisdictionType), MainHeaderFont, true);
                    if (!specialWardJurisdiction)
                        jurisdictionHeader = result.JurisdictionName;
                    else
                        jurisdictionHeader = result.JurisdictionName.Substring(0, wardSplitterIndex);

                    phrase = new Phrase(string.Format(&amp;quot;{0}&amp;quot;, jurisdictionHeader), SubHeaderFont);

                    cell = new PdfPCell(phrase);
                    cell.Border = Rectangle.NO_BORDER;
                    cell.BackgroundColor = PrimaryColor;
                    cell.PaddingLeft = CellPaddingLeft;
                    headerCells.Add(cell);

                    var addresses = (from oa in _context.OfficialAddresses
                                     join a in _context.Addresses
                                     on oa.AddressId equals a.AddressId
                                     where oa.ElectedOfficialId == result.ElectedOfficialId
                                     select new AddressData
                                     {
                                         AddressId = a.AddressId,
                                         Address = a.Address1,
                                         City = a.City,
                                         State = a.State,
                                         Zip = a.Zip,
                                         Phone = a.Phone,
                                         Fax = a.Fax,
                                         Email = a.Email,
                                         Web = a.URL,
                                         SortOrder = oa.SortOrder
                                     }).ToList();


                    bool includeAddressHeader = (addresses != null &amp;amp;&amp;amp; addresses.Count() &amp;gt; 1);
                    foreach (var address in addresses)
                        GenerateAddressTemplate(headerCells, address, includeAddressHeader);


                    foreach(var item in headerCells)
                        tempTable.AddCell(item);
                    addJurisdictionTypeHeader = false;


                }


                addBackgroundColor = counter % 2 == 0;

                phrase = new Phrase(string.Format(&amp;quot;{0} {1} {2}&amp;quot;, result.FirstName, result.MiddleName, result.LastName).Replace(&amp;quot;  &amp;quot;, &amp;quot; &amp;quot;).Trim(), DetailFont);
                if (specialWardJurisdiction == true)
                    result.OfficeName = string.Format(&amp;quot;{0} {1}&amp;quot;,result.OfficeName,
                        result.JurisdictionName.Substring(wardSplitterIndex + 1,
                        result.JurisdictionName.Length - wardSplitterIndex -1));

                phrase.Add(new Phrase(string.Format(&amp;quot; ({0})&amp;quot;, result.OfficeName), DetailFont));

                AddCell(detailCells, phrase, addBackgroundColor);

                if (result.Appointed == false)
                {

                    phrase = new Phrase(&amp;quot;ELECTED &amp;quot;, LabelFontBold);
                    phrase.Add(new Phrase(string.Format(&amp;quot;{0:d}&amp;quot;, result.ElectionDate), DetailFont));

                    //phrase.Add(new Phrase(&amp;quot; TERM &amp;quot;, LabelFontBold));
                    //phrase.Add(new Phrase(string.Format(&amp;quot;{0}&amp;quot;, result.Term), DetailFont));\


                    if (result.ElectionDate.HasValue)
                    {
                        phrase.Add(new Phrase(&amp;quot; NEXT ELECTION &amp;quot;, LabelFontBold));
                        phrase.Add(new Phrase(string.Format(&amp;quot;{0}&amp;quot;, string.Format(&amp;quot;{0}&amp;quot;, result.ElectionDate.Value.AddYears(result.Term).Year)), DetailFont));
                    }
                    AddCell(detailCells, phrase, addBackgroundColor);



                }
                else
                    AddCell(detailCells, &amp;quot;Appointed&amp;quot;, LabelFontBold, true, addBackgroundColor);

                


                foreach (var item in detailCells)
                    tempTable.AddCell(item);

                if (CanFitInColumn(tempTable))
                {
                    finalTable = new PdfPTable(tempTable);
                }
                else
                {
                    if (finalTable.Rows.Count() &amp;gt; 0)
                        tables.Add(finalTable);
                    else
                        tables.Add(tempTable);

                    tempTable = new PdfPTable(1);
                    foreach(var item in headerCells)
                        tempTable.AddCell(item);
                    foreach(var item in detailCells)
                        tempTable.AddCell(item);
                }

                totalDetailCells += detailCells.Count();
                counter++;
            }

            int totalCells = 0;
            foreach (var t in tables)
                totalCells += t.Rows.Count();

            if (totalCells != (totalDetailCells + (headerCells.Count() * tables.Count())))
                tables.Add(finalTable);

            foreach (var t in tables)
                t.SpacingAfter = TableSpacingAfter;

            return tables;
            
            
        }

        private IList&amp;lt;PdfPTable&amp;gt; GenerateOfficeTemplate(Document document, PdfWriter writer, ref ColumnText columns, ElectedOfficialData result, JurisdictionType jurisdictionType, bool addOfficeHeader, bool includeOfficeNameInHeader)
        {
            IList&amp;lt;PdfPTable&amp;gt; tables = new List&amp;lt;PdfPTable&amp;gt;();
            IList&amp;lt;PdfPCell&amp;gt; cells = new List&amp;lt;PdfPCell&amp;gt;();

            PdfPCell cell;
            Phrase phrase;

            if (addOfficeHeader)
            {
                // for federal add title
                if (includeOfficeNameInHeader)
                    AddCell(cells, string.Format(&amp;quot;{0}\n{1}&amp;quot;, result.JurisdictionName, result.OfficeName), MainHeaderFont, true);
                else
                    AddCell(cells, string.Format(&amp;quot;{0}&amp;quot;, result.JurisdictionName), MainHeaderFont, true);
            }


            phrase = new Phrase(string.Format(&amp;quot;{0} {1} {2}&amp;quot;, result.FirstName, result.MiddleName, result.LastName).Replace(&amp;quot;  &amp;quot;, &amp;quot; &amp;quot;).Trim(), SubHeaderFont);
            cell = new PdfPCell(phrase);
            cell.Border = Rectangle.NO_BORDER;
            cell.BackgroundColor = PrimaryColor;
            cell.PaddingLeft = CellPaddingLeft;
            cells.Add(cell);



            if (result.Appointed == false)
            {
                phrase = new Phrase(&amp;quot;LAST ELECTED&amp;quot;, LabelFontBold);
                phrase.Add(new Phrase(string.Format(&amp;quot; {0:d} &amp;quot;, result.ElectionDate), DetailFont));

                if (result.ElectionDate.HasValue)
                {
                    phrase.Add(new Phrase(&amp;quot; NEXT ELECTION &amp;quot;, LabelFontBold));
                    phrase.Add(new Phrase(string.Format(&amp;quot;{0}&amp;quot;, string.Format(&amp;quot;{0}&amp;quot;, result.ElectionDate.Value.AddYears(result.Term).Year)), DetailFont));
                }

                AddCellPadTop(cells, phrase);
            }
            else
                AddCellPadTop(cells, &amp;quot;Appointed&amp;quot;, LabelFontBold, true);


            var addresses = (from oa in _context.OfficialAddresses
                             join a in _context.Addresses
                             on oa.AddressId equals a.AddressId
                             where oa.ElectedOfficialId == result.ElectedOfficialId
                             select new AddressData
                             {
                                 AddressId = a.AddressId,
                                 Address = a.Address1,
                                 City = a.City,
                                 State = a.State,
                                 Zip = a.Zip,
                                 Phone = a.Phone,
                                 Fax = a.Fax,
                                 Email = a.Email,
                                 Web = a.URL,
                                 SortOrder = oa.SortOrder
                             }).ToList();


            bool includeAddressHeader = (addresses != null &amp;amp;&amp;amp; addresses.Count() &amp;gt; 1);
            foreach (var address in addresses)
                GenerateAddressTemplate(cells, address, includeAddressHeader);


            var table = new PdfPTable(1);
            foreach (var item in cells)
                table.AddCell(item);
            table.SpacingAfter = TableSpacingAfter;

            tables.Add(table);

            return tables;
        }


        private IList&amp;lt;PdfPCell&amp;gt; GenerateAddressTemplate(IList&amp;lt;PdfPCell&amp;gt; cells, AddressData addressData, bool generateHeader = false)
        {
            if (generateHeader == true)
            {
                Font font = new Font(DetailFont);
                font.SetStyle(Font.BOLD);
                if (addressData.SortOrder &amp;lt;= 1)
                    AddCellPadTop(cells, &amp;quot;Main Office&amp;quot;, font, true);
                else if (addressData.SortOrder &amp;gt; 1)
                    AddCellPadTop(cells, &amp;quot;Secondary Office&amp;quot;, font, true);
            }

            AddCell(cells, string.Format(&amp;quot;{0}&amp;quot;, addressData.Address), DetailFont, false);
            AddCell(cells, string.Format(&amp;quot;{0}, {1} {2}&amp;quot;, addressData.City, addressData.State, addressData.Zip), DetailFont, false);

            AddLabelTextCell(cells, &amp;quot;TEL   &amp;quot;, string.IsNullOrEmpty(addressData.Phone) || addressData.Phone.Trim() == &amp;quot;&amp;quot; ? string.Empty : string.Format(&amp;quot;{0:(###) ###-####}&amp;quot;, Convert.ToInt64(addressData.Phone)), false);
            AddLabelTextCell(cells, &amp;quot;FAX   &amp;quot;, string.IsNullOrEmpty(addressData.Fax)  || addressData.Fax.Trim() == &amp;quot;&amp;quot; ? string.Empty : string.Format(&amp;quot;{0:(###) ###-####}&amp;quot;,  Convert.ToInt64(addressData.Fax)) , false);
            AddLabelTextCell(cells, &amp;quot;WEB   &amp;quot;, addressData.Web, false);
            AddLabelTextCell(cells, &amp;quot;EMAIL &amp;quot;, addressData.Email, false);

            return cells;
        }





        private bool CanFitInColumn(PdfPTable table)
        {
            Document document = new Document(PageSize.LETTER);
            PdfWriter writer = PdfWriter.GetInstance(document, new MemoryStream());
            document.Open();
            ColumnText columnText = new ColumnText(writer.DirectContent);
            InitializeFakeColumn(columnText);
            columnText.AddElement(table);
            int tempStatus = columnText.Go(true);
            return !ColumnText.HasMoreText(tempStatus);
        }


        private ColumnText PageHeader(ColumnText columns, string headerText)
        {

            PdfPTable myTable = new PdfPTable(1);
            Rectangle rec = PageSize.LETTER;

            myTable.SetWidthPercentage(new float[] { PageSize.LETTER.Width }, rec);
 
            PdfPCell cell = new PdfPCell( new Phrase(headerText, TitleFont));
            cell.Colspan = 2;
            cell.Border= Rectangle.BOTTOM_BORDER;
            if (PageCount % 2 == 0)
            {
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.PaddingRight = CellPaddingLeft;
            }
            else
            {
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.PaddingLeft = CellPaddingLeft;
            }


            myTable.AddCell(cell);

            columns.SetSimpleColumn(20, 90, PageSize.LETTER.Width - 16, PageSize.LETTER.Height - 20);
            columns.AddElement(myTable);
            columns.Go(false);

            return columns;
        }

    }
}
&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1757-refactoring-suggestions" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1679</id>
    <published>2011-05-20T07:49:48-07:00</published>
    <updated>2011-05-23T07:51:02-07:00</updated>
    <title>[C#] Need help with refactoring &amp; optimizing </title>
    <content type="html">&lt;p&gt;Need some help optimizing &amp;amp; cleaning up the following two methods. 
&lt;br /&gt;Thanks!&lt;/p&gt;

&lt;p&gt;-- fixed up some of the errors within the code&lt;/p&gt;

&lt;pre&gt;    public class MyClass1
    {  
        private DataDestination1 _destination = new DataDestination1();
        private DataSource _source = new DataSource();

        public void ImportVoters()
        {
            LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - Beginning Import&amp;quot;, TaskName));
            var voters = _source.GetVoters(StartDate, EndDate);

            if (voters == null || !voters.Any())
            {
                LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - No voter data found for dates between {1} and {2}&amp;quot;, TaskName, StartDate, EndDate));
                return;
            }

            int totalImported = 0;
            int totalRecords = voters.Count();
            var options = new ParallelOptions { MaxDegreeOfParallelism = _maxParallel };

            var exceptions = new ConcurrentQueue&amp;lt;Exception&amp;gt;();
            var loopResult = Parallel.ForEach(voters, options, voter =&amp;gt;
            {
                try
                {
                    _destination.Push(voter);
                    var signature = _source.GetSignature(voter.CERTNUM);
                    if (signature != null)
                        _destination.Push(signature);
                    Interlocked.Increment(ref totalImported);
                }
                catch (Exception exception)
                {
                    exceptions.Enqueue(exception);
                    LoggingEngine.Instance.Error(&amp;quot;Error Import ID&amp;quot; + voter.ID + &amp;quot; &amp;quot; + exception.Message);
                }

                if (totalImported % 1000 == 0)
                    LoggingEngine.Instance.Info(Thread.CurrentThread.ManagedThreadId + &amp;quot; - &amp;quot; + &amp;quot; Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
            });

            if (exceptions.Count() &amp;gt; 0) throw new ImportException(exceptions);

            LoggingEngine.Instance.Info(&amp;quot;Import Competed: Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
        }

        private void ImportLogs()
        {
            LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - Beginning log data import&amp;quot;, TaskName));
            var logs = _source.GetVoterLogs(StartDate, EndDate);
            if (logs == null || !logs.Any())
            {
                LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - No log data found for dates between {1} and {2}&amp;quot;, TaskName, StartDate, EndDate));
                return;
            }

            int totalImported = 0;
            int totalRecords = logs.Count();
            var options = new ParallelOptions { MaxDegreeOfParallelism = _maxParallel };

            var exceptions = new ConcurrentQueue&amp;lt;Exception&amp;gt;();

            var loopResult = Parallel.ForEach(logs, options, log =&amp;gt;
            {
                try
                {
                    _destination.Push(log);
                    Interlocked.Increment(ref totalImported);
                }
                catch (Exception exception)
                {
                    exceptions.Enqueue(exception);
                    LoggingEngine.Instance.Error(&amp;quot;Error Import ID&amp;quot; + log.ID+ &amp;quot; &amp;quot; + exception.Message);
                }

                if (totalImported % 1000 == 0)
                    LoggingEngine.Instance.Info(Thread.CurrentThread.ManagedThreadId + &amp;quot; - &amp;quot; + &amp;quot; Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
            });
            if (exceptions.Count() &amp;gt; 0) throw new ImportException(exceptions);

            LoggingEngine.Instance.Info(&amp;quot;Import Complete: Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
        }
       
    }




    public class MyClass2
    {  
        private DataDestination2  _destination = new DataDestination2();
        private DataSource _source = new DataSource();

        public void ImportVoters()
        {
            LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - Beginning Import&amp;quot;, TaskName));
            var voters = _source.GetVoters(StartDate, EndDate);

            if (voters == null || !voters.Any())
            {
                LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - No voter data found for dates between {1} and {2}&amp;quot;, TaskName, StartDate, EndDate));
                return;
            }

            int totalImported = 0;
            int totalRecords = voters.Count();
            var options = new ParallelOptions { MaxDegreeOfParallelism = _maxParallel };

            var exceptions = new ConcurrentQueue&amp;lt;Exception&amp;gt;();
            var loopResult = Parallel.ForEach(voters, options, voter =&amp;gt;
            {
                try
                {
                    _destination.Push(voter);
                    var signature = _source.GetSignature(voter.CERTNUM);
                    if (signature != null)
                        _destination.Push(signature);
                    Interlocked.Increment(ref totalImported);
                }
                catch (Exception exception)
                {
                    exceptions.Enqueue(exception);
                    LoggingEngine.Instance.Error(&amp;quot;Error Import ID&amp;quot; + voter.ID + &amp;quot; &amp;quot; + exception.Message);
                }

                if (totalImported % 1000 == 0)
                    LoggingEngine.Instance.Info(Thread.CurrentThread.ManagedThreadId + &amp;quot; - &amp;quot; + &amp;quot; Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
            });
            if (exceptions.Count() &amp;gt; 0) throw new ImportException(exceptions);
            LoggingEngine.Instance.Info(&amp;quot;Import Competed: Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
        }

        private void ImportLogs()
        {
            LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - Beginning log data import&amp;quot;, TaskName));
            var logs = _source.GetVoterLogs(StartDate, EndDate);
            if (logs == null || !logs.Any())
            {
                LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - No log data found for dates between {1} and {2}&amp;quot;, TaskName, StartDate, EndDate));
                return;
            }

            int totalImported = 0;
            int totalRecords = logs.Count();
            var options = new ParallelOptions { MaxDegreeOfParallelism = _maxParallel };

            var exceptions = new ConcurrentQueue&amp;lt;Exception&amp;gt;();

            var loopResult = Parallel.ForEach(logs, options, log =&amp;gt;
            {
                try
                {
                    _destination.Push(log);
                    Interlocked.Increment(ref totalImported);
                }
                catch (Exception exception)
                {
                    exceptions.Enqueue(exception);
                    LoggingEngine.Instance.Error(&amp;quot;Error Import ID&amp;quot; + log.ID+ &amp;quot; &amp;quot; + exception.Message);
                }

                if (totalImported % 1000 == 0)
                    LoggingEngine.Instance.Info(Thread.CurrentThread.ManagedThreadId + &amp;quot; - &amp;quot; + &amp;quot; Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
            });
            if (exceptions.Count() &amp;gt; 0) throw new ImportException(exceptions);
            LoggingEngine.Instance.Info(&amp;quot;Import Complete: Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
        }

        private void ImportOtherData()
        {
            LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - Beginning other data import&amp;quot;, TaskName));
            var otherData = _source.GetOtherData(StartDate, EndDate);
            if (otherData == null || !otherData.Any())
            {
                LoggingEngine.Instance.Info(String.Format(&amp;quot;{0} - No other data found for dates between {1} and {2}&amp;quot;, TaskName, StartDate, EndDate));
                return;
            }

            int totalImported = 0;
            int totalRecords = logs.Count();
            var options = new ParallelOptions { MaxDegreeOfParallelism = _maxParallel };

            var exceptions = new ConcurrentQueue&amp;lt;Exception&amp;gt;();

            var loopResult = Parallel.ForEach(otherData, options, data=&amp;gt;
            {
                try
                {
                    _destination.Push(data);
                    Interlocked.Increment(ref totalImported);
                }
                catch (Exception exception)
                {
                    exceptions.Enqueue(exception);
                    LoggingEngine.Instance.Error(&amp;quot;Error Import ID&amp;quot; + data.ID+ &amp;quot; &amp;quot; + exception.Message);
                }

                if (totalImported % 1000 == 0)
                    LoggingEngine.Instance.Info(Thread.CurrentThread.ManagedThreadId + &amp;quot; - &amp;quot; + &amp;quot; Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
            });
            if (exceptions.Count() &amp;gt; 0) throw new ImportException(exceptions);
            LoggingEngine.Instance.Info(&amp;quot;Import Complete: Imported &amp;quot; + totalImported + &amp;quot; of &amp;quot; + totalRecords + &amp;quot; records &amp;quot;);
        }
       
    }
      &lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1679-need-help-with-refactoring-optimizing" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor560747</id>
    <published>2011-04-13T23:51:58-07:00</published>
    <title>[Python] On isprime</title>
    <content type="html">&lt;p&gt;How about something like this?&lt;/p&gt;

&lt;pre&gt;def is_prime(number): 
	if number &amp;lt; 2: return False
	return all(number % i for i in xrange(2, number))&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1647-isprime/refactors/560747" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1648</id>
    <published>2011-04-13T20:38:37-07:00</published>
    <updated>2011-04-15T09:14:17-07:00</updated>
    <title>[C#] Cleaning up this method</title>
    <content type="html">&lt;p&gt;Is there any cleaner way to write this method&lt;/p&gt;

&lt;pre&gt;        private ReportData SetPartnerInfo(ReportData reportData, string partnerPrefix, Partner partner)
        {
            PropertyInfo propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;IDType&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.IdentificationType, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;ID&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.IdentificationId1, propertyInfo.PropertyType), null);


            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;FirstName&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.FirstName, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;MiddleName&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.MiddleName, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;LastName&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.LastName, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;LastNameOnBirthCertificate&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.LastNameOnBirthCert, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;Gender&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.Gender, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;ResidenceAddress&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.Address1Combined, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;City&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.City, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;County&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.County, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;State&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.State, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;DateOfBirth&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, partner.BirthDate, null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;Age&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.Age, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;Birthplace&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.BirthPlace, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;SSN&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.SSN, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;Occupation&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.Occupation, propertyInfo.PropertyType), null);

            // Set Parent Information
            var partnerParent = partner.Parents.Where(p =&amp;gt; p.ParentType == PersonATypeCode).FirstOrDefault();

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;ParentAName&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partnerParent.FullName, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;ParentAAddress&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partnerParent.CityZipCombined, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;ParentABirthplace&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partnerParent.BirthPlace, propertyInfo.PropertyType), null);


            partnerParent = partner.Parents.Where(p =&amp;gt; p.ParentType == PersonBTypeCode).FirstOrDefault();

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;ParentBName&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partnerParent.FullName, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;ParentBAddress&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partnerParent.CityZipCombined, propertyInfo.PropertyType), null);

            propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;ParentBBirthplace&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partnerParent.BirthPlace, propertyInfo.PropertyType), null);


            var partnerRaces = partner.PartnerRaces;
            if (partnerRaces != null &amp;amp;&amp;amp; partnerRaces.Count() &amp;gt; 0)
            {
                string race = (partnerRaces.Count() == 1 ? partnerRaces.FirstOrDefault().RaceDescription : &amp;quot;OTHER&amp;quot;);
                propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;Race&amp;quot;);
                if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(race, propertyInfo.PropertyType), null);

            }

            if (propertyInfo != null) propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;OfHispanicOrigin&amp;quot;);
            if (propertyInfo != null) propertyInfo.SetValue(reportData, partner.HispanicOrigin, null);


            if (!string.IsNullOrEmpty(partner.HispanicType))
            {
                var partnerOriginInfo = _cuContext.HispanicTypeLookups.Where(ht =&amp;gt; ht.Code == partner.HispanicType).FirstOrDefault();
                if (partnerOriginInfo != null)
                {
                    propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;OfHispanicOriginInfo&amp;quot;);
                    if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partnerOriginInfo.Description, propertyInfo.PropertyType), null);
                }

            }

            int partnerHighestGradeCompleted = 0;

            if (Int32.TryParse(partner.Education, out partnerHighestGradeCompleted))
            {
                if (partnerHighestGradeCompleted &amp;gt; 12)
                {
                    propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;EducationInfo&amp;quot;);
                    if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(&amp;quot;12&amp;quot;, propertyInfo.PropertyType), null);
                    propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;HigherEducationInfo&amp;quot;);
                    if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.Education, propertyInfo.PropertyType), null);
                }
                else
                {
                    propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;EducationInfo&amp;quot;);
                    if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(partner.Education, propertyInfo.PropertyType), null);
                    propertyInfo = reportData.GetType().GetProperty(partnerPrefix + &amp;quot;HigherEducationInfo&amp;quot;);
                    if (propertyInfo != null) propertyInfo.SetValue(reportData, Convert.ChangeType(&amp;quot;00&amp;quot;, propertyInfo.PropertyType), null);
                }
            }


            return reportData;

        }&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1648-cleaning-up-this-method" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code831</id>
    <published>2009-04-18T18:14:09-07:00</published>
    <updated>2009-06-23T09:26:59-07:00</updated>
    <title>[C#] Help me Refactor My Classes &amp; Methods</title>
    <content type="html">&lt;p&gt;Please help me refactor this so that it is alot more simplified. I have numerous other model classes that do the same thing
&lt;br /&gt;Thanks in advance&lt;/p&gt;

&lt;pre&gt;UI Layer

        private void SaveEquipment()
        {
            int guid = new EquipmentService().SaveEquipment(GetEquipmentFromFormFields());
        }

        private Equipment GetEquipmentFromFormFields()
        {
            if (OriginalEquipment != null)
            {
                OriginalEquipment.Make = Make;
                OriginalEquipment.Description = Description;
                OriginalEquipment.EquipmentType = new CustomType(OwnershipId, OwnershipDescription);
                OriginalEquipment.Serial = Serial;
                OriginalEquipment.SvcNumber = SvcNumber;
                OriginalEquipment.OwnershipStatus = new CustomType(OwnershipId, OwnershipDescription);
                OriginalEquipment.PurchaseYear = PurchaseYear;
                OriginalEquipment.PurchaseRequestYear = PurchaseRequestYear;
                OriginalEquipment.CurrentLocation = new CustomType(CurrentLocationId, CurrentLocationName);
                OriginalEquipment.IsDHCP = IsDHCP;
                OriginalEquipment.Subnet = Subnet;
                OriginalEquipment.IPAddress = IPAddress;
                OriginalEquipment.Gateway = Gateway;
                OriginalEquipment.Mask = Mask;
                OriginalEquipment.DNSOne = DNSOne;
                OriginalEquipment.DNSTwo = DNSTwo;
                OriginalEquipment.Status = new CustomType(EquipmentStatusId, EquipmentStatusName);
            }
            else
            {
                OriginalEquipment = new Equipment(
                 EquipmentGuid
               , EquipmentName
               , Make
               , Description
               , new CustomType(TypeId, TypeDescription)
               , Serial
               , SvcNumber
               , new CustomType(OwnershipId, OwnershipDescription)
               , PurchaseYear
               , PurchaseRequestYear
               , new CustomType(CurrentLocationId, CurrentLocationName)
               , IsDHCP
               , Subnet
               , IPAddress
               , Gateway
               , Mask
               , DNSOne
               , DNSTwo
               , LastChangeDate
               , new CustomType(EquipmentStatusId, EquipmentStatusName)
                );
            }
            return OriginalEquipment;
        }

        private Equipment OriginalEquipment
        {
            get
            {
                if (Session[&amp;quot;OriginalEquipment&amp;quot;] != null)
                    return Session[&amp;quot;OriginalEquipment&amp;quot;] as Equipment;
                else
                    return null;
            }
            set { Session[&amp;quot;OriginalEquipment&amp;quot;] = value; }
        }

// Model Layer

namespace Model
{
    public class Equipment
    {
        private int? _guid;
        private string _name;
        private string _make;
        private string _description;
        private CustomType _equipmentType;
        private string _serial;
        private string _svcNumber;
        private CustomType _ownershipStatus;
        private string _purchaseYear;
        private string _purchaseRequestYear;
        private CustomType _currentLocation;
        private int _isDHCP;
        private string _subnet;
        private string _ipAddress;
        private string _gateway;
        private string _mask;
        private string _dnsOne;
        private string _dnsTwo;
        private DateTime? _lastChangeDate;
        private CustomType _status;
        private Dictionary&amp;lt;string, string&amp;gt; _dirtyProperties = new Dictionary&amp;lt;string, string&amp;gt;();

        public Equipment() { }

        public Equipment(
                int? guid
                , string name
                , string make
                , string description
                , CustomType equipmentType
                , string serial
                , string svcNumber
                , CustomType ownershipStatus
                , string purchaseYear
                , string purchaseRequestYear
                , CustomType currentLocation
                , int isDHCP
                , string subnet
                , string ipAddress
                , string gateway
                , string mask
                , string dnsOne
                , string dnsTwo
                , DateTime? lastChangeDate
                , CustomType status
            )
        {
            Guid = guid;
            Name = name;
            Make = make;
            Description = description;
            EquipmentType = equipmentType;
            Serial = serial;
            SvcNumber = svcNumber;
            OwnershipStatus = ownershipStatus;
            PurchaseYear = purchaseYear;
            PurchaseRequestYear = purchaseRequestYear;
            CurrentLocation = currentLocation;
            IsDHCP = isDHCP;
            Subnet = subnet;
            IPAddress = ipAddress;
            Gateway = gateway;
            Mask = mask;
            DNSOne = dnsOne;
            DNSTwo = dnsTwo;
            Status = status;
        }

        public int? Guid
        {
            get { return _guid; }
            private set
            {
                if (value.HasValue)
                {
                    if (value &amp;lt;= 0)
                        throw new Exception(&amp;quot;Invalid Guid&amp;quot;);
                    if (_guid != null &amp;amp;&amp;amp; _guid != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;equipment_id&amp;quot;))
                        _dirtyProperties.Add(&amp;quot;equipment_id&amp;quot;, value.ToString());
                    _guid = value;
                }
            }
        }

        public string Name
        {
            get { return _name; }
            private set
            {
                if (string.IsNullOrEmpty(value))
                    throw new Exception(&amp;quot;Invalid Equipment Name&amp;quot;);
                if (_name != null &amp;amp;&amp;amp; _name != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;equipment_name&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;equipment_name&amp;quot;, value);
                _name = value;
            }
        }

        public string Make
        {
            get { return _make; }
            set
            {
                if (_make != null &amp;amp;&amp;amp; _make != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;make_model&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;make_model&amp;quot;, value);
                _make = value;
            }
        }

        public string Description
        {
            get { return _description; }
            set
            {
                if (_description != null &amp;amp;&amp;amp; _description != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;short_desc&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;short_desc&amp;quot;, value);
                _description = value;
            }
        }

        public CustomType EquipmentType
        {
            get { return _equipmentType; }
            set
            {
                if (_equipmentType != null &amp;amp;&amp;amp; _equipmentType != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;equipment_type_id&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;equipment_type_id&amp;quot;, value.Id);
                _equipmentType = value;
            }
        }

        public string Serial
        {
            get { return _serial; }
            set
            {
                if (_serial != null &amp;amp;&amp;amp; _serial != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;serial_number&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;serial_number&amp;quot;, value);
                _serial = value;
            }
        }


        public string SvcNumber
        {
            get { return _svcNumber; }
            set
            {
                if (_svcNumber != null &amp;amp;&amp;amp; _svcNumber != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;service_number&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;service_number&amp;quot;, value);
                _svcNumber = value;
            }
        }

        public CustomType OwnershipStatus
        {
            get { return _ownershipStatus; }
            set
            {
                if (_ownershipStatus != null &amp;amp;&amp;amp; _ownershipStatus != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;ownership_status&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;ownership_status&amp;quot;, value.Id);
                _ownershipStatus = value;
            }
        }

        public string PurchaseYear
        {
            get { return _purchaseYear; }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    if (!Helper.IsStringNumeric(value) || value.Length != 4)
                        throw new Exception(&amp;quot;Invalid Purchase Year&amp;quot;);
                    if (_purchaseYear != null &amp;amp;&amp;amp; _purchaseYear != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;purchase_date&amp;quot;))
                        _dirtyProperties.Add(&amp;quot;purchase_date&amp;quot;, value);
                    _purchaseYear = value;
                }
            }
        }

        public string PurchaseRequestYear
        {
            get { return _purchaseRequestYear; }
            set
            {
                if (!string.IsNullOrEmpty(value))
                {
                    if (!Helper.IsStringNumeric(value) || value.Length != 4)
                        throw new Exception(&amp;quot;Invalid Purchase Request Year&amp;quot;);
                    if (_purchaseRequestYear != null &amp;amp;&amp;amp; _purchaseRequestYear != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;purchase_req_date&amp;quot;))
                        _dirtyProperties.Add(&amp;quot;purchase_req_date&amp;quot;, value);
                    _purchaseRequestYear = value;
                }
            }
        }

        public CustomType CurrentLocation
        {
            get { return _currentLocation; }
            set
            {
                if (_currentLocation != null &amp;amp;&amp;amp; _currentLocation != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;current_location_id&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;current_location_id&amp;quot;, value.Id);
                _currentLocation = value;
            }
        }

        public int IsDHCP
        {
            get { return _isDHCP; }
            set
            {
                if (_isDHCP != null &amp;amp;&amp;amp; _isDHCP != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;dhcp&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;dhcp&amp;quot;, value.ToString());
                _isDHCP = value;
            }
        }

        public string Subnet
        {
            get { return _subnet; }
            set
            {
                if (_subnet != null &amp;amp;&amp;amp; _subnet != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;subnet&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;subnet&amp;quot;, value);
                _subnet = value;
            }
        }

        public string IPAddress
        {
            get { return _ipAddress; }
            set
            {
                if (_ipAddress != null &amp;amp;&amp;amp; _ipAddress != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;ipaddr&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;ipaddr&amp;quot;, value);
                _ipAddress = value;
            }
        }

        public string Gateway
        {
            get { return _gateway; }
            set
            {
                if (_gateway != null &amp;amp;&amp;amp; _gateway != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;default_gateway&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;default_gateway&amp;quot;, value);
                _gateway = value;
            }
        }
        public string Mask
        {
            get { return _mask; }
            set
            {
                if (_mask != null &amp;amp;&amp;amp; _mask != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;netmask&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;netmask&amp;quot;, value);
                _mask = value;
            }
        }

        public string DNSOne
        {
            get { return _dnsOne; }
            set
            {
                if (_dnsOne != null &amp;amp;&amp;amp; _dnsOne != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;dns_1&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;dns_1&amp;quot;, value);
                _dnsOne = value;
            }
        }


        public string DNSTwo
        {
            get { return _dnsTwo; }
            set
            {
                if (_dnsTwo != null &amp;amp;&amp;amp; _dnsTwo != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;dns_2&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;dns_2&amp;quot;, value);
                _dnsTwo = value;
            }
        }

        public DateTime? LastChangeDate
        {
            get { return _lastChangeDate; }
            private set
            {
                if (value.HasValue)
                    _lastChangeDate = value;
            }
        }

        public CustomType Status
        {
            get { return _status; }
            set
            {
                if (_status != null &amp;amp;&amp;amp; _status != value &amp;amp;&amp;amp; !_dirtyProperties.ContainsKey(&amp;quot;equipment_status_id&amp;quot;))
                    _dirtyProperties.Add(&amp;quot;equipment_status_id&amp;quot;, value.Id);
                _status = value;
            }
        }

        public Dictionary&amp;lt;string, string&amp;gt; DirtyProperties
        {
            get { return _dirtyProperties; }
            set { _dirtyProperties = value; }
        }
    }

    
    // CustomType Class
     public class CustomType
    {
        private string _id;
        private string _description;

        public CustomType() { }

        public CustomType(string id)
        {
            Id = id;
            Description = string.Empty;
        }

        public CustomType(string id, string description)
        {
            Id = id;
            Description = description;
        }

        public string Id 
        { 
            get { return _id; } 
            set { _id = value; } 
        }
        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }
    }
}

       

namespace DAL
{
    public class EquipmentDB
    {
        public bool UpdateEquipment(Equipment entity)
        {
             if (entity.DirtyProperties.Count &amp;lt; 1)
                return false;
            bool updated;
            using (TransactionScope myScope = new TransactionScope(TransactionScopeOption.Required))
            {
                using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
                {
                    using (SqlCommand myCommand = new SqlCommand(&amp;quot;ts_create_or_match_equipment_2&amp;quot;, myConnection))
                    {
                        foreach (KeyValuePair&amp;lt;string, string&amp;gt; kvp in entity.DirtyProperties)
                        {

                            if (kvp.Key == &amp;quot;equipment_type_id&amp;quot;
                                || kvp.Key == &amp;quot;current_location_id&amp;quot;
                                || kvp.Key == &amp;quot;dhcp&amp;quot;
                                || kvp.Key == &amp;quot;equipment_status_id&amp;quot;)
                                myCommand.Parameters.Add(&amp;quot;@&amp;quot; + kvp.Key, SqlDbType.Int).Value = Int32.Parse(kvp.Value);
                            else if (kvp.Key == &amp;quot;LastChangeDate&amp;quot;)
                                myCommand.Parameters.Add(&amp;quot;@&amp;quot; + kvp.Key, SqlDbType.DateTime).Value = DateTime.Parse(kvp.Value);
                            else
                                myCommand.Parameters.AddWithValue(&amp;quot;@&amp;quot; + kvp.Key, kvp.Value);
                        }
                        myCommand.CommandType = CommandType.StoredProcedure;
                        myConnection.Open();
                        myCommand.ExecuteNonQuery();
                        updated = true;
                    }
                    myConnection.Close();
                }
                myScope.Complete();
            }
            return true;
        }

        public int InsertEquipment(Equipment entity)
        {
            int id = 0;

            using (TransactionScope myScope = new TransactionScope(TransactionScopeOption.Required))
            {
                using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
                {
                    using (SqlCommand myCommand = new SqlCommand(&amp;quot;ts_create_or_match_equipment_2&amp;quot;, myConnection))
                    {
                        myCommand.Parameters.Add(&amp;quot;@equipment_name&amp;quot;, SqlDbType.VarChar, 64).Value = entity.Name;
                        myCommand.Parameters.Add(&amp;quot;@make_model&amp;quot;, SqlDbType.VarChar, 64).Value = entity.Make;
                        myCommand.Parameters.Add(&amp;quot;@short_desc&amp;quot;, SqlDbType.VarChar, 64).Value = entity.Description;
                        if (!string.IsNullOrEmpty(entity.EquipmentType.Id))
                            myCommand.Parameters.Add(&amp;quot;@equipment_type_id&amp;quot;, SqlDbType.Int).Value = Int32.Parse(entity.EquipmentType.Id);
                        myCommand.Parameters.Add(&amp;quot;@serial_number&amp;quot;, SqlDbType.VarChar, 64).Value = entity.Serial;
                        myCommand.Parameters.Add(&amp;quot;@service_number&amp;quot;, SqlDbType.VarChar, 64).Value = entity.SvcNumber;
                        myCommand.Parameters.Add(&amp;quot;@ownership_status&amp;quot;, SqlDbType.Char).Value = entity.OwnershipStatus.Id;
                        myCommand.Parameters.Add(&amp;quot;@current_location_id&amp;quot;, SqlDbType.Int).Value = Int32.Parse(entity.CurrentLocation.Id);
                        myCommand.Parameters.Add(&amp;quot;@dhcp&amp;quot;, SqlDbType.Int).Value = entity.IsDHCP;
                        myCommand.Parameters.Add(&amp;quot;@subnet&amp;quot;, SqlDbType.VarChar, 20).Value = entity.Subnet;
                        myCommand.Parameters.Add(&amp;quot;@ipaddr&amp;quot;, SqlDbType.VarChar, 20).Value = entity.IPAddress;
                        myCommand.Parameters.Add(&amp;quot;@default_gateway&amp;quot;, SqlDbType.VarChar, 20).Value = entity.Gateway;
                        myCommand.Parameters.Add(&amp;quot;@netmask&amp;quot;, SqlDbType.VarChar, 20).Value = entity.Mask;
                        myCommand.Parameters.Add(&amp;quot;@dns_1&amp;quot;, SqlDbType.VarChar, 20).Value = entity.DNSOne;
                        myCommand.Parameters.Add(&amp;quot;@dns_2&amp;quot;, SqlDbType.VarChar, 20).Value = entity.DNSTwo;
                        myCommand.Parameters.Add(&amp;quot;@equipment_status_id&amp;quot;, SqlDbType.Int).Value = Int32.Parse(entity.Status.Id);
                        myCommand.CommandType = CommandType.StoredProcedure;
                        myConnection.Open();
                        id = myCommand.ExecuteNonQuery();
                    }
                    myConnection.Close();
                }
                myScope.Complete();
            }
            return id;
        }

    }
}&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/831-help-me-refactor-my-class-function" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor152877</id>
    <published>2009-03-24T22:41:33-07:00</published>
    <title>[C#] On Refactoring Help Needed</title>
    <content type="html">&lt;p&gt;How does sp_InsertAddress and sp_UpdateAddress figure out that you are inserting/updating a current address as opposed to a former or mailing address? Is this based on the @address_street_type parameter containing &amp;quot;Current Address&amp;quot;, &amp;quot;Former Address&amp;quot;, or &amp;quot;Mailing Address&amp;quot; ? Or is @address_street_type actually suppose to contain &amp;quot;Avenue&amp;quot;, &amp;quot;Street&amp;quot;, &amp;quot;Road&amp;quot;, &amp;quot;Place&amp;quot;, &amp;quot;Lane&amp;quot;, &amp;quot;Boulevard&amp;quot;, etc?&lt;/p&gt;

&lt;p&gt;-- I forgot to add a parameter for @address_type. This would be used to detect if it is a current/former/mailing address.&lt;/p&gt;

&lt;p&gt;Can I assume that using the @gender at lines 442, 452, 654, 664 typos? Same for getAddressCity() being put into @address_state?&lt;/p&gt;

&lt;p&gt;-- Yes sorry about that.&lt;/p&gt;

&lt;p&gt;Can the interfaces IName, IAddress, and IPerson be changed or deleted? With your code above it doesn't look like they are actually used much.&lt;/p&gt;

&lt;p&gt;-- Yes they can be changed.&lt;/p&gt;

&lt;p&gt;Below is a quick refactoring, but there is still room for a lot more that can be done.&lt;/p&gt;

&lt;p&gt;-- Thanks for your help!&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/798-refactoring-help-needed/refactors/152877" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code798</id>
    <published>2009-03-24T00:41:50-07:00</published>
    <updated>2009-03-24T22:41:33-07:00</updated>
    <title>[C#] Refactoring Help Needed</title>
    <content type="html">&lt;p&gt;Please help me make this code more maintainable.&lt;/p&gt;

&lt;p&gt;Thanks in advance&lt;/p&gt;

&lt;pre&gt;public interface IName
{
    string getLastName();
    string getFirstName();
    string getMiddleName();
    string getSuffixName();
}

public class Name : IName
{
    private string _lastName;
    private string _firstName;
    private string _middleName;
    private string _suffixName;

    // Validation Methods
    // private set methods

    #region IName Members

    public string getLastName()
    {
        return _lastName;
    }

    public string getFirstName()
    {
        return _firstName;
    }

    public string getMiddleName()
    {
        return _middleName;
    }

    public string getSuffixName()
    {
        return _suffixName;
    }

    #endregion
}


public interface IAddress
{
    string getAddressNumber();
    string getAddressDirection();
    string getAddressStreet();
    string getAddressStreetType();
    string getAddressAptNum();
    string getAddressCity();
    string getAddressState();
    string getAddressZipcode();
    string getAddressCounty();
}

public class Address : IAddress
{
    private string _addressNumber;
    private string _addressDirection;
    private string _addressStreet;
    private string _addressStreetType;
    private string _addressAptNum;
    private string _addressrCity;
    private string _addressState;
    private string _addressZipcode;
    private string _addressCounty;

    // Validation Methods
    // private Set Methods
    // public get methods


    #region IAddress Members

    public string getAddressNumber()
    {
        return _addressNumber;
    }

    public string getAddressDirection()
    {
        return _addressDirection;
    }

    public string getAddressStreet()
    {
        return _addressStreet;
    }

    public string getAddressStreetType()
    {
        return _addressStreetType;
    }

    public string getAddressAptNum()
    {
        return _addressAptNum;
    }

    public string getAddressCity()
    {
        return _addressrCity;
    }

    public string getAddressState()
    {
        return _addressState;
    }

    public string getAddressZipcode()
    {
        return _addressZipcode;
    }

    public string getAddressCounty()
    {
        return _addressCounty;
    }

    #endregion
}
public interface IPerson
{
    int getId();
    IName getCurrentName();
    IName getFormerName();

    IAddress getCurrentAddress();
    IAddress getFormerAddress();
    IAddress getMailingAddress();

    DateTime getBirthdate();
    string getGender();
    string getSSNumber();
    string getPersonType();
    DateTime getRegistrationDate();
    string getIPAddress();
    string getBrowserInfo();

    string getHomePhone();
    string getWorkPhone();
    string getCellPhone();
    string getFaxNumber();
    string getEmailAddress();
    string getSecondaryEmailAddress();
    string getDriversLicense();

    bool save();
    void load();

}

public class Person : IPerson
{
    private int _id;
    private IName _currentName;
    private IName _formerName;

    private IAddress _currentAddress;
    private IAddress _formerAddress;
    private IAddress _mailingAddress;

    private DateTime _birthdate;
    private string _gender;
    private string _ssNumber;
    private string _personType;
    private DateTime _registrationDate;
    private string _ipAddress;
    private string _browserInfo;
    private string _driversLicense;

    private string _homePhone;
    private string _workPhone;
    private string _cellPhone;
    private string _faxNumber;
    private string _emailAddress;
    private string _secondaryEmailAddress;
    
    
    // private set methods

    #region IPerson Members

    public bool save()
    {
        DataLayer dl = new DataLayer();
        if (_id == 0)
            return dl.insertPerson(this);
        else
            return dl.updatePerson(this);
    }

    public void load()
    {
    }

    public int getId()
    {
        return _id;
    }

    public IName getCurrentName()
    {
        return _currentName;
    }

    public IName getFormerName()
    {
        return _formerName;
    }

    public IAddress getCurrentAddress()
    {
        return _currentAddress;
    }

    public IAddress getFormerAddress()
    {
        return _formerAddress;
    }

    public IAddress getMailingAddress()
    {
        return _mailingAddress;
    }

    public DateTime getBirthdate()
    {
        return _birthdate;
    }

    public string getGender()
    {
        return _gender;
    }

    public string getSSNumber()
    {
        return _ssNumber;
    }

    public string getPersonType()
    {
        return _personType;
    }

    public DateTime getRegistrationDate()
    {
        return _registrationDate;
    }

    public string getIPAddress()
    {
        return _ipAddress;
    }

    public string getBrowserInfo()
    {
        return _browserInfo;
    }

    public string getHomePhone()
    {
        return _homePhone;
    }

    public string getWorkPhone()
    {
        return _workPhone;
    }

    public string getCellPhone()
    {
        return _cellPhone;
    }

    public string getFaxNumber()
    {
        return _faxNumber;
    }

    public string getEmailAddress()
    {
        return _emailAddress;
    }

    public string getSecondaryEmailAddress()
    {
        return _secondaryEmailAddress;
    }

    public string getDriversLicense()
    {
        return _driversLicense;
    }

    #endregion
}

public class DataLayer
{

    public bool insertPerson(IPerson person)
    {
        bool inserted = false;
        SqlConnection cnDB = DatabaseConnection.GetOpenDBConnection();
        try
        {
            SqlCommand cmDB = new SqlCommand(&amp;quot;sp_InsertName&amp;quot;, cnDB);
            cmDB.CommandType = CommandType.StoredProcedure;
            cmDB.Parameters.Add(&amp;quot;@last_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@last_name&amp;quot;].Value = person.getCurrentName().getLastName();
            cmDB.Parameters.Add(&amp;quot;@first_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@first_name&amp;quot;].Value = person.getCurrentName().getFirstName();
            cmDB.Parameters.Add(&amp;quot;@middle_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@middle_name&amp;quot;].Value = person.getCurrentName().getMiddleName();
            cmDB.Parameters.Add(&amp;quot;@suffix_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@suffix_name&amp;quot;].Value = person.getCurrentName().getSuffixName();
            int id = cmDB.ExecuteNonQuery();

            cmDB = new SqlCommand(&amp;quot;sp_InsertName&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@former_last_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@former_last_name&amp;quot;].Value = person.getFormerName().getLastName();
            cmDB.Parameters.Add(&amp;quot;@former_first_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@former_first_name&amp;quot;].Value = person.getFormerName().getFirstName();
            cmDB.Parameters.Add(&amp;quot;@former_middle_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@former_middle_name&amp;quot;].Value = person.getFormerName().getMiddleName();
            cmDB.Parameters.Add(&amp;quot;@former_suffix_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@former_suffix_name&amp;quot;].Value = person.getFormerName().getSuffixName();
            cmDB.ExecuteNonQuery();

            // Insert Current Address

            cmDB = new SqlCommand(&amp;quot;sp_InsertAddress&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@address_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_number&amp;quot;].Value = person.getCurrentAddress().getAddressNumber();
            cmDB.Parameters.Add(&amp;quot;@address_direction&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_direction&amp;quot;].Value = person.getCurrentAddress().getAddressDirection();
            cmDB.Parameters.Add(&amp;quot;@address_street&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street&amp;quot;].Value = person.getCurrentAddress().getAddressStreet();
            cmDB.Parameters.Add(&amp;quot;@address_street_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street_type&amp;quot;].Value = person.getCurrentAddress().getAddressStreetType();
            cmDB.Parameters.Add(&amp;quot;@address_apt_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_apt_number&amp;quot;].Value = person.getCurrentAddress().getAddressAptNum();
            cmDB.Parameters.Add(&amp;quot;@address_city&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_city&amp;quot;].Value = person.getCurrentAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_state&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_state&amp;quot;].Value = person.getCurrentAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_zipcode&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_zipcode&amp;quot;].Value = person.getCurrentAddress().getAddressZipcode();
            cmDB.Parameters.Add(&amp;quot;@address_county&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_county&amp;quot;].Value = person.getCurrentAddress().getAddressCounty();
            cmDB.ExecuteNonQuery();

            // Insert Former Address

            cmDB = new SqlCommand(&amp;quot;sp_InsertAddress&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@address_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_number&amp;quot;].Value = person.getFormerAddress().getAddressNumber();
            cmDB.Parameters.Add(&amp;quot;@address_direction&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_direction&amp;quot;].Value = person.getFormerAddress().getAddressDirection();
            cmDB.Parameters.Add(&amp;quot;@address_street&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street&amp;quot;].Value = person.getFormerAddress().getAddressStreet();
            cmDB.Parameters.Add(&amp;quot;@address_street_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street_type&amp;quot;].Value = person.getFormerAddress().getAddressStreetType();
            cmDB.Parameters.Add(&amp;quot;@address_apt_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_apt_number&amp;quot;].Value = person.getFormerAddress().getAddressAptNum();
            cmDB.Parameters.Add(&amp;quot;@address_city&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_city&amp;quot;].Value = person.getFormerAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_state&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_state&amp;quot;].Value = person.getFormerAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_zipcode&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_zipcode&amp;quot;].Value = person.getFormerAddress().getAddressZipcode();
            cmDB.Parameters.Add(&amp;quot;@address_county&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_county&amp;quot;].Value = person.getFormerAddress().getAddressCounty();
            cmDB.ExecuteNonQuery();

            // Insert Mailing Address

            cmDB = new SqlCommand(&amp;quot;sp_InsertAddress&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@address_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_number&amp;quot;].Value = person.getMailingAddress().getAddressNumber();
            cmDB.Parameters.Add(&amp;quot;@address_direction&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_direction&amp;quot;].Value = person.getMailingAddress().getAddressDirection();
            cmDB.Parameters.Add(&amp;quot;@address_street&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street&amp;quot;].Value = person.getMailingAddress().getAddressStreet();
            cmDB.Parameters.Add(&amp;quot;@address_street_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street_type&amp;quot;].Value = person.getMailingAddress().getAddressStreetType();
            cmDB.Parameters.Add(&amp;quot;@address_apt_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_apt_number&amp;quot;].Value = person.getMailingAddress().getAddressAptNum();
            cmDB.Parameters.Add(&amp;quot;@address_city&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_city&amp;quot;].Value = person.getMailingAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_state&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_state&amp;quot;].Value = person.getMailingAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_zipcode&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_zipcode&amp;quot;].Value = person.getMailingAddress().getAddressZipcode();
            cmDB.Parameters.Add(&amp;quot;@address_county&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_county&amp;quot;].Value = person.getMailingAddress().getAddressCounty();
            cmDB.ExecuteNonQuery();

            // insert Personal Info

            cmDB = new SqlCommand(&amp;quot;sp_InsertPersonalInfo&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@birthdate&amp;quot;, System.Data.SqlDbType.DateTime);
            cmDB.Parameters[&amp;quot;@birthdate&amp;quot;].Value = person.getBirthdate();
            cmDB.Parameters.Add(&amp;quot;@gender&amp;quot;, System.Data.SqlDbType.VarChar,1);
            cmDB.Parameters[&amp;quot;@gender&amp;quot;].Value = person.getGender();
            cmDB.Parameters.Add(&amp;quot;@ss_number&amp;quot;, System.Data.SqlDbType.VarChar,20);
            cmDB.Parameters[&amp;quot;@ss_number&amp;quot;].Value = person.getSSNumber();
            cmDB.Parameters.Add(&amp;quot;@person_type&amp;quot;, System.Data.SqlDbType.VarChar,20);
            cmDB.Parameters[&amp;quot;@person_type&amp;quot;].Value = person.getPersonType();
            cmDB.Parameters.Add(&amp;quot;@registration_date&amp;quot;, System.Data.SqlDbType.DateTime);
            cmDB.Parameters[&amp;quot;@registration_date&amp;quot;].Value = person.getRegistrationDate();
            cmDB.Parameters.Add(&amp;quot;@ip_address&amp;quot;, System.Data.SqlDbType.VarChar,20);
            cmDB.Parameters[&amp;quot;@ip_address&amp;quot;].Value = person.getIPAddress();
            cmDB.Parameters.Add(&amp;quot;@browser_info&amp;quot;, System.Data.SqlDbType.VarChar,20);
            cmDB.Parameters[&amp;quot;@browser_info&amp;quot;].Value = person.getBrowserInfo();
            cmDB.Parameters.Add(&amp;quot;@drivers_license&amp;quot;, System.Data.SqlDbType.VarChar,20);
            cmDB.Parameters[&amp;quot;@drivers_license&amp;quot;].Value = person.getDriversLicense();
            cmDB.ExecuteNonQuery();

            //insert email address contact type
            cmDB = new SqlCommand(&amp;quot;sp_InsertContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar,50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Email&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@gender&amp;quot;].Value = person.getEmailAddress();
            cmDB.ExecuteNonQuery();

            //insert secondary email address contact type
            cmDB = new SqlCommand(&amp;quot;sp_InsertContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Secondary Email&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@gender&amp;quot;].Value = person.getSecondaryEmailAddress();
            cmDB.ExecuteNonQuery();

            //insert home phone contact type
            cmDB = new SqlCommand(&amp;quot;sp_InsertContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Home Phone&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact&amp;quot;].Value = person.getHomePhone();
            cmDB.ExecuteNonQuery();

            //insert work phone contact type
            cmDB = new SqlCommand(&amp;quot;sp_InsertContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Work Phone&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact&amp;quot;].Value = person.getWorkPhone();
            cmDB.ExecuteNonQuery();

            //insert cell phone contact type
            cmDB = new SqlCommand(&amp;quot;sp_InsertContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Cell Phone&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact&amp;quot;].Value = person.getCellPhone();
            cmDB.ExecuteNonQuery();

            //insert cell phone contact type
            cmDB = new SqlCommand(&amp;quot;sp_InsertContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Fax Number&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact&amp;quot;].Value = person.getFaxNumber();
            cmDB.ExecuteNonQuery();


            inserted = true;
        }
        catch (SqlException sqlEx)
        {
            throw new Exception(GetSqlExceptionMessage(sqlEx.Number));
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (cnDB.State == ConnectionState.Open)
                cnDB.Close();
        }
        return inserted;
    }

    public bool updatePerson(IPerson person)
    {
        bool inserted = false;
        SqlConnection cnDB = DatabaseConnection.GetOpenDBConnection();
        try
        {
            string id = person.getId();

            SqlCommand cmDB = new SqlCommand(&amp;quot;sp_UpdateName&amp;quot;, cnDB);
            cmDB.CommandType = CommandType.StoredProcedure;
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@last_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@last_name&amp;quot;].Value = person.getCurrentName().getLastName();
            cmDB.Parameters.Add(&amp;quot;@first_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@first_name&amp;quot;].Value = person.getCurrentName().getFirstName();
            cmDB.Parameters.Add(&amp;quot;@middle_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@middle_name&amp;quot;].Value = person.getCurrentName().getMiddleName();
            cmDB.Parameters.Add(&amp;quot;@suffix_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@suffix_name&amp;quot;].Value = person.getCurrentName().getSuffixName();
            cmDB.ExecuteNonQuery();

            cmDB = new SqlCommand(&amp;quot;sp_UpdateName&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@former_last_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@former_last_name&amp;quot;].Value = person.getFormerName().getLastName();
            cmDB.Parameters.Add(&amp;quot;@former_first_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@former_first_name&amp;quot;].Value = person.getFormerName().getFirstName();
            cmDB.Parameters.Add(&amp;quot;@former_middle_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@former_middle_name&amp;quot;].Value = person.getFormerName().getMiddleName();
            cmDB.Parameters.Add(&amp;quot;@former_suffix_name&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@former_suffix_name&amp;quot;].Value = person.getFormerName().getSuffixName();
            cmDB.ExecuteNonQuery();

            // Update Current Address

            cmDB = new SqlCommand(&amp;quot;sp_UpdateAddress&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@address_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_number&amp;quot;].Value = person.getCurrentAddress().getAddressNumber();
            cmDB.Parameters.Add(&amp;quot;@address_direction&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_direction&amp;quot;].Value = person.getCurrentAddress().getAddressDirection();
            cmDB.Parameters.Add(&amp;quot;@address_street&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street&amp;quot;].Value = person.getCurrentAddress().getAddressStreet();
            cmDB.Parameters.Add(&amp;quot;@address_street_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street_type&amp;quot;].Value = person.getCurrentAddress().getAddressStreetType();
            cmDB.Parameters.Add(&amp;quot;@address_apt_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_apt_number&amp;quot;].Value = person.getCurrentAddress().getAddressAptNum();
            cmDB.Parameters.Add(&amp;quot;@address_city&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_city&amp;quot;].Value = person.getCurrentAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_state&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_state&amp;quot;].Value = person.getCurrentAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_zipcode&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_zipcode&amp;quot;].Value = person.getCurrentAddress().getAddressZipcode();
            cmDB.Parameters.Add(&amp;quot;@address_county&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_county&amp;quot;].Value = person.getCurrentAddress().getAddressCounty();
            cmDB.ExecuteNonQuery();

            // Update Former Address

            cmDB = new SqlCommand(&amp;quot;sp_UpdateAddress&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@address_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_number&amp;quot;].Value = person.getFormerAddress().getAddressNumber();
            cmDB.Parameters.Add(&amp;quot;@address_direction&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_direction&amp;quot;].Value = person.getFormerAddress().getAddressDirection();
            cmDB.Parameters.Add(&amp;quot;@address_street&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street&amp;quot;].Value = person.getFormerAddress().getAddressStreet();
            cmDB.Parameters.Add(&amp;quot;@address_street_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street_type&amp;quot;].Value = person.getFormerAddress().getAddressStreetType();
            cmDB.Parameters.Add(&amp;quot;@address_apt_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_apt_number&amp;quot;].Value = person.getFormerAddress().getAddressAptNum();
            cmDB.Parameters.Add(&amp;quot;@address_city&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_city&amp;quot;].Value = person.getFormerAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_state&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_state&amp;quot;].Value = person.getFormerAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_zipcode&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_zipcode&amp;quot;].Value = person.getFormerAddress().getAddressZipcode();
            cmDB.Parameters.Add(&amp;quot;@address_county&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_county&amp;quot;].Value = person.getFormerAddress().getAddressCounty();
            cmDB.ExecuteNonQuery();

            // Update Mailing Address

            cmDB = new SqlCommand(&amp;quot;sp_UpdateAddress&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@address_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_number&amp;quot;].Value = person.getMailingAddress().getAddressNumber();
            cmDB.Parameters.Add(&amp;quot;@address_direction&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_direction&amp;quot;].Value = person.getMailingAddress().getAddressDirection();
            cmDB.Parameters.Add(&amp;quot;@address_street&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street&amp;quot;].Value = person.getMailingAddress().getAddressStreet();
            cmDB.Parameters.Add(&amp;quot;@address_street_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_street_type&amp;quot;].Value = person.getMailingAddress().getAddressStreetType();
            cmDB.Parameters.Add(&amp;quot;@address_apt_number&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_apt_number&amp;quot;].Value = person.getMailingAddress().getAddressAptNum();
            cmDB.Parameters.Add(&amp;quot;@address_city&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_city&amp;quot;].Value = person.getMailingAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_state&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_state&amp;quot;].Value = person.getMailingAddress().getAddressCity();
            cmDB.Parameters.Add(&amp;quot;@address_zipcode&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_zipcode&amp;quot;].Value = person.getMailingAddress().getAddressZipcode();
            cmDB.Parameters.Add(&amp;quot;@address_county&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@address_county&amp;quot;].Value = person.getMailingAddress().getAddressCounty();
            cmDB.ExecuteNonQuery();

            // Update Personal Info

            cmDB = new SqlCommand(&amp;quot;sp_UpdatePersonalInfo&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@birthdate&amp;quot;, System.Data.SqlDbType.DateTime);
            cmDB.Parameters[&amp;quot;@birthdate&amp;quot;].Value = person.getBirthdate();
            cmDB.Parameters.Add(&amp;quot;@gender&amp;quot;, System.Data.SqlDbType.VarChar, 1);
            cmDB.Parameters[&amp;quot;@gender&amp;quot;].Value = person.getGender();
            cmDB.Parameters.Add(&amp;quot;@ss_number&amp;quot;, System.Data.SqlDbType.VarChar, 20);
            cmDB.Parameters[&amp;quot;@ss_number&amp;quot;].Value = person.getSSNumber();
            cmDB.Parameters.Add(&amp;quot;@person_type&amp;quot;, System.Data.SqlDbType.VarChar, 20);
            cmDB.Parameters[&amp;quot;@person_type&amp;quot;].Value = person.getPersonType();
            cmDB.Parameters.Add(&amp;quot;@registration_date&amp;quot;, System.Data.SqlDbType.DateTime);
            cmDB.Parameters[&amp;quot;@registration_date&amp;quot;].Value = person.getRegistrationDate();
            cmDB.Parameters.Add(&amp;quot;@ip_address&amp;quot;, System.Data.SqlDbType.VarChar, 20);
            cmDB.Parameters[&amp;quot;@ip_address&amp;quot;].Value = person.getIPAddress();
            cmDB.Parameters.Add(&amp;quot;@browser_info&amp;quot;, System.Data.SqlDbType.VarChar, 20);
            cmDB.Parameters[&amp;quot;@browser_info&amp;quot;].Value = person.getBrowserInfo();
            cmDB.Parameters.Add(&amp;quot;@drivers_license&amp;quot;, System.Data.SqlDbType.VarChar, 20);
            cmDB.Parameters[&amp;quot;@drivers_license&amp;quot;].Value = person.getDriversLicense();
            cmDB.ExecuteNonQuery();

            //Update email address contact type
            cmDB = new SqlCommand(&amp;quot;sp_UpdateContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Email&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@gender&amp;quot;].Value = person.getEmailAddress();
            cmDB.ExecuteNonQuery();

            //Update secondary email address contact type
            cmDB = new SqlCommand(&amp;quot;sp_UpdateContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Secondary Email&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@gender&amp;quot;].Value = person.getSecondaryEmailAddress();
            cmDB.ExecuteNonQuery();

            //Update home phone contact type
            cmDB = new SqlCommand(&amp;quot;sp_UpdateContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Home Phone&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact&amp;quot;].Value = person.getHomePhone();
            cmDB.ExecuteNonQuery();

            //Update work phone contact type
            cmDB = new SqlCommand(&amp;quot;sp_UpdateContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Work Phone&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact&amp;quot;].Value = person.getWorkPhone();
            cmDB.ExecuteNonQuery();

            //Update cell phone contact type
            cmDB = new SqlCommand(&amp;quot;sp_UpdateContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Cell Phone&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact&amp;quot;].Value = person.getCellPhone();
            cmDB.ExecuteNonQuery();

            //Update cell phone contact type
            cmDB = new SqlCommand(&amp;quot;sp_UpdateContactType&amp;quot;, cnDB);
            cmDB.Parameters.Add(&amp;quot;@person_id&amp;quot;, System.Data.SqlDbType.Int);
            cmDB.Parameters[&amp;quot;@person_id&amp;quot;].Value = id;
            cmDB.Parameters.Add(&amp;quot;@contact_type&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact_type&amp;quot;].Value = &amp;quot;Fax Number&amp;quot;;
            cmDB.Parameters.Add(&amp;quot;@contact&amp;quot;, System.Data.SqlDbType.VarChar, 50);
            cmDB.Parameters[&amp;quot;@contact&amp;quot;].Value = person.getFaxNumber();
            cmDB.ExecuteNonQuery();
            inserted = true;
        }
        catch (SqlException sqlEx)
        {
            throw new Exception(GetSqlExceptionMessage(sqlEx.Number));
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (cnDB.State == ConnectionState.Open)
                cnDB.Close();
        }
        return inserted;

    }
}

&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/798-refactoring-help-needed" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code790</id>
    <published>2009-03-17T21:25:19-07:00</published>
    <updated>2009-03-19T08:03:21-07:00</updated>
    <title>[C#] Import File</title>
    <content type="html">&lt;p&gt;How would you refactor this?&lt;/p&gt;

&lt;pre&gt;    protected void btnUpload_Click(object sender, EventArgs e)
    {
        try
        {
            string strImportType = ddlImportType.SelectedValue.ToUpper();
            string strElection = ddlElection.SelectedValue.Trim();
            Stream fileStream = FileUpload1.FileContent;
            verifyUser();

            if (!isValidFile(FileUpload1.FileName.ToString().Trim())) return;

            DataSet dsImport = buildDataSet(fileStream, &amp;quot;Import&amp;quot;, &amp;quot;\t&amp;quot;);

            int rowsCount = dsImport.Tables[0].Rows.Count;
            int rowsImportedCount = 0;

            if (!isValidData(dsImport, strElection, strImportType)) return;

            switch (strImportType)
            {
                case &amp;quot;USERS&amp;quot;:
                    rowsImportedCount = cDataLayer.importVoters(dsImport.Tables[&amp;quot;Import&amp;quot;], strElection);
                    break;
                case &amp;quot;OFFICES&amp;quot;:
                    rowsImportedCount = cDataLayer.importOffices(dsImport.Tables[&amp;quot;Import&amp;quot;]);
                    break;
                case &amp;quot;GROUP OFFICES&amp;quot;:
                    rowsImportedCount = cDataLayer.importGroupOffices(dsImport.Tables[&amp;quot;Import&amp;quot;], strElection);
                    break;
            }
            jsMsgBox(&amp;quot;Imported &amp;quot; + rowsCount + &amp;quot; of &amp;quot; + rowsImportedCount + &amp;quot; rows successfully!&amp;quot;);
        }
        catch (Exception ex)
        {
            jsMsgBox(ex.Message);
        }
    }

    private Boolean isValidFile(string strFileName)
    {
        if (strFileName == string.Empty)
        {
            jsMsgBox(&amp;quot;No File Selected.&amp;quot;);
            return false;
        }
        return true;
    }

    private bool isValidData(DataSet dsImport, string strElection, string strImportType)
    {
        bool valid = true;
        int rowCount = dsImport.Tables[0].Rows.Count;
        int colCount = dsImport.Tables[0].Columns.Count;
        string errorFormat = &amp;quot;The import file is not in the correct format. Import cancelled.&amp;quot;;
        string errorElection = &amp;quot;The import file does not contain the specified election. Import cancelled.&amp;quot;;

        if (rowCount &amp;lt; 1) return false;

        switch (strImportType)
        {
  
            case &amp;quot;USERS&amp;quot;:
                if (colCount != 19)
                {
                    jsMsgBox(errorFormat);
                    return false;
                }
                if (dsImport.Tables[0].Rows[1].ItemArray[2].ToString() != strElection)
                {
                    jsMsgBox(errorElection);
                    return false;
                }    
                break;
            case &amp;quot;OFFICES&amp;quot;:
                if (colCount != 3)
                {
                    jsMsgBox(errorFormat);
                    return false;
                }
                break;
            case &amp;quot;GROUP OFFICES&amp;quot;:
                if (colCount != 6)
                {
                    jsMsgBox(errorFormat);
                    return false;
                }
                if (dsImport.Tables[0].Rows[1].ItemArray[0].ToString() != strElection)
                {
                    jsMsgBox(errorElection);
                    return false;
                }
                break;
            default:
                jsMsgBox(&amp;quot;Invalid Import Type Specified&amp;quot;);
                valid = false;
                break;
        }
        return valid;
    }

    public DataSet buildDataSet(Stream fileStream, string tableName, string delimeter)
    {
        DataSet domains = new DataSet();
        domains.Tables.Add(tableName);
        try
        {
            StreamReader reader = new StreamReader(fileStream);
            string[] columns = reader.ReadLine().Split(delimeter.ToCharArray());
            foreach (string col in columns)
            {
                bool added = false;
                int i = 0;
                while (!(added))
                {
                    string columnName = col;
                    if (!(domains.Tables[tableName].Columns.Contains(columnName)))
                    {
                        domains.Tables[tableName].Columns.Add(columnName, typeof(string));
                        added = true;
                    }
                    else
                    {
                        i++;
                    }
                }
            }
            string strLine = string.Empty;
            do
            {
                strLine = reader.ReadLine();
                if (!string.IsNullOrEmpty(strLine))
                {
                    string[] items = strLine.Split(delimeter.ToCharArray());
                    domains.Tables[tableName].Rows.Add(items);
                }
            } while (strLine != null);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return domains;
    }





&lt;/pre&gt;</content>
    <author>
      <name>zsysop.myopenid.com</name>
      <email>zsysop@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/790-import-file" rel="alternate"/>
  </entry>
</feed>

