ict.ken.be

 

Posts in Category: Notes

Azure Cloud & Storage Services 

Categories: Azure Notes

Some notes from Windows Azure Fundamentals by http://mattmilner.com

Fabric controller will keep the requested number of instances running.

Package & Configuration files

  • .cscfg is xml stating the os
  • .cspkg is just a zip file

Service Definition

  • Virtual machine sizing
  • Endpoints
  • Certificates
  • Websites (web role)
  • Environment variables
  • Startup tasks
  • Configuration settings declarations

Service configuration

  • Operation System
  • Instance count
  • Values for configuration settings
  • Certificate thumbprint

Managing Cloud Services

  • Affinity groups
  • Fault domains
  • Upgrade domains
  • VIP swap
  • REST API

Storage Services

  • x509 certificate and SSL
  • Storage Account Keys
  • ETags
  • Azure Storage Explorer

Tables

  • PartitionKey, RowKey, Entity (key/value pairs), Timestamp
  • Max 255 fields including keys
  • Matching partition keys = data in same physical partition
  • Transactions only on the same partition

Blobs/CDN

  • Root container - Named container (first dir) - Blob (second dir and filename) 
  • http://<account>.blob.core.windows.net/images/web/background.jpg
  • Block blobs vs Page blobs
  • Content-cache metadata=TTL in CDN

Queues (max. 7 days)

  • No capitals in name allowed
  • 64kb Max after base64 encoded and including xml headers
  • eg. worker role that creates thumbnails or processes video
  • A worker role can update a message.

Mercurial - Notes 

Categories: Mercurial Notes

Mercurial - HG

http://mercurial.selenic.com

  • Created by Matt Mackall at same time Git started.
  • DVCS written in Python
  • No partial commits (only atomic commits)
  • Three-way merging

Source control for tracking and sharing
Terms: Source, revision, version controlling
Types: Manual merging, File locking, Version merging
Architecture: Centralized, Distributed (no central server, appointed central server or lieutenants/commander)

Install TortoiseHg
Global settings
Username: firstname lastname <email address> (is mostly used as a convention)
Extensions: graphlog
-> updates the mercurial.ini file in each users root (c:/users/user/mercurial.ini)

Commands
hg help
hg init / hg ci (.hg folder is repository for all subfolders)
hg status
hg add
hg add foo.txt
hg commit (will prompt for change message, will commit all folders, emty folders will not be added !)
hg commit -m "your message" / hg ci -m "message"
hg log --limit 5 / hg -l 5 (will show last 5 changes)
hg glog

hg diff
hg revert --all
hg revert foo.txt (will create a copy of your discarded file in same folder with .orig extension)
hg revert foo.txt --no-backup

Ignore files for adding:

  • create .hgignore in root 
syntax: glob
*.orig
[Bb]in
foo.*
foo??.txt

syntax: regexp

You can only undo the most recent commit and when it has not yet been shared with another repository.
hg rollback

hg update 1 (locally: revision number of the changeset)
hg update e99fffee (globally: changeset identifier)

del foo.txt
hg remove foo.txt

Working with a server

md repository
hg init
hg serve (will run http server on localhost:8000)
cd .hg

  • create file hgrc
[web]
push_ssl=false
allow_push=*

hg clone http://localhost:8000 hgclientfolder
hg push
hg out (compare local outgoing with server version)
hg incoming (compare local incoming from server)

Pulling changes from server, will update your local repository but not your working copy!
hg pull
hg update

Branching
Implicit branches
Created by a commit
Keep time of changes short

Clones

  • Can be used if we need to bugfix something quickly and we are in the middle of a development we can not yet check in.
  • Although multiple clones on one machine is not advised.
  • Fork if you want to create a new flavor and do not have the intention to commit back
  • Fork if you want to contribute on open source project, do all your changes and when finished you request a pull request to the main repository.

Named branches

  • we always start in default
  • branch name stored with changeset
  • mostly we create a branch for releases to other environments

hg update -r 6
hg branch
hg branches
hg identify -n
hg branch production (use bookmark feature if you want same branching strategy as git)
hg ci -m "quickfix"
hg update default

hg up branchtobeclosed
hg ci --close-branch -m"no longer needed"
hg up default

Merging 
hg heads
hg up default (make sure you are in branch you want to merge to)
hg merge production
hg ci -m "merge"

hg parent (show the changeset that's in the working directory)
hg paths (shows a list of known remote repositories)
hg tag version-1.0 (marks the hex number of the changeset)
hg tag -r . Version-1.1
.hgtags sometimes needs merging too :)

HTTP Fundamentals - Notes 

Categories: Network Notes

by Scott Allen

  • HTTP: HyperText Transfer Protocol
  • URL: Uniform Resource Locator

urlScheme://host:port/urlPath?q=query#fragment

URL Encoding
Safe Characters: a-z A-Z 0-9 $-_.+*'(),

Common MIME Types

  • Type/Subtype
  • application/atom+xml
  • application/json
  • image/gif
  • image/png
  • video/mp4
  • text/xml
  • text/html
  • text/plain

Content Negotiation

html: http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4
date: http://tools.ietf.org/html/rfc822#section-5.1

HTTP Transaction: HTTP Request + HTTP Response

telnet odetocode.com 80
GET /odetocode.jpg HTTP/1.1
Host: www.odetocode.com
enter key twice

HTTP Request Methods
GET, POST, PUT, DELETE, HEAD
Safe versus Unsafe: http://en.wikipedia.org/wiki/Post/Redirect/Get

Request Message
[method] [URL] [version]
[headers]
[body]

GET / HTTP/1.1
Host: server.com
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language:fr-FR
Accept-Encoding: gzip,deflate,sdch
Date: Fri, 9 Aug 2002 21:12:00 GMT
Referer, User-Agent, Accept, Cookie, If-Modified-Since, Accept-Charset

The default q value is 1.0 preference of accept

Response Message
[version] [status] [reason]
[headers]
[body]

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
X-headers are reserved for nonstandard headers

301 permanent do not come here again
302 temporarly eg. redirect after sign-in

TCP: Transmision Control Protocol -> Reliable (Transport)
not UDP: User Datagram Protocol -> Unreliable
Opens a socket on IP
IP: Internet Protocol (Network)
Ethernet (Data Link)

private static string GetResource(Uri uri)
{
var hostEntry = Dns.GetHostEntry(host);
var socket = CreateSocket(uri.hostEntry);
SendRequest(socket, uri.Host, uri.PathAndQuery);
return GetResponse(socket);
}

private static Socket CreateSocket(IPHostEntry hostEntry)
{
const int httpPort = 80;
var endPoint = new IPEndPoint(hostEntry.AddressList[0], httpPort);
var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, Protocol.Tcp);
socket.Connect(endPoint);
if (socket.Connected) return socket;
return null;
}

private static void SendRequest(Socket socket, string host, string resource)
{
var requestMessage = String.Format(
"GET {0} HTTP/1.1\r\n" +
"Host: {1}\r\n" +
"\r\n", resource, host
);
var requestBytes = Encoding.ASCII.GetBytes(requestMessage);
socket.Send(requestBytes);
}
private static string GetResponse(Socket socket)
{
int bytes = 0;
byte[] buffer = new byte[256];
var result = new StringBuilder();
do
{
bytes = socket.Receive(buffer);
result.Append(Encoding.ASCII.GetString(buffer, 0, bytes));
}
return result.ToString();
}

http://wireshark.org
Capture Options
Capture Filter: host odetocode.com
3 step TCP Handshake

www.ietf.org/rfs/rfc2616.txt
A single-user client SHOULD NOT maintain more than 2 connections with any server or proxy.

http://en.wikipedia.org/wiki/Slow-start

Default connection close about 5 seconds.
Shared hosts often send 'Connection: close' in header to allow more connections.

HTTP Architecture

http://odata.netflix.com/v2/Catalog/ (https://hidemyass.com/)
REST: www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
Forward Proxy: using a proxy as an access control device (by dropping messages)
Reverse Proxy: eg. loadbalancer
Fiddler installs itself as a local 127.0.0.1:8888 proxy in your browser

Caching
Chrome: about:cache

Cache It: HTTP/1.1 200 OK GET
Don't cache: PUT, POST, DELETE

Cache-Control: private, max-age=0
Expires: ... should no longer be used
Pragma: ... should no longer be used

Cache Control

  • public: A response for everyone
  • private: A response for a single user
  • no-cache, must-revalidate: Don't cache the response
  • no-store: You never saw this response
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));

If-Modified-Since: Wed, 14 Sep 2011 19:02:18 GMT

Etag: "07f2a22ffd9cc1:0" hash of the resource
If-None-Match: "07f2a22ffd9cc1:0"

HTTP Security
Cookies and Authentication
http://tools.ietf.org/html/rfc6265
About 4kb max

Saving State
ViewState <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/foo" />
Store in database
SessionState Store
Cookies

Set-Cookie: ASP.NET_SessionId=foo; path=/; HttpOnly

domain=.searchengine.com (include subdomains)
expires=Monday, 09-July-2012 21:12:00 GMT

Security

Basic Authentication
WWW-Authenticate: Basic realm="localhost"
Authorization: Basic base64encodedusernameandpassword

Digest Authentication
WWW-Authenticate: Digest realm="localhost", qop="auth,auth-int", nonce="...", opaque="..."

Windows Authentication
WWW-Authenticate: Negotiate
NTLM and Kerberos

Forms Authentication
Location: /login?ReturnUrl=/account

OpenID: Google, Yahoo, myOpenId, StackExchange, facebook

HTTPS
Adds a SSL/TLS layer inbetween application and transport layer
Certificate with Public/Private key
Everything except the hostname

Unit Testing with MSTest - Notes 

by Phani Tipparaju

Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll

[TestClass]

[TestMethod]
public void AnEmptyTest() {}

Arrange, Act, Assert (3 A's pattern)

Test Run Configuration:
.testsettings files
Test - Select Active Test Setting

\Common7\IDE\MSTest.exe
/testcontainer:[filename]
/test:[testname]
/testlist:[testlistpath]
/testsettings
http://msdn.microsoft.com/en-us/library/ms182489.aspx#test

Asserts and Testing Lifecycle

Configure a resource shared among your tests (db, object, log)

// once before and after each unit tests.
[TestInitialize]
public void TestInitialize() {}
[TestCleanup]
public void TestCleanUp() {}
//once before and after all tests in the class
[ClassInitialize]
public static void ClassInitialize(TestContext context) {}
[ClassCleanup]
public static void ClassCleanup() {}

//once before and after all tests in assembly
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context) {}
[AssemblyCleanup]
public static void AssemblyCleanUp() {}

Asserting

Assert.AreEqual(expected, actual, failMessage); // objectOne.Equals(objectTwo)
Assert.AreEqual(expected, actual, delta, failMessage);
Assert.AreEqual(expected, actual, true); // ignore case with strings
Assert.AreSame(a, b); // checks reference then value

CollectionAssert.AllItemsAreNotNull(collection, failMessage);
CollectionAssert.AllItemsAreUnique(collection, failMessage);
CollectionAssert.AreEqual(expected, actual); // compares element by element on reference base
CollectionAssert.AreEquivalent(expected, actual); // order of elements not important
CollectionAssert.IsSubsetOf(subset_collection, collection, failMessage);
StringAssert.Contains("string","find");
StringAssert.Matches("Search for whitespaces", new System.Text.RegularExpressions.Regex(@"\s"));
StringAssert.StartsWith("string","start string");
StringAssert.EndsWith("string","end string");

TestContext

  • Set by runtime
  • Provides information about the unit test run environment
  • Path to deployment directory
  • Test name
  • URL of the web service
  • Page object of asp.net apps
  • Access to data source with data rows
public TestContext TestContext { get; set; }
TestContext.WriteLine("TestRunDirectory: {0}", TestContext.TestRunDirectory);
TestContext.WriteLine("TestName: {0}", TestContext.TestName);
TestContext.WriteLine("Outcome: {0}", TestContext.CurrentTestOutcome);

Data driven unit-test

Test View - RightClick Properties - Data Connection String
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML"),
"|DataDirectory|\\UserDetails.xml", "User", DataAccessMethod.Sequential),
DeploymentItem("UserDetailsEntryTest\\UserDetails.xml"), TestMethod]

string email = Convert.ToString(TestContext.DataRow["email"]);

Web Performance Test 

(since it is not part of the standard visual studio I use Selenium)
Create Web App > Create a test project & add web test > Record the web test > Parameterize - Insert Rules - Dynamic Params - Loops > Run Web Test > Analyse results
Web Tests work at HTTP Layer
Microsoft.VisualStudio.TestTools.WebTesting.ExtractionRule
Microsoft.VisualStudio.TestTools.WebTesting.ValidationRule
public class MyCustomWebTest : WebTest {}

Unit Test Features

Ordered Tests

  • Appears as a single test in the Test Window (double click to see individual results)
  • Can execute one test many times
  • Used to group tests together, can contain other ordered tests but no load tests.

Generic Tests

  • Integrate Non-VS automated testing tools
  • Can be run from command line
  • Must return a value of Pass or Fail (return 0 is pass all else is fail)
  • Uses your credentials (trust the author and know what the program will do)

Test Attributes (will show up in .trx xml file)

[Owner("Ken")]
[Description("This is for testing")]
[TestProperty("MyCustomVersion","1.0.1.2")]
[TimeOut(1000)] // in milliseconds
[Priority(1)] // not used by the system, but you can use to sort them in the test list editor
[Ignore] // do not run test
[TestCategory("MyCategory")]
[ExpectedException(typeof(DivideByZeroException))]

Relate to Team Foundation Server
[CssIteration] // Classification.Iteration
[CssProjectStructure] // Classification.Area
[WorkItem] // User Story

WebServiceHelper

[Microsoft.VisualStudio.TestTools.UnitTesting.Web.AspNetDevelopmentServer("WcfService1", "path to service")]
public void TestMethod1()
{
var target = new WebServiceTesting.ServiceReference.ServiceClient();
var protocol = new System.Web.Services.Protocols.HttpGetClientProtocol();
protocol.Url = "http://myservice.svc";
Assert.IsTrue(WebServiceHelper.TryUrlRedirection(protocol, testContextInstance, "WcfService1"));
actual = target.GetData(1);
Assert.AreEqual(1,actual);
}

TestConfigurationSection

  • Instead of providing values in code, depend on configuration files
  • Allows flexibility for regions and file formats.

1. Create a app.config
2. Define "TestConfigurationSection"
<configSections>
<section name="microsoft.visualstudio.testtools" type="..." />
</configSections>
3. Define connectionstrings
<connectionStrings>
<add name="MyExcel" connectionstring="Dsn=Excel ..." providerName="System.Data.Odbc" />
</connectionStrings>
4. Define data source
<microsoft.visualstudio.testtools>
<dataSources>
<add name="MyExcelDataSource" connectionstring="MyExcel" dataTable="Sheet1$" dataAccessMethod="Sequential" />
</dataSources>
</microsoft.visualstudio.testtools>
5. Use the "DataSourceAttribute" for the test method
[DataSource("MyExcelDataSource")] instead of using [DataSource]

Rhino Mocks Fundamentals - Notes 

Categories: Notes Testing

by Jim Cooper

codesimply.blogspot.com

A good unit test

  • Atomic
  • Deterministic (it should pass or fail)
  • Repeatable
  • Order Independent & Isolated
  • Fast
  • Easy to setup
var mockStudentRepository = MockRepository.GenerateMock<IStudentRepository>();
var student = new Student() { ... };
studentService.RegisterNewStudent(student);
mockStudentRepository.AssertWasCalled(x => x.Save(student));

//using mocks to verify property setters
var mockStudentView = MockRepository.GenerateMock<IStudentView>();
mockstudentView.AssertWasCalled(x => x.WasStudentSaved = true);

//using stubs to control the program flow
var mockStudentValidator = MockRepository.GenerateMock<IStudentValidator>();
mockStudentValidator.Stub(x => x.ValidateStudent(Arg<Student>.Is.Anything)).Return(true);
mockStudentView.Stub(x => x.ShouldSaveStudent).Return(true);

//do not use GenerateStub cause it will not work for read-only properties
var mockStudentView = MockRepository.GenerateStub<IStudentView>();
mockstudentView.ShouldSaveStudent = true;
  • It's much easier to always use GenerateMock, you might need it anyway
  • Actualy generatemock actually is a generatetestdouble
  • Use Arrange,Act,Assert instead of Record,Replay (legacy: Record, Playback, Expect.Call, ReplayAll, VerifyAll, DynamicMocks vs StrictMocks)
//constraints
Arg<Student>.Is.Anything,NotNull,Same,...
Arg<Student>.Matches(y => y.Id == expectedStudentId && y.FirstName == expectedFirstName)
Arg<Student>.Matches(y => IsCustomerMatching(student, expectedStudentId, expectedFirstName)
Arg<List<Student>>.List.ContainsAll(new List<Student> {student1, student2, student3})
Arg<List<Student>>.List.Count(Rhino.Mocks.Constraints.Is.Equal(3))
Arg<List<Student>>.List.IsIn(student1)
Text.Contains("one"),EndsWidth,StartWith,Like,...
//example custom constraint
mockStudentRepository.AssertWasCalled(x => x.Save(Arg<Student>.Matches(new StudentConstraint(expectedStudent))));
public class StudentConstraint : AbstractConstraint
{
public StudentContraint(Student expectedStudent) {}
public override bool Eval(object actual) {}
public override string Message { get; set; } //called if eval is false
}

Avoid using out & ref parameters
out Arg<Student>.Out(new Student()).Dummy
ref Arg<Student>.Ref(Rhino.Mocks.Constraints.Is.Anything, new Student()).Dummy

Page 2 of 5 << < 1 2 3 4 5 > >>