<?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:users1322</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/1322" rel="self"/>
  <title>Sekhat</title>
  <updated>Wed Jan 26 14:06:41 -0800 2011</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor553205</id>
    <published>2011-01-26T14:06:41-08:00</published>
    <title>[C#] On simplify the timer tick method  </title>
    <content type="html">&lt;p&gt;I only took a stab at the first timer tick, I have no idea if this code works, but I've only really split methods out.&lt;/p&gt;

&lt;p&gt;It's worth noting that some of the methods I've split out should probably exist on other classes in your application rather than grouped within which ever class this exists in. Any who, my goal was to try and make the code easier to follow. Though with limited context of the terminology you use and knowledge of what external methods that you used do I may have broken up methods incorrectly.&lt;/p&gt;

&lt;p&gt;What you should take away from this though is not code you can copy and paste, but rather ideas on how you can refactor your code yourself :)&lt;/p&gt;

&lt;pre&gt;    private void DispatcherTimerForPing_Tick(object sender, EventArgs eventArgs)
        {

            try
            {
                new System.Threading.Tasks.Task(UpdateChatWindow).Start();

            }
            catch (Exception exception)
            {
                _msgBox.ShowException(exception);
            }

            GC.Collect();
            GC.SuppressFinalize(this);
        }


    private void UpdateChatWindows()
    {
        Account.Ping = _service.Ping(Account);

        new System.Action(UpdateGui).OnUIThread();                        
    }

    private void UpdateGui()
    {
        RefreshDetailData();
        UpdateMessagesOnScreen();
    }

    private void RefreshDetailData()
    {
       //refresh detailData object on chatScreen
        foreach (var item in _chatScreenManager.ActiveChatScreens)
        {
            var detailData = _service.DetailData(Account, item.Key);


            //repair broken data IsFriend
            foreach (var f in Friends.Where(f =&amp;gt; f.Nick == detailData.Info.Nick))
            {
                detailData.Info.IsFriend = true;
            }

            //publish on chat screen
            _chatScreenEventAgg.Publish(detailData);
        }
    }

    private void UpdateMessagesOnScreen()
    {
        //check if you have new messanges
        if (Account.Ping.Rp &amp;gt; 0)
        {
            //load new messanges
            for (int i = 0; i &amp;lt; Account.Ping.Rp; i++)
            {                                
                try
                {
                    //load new message
                    var rp = _service.LoadRp(Account);

                    //if user have some message
                    if (rp != null)
                    {
                        //check if chat screen for user is open
                        if (!IsChatScreenForContactActive(rp.Nick))
                        {
                            OpenChatWindowWithHistory(rp);

                            PublishAndSaveMessage(rp);
                        }
                        else
                        {
                            PublishAndSaveMessage(rp);
                        }                        
                    }
                }
                catch (Exception exception)
                {
                    if (exception.Message == &amp;quot;Nem&#195;&#161;&#197;&#161; &#197;&#190;iadne nov&#195;&#169; spr&#195;&#161;vy&amp;quot;)
                    {

                    }
                    _msgBox.ShowException(exception);
                }                               
            }
        }
    }

    private void OpenChatWindowWithHistory(/* whatever type rp is */ rp)
    {
        //open chat screen
        _chatScreenManager.OpenChatScreen(Account,_service.DetailData(Account, rp.Nick),
            Account.Nick);

        //add message to history
        AddConversationHistory(rp.Nick);
    }

    private void PublishAndSaveMessage(/* whatever type rp is */ rp)
    {
        //publish message on chat screen
        PublishOnChatScreen(rp);

        //save message
        _msgHistory.SaveRp(rp);
    }

    private void IsChatScreenForContactActive(string nick)
    {
        _chatScreenManager.ActiveChatScreens.ContainsKey(nick)
    }
&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1585-simplify-the-timer-tick-method/refactors/553205" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor553018</id>
    <published>2011-01-24T16:57:29-08:00</published>
    <title>[C#] On if / switch horror </title>
    <content type="html">&lt;p&gt;this should behave exactly as yours currently does (including the fact that it'll return colWidth if your colName does not equal col0 - 4)&lt;/p&gt;

&lt;p&gt;Nicer on my eyes at least :)&lt;/p&gt;

&lt;pre&gt;Dictionary&amp;lt;string, int&amp;gt; columnToMinimumRequiredWidthMapping = new Dictionary&amp;lt;string, int&amp;gt;()
        {
            { &amp;quot;col0&amp;quot;, 0 },
            { &amp;quot;col1&amp;quot;, 270 },
            { &amp;quot;col2&amp;quot;, 520 },
            { &amp;quot;col3&amp;quot;, 770 },
            { &amp;quot;col4&amp;quot;, 1020 }
        };

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string colName = parameter.ToString();
            int windowWidth = System.Convert.ToInt32(value.ToString());
            const int colWidth = 180;

            if (columnToMinimumRequiredWidthMapping.ContainsKey(colName))
            {
                return windowWidth &amp;gt;= columnToMinimumRequiredWidthMapping[colName] ? colWidth : 0;
            }
            
            return colWidth;
        }&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1583-if-switch-horror/refactors/553018" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor553014</id>
    <published>2011-01-24T16:25:33-08:00</published>
    <title>[C#] On Validate a week</title>
    <content type="html">&lt;p&gt;Well that brings it down to 2 iterations. One for an array and one for the week order / day validation. With (I hope) a small loss in legibility. Thoughts?&lt;/p&gt;

&lt;pre&gt;public class WeekValidator
    {
        public bool IsValidSevenDayWeek(IEnumerable&amp;lt;DayOfWeek&amp;gt; week)
        {
            var weekDays = week.ToArray();

            return ContainsSevenDays(weekDays) &amp;amp;&amp;amp;
                   DaysAreAValidContinuousWeek(weekDays);
        }

        private static bool ContainsSevenDays(DayOfWeek[] weekDays)
        {
            return weekDays != null &amp;amp;&amp;amp; 
                   weekDays.Length == 7;
        }

        private bool DaysAreAValidContinuousWeek(DayOfWeek[] weekDays)
        {            
            for (int i = 0; i &amp;lt; 7; i++)
            {
                if (!IsAValidDay(weekDays[i]))
                    return false;

                if (i &amp;gt; 0) // I don't like this, but we can't check the next day without there being a previous day
                    if (!IsNextDay((int)weekDays[i], (int)weekDays[i - 1]))
                    {
                        return false;
                    }
            }

            return true;
        }

        private bool IsAValidDay(DayOfWeek day)
        {
            return Enum.IsDefined(typeof(DayOfWeek), day);
        }

        private bool IsNextDay(int currentDay, int previousDay)
        {
            currentDay %= 7;
            previousDay %= 7;

            return currentDay == (previousDay + 1) % 7;
        }
    }&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1529-validate-a-week/refactors/553014" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor552991</id>
    <published>2011-01-24T10:39:02-08:00</published>
    <title>[C#] On Validate a week</title>
    <content type="html">&lt;p&gt;Modified to satisfy Ants extra test case&lt;/p&gt;

&lt;pre&gt;    public class WeekValidator
    {
        public bool IsValidSevenDayWeek(IEnumerable&amp;lt;DayOfWeek&amp;gt; week)
        {
            return ContainsSevenDays(week) &amp;amp;&amp;amp;
                   IsWeekInOrder(week);
        }

        private static bool ContainsSevenDays(IEnumerable&amp;lt;DayOfWeek&amp;gt; week)
        {
            return week != null &amp;amp;&amp;amp; 
                   week.Count() == 7 &amp;amp;&amp;amp; 
                   week.All(p =&amp;gt; Enum.IsDefined(typeof(DayOfWeek), p));
        }

        private bool IsWeekInOrder(IEnumerable&amp;lt;DayOfWeek&amp;gt; week)
        {
            DayOfWeek[] weekDays = week.ToArray();

            for (int i = 1; i &amp;lt; 7; i++)
            {
                if (!IsNextDay(
                    (int)weekDays[i],
                    (int)weekDays[i - 1]))
                {
                    return false;
                }
            }

            return true;
        }

        private bool IsNextDay(int currentDay, int previousDay)
        {
            currentDay %= 7;
            previousDay %= 7;

            return currentDay == (previousDay + 1) % 7;
        }
    }&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1529-validate-a-week/refactors/552991" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor552990</id>
    <published>2011-01-24T10:24:16-08:00</published>
    <title>[C#] On Validate a week</title>
    <content type="html">&lt;p&gt;You're quite right; it would. His tests don't test that surprisingly. Which is why it wasn't caught :P&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1529-validate-a-week/refactors/552990" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor552731</id>
    <published>2011-01-21T10:44:00-08:00</published>
    <title>[C#] On Validate a week</title>
    <content type="html">&lt;p&gt;I reimplemented your tests, I think this may be a little easier to understand.&lt;/p&gt;

&lt;p&gt;I figured the IsWeekInOrder is going to determine if all days are distinct anyway, so the check in your original ContainsSevenDistinctDays was not need :)&lt;/p&gt;

&lt;pre&gt;    public class WeekValidator
    {
        public bool IsValidSevenDayWeek(IEnumerable&amp;lt;DayOfWeek&amp;gt; week)
        {
            return ContainsSevenDays(week) &amp;amp;&amp;amp; 
                   IsWeekInOrder(week);
        }

        private static bool ContainsSevenDays(IEnumerable&amp;lt;DayOfWeek&amp;gt; week)
        {
            return week != null &amp;amp;&amp;amp; week.Count() == 7;            
        }

        private bool IsWeekInOrder(IEnumerable&amp;lt;DayOfWeek&amp;gt; week)
        {            
            DayOfWeek[] weekDays = week.ToArray();

            for (int i = 1; i &amp;lt; 7; i++)
            {
                if (!IsNextDay(
                    (int)weekDays[i],
                    (int)weekDays[i - 1]))
                {
                    return false;
                }
            }

            return true;
        }

        private bool IsNextDay(int currentDay, int previousDay)
        {
            currentDay %= 7;
            previousDay %= 7;
            
            return currentDay == (previousDay + 1) % 7;
        }
    }&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1529-validate-a-week/refactors/552731" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1579</id>
    <published>2011-01-21T10:15:50-08:00</published>
    <updated>2011-01-23T07:47:55-08:00</updated>
    <title>[C#] Refactor my tests</title>
    <content type="html">&lt;p&gt;Hey, here a some tests of mine, that I think are due some refactorings. Can you guys help out?&lt;/p&gt;

&lt;pre&gt;public class BuilderTests
    {
        [Fact]
        public void GivenThereAreNoTasksWhenTheBuildIsExecutedTheBuildSucceeds()
        {
            Builder builder = new Builder();

            bool result = builder.Build();

            Assert.True(result);
        }

        [Fact]
        public void GivenThereIsOneTaskWhenTheBuildIsExecutedTheTaskIsExecuted()
        {
            TestBuildTask task = new TestBuildTask(true);
            Builder builder = new Builder(task);

            builder.Build();

            Assert.True(task.WasExecuted);
        }

        [Fact]
        public void GivenThereIsOneTaskWhichWillFailsWhenTheBuildIsExecutedThenBuildFails()
        {
            Builder builder = new Builder(new TestBuildTask(false));

            bool result = builder.Build();

            Assert.False(result);
        }

        [Fact]
        public void GivenThereIsOneTaskWhichWillSucceedWhenTheBuildIsExecutedThenBuildSucceeds()
        {
            Builder builder = new Builder(new TestBuildTask(true));

            bool result = builder.Build();

            Assert.True(result);
        }

        [Fact]
        public void GivenThereAreMultipleTasksAndAllTasksWillSucceedWhenTheBuildIsExecutedThenAllTasksAreExecuted()
        {
            var tasks = new TestBuildTask[] 
            { 
                new TestBuildTask(true),
                new TestBuildTask(true),
                new TestBuildTask(true)
            };
            Builder builder = new Builder(tasks);

            builder.Build();

            foreach (var task in tasks)
                Assert.True(task.WasExecuted);
        }

        [Fact]
        public void GivenThereAreMultipleTasksAndOneTaskWillFailWhenTheBuildIsExecutedThenTheBuildWillFail()
        {
            var tasks = new TestBuildTask[] 
            { 
                new TestBuildTask(true),
                new TestBuildTask(false),
                new TestBuildTask(true)
            };

            Builder builder = new Builder(tasks);

            bool result = builder.Build();

            Assert.False(result);
        }

        [Fact]
        public void GivenThereAreMultipleTasksAndOneTaskWillFailsWhenTheBuildIsExecutedThenNoTasksAfterTheFailureAreExecuted()
        {
            var tasks = new TestBuildTask[] 
            { 
                new TestBuildTask(true),
                new TestBuildTask(false),
                new TestBuildTask(true)
            };

            Builder builder = new Builder(tasks);

            builder.Build();

            Assert.False(tasks[2].WasExecuted);
        }

        private class TestBuildTask : IBuildTask
        {
            private bool succeed;

            public TestBuildTask(bool succeed)
            {
                this.succeed = succeed;
            }

            public bool WasExecuted { get; private set; }

            public bool Execute()
            {
                WasExecuted = true;

                return succeed;
            }
        }
    }&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1579-refactor-my-tests" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1435</id>
    <published>2010-09-21T10:02:19-07:00</published>
    <updated>2010-09-25T18:27:45-07:00</updated>
    <title>[C#] Best way to refactor this?</title>
    <content type="html">&lt;p&gt;Is there a good way to refactor this into something better?&lt;/p&gt;

&lt;pre&gt;namespace Marcidia.Net
{
    [MarcidiaComponent(
        &amp;quot;Network and Connections Subsystem&amp;quot;, false, 
        Description=&amp;quot;The core component of the Network and Connection sub system&amp;quot;)]
    public class ConnectionManager : MarcidiaComponent, IDisposable, IConnectionSourceRegistrar, IConnectionHandlerRegistrar, IConnectionManager
    {
        List&amp;lt;IConnection&amp;gt; connections;
        Dictionary&amp;lt;string, IConnectionSource&amp;gt; connectionSources;
        Dictionary&amp;lt;string, IConnectionHandler&amp;gt; sourceToHandlerMap;
        ILogger logger;

        public ConnectionManager(Mud mud)
            : base(mud)
        {
            connectionSources = new Dictionary&amp;lt;string, IConnectionSource&amp;gt;();
            sourceToHandlerMap = new Dictionary&amp;lt;string, IConnectionHandler&amp;gt;();
            connections = new List&amp;lt;IConnection&amp;gt;();

            mud.Initialized += mud_Initialized;

            mud.Services.AddService&amp;lt;IConnectionHandlerRegistrar&amp;gt;(this);
            mud.Services.AddService&amp;lt;IConnectionSourceRegistrar&amp;gt;(this);
            mud.Services.AddService&amp;lt;IConnectionManager&amp;gt;(this);
        }        

        public override void Initialize()
        {
            logger = Mud.Services.GetService&amp;lt;ILogger&amp;gt;();
        }

        public void RegisterConnectionSource(string name, IConnectionSource connectionSource)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentException(&amp;quot;name is null or empty.&amp;quot;, &amp;quot;name&amp;quot;);

            if (connectionSource == null)
                throw new ArgumentNullException(&amp;quot;connectionSource&amp;quot;, &amp;quot;connectionSource is null.&amp;quot;);

            if (connectionSources.ContainsKey(name))
                throw new ArgumentException(
                    string.Format(&amp;quot;A connection source has already been registered with the name: {0}&amp;quot;, name),
                    &amp;quot;name&amp;quot;);

            connectionSources.Add(name, connectionSource);
        }

        public void RegisterConnectionHandler(string sourceName, IConnectionHandler connectionHandler)
        {
            if (String.IsNullOrEmpty(sourceName))
                throw new ArgumentException(&amp;quot;sourceName is null or empty.&amp;quot;, &amp;quot;sourceName&amp;quot;);
            if (connectionHandler == null)
                throw new ArgumentNullException(&amp;quot;connectionHandler&amp;quot;, &amp;quot;connectionHandler is null.&amp;quot;);

            if (connectionSources.ContainsKey(sourceName))
                throw new ArgumentException(
                    string.Format(&amp;quot;A Connection handler has already been registered for connection source: {0}&amp;quot;, sourceName),
                    &amp;quot;sourceName&amp;quot;);

            sourceToHandlerMap.Add(sourceName, connectionHandler);
        }

        public void Dispose()
        {
            foreach (var connectionSource in connectionSources.Values)
            {
                connectionSource.NewConnection -= connectionSource_NewConnection;
                connectionSource.Stop();                
            }
        }

        private void mud_Initialized(object sender, EventArgs e)
        {
            // As we need to wait until everything is initialized prior to wiring everything up,
            // we tie into the mud initialized event. Here we check for matching sources and handlers and wire them up
            foreach (var sources in connectionSources)
            {
                string sourceName = sources.Key;
                IConnectionSource connectionSource = sources.Value;

                if (sourceToHandlerMap.ContainsKey(sourceName))
                {
                    connectionSource.NewConnection += connectionSource_NewConnection;
                    connectionSource.Start();
                }
                else
                {
                    logger.Log(LogLevels.Warning, &amp;quot;Connection source {0} was registered but has no connection handler&amp;quot;, sourceName);
                }

            }
        }

        private void connectionSource_NewConnection(object sender, ConnectionEventArgs e)
        {
            lock (connections)
            {
                connections.Add(e.Connection);

                e.Connection.ConnectionLost += ConnectionClosed;
                e.Connection.ConnectionClosed += ConnectionClosed;
            }

            string connectionSourceKey = connectionSources.Single(s =&amp;gt; s.Value == sender).Key;

            IConnectionHandler handler = sourceToHandlerMap[connectionSourceKey];

            handler.HandleConnection(e.Connection);
        }

        private void ConnectionClosed(object sender, EventArgs e)
        {
            IConnection connection = (IConnection)sender;

            lock (connections)
            {
                connections.Remove(connection);
            }
        }

        public IEnumerable&amp;lt;IConnection&amp;gt; GetAllConnections()
        {
            lock (connections)
                return connections.ToArray();
        }
    }
}
&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1435-best-way-to-refactor-this" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1434</id>
    <published>2010-09-21T10:01:12-07:00</published>
    <updated>2010-09-21T10:01:12-07:00</updated>
    <title>[C#] Best way to refactor this?</title>
    <content type="html">&lt;p&gt;Is there a good way to refactor this into something better?&lt;/p&gt;

&lt;pre&gt;namespace Marcidia.Net
{
    [MarcidiaComponent(
        &amp;quot;Network and Connections Subsystem&amp;quot;, false, 
        Description=&amp;quot;The core component of the Network and Connection sub system&amp;quot;)]
    public class ConnectionManager : MarcidiaComponent, IDisposable, IConnectionSourceRegistrar, IConnectionHandlerRegistrar, IConnectionManager
    {
        List&amp;lt;IConnection&amp;gt; connections;
        Dictionary&amp;lt;string, IConnectionSource&amp;gt; connectionSources;
        Dictionary&amp;lt;string, IConnectionHandler&amp;gt; sourceToHandlerMap;
        ILogger logger;

        public ConnectionManager(Mud mud)
            : base(mud)
        {
            connectionSources = new Dictionary&amp;lt;string, IConnectionSource&amp;gt;();
            sourceToHandlerMap = new Dictionary&amp;lt;string, IConnectionHandler&amp;gt;();
            connections = new List&amp;lt;IConnection&amp;gt;();

            mud.Initialized += mud_Initialized;

            mud.Services.AddService&amp;lt;IConnectionHandlerRegistrar&amp;gt;(this);
            mud.Services.AddService&amp;lt;IConnectionSourceRegistrar&amp;gt;(this);
            mud.Services.AddService&amp;lt;IConnectionManager&amp;gt;(this);
        }        

        public override void Initialize()
        {
            logger = Mud.Services.GetService&amp;lt;ILogger&amp;gt;();
        }

        public void RegisterConnectionSource(string name, IConnectionSource connectionSource)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentException(&amp;quot;name is null or empty.&amp;quot;, &amp;quot;name&amp;quot;);

            if (connectionSource == null)
                throw new ArgumentNullException(&amp;quot;connectionSource&amp;quot;, &amp;quot;connectionSource is null.&amp;quot;);

            if (connectionSources.ContainsKey(name))
                throw new ArgumentException(
                    string.Format(&amp;quot;A connection source has already been registered with the name: {0}&amp;quot;, name),
                    &amp;quot;name&amp;quot;);

            connectionSources.Add(name, connectionSource);
        }

        public void RegisterConnectionHandler(string sourceName, IConnectionHandler connectionHandler)
        {
            if (String.IsNullOrEmpty(sourceName))
                throw new ArgumentException(&amp;quot;sourceName is null or empty.&amp;quot;, &amp;quot;sourceName&amp;quot;);
            if (connectionHandler == null)
                throw new ArgumentNullException(&amp;quot;connectionHandler&amp;quot;, &amp;quot;connectionHandler is null.&amp;quot;);

            if (connectionSources.ContainsKey(sourceName))
                throw new ArgumentException(
                    string.Format(&amp;quot;A Connection handler has already been registered for connection source: {0}&amp;quot;, sourceName),
                    &amp;quot;sourceName&amp;quot;);

            sourceToHandlerMap.Add(sourceName, connectionHandler);
        }

        public void Dispose()
        {
            foreach (var connectionSource in connectionSources.Values)
            {
                connectionSource.NewConnection -= connectionSource_NewConnection;
                connectionSource.Stop();                
            }
        }

        private void mud_Initialized(object sender, EventArgs e)
        {
            // As we need to wait until everything is initialized prior to wiring everything up,
            // we tie into the mud initialized event. Here we check for matching sources and handlers and wire them up
            foreach (var sources in connectionSources)
            {
                string sourceName = sources.Key;
                IConnectionSource connectionSource = sources.Value;

                if (sourceToHandlerMap.ContainsKey(sourceName))
                {
                    connectionSource.NewConnection += connectionSource_NewConnection;
                    connectionSource.Start();
                }
                else
                {
                    logger.Log(LogLevels.Warning, &amp;quot;Connection source {0} was registered but has no connection handler&amp;quot;, sourceName);
                }

            }
        }

        private void connectionSource_NewConnection(object sender, ConnectionEventArgs e)
        {
            lock (connections)
            {
                connections.Add(e.Connection);

                e.Connection.ConnectionLost += ConnectionClosed;
                e.Connection.ConnectionClosed += ConnectionClosed;
            }

            string connectionSourceKey = connectionSources.Single(s =&amp;gt; s.Value == sender).Key;

            IConnectionHandler handler = sourceToHandlerMap[connectionSourceKey];

            handler.HandleConnection(e.Connection);
        }

        private void ConnectionClosed(object sender, EventArgs e)
        {
            IConnection connection = (IConnection)sender;

            lock (connections)
            {
                connections.Remove(connection);
            }
        }

        public IEnumerable&amp;lt;IConnection&amp;gt; GetAllConnections()
        {
            lock (connections)
                return connections.ToArray();
        }
    }
}
&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1434-best-way-to-refactor-this" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1433</id>
    <published>2010-09-21T09:57:33-07:00</published>
    <updated>2010-09-21T09:57:33-07:00</updated>
    <title>[C#] Best way to refactor this?</title>
    <content type="html">&lt;p&gt;Is there a good way to refactor this into something better?&lt;/p&gt;

&lt;pre&gt;namespace Marcidia.Net
{
    [MarcidiaComponent(
        &amp;quot;Network and Connections Subsystem&amp;quot;, false, 
        Description=&amp;quot;The core component of the Network and Connection sub system&amp;quot;)]
    public class ConnectionManager : MarcidiaComponent, IDisposable, IConnectionSourceRegistrar, IConnectionHandlerRegistrar, IConnectionManager
    {
        List&amp;lt;IConnection&amp;gt; connections;
        Dictionary&amp;lt;string, IConnectionSource&amp;gt; connectionSources;
        Dictionary&amp;lt;string, IConnectionHandler&amp;gt; sourceToHandlerMap;
        ILogger logger;

        public ConnectionManager(Mud mud)
            : base(mud)
        {
            connectionSources = new Dictionary&amp;lt;string, IConnectionSource&amp;gt;();
            sourceToHandlerMap = new Dictionary&amp;lt;string, IConnectionHandler&amp;gt;();
            connections = new List&amp;lt;IConnection&amp;gt;();

            mud.Initialized += mud_Initialized;

            mud.Services.AddService&amp;lt;IConnectionHandlerRegistrar&amp;gt;(this);
            mud.Services.AddService&amp;lt;IConnectionSourceRegistrar&amp;gt;(this);
            mud.Services.AddService&amp;lt;IConnectionManager&amp;gt;(this);
        }        

        public override void Initialize()
        {
            logger = Mud.Services.GetService&amp;lt;ILogger&amp;gt;();
        }

        public void RegisterConnectionSource(string name, IConnectionSource connectionSource)
        {
            if (String.IsNullOrEmpty(name))
                throw new ArgumentException(&amp;quot;name is null or empty.&amp;quot;, &amp;quot;name&amp;quot;);

            if (connectionSource == null)
                throw new ArgumentNullException(&amp;quot;connectionSource&amp;quot;, &amp;quot;connectionSource is null.&amp;quot;);

            if (connectionSources.ContainsKey(name))
                throw new ArgumentException(
                    string.Format(&amp;quot;A connection source has already been registered with the name: {0}&amp;quot;, name),
                    &amp;quot;name&amp;quot;);

            connectionSources.Add(name, connectionSource);
        }

        public void RegisterConnectionHandler(string sourceName, IConnectionHandler connectionHandler)
        {
            if (String.IsNullOrEmpty(sourceName))
                throw new ArgumentException(&amp;quot;sourceName is null or empty.&amp;quot;, &amp;quot;sourceName&amp;quot;);
            if (connectionHandler == null)
                throw new ArgumentNullException(&amp;quot;connectionHandler&amp;quot;, &amp;quot;connectionHandler is null.&amp;quot;);

            if (connectionSources.ContainsKey(sourceName))
                throw new ArgumentException(
                    string.Format(&amp;quot;A Connection handler has already been registered for connection source: {0}&amp;quot;, sourceName),
                    &amp;quot;sourceName&amp;quot;);

            sourceToHandlerMap.Add(sourceName, connectionHandler);
        }

        public void Dispose()
        {
            foreach (var connectionSource in connectionSources.Values)
            {
                connectionSource.NewConnection -= connectionSource_NewConnection;
                connectionSource.Stop();                
            }
        }

        private void mud_Initialized(object sender, EventArgs e)
        {
            // As we need to wait until everything is initialized prior to wiring everything up,
            // we tie into the mud initialized event. Here we check for matching sources and handlers and wire them up
            foreach (var sources in connectionSources)
            {
                string sourceName = sources.Key;
                IConnectionSource connectionSource = sources.Value;

                if (sourceToHandlerMap.ContainsKey(sourceName))
                {
                    connectionSource.NewConnection += connectionSource_NewConnection;
                    connectionSource.Start();
                }
                else
                {
                    logger.Log(LogLevels.Warning, &amp;quot;Connection source {0} was registered but has no connection handler&amp;quot;, sourceName);
                }

            }
        }

        private void connectionSource_NewConnection(object sender, ConnectionEventArgs e)
        {
            lock (connections)
            {
                connections.Add(e.Connection);

                e.Connection.ConnectionLost += ConnectionClosed;
                e.Connection.ConnectionClosed += ConnectionClosed;
            }

            string connectionSourceKey = connectionSources.Single(s =&amp;gt; s.Value == sender).Key;

            IConnectionHandler handler = sourceToHandlerMap[connectionSourceKey];

            handler.HandleConnection(e.Connection);
        }

        private void ConnectionClosed(object sender, EventArgs e)
        {
            IConnection connection = (IConnection)sender;

            lock (connections)
            {
                connections.Remove(connection);
            }
        }

        public IEnumerable&amp;lt;IConnection&amp;gt; GetAllConnections()
        {
            lock (connections)
                return connections.ToArray();
        }
    }
}
&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1433-best-way-to-refactor-this" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code1164</id>
    <published>2010-02-02T12:01:01-08:00</published>
    <updated>2010-02-04T09:16:06-08:00</updated>
    <title>[C#] Created a Telnet Parser with TDD. All tests pass, further refactoring?</title>
    <content type="html">&lt;p&gt;So I've was just using TDD (as I'm still learning this process) to write a Telnet command parser that parses out the non command bytes, and the individual commands from a byte array. It fires an event each time a command is parsed and returns a byte array of the data without the telnet commands in it. I've only done tiny tiny tiny bits of refactoring, so I'm wondering, how much further would any experienced TDD'ers take the refactoring from here...&lt;/p&gt;

&lt;pre&gt;public class TelnetParser
    {
        public event EventHandler&amp;lt;TelnetCommandEventArgs&amp;gt; Command;

        protected void OnCommand(TelnetCommandEventArgs e)
        {
            if (Command != null)
                Command(this, e);
        }

        public byte[] Parse(byte[] bytes)
        {            
            byte subOptionCode = 0;
            List&amp;lt;byte&amp;gt; subnegotiation = null;
            List&amp;lt;byte&amp;gt; nonCommandOutput = new List&amp;lt;byte&amp;gt;();
            List&amp;lt;byte&amp;gt; output = nonCommandOutput;

            for (int i = 0; i &amp;lt; bytes.Length; i++)
            {
                if (bytes[i] == (byte)TelnetCommand.IAC)                    
                {
                    i++;
                    var command = (TelnetCommand)bytes[i];

                    switch (command)
                    {
                        case TelnetCommand.IAC:
                            output.Add((byte)TelnetCommand.IAC);
                            break;
                        case TelnetCommand.WILL:
                        case TelnetCommand.WONT:
                        case TelnetCommand.DO:
                        case TelnetCommand.DONT:
                            i++;
                            byte optionCode = bytes[i];
                            OnCommand(new TelnetCommandEventArgs(command, optionCode));
                            break;
                        case TelnetCommand.SB:
                            i++;
                            subnegotiation = new List&amp;lt;byte&amp;gt;();
                            output = subnegotiation;
                            subOptionCode = bytes[i];
                            break;
                        case TelnetCommand.SE:
                            OnCommand(new TelnetCommandEventArgs(command, subOptionCode, subnegotiation.ToArray()));
                            output = nonCommandOutput;
                            break;
                        default:
                            OnCommand(new TelnetCommandEventArgs(command));
                            break;
                    }
                }
                else
                {
                    output.Add(bytes[i]);
                }
            }

            return nonCommandOutput.ToArray();
        }
    }

    public enum TelnetCommand : byte
    {
        SE = 240,
        NOP = 241,
        DM = 242,
        Break = 243,
        IP = 244,
        AO = 245,
        AYT = 246,
        EC = 247,
        EL = 248,
        GA = 249,
        SB = 250,
        WILL = 251,
        WONT = 252,
        DO = 253,
        DONT = 254,
        IAC = 255
    }

    public class TelnetCommandEventArgs : EventArgs
    {
        public Byte[] Data { get; private set; }
        public byte OptionCode { get; private set; }
        public TelnetCommand TelnetCommand { get; private set; }

        public TelnetCommandEventArgs(TelnetCommand command, byte subOptionCode, byte[] data)
        {
            TelnetCommand = command;
            OptionCode = subOptionCode;
            Data = data;
        }

        public TelnetCommandEventArgs(TelnetCommand command, byte optionCode)
            : this(command, optionCode, new byte[0])
        {            
        }

        public TelnetCommandEventArgs(TelnetCommand command)
            : this(command, 0)
        {            
        }
    }

    [TestFixture]
    public class TelnetParserTests
    {
        [Test]
        public void When_No_Commands_In_Data_Returns_Input_Data()
        {
            TelnetParser parser = new TelnetParser();
            byte[] bytes = new byte[] { 1, 2, 3, 4, 5 };

            byte[] returnBytes = parser.Parse(bytes);

            Assert.AreElementsEqual(bytes, returnBytes, &amp;quot;Output bytes were wrong&amp;quot;);
        }

        [Test]
        public void When_Two_Command_Parameters_Output_Byte_Array_Has_One_Byte_Equal_To_The_Command_Byte_Value()
        {
            TelnetParser parser = new TelnetParser();
            byte[] bytes = new byte[] { (byte)TelnetCommand.IAC, (byte)TelnetCommand.IAC };
            byte[] expected = new byte[] { (byte)TelnetCommand.IAC };

            byte[] returnBytes = parser.Parse(bytes);

            Assert.AreElementsEqual(expected, returnBytes, &amp;quot;Output bytes are wrong&amp;quot;);
        }

        [Test]
        public void When_Two_Command_Parameters_In_Input_With_Non_Command_Characters_Command_Parameters_Are_Replaced_With_A_Single_In_Output()
        {
            TelnetParser parser = new TelnetParser();
            byte[] bytes = new byte[] { 1, 2, (byte)TelnetCommand.IAC, (byte)TelnetCommand.IAC, 3, 4 };
            byte[] expected = new byte[] { 1, 2, (byte)TelnetCommand.IAC, 3, 4 };

            byte[] returnBytes = parser.Parse(bytes);

            Assert.AreElementsEqual(expected, returnBytes);
        }

        [Test]
        public void When_Telnet_Command_Found_Fires_Event()
        {
            TelnetParser parser = new TelnetParser();
            byte[] bytes = new byte[] { (byte)TelnetCommand.IAC, (byte)TelnetCommand.NOP };
            TelnetCommand foundCommand = (TelnetCommand)0;

            parser.Command +=
                (object sender, TelnetCommandEventArgs eventArgs) =&amp;gt;
                {
                    foundCommand = eventArgs.TelnetCommand;
                };

            parser.Parse(bytes);

            Assert.AreEqual(TelnetCommand.NOP, foundCommand, &amp;quot;Incorrect command set&amp;quot;);
        }

        [Test]
        public void When_Option_Command_Found_EventArgs_Contains_Option_Code()
        {
            TelnetParser parser = new TelnetParser();
            byte[] bytes = new byte[] 
            { 
                (byte)TelnetCommand.IAC, (byte)TelnetCommand.WILL, 1,
                (byte)TelnetCommand.IAC, (byte)TelnetCommand.WONT, 2,
                (byte)TelnetCommand.IAC, (byte)TelnetCommand.DO, 3,
                (byte)TelnetCommand.IAC, (byte)TelnetCommand.DONT, 4
            };

            byte[] expectedOptionCodes = new byte[] { 1, 2, 3, 4 };
            List&amp;lt;byte&amp;gt; optionCodes = new List&amp;lt;byte&amp;gt;();

            parser.Command += (sender, e) =&amp;gt; { optionCodes.Add(e.OptionCode); };

            parser.Parse(bytes);

            Assert.AreElementsEqual(expectedOptionCodes, optionCodes);
        }

        [Test]
        public void When_Option_Is_Start_Sub_Negotiation_EventArgs_Has_Gathered_Data_Until_End_Sub_Negotiation()
        {
            TelnetParser parser = new TelnetParser();
            byte[] bytes = new byte[]
            {
                (byte)TelnetCommand.IAC, (byte)TelnetCommand.SB, 1, 2, 3, 4, (byte)TelnetCommand.IAC, (byte)TelnetCommand.SE
            };
            byte expectedOptionCode = 1;
            byte[] expectedData = new byte[] { 2, 3, 4 };

            byte actualOptionCode = 1;
            byte[] actualData = null;

            parser.Command += (sender, e) =&amp;gt; { actualData = e.Data; actualOptionCode = e.OptionCode; };

            parser.Parse(bytes);

            Assert.AreEqual(expectedOptionCode, actualOptionCode);
            Assert.AreElementsEqual(expectedData, actualData, &amp;quot;Sub negotiation data was not parsed correctly&amp;quot;);
        }

        [Test]
        public void When_Subnegotiation_Ends_Non_Command_Data_Is_Still_Appended_To_Output()
        {
            TelnetParser parser = new TelnetParser();
            byte[] bytes = new byte[] { (byte)TelnetCommand.IAC, (byte)TelnetCommand.SB, 1, 2, 3, 4, (byte)TelnetCommand.IAC, (byte)TelnetCommand.SE, 5, 6, 7, 8 };
            byte[] expectedBytes = new byte[] { 5, 6, 7, 8 };

            byte[] returnedBytes = parser.Parse(bytes);

            Assert.AreElementsEqual(expectedBytes, returnedBytes);
        }
    }&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1164-created-a-telnet-parser-with-tdd-all-tests-pass-further-refactoring" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor148854</id>
    <published>2009-02-26T14:19:40-08:00</published>
    <title>[C#] On HTML Reprocessing Code</title>
    <content type="html">&lt;p&gt;Though I guess not, I just didn't want to read it all straight away.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Sekhat</name>
      <email>nik@terminaldischarge.net</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/766-html-reprocessing-code/refactors/148854" rel="alternate"/>
  </entry>
</feed>

