Avoid Fat XIBs

Storyboards, introduced in iOS 5, are quickly replacing XIBs. However, XIBs are still useful in some cases. If you need to target pre-iOS 5 devices, or you have a custom reusable view, then you can’t really avoid them.

If you’re forced into using XIBs, make them as uncomplicated as possible. Try to create one XIB per view controller, and if possible, break out a view controller’s view hierarchy into separate XIBs.

Note that when you load a XIB into memory, all of its contents are loaded into memory, including any images. If you have a view you’re not using immediately, then you’re wasting precious memory. It’s worth noting that this won’t happen with storyboards, since a storyboard will only instantiate a view controller when it’s needed.

When you load a XIB, any image files are cached, along with sound files if you’re developing for OS X. Apple’s documentation has this to say:

When you load a nib file that contains references to image or sound resources, the nib-loading code reads the actual image or sound file into memory and and caches it. In OS X, image and sound resources are stored in named caches so that you can access them later if needed. In iOS, only image resources are stored in named caches. To access images, you use the imageNamed: method of NSImage or UIImage, depending on your platform.

Come reinizializzare, reimpostare o ripristinare il PC

Se hai problemi con il PC, puoi provare a reinizializzarlo, reimpostarlo o ripristinarlo. La reinizializzazione del PC comporta la reinstallazione di Windows mantenendo le tue impostazioni e i tuoi file personali, nonché le app fornite con il PC e le app installate da Windows Store. La reimpostazione del PC comporta la reinstallazione di Windows, con l'eliminazione di file, impostazioni e app, ad eccezione delle app fornite con il PC. Il ripristino del PC consente di annullare le modifiche apportate recentemente al sistema.
Se vuoi eseguire il backup e il ripristino dei tuoi file usando Cronologia file, vedi Configurare un'unità per Cronologia file. Se vuoi riavviare il computer, vedi Spegnimento, sospensione o ibernazione del PC.

Prima di iniziare a reinizializzare o reimpostare il PC

Nella maggior parte dei casi, dopo aver avviato la reinizializzazione o la reimpostazione del PC, l'operazione verrà completata automaticamente. Tuttavia, se alcuni file richiesti da Windows sono mancanti, dovrai inserire un supporto di ripristino, in genere un disco DVD o una chiavetta USB. In tal caso, l'elemento necessario dipende dal PC.
Se il tuo PC è stato fornito con Windows 8.1 o Windows RT 8.1, saranno necessari i dischi o la chiavetta USB inclusi con il PC. Controlla la documentazione relativa al PC per verificare se il PC è dotato di tali dischi o supporti. In alcuni casi, tali dischi o supporti potrebbero essere stati creati durante la prima configurazione del PC.
Se hai eseguito l'aggiornamento del PC a Windows 8.1 o Windows RT 8.1 con un DVD, puoi usare quel disco. Se non hai il supporto per Windows 8.1 o Windows RT 8.1, contatta il supporto Microsoft .

Reinizializzare il PC senza influire sui file

Se le prestazioni del tuo PC risultano peggiorate rispetto al passato e non ne conosci il motivo, puoi reinizializzarlo senza eliminare i tuoi file né modificare le tue impostazioni.

Nota

  • Se hai eseguito l'aggiornamento del PC da Windows 8 a Windows 8.1 e nel PC esiste una partizione di ripristino diWindows 8, la reinizializzazione del PC ripristinerà Windows 8. Dovrai eseguire l'aggiornamento a Windows 8.1 al termine della reinizializzazione.

Avviso

  • Le app installate da siti Web e DVD verranno rimosse. Le app fornite con il PC e quelle installate da Windows Store verranno reinstallate. Dopo la reinizializzazione del PC, Windows visualizza sul desktop un elenco delle app rimosse.

Per reinizializzare il PC

  1. Scorri rapidamente dal bordo destro dello schermo, tocca Impostazioni e quindi Modifica impostazioni computer.
    Se usi un mouse, posiziona il puntatore nell'angolo superiore destro dello schermo, muovilo verso il basso, fai clic suImpostazioni e quindi su Modifica impostazioni computer.
  2. Tocca o fai clic su Aggiorna e ripristina e quindi tocca o fai clic su Ripristino.
  3. In Reinizializza il PC conservando i tuoi file tocca o fai clic su Per iniziare.
  4. Segui le istruzioni visualizzate.

Rimuovere tutto e reinstallare Windows

Se vuoi riciclare il PC, cederlo ad altre persone o ricominciare dall'inizio, puoi ripristinarne interamente le impostazioni di fabbrica.

Nota

  • Se hai eseguito l'aggiornamento del PC da Windows 8 a Windows 8.1 e nel PC esiste una partizione di ripristino diWindows 8, la reimpostazione del PC ripristinerà Windows 8. Dovrai eseguire l'aggiornamento a Windows 8.1 al termine della reimpostazione.

Avviso

  • Tutti i file personali verranno eliminati e le impostazioni verranno reimpostate. Tutte le app installate verranno rimosse. Verranno reinstallate soltanto le app fornite con il PC.

Per ripristinare le impostazioni di fabbrica del PC

  1. Scorri rapidamente dal bordo destro dello schermo, tocca Impostazioni e quindi Modifica impostazioni computer.
    Se usi un mouse, posiziona il puntatore nell'angolo superiore destro dello schermo, muovilo verso il basso, fai clic suImpostazioni e quindi su Modifica impostazioni computer.
  2. Tocca o fai clic su Aggiorna e ripristina e quindi tocca o fai clic su Ripristino.
  3. In Rimuovi tutto e reinstalla Windows tocca o fai clic su Per iniziare.
  4. Segui le istruzioni visualizzate.

    Nota

    • Ti verrà chiesto se vuoi cancellare i dati in modo rapido o completo. Se scegli di cancellarli in modo rapido, alcuni dati potrebbero essere recuperabili tramite software speciale. Se scegli di cancellarli in modo completo, l'operazione richiederà un tempo maggiore ma sarà molto più improbabile recuperare i dati.

Ripristinare uno stato precedente del PC

Se pensi che un'app o un driver installato di recente causi problemi al tuo PC, puoi ripristinare Windows a uno stato precedente, detto punto di ripristino. Ripristino configurazione di sistema non modifica i file personali, ma potrebbe rimuovere app e driver installati di recente.

Note

  • Ripristino configurazione di sistema non è disponibile per Windows RT 8.1.
  • Windows crea automaticamente un punto di ripristino quando si installano app desktop e nuovi aggiornamenti di Windows, se l'ultimo punto di ripristino risale a più di 7 giorni prima. Puoi anche creare un punto di ripristino manualmente in qualsiasi momento.

Per ripristinare uno stato precedente del PC

  1. Scorri rapidamente dal bordo destro dello schermo e quindi tocca Cerca.
    Se usi un mouse, posiziona il puntatore nell'angolo superiore destro dello schermo, muovilo verso il basso e quindi fai clic su Cerca.
  2. Immetti pannello di controllo nella casella di ricerca e tocca o fai clic su Pannello di controllo.
  3. Immetti ripristino nella casella di ricerca del Pannello di controllo e tocca o fai clic su Ripristino.
  4. Tocca o fai clic su Apri Ripristino configurazione di sistema e quindi segui le istruzioni.

Use a reuseIdentifier Where Appropriate

A common mistake in app development is not setting the correct reuseIdentifier for UITableViewCells, for UICollectionViewCells, or even UITableViewHeaderFooterViews.

For maximum performance, a table view’€™s data source should generally reuse UITableViewCell objects when it assigns cells to rows in tableView:cellForRowAtIndexPath:. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.
What happens if you don’t use a reuseIdentifier?

If you don’t, your table view will configure a brand-new cell each time a row is displayed. This is an expensive operation and will definitely affect the scrolling performance of your app.
Since the introduction of iOS 6, you’re expected to use reuseIdentifiers for header and footer views, as well as UICollectionView’s cells and supplementary views.

To use reuseIdentifiers, call this method from your data source object when asked to provide a new cell for the table view:

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

This method dequeues an existing cell if one is available, or creates a new one if necessary using the previously registered nib file or class. If no cell is available for reuse, and you did not register a class or nib file, this method returns nil.

Xcode 5: general info


Xcode is the most used IDE for iOS development. Apple is doing a great job in updating and adding features to it. Knowing how to take advantage of its capabilities can help you code faster and more efficiently. Check out this Guide for Xcode 5 shortcuts, tips and tricks.

Xcode’s workspace window is split into 5 main areas: the toolbar, the navigation area, the editing area, the debug area and the utility area:


Navigating in Xcode

The navigation area has a toolbar as well. It has 8 tabs: project navigator, symbol navigator, find navigator, issue navigator, test navigator, debug navigator, breakpoint navigator and log navigator. You can quickly select one of them by pressing ⌘ and the index corresponding to it.

- ⌘1 Project Navigator
- ⌘2 Symbol Navigator
- ⌘3 Find Navigator
- ⌘4 Issue Navigator
- ⌘5 Test Navigator
- ⌘6 Debug Navigator
- ⌘7 Breakpoint Navigator
- ⌘8 Log Navigator


And if you need the extra space and want to get rid of the navigator then use ⌘0 (command zero).

At the bottom of the navigation area there are the navigation filters. These are different for each tab and are very helpful. In the project navigator tab, the filters allow you to see the recently modified or recently edited files. Recently modified lets you focus on your SCM changes.


You can also enter some text and try to filter the name of the files if you know what you’re looking for. However, better than using that filter is to use open quickly. The keyboard shortcut for that is:
⇧⌘ o Open quickly


This is very handy and very smart. Even if you don’t remember the full name of the class or method you’re searching for it can still help you find it.


I didn’t even have to specify the full words (why write view controller when you can write just a few letters) and it still found what I was looking for.

And if you want to open the file and go to line 246 because you know that’s where that method is then you can just add :246 in the open quickly window and Xcode will do that for you. And if you want to skip to another line then just press

⌘ L Go to line

and enter the line number.


Show line numbers

If you wish to show line numbers in Xcode 5 simply hold down the cmd and , buttons together and a window will pop up. In this window click Text Editing along the top options and then make sure the checkbox for Show: Line Numbers is selected.


Another very useful keyboard shortcut is the one that allows you to switch between the .h and .m file for a class.

⌃⌘⇡ Jump to Next counterpart

And a very similar keyboard shortcut if you want to go back to the previous file you were looking at. Or forward again:

⌃⌘⇢ Go forward

⌃⌘⇠ Go back

Editing

When you’re editing the code you might decide that an instance variable’s name is not as suggestive as it should be or that there is a spelling mistake in it. You want to rename all instances of that variable, but only in a certain scope. Select one of the instances and then hit:

⌃⌘E Edit all in scope

You’ll see that all the occurrences of that variable have boxes around it. Editing one will update all the others. This is very helpful for code refactoring and cleaning. Also very useful during refactoring is moving lines around. To do this you press:

⌥⌘[ Move line up

⌥⌘] Move line down

The indentation will be fixed as you move lines up or down, but if you still have some code that’s not properly indented then use this shortcut:

⌃I Re-indent code

If you want to Auto-Indent a block of code, check out this article: Auto-Indent Lines of code in Xcode.

If you need to comment things out just press:

⌘/ Comment/uncomment line or selection

Apart from the standard editor Xcode also has an assistant editor and a version editor. To switch from one to another you use the following:

⌘↩ Standard editor

⌥⌘↩ Assistant editor

⌥⇧⌘↩ Version editor

The assistant editor is excellent for auxiliary content. It tracks the contents of the main editor. If you need to see the superclass for your class at the same time as you’re editing the class just switch on the assistant editor. You can see counterparts, callers or test callers, includes and lots more. It is very powerful and I encourage you to use it. If you want to open a file in the assistant editor just hold the option key (⌥) down:

⌥⌘, Open in assistant editor

Debugging

Normally we set or remove breakpoints by clicking the margins of the document. You can also do this via keyboard shortcuts:

⌘\ Add/remove breakpoint at current line

In the breakpoint navigator you can see all the existing breakpoints. To get to the navigator you press ⌘7

⌘Y Activate or deactivate breakpoints

Very useful while debugging is the exception breakpoint. If your app is crashing just add an exception breakpoint and the program will stop at the line that’s causing the problem. You can do this by pressing the + at the bottom of the breakpoints navigator or from Xcode’s main menu by going to Debug-> Breakpoints -> Create exception breakpoint.


Testing

To run all the tests in your project use ⌘U . Or ⌃⌘U to test without building.

The test editor is your best friend when running your tests. You get to it by pressing ⌘5 From here you can run only one test by pressing the little play button that appears next to it, a whole test suite or all your tests.


You can also filter results so you can see only the failing tests:


If you want to debug the test then you can add a test failure breakpoint from the breakpoint navigator the same way you would add an exception breakpoint.

Source control

⌥⌘C Commit code

⌥⌘X Update

⌃⌥⌘X Update all

You can use the version navigator to check what’s changed in a file and who’s to blame.

⌥⇧⌘↩ Show version editor

Interface Builder

⌘= Size to fit content

⌘_ Add horizontal guide

⌘| Add vertical guide

iPhone Simulator

⌘⇠ Rotate left

⌘⇢ Rotate right

⌃⌘Z Shake gesture

⇧⌘H Home

⇧⌘M Simulate memory warning

⌘T Toggle slow animations

Using report parameters in local mode

What are report parameters used for?

The most common use of report parameters is to specify a criterion for subsetting data. The value of the parameter may be set programmatically by the host application, or one report may pass a parameter to another report.

When you drillthrough from one report to another, the main report passes the id of the item the user clicked on to the drillthrough report as a report parameter. The drillthrough report then uses the parameter value to only display data corresponding to the item the user clicked on.

When a master-detail report is implemented using subreports, the main report passes the id of the master item to the subreport as a report parameter. The subreport uses the parameter value to only display detail rows corresponding to the specified master item.

Subsetting data can be done in two ways: (a) The host application can examine the value of the parameter being passed to a subreport or drillthrough report (in the corresponding event handlers) and only supply the subset of data corresponding to the parameter value to ReportViewer. Or (b) the host application can supply the entire data to ReportViewer, and in the RDL file specify a filter that only lets in values that match the parameter value (see screenshot).

Report parameters can be used for other purposes too. In the example below a report parameter is used to control the visiblity of a text box.

Defining a report parameter

To add a parameter to a report, from the menu choose Report > Report Parameters command. Press Add to add a parameter.

The value of a parameter can be used in expressions as Parameters!Foo.Value where Foo is the name of the parameter.

Parameter Prompting

When operating in remote mode ReportViewer automatically prompts the user for parameter values unless told not to do so.

When operating in local processing mode, ReportViewer does not prompt for parameter values. The rationale is as follows: The most common use of report parameters is to pass to queries as values of query parameters. But unlike the Report Server, the ReportViewer control does not execute queries itself. Rather, queries are executed by the host application, and the result is passed to the ReportViewer control. So the ReportViewer control does not have the opportunity to set query parameters.

In local mode the host application must handle parameter prompting, as seen in the example below.

Example

In the example below, the application (an RSS Browser) has a textbox for specifying news items of interest, and a checkbox for turning descriptions on or off. Note that this textbox, checkbox, the url dropdown and the load button are all implemented by the host application. UI features of the ReportViewer control such as toolbar have been turned off in this application.

The ability to turn descriptions on or off, and the ability to filter news items are implemented using report parameters.

In the RDL the visibility of the description textbox is controlled using a boolean report parameter, like this:

        <Textbox Name="Description">
<Visibility>
<Hidden>=not(Parameters!ShowDescriptions.Value)</Hidden>
</Visibility>
....
....
</Textbox>
The host application then sets the value of the ShowDescriptions parameter based on the value of the checkbox, like this:

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
ReportParameter p = new
ReportParameter("ShowDescriptions", checkBox1.Checked ? "true" : "false");
this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { p });
this.reportViewer1.RefreshReport();
}

TDD Kata | String Calculator

Kata is a Japanese word describing detailed choreographed patterns of movements practiced either solo or in pairs. most commonly known for the presence in the martial arts.
The idea is if you practice something regularly, at some point it will be come natural. (As they call it "Muscle memory" :)).
Even though Test Driven Development has been preached as best practice for years now, there is still resistance in many IT shops to adapt TDD (Test Driven Developer). So the best way to teach your team to start making TDD part of their daily development practice is by running small hands on sessions, KATA.
Yesterday, the architect (a very passionate developer and lead) at my job took the team through one 1hr journey of solving a simple but yet complex enough problem to have the taste of TDD (Red-Green-Re factor) .
You can find the problem definition at Roy’s String Calculator TDD Kata.
 

String Calculator

The following is a TDD Kata- an exercise in coding, refactoring and test-first, that you should apply daily for at least 15 minutes (I do 30).
 

Before you start:

  • Try not to read ahead.
  • Do one task at a time. The trick is to learn to work incrementally.
  • Make sure you only test for correct inputs. there is no need to test for invalid inputs for this kata

    String Calculator

    1. Create a simple String calculator with a method int Add(string numbers)
      1. The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0) for example “” or “1” or “1,2”
      2. Start with the simplest test case of an empty string and move to 1 and two numbers
      3. Remember to solve things as simply as possible so that you force yourself to write tests you did not think about
      4. Remember to refactor after each passing test
    2. Allow the Add method to handle an unknown amount of numbers
    3. Allow the Add method to handle new lines between numbers (instead of commas).
      1. the following input is ok:  “1\n2,3”  (will equal 6)
      2. the following input is NOT ok:  “1,\n” (not need to prove it - just clarifying)
      1. Support different delimiters
      2. to change a delimiter, the beginning of the string will contain a separate line that looks like this:   “//[delimiter]\n[numbers…]” for example “//;\n1;2” should return three where the default delimiter is ‘;’ .
      3. the first line is optional. all existing scenarios should still be supported
    4. Calling Add with a negative number will throw an exception “negatives not allowed” - and the negative that was passed.if there are multiple negatives, show all of them in the exception message
      stop here if you are a beginner. Continue if you can finish the steps so far in less than 30 minutes.
    5. Numbers bigger than 1000 should be ignored, so adding 2 + 1001  = 2
    6. Delimiters can be of any length with the following format:  “//[delimiter]\n” for example: “//[***]\n1***2***3” should return 6
    7. Allow multiple delimiters like this:  “//[delim1][delim2]\n” for example “//[*][%]\n1*2%3” should return 6.
    8. make sure you can also handle multiple delimiters with length longer than one char
    I am sharing my first attempt to develop the String Calculator add functionality using TDD.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;
    namespace TDDFun
    {
    public class StringCalculator
        {
    public double Add(string numbers)
            {
    Double sum = 0;
    if (string.IsNullOrEmpty(numbers))
                {
                    sum = 0;
                }
    else
                {
    const string regex1 = “(\\//)”;
    const string regex2 = “(.*?)”;
    const string regex3 = “(\\n)”;
    const string regex4 = “(.*?\\d)”;
    var delimiters = new List<string>();
    var r = new Regex(regex1 + regex2 + regex3 + regex4, RegexOptions.IgnoreCase | RegexOptions.Singleline);
    Match m = r.Match(numbers);
    if (m.Success)
                    {
    string delimiterCollection = m.Groups[2].ToString();
    int numberStartIndex = m.Groups[3].Index;
    const string re5 = “(\\[.*?\\])”;
    var r2 = new Regex(re5, RegexOptions.IgnoreCase | RegexOptions.Singleline);
    MatchCollection m2 = r2.Matches(delimiterCollection);
    if (m2.Count > 0)
                        {
    foreach (Match x in m2)
                            {
    delimiters.Add(x.ToString().Replace(“[", "").Replace("]“, “”));
                            }
                        }
    else
                        {
    delimiters.Add(delimiterCollection);
                        }
                        numbers = numbers.Remove(0, numberStartIndex + 1);
                    }
    else
                    {
    delimiters.Add(“\n”);
    delimiters.Add(“,”);
                    }
    string[] splittedNumbers = numbers.Split(delimiters.ToArray(), StringSplitOptions.None);
                    ValiateNumbers(splittedNumbers);
    foreach (string s in splittedNumbers)
                    {
    double ss = Double.Parse(s);
                        sum += ss <= 1000 ? ss : 0;
                    }
                }
    return sum;
            }
    private static void ValiateNumbers(IEnumerable<string> numbers)
            {
    double x;
    var negativeNumbers = new List<string>();
    foreach (string s in numbers)
                {
    Validator.IsRequiredField(Double.TryParse(s, out x), “Validation Error”);
    if (Double.Parse(s) < 0)
                    {
    negativeNumbers.Add(s);
                    }
                }
    Validator.IsRequiredField(negativeNumbers.Count <= 0,
    “Negatives not allowed “ + ShowAllNegatives(negativeNumbers));
            }
    private static string ShowAllNegatives(List<string> negativeNumbers)
            {
    var sb = new StringBuilder();
    int counter = 0;
                negativeNumbers.ForEach(k =>
                                            {
    if (counter == 0)
                                                {
                                                    sb.Append(k);
                                                    counter++;
                                                }
    else
                                                {
                                                    sb.Append(“;” + k);
                                                }
                                            });
    return sb.ToString();
            }
        }
    public static class Validator
        {
    public static void IsRequiredField(bool criteria, string message)
            {
    if (!criteria)
                {
    throw new ValidationException(message);
                }
            }
        }
    public class ValidationException : ApplicationException
        {
    public ValidationException(string message) : base(message)
            {
            }
        }
    }
     
     
    using NUnit.Framework;
    namespace TDDFun
    {
        [TestFixture]
    public class StringCalculatorTest
        {
    private StringCalculator calculator;
            [SetUp]
    public void SetUp()
            {
                calculator = new StringCalculator();
            }
            [Test]
    public void Add_DecimalNumbers_ShouldReturnDouble()
            {
    Assert.IsTrue(calculator.Add(“//;\n1.1;1.2″) == 2.3);
            }
            [Test]
    public void Add_EmptyString_ShouldReturnZero()
            {
    Assert.IsTrue(calculator.Add(string.Empty) == 0);
            }
            [Test]
    public void Add_NewLineSeparators_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“1\n2\n34\n5″) == 42);
            }
            [Test]
    public void Add_NewLineSeparatorsCommasCombined_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“1\n2,34,5″) == 42);
            }
            [Test]
    public void Add_NonNumericStringPassed_ShouldThrowException()
            {
    Assert.Throws<ValidationException>(() => calculator.Add(“XT”));
            }
            [Test]
    public void Add_NullString_ShouldReturnZero()
            {
    Assert.IsTrue(calculator.Add(null) == 0);
            }
            [Test]
    public void Add_NumbersGreaterThan1000_ShouldBeIgnored()
            {
    Assert.IsTrue(calculator.Add(“//[***]\n1.1***1000.2″) == 1.1);
            }
            [Test]
    public void Add_OneString_ShouldReturnItself()
            {
    Assert.IsTrue(calculator.Add(“3″) == 3);
            }
            [Test]
    public void Add_SpacesBetweenDelimiters_ShouldBeHandled()
            {
    Assert.IsTrue(calculator.Add(“//[***][kkk]\n1.1   ***  1.2kkk   2″) == 4.3);
            }
            [Test]
    public void Add_SpecialDelimiterWithMultipleNegativeNumber_ShouldThrows()
            {
    var exception = Assert.Throws<ValidationException>(() => calculator.Add(“//[***]\n-1***-2″));
    Assert.AreEqual(exception.Message, “Negatives not allowed -1;-2″);
            }
            [Test]
    public void Add_ThreeString_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“3,33,4″) == 40);
            }
            [Test]
    public void Add_TwoNegativeString_ShouldThrowException()
            {
    var exception = Assert.Throws<ValidationException>(() => calculator.Add(“-1,-2″));
    Assert.AreEqual(exception.Message, “Negatives not allowed -1;-2″);
            }
            [Test]
    public void Add_TwoString_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“3,33″) == 36);
            }
            [Test]
    public void Add_WithDelimiterAndColon_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//;\n1;2″) == 3);
            }
            [Test]
    public void Add_WithMultipleNegativeNumber_ThrowsExceptionShowingAllNegativeNumbers()
            {
    var exception = Assert.Throws<ValidationException>(() => calculator.Add(“//;\n-1;-2″));
    Assert.AreEqual(exception.Message, “Negatives not allowed -1;-2″);
            }
            [Test]
    public void Add_WithNegativeNumber_ThrowsException()
            {
    Assert.Throws<ValidationException>(() => calculator.Add(“//;\n1;-2″));
            }
            [Test]
    public void Add_WithOneSpecialDelimiters_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[***]\n1.1***1.2″) == 2.3);
            }
            [Test]
    public void Add_WithSpecialDelimitersOnlyOneChar_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[*]\n1.1*1.2″) == 2.3);
            }
            [Test]
    public void Add_WithSwithAndAnySpecialDelimiters_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//***\n1.1***1.2″) == 2.3);
            }
            [Test]
    public void Add_WithThreeSpecialDelimiters_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[***][kkk][GGG]\n1.1***1.2kkk2GGG4.7″) == 9.0);
            }
            [Test]
    public void Add_WithTwoSpecialDelimiters_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[***][kkk]\n1.1***1.2kkk2″) == 4.3);
            }
            [Test]
    public void Add_WithTwoSpecialDelimitersOnlyOneChar_ShouldPass()
            {
    Assert.IsTrue(calculator.Add(“//[*][%]\n1*2%3″) == 6);
            }
        }
    }














































    Professional Test Driven Development with C#: Developing Real World

    Test-driven development (TDD) practice helps developers recognize a well-designed application, and encourages writing a test before writing the functionality that needs to be implemented. This hands-on guide provides invaluable insight for creating successful test-driven development processes.

    With source code and examples featured in both C# and .NET, the book walks you through the TDD methodology and shows how it is applied to a real-world application. You’ll witness the application built from scratch and details each step that is involved in the development, as well as any problems that were encountered and the solutions that were applied. Test-Driven-Developement-with-csharp

    • Clarifies the motivation behind test-driven development (TDD), what it is, and how it works
    • Reviews the various steps involved in developing an application and the testing that is involved prior to implementing the functionality
    • Discusses unit testing and refactoring

    Professional Test-Driven Development with C# shows you how to create great TDD processes right away.

    Start working with test driven development processes to build better applications If you want to write robust software that is simple to implement and maintain, you need to use Test Driven Development (TDD). This hands–on guide shows you how, providing invaluable insight for creating effective TDD processes. With the help of source code and examples featured in C#, the authors walk you through the TDD methodology and show you how to apply it to a real–world application. You′ll explore the application as it′s built from scratch and follow each step involved in development, including problems that arise and the solutions to apply. Within no time, you′ll be designing your own successful TDD processes. Professional Test Driven Development with C# : Describes common software problems and provides refactoring practices that resolve them Shows patterns that can be used to test WPF and Silverlight applications Helps you ensure that when a defect is fixed it stays fixed without causing unexpected side effects Shows how to structure your MVC application for testability Shares the easy steps that can be taken to test WCF services Explains how to run integration tests to ensure that everything works as planned Uncovers best practices for writing good tests that are readable and maintainable Wrox Professional guides are planned and written by working programmers to meet the real–world needs of programmers, developers, and IT professionals. Focused and relevant, they address the issues technology professionals face every day. They provide examples, practical solutions, and expert education in new technologies, all designed to help programmers do a better job. wrox.com Programmer Forums Join our Programmer to Programmer forums to ask and answer programming questions about this book, join discussions on the hottest topics in the industry, and connect with fellow programmers from around the world. Code Downloads Take advantage of free code samples from this book, as well as code samples from hundreds of other books, all ready to use. Read More Find articles, ebooks, sample chapters, and tables of contents for hundreds of books, and more reference resources on programming topics that matter to you.

    Purely Functional Data Structures: An F# Binary Tree

    Here’s my F# implementation of a binary tree:

    #light

    type Elem = int

    type Tree = E | T of Tree * Elem * Tree

    let empty = E

    let rec mem = function
    | x, E -> false
    | x, T(a, y, b) when x < y -> mem(x, a)
    | x, T(a, y, b) when y < x -> mem(x, b)
    | _ -> true

    let rec insert = function
    | x, E -> T(E, x, E)
    | x, T(a, y, b) when x < y -> T(insert(x, a), y, b)
    | x, T(a, y, b) when y < x -> T(a, y, insert(x, b))
    | _, s -> s

    Here's what the tree looks like in use:
    > let t = T(E, 1, E);;

    val t : Tree

    > t;;

    val it : Tree = T (E,1,E)

    > let t1 = insert(0, t);;

    val t1 : Tree

    > t1;;

    val it : Tree = T (T (E,0,E),1,E)

    > let t2 = insert(10, t1);;

    val t2 : Tree

    > t2;;

    val it : Tree = T (T (E,0,E),1,T (E,10,E))

    > let t3 = insert(5, t2);;

    val t3 : Tree

    > t3;;

    val it : Tree = T (T (E,0,E),1,T (T (E,5,E),10,E))

    > mem(10, t1);;

    val it : bool = false

    > mem(10, t2);;

    val it : bool = true

    Building of an organizational chart for AdventureWorks & AdventureWorks2008

    -- SQL recursive CTE to find subordinates of executive, manager & supervisor
    -- Tree processing - find all descendants - find children - self-referencing table
    DECLARE @EmployeeID INT
    SET @EmployeeID = 109
    USE AdventureWorks;
    WITH cteEmployeeName
    AS (SELECT FullName = FirstName + ' ' + LastName,
    EmployeeID
    FROM HumanResources.Employee e
    INNER JOIN Person.Contact c
    ON e.ContactID = c.ContactID),
    cteSubordinates
    AS (SELECT EmployeeID,
    LEVEL = 0
    FROM HumanResources.Employee
    WHERE EmployeeID = @EmployeeID
    UNION ALL
    SELECT e.EmployeeID,
    LEVEL + 1
    FROM cteSubordinates cte
    INNER JOIN HumanResources.Employee e
    ON cte.EmployeeID = e.ManagerID)
    SELECT FullName,
    s.EmployeeID,
    LEVEL
    FROM cteSubordinates s
    INNER JOIN cteEmployeeName en
    ON s.EmployeeID = en.EmployeeID
    /*
    FullName EmployeeID Level
    Ken Sánchez 109 0
    David Bradley 6 1
    Terri Duffy 12 1
    Jean Trenary 42 1
    Laura Norman 140 1
    James Hamilton 148 1
    Brian Welcker 273 1
    Stephen Jiang 268 2
    Amy Alberts 284 2

    */

    ------------
    -- SQL Server 2008 tree processing functions - MSSQL organization chart - orgchart
    -- T-SQL recursive Common Table Expression - CTE - SQL hierarchyid
    USE AdventureWorks2008;
    GO
    WITH cteDirectReports(ManagerID,EmployeeID,ManagerLevel)
    AS (SELECT OrganizationNode.GetAncestor(1),
    OrganizationNode,
    OrganizationLevel - 1
    FROM HumanResources.Employee
    WHERE OrganizationLevel = 0
    UNION ALL
    SELECT e.OrganizationNode.GetAncestor(1),
    e.OrganizationNode,
    OrganizationLevel - 1
    FROM HumanResources.Employee e
    INNER JOIN cteDirectReports d
    ON e.OrganizationNode.GetAncestor(1) = d.EmployeeID)
    SELECT Manager = replicate('_',(ManagerLevel) * 4) + CO.LastName + ', ' +
    CO.FirstName,
    Employee = C.LastName + ', ' + C.FirstName,
    ManagerLevel,
    EmployeeLevel = ManagerLevel + 1
    FROM cteDirectReports DR
    INNER JOIN HumanResources.Employee E
    ON DR.EmployeeID = E.OrganizationNode
    INNER JOIN Person.Person C
    ON E.BusinessEntityID = C.BusinessEntityID
    INNER JOIN HumanResources.Employee EM
    ON DR.ManagerID = EM.OrganizationNode
    INNER JOIN Person.Person CO
    ON EM.BusinessEntityID = CO.BusinessEntityID
    ORDER BY DR.EmployeeID

    GO

    Advertsing

    125X125_06

    TagCloud

    MonthList

    CommentList