ict.ken.be

 

Posts in Category: Notes

Resharper Shortcuts 

Categories: Notes Shortcuts

ReSharper Fundamentals

by James Kovacs

It wasn't the end of the world, but at least we got cheap licenses from JetBrains. Tx

Check their site for docs and videos.
Keep your hands on the keyboard.

Code Browsing

Navigate ALT-R,N
Find ALT-R,F
Navigate To ALT-µ

Goto Type CTRL-T use capital abbreviations
Goto File CTRL-SHIFT-T
Recent Files CTRL-, (VS edit.navigate.to)
Related Files CTRL-ALT-F7

Next Member ALT-UP
Previous Member ALT-DOWN
File Member CTRL-\
?? Containing Declaration CTRL-[

Goto Derived ALT-END
Goto Implementation CTRL-F12
Goto Base ALT-HOME
View Type Hierarchy CTRL-E,H
Goto Declaration F12
Goto Type of Symbol CTRL-SHIFT-F11

Find Usages SHIFT-F12
Highlight Usages ALT-SHIFT-F11 was Debug.StepInsideSpecific
Next Usage CTRL-ALT-PAGEUP
Previous Usage CTRL-ALT-PAGEDOWN
Advanced Find Usages CTRL-ALT-SHIFT-F12

Set/Remove Bookmark CTRL-SHIFT-[0-9]
Goto Bookmarks CTRL-[0-9]
View Bookmarks CTRL-µ

Goto Symbol ALT-SHIFT-T
Inspect This CTRL-ALT-SHIFT-A

Locate File ALT-SHIFT-L (VS team and diagram)

Code Cleanup

Quick Fix ALT-Enter
Next Highlight ALT-PAGEDOWN
Previous Highlight ALT-PAGEUP

Move Code Up/Down CTRL-ALT-SHIFT-UP/DOWN
Move Code In/Out CTRL-ALT-SHIFT-LEFT/RIGHT
Clipboard ring CTRL-SHIFT-V
View File Structure CTRL-ALT-F

Code Cleanup CTRL-E,C
Silent Code Cleanup CTRL-E,F
Resharper - Options - Code Editing - C# - Formatting Style - At end of line (K&R style)
Code Style Sharing - Per solution stored in a file.
You can select solution, project or folder and it will do cleanup everywhere.
Remove Unused Code ALT-ENTER
Safe Delete ALT-DEL

Refactoring

Refactor This CTRL-SHIFT-R
Extend Selection CTRL-ALT-RIGHT
Shrink Selection CTRL-ALT-LEFT
Rename CTRL-R,R

Introduce Variable CTRL-R,V
Introduce Field CTRL-R,F
Inline var/field CTRL-R,I

Extract Method CTRL-R,M
Inline Method CTRL-R,I
Introduce Parameter CTRL-R,P

Create New File CTRL-ALT-INSERT
Move Static Member CTRL-R,O
Move To Another File CTRL-R,O
Move To Folder CTRL-R,O
Move Type To Namespace CTRL-R,O
Static <> Extension CTRL-SHIFT-R
Method <> Property CTRL-SHIFT-R
Method <> Indexer CTRL-SHIFT-R
Encapsulate Field CTRL-SHIFT-R
Property <> Autoprop CTRL-SHIFT-R
Extract Superclass CTRL-SHIFT-R
Extract Interface CTRL-SHIFT-R
Pull Member Up/Down CTRL-SHIFT-R
Copy Type CTRL-SHIFT-R
Constructor to factory CTRL-SHIFT-R
Anonymous to Named CTRL-SHIFT-R
Interface <> AbstractClass CTRL-SHIFT-R
Use Base Type Where Possible CTRL-SHIFT-R
Extract Class from Parameters CTRL-SHIFT-R
Resource extraction CTRL-SHIFT-R
Code Editing - Localization - Uncheck don't analyse verbatim strings
Project - Properties - Localizable Yes - Inspector Pessimistic - [Localizable(false)]
Goto base ALT-HOME
Goto derived ALT-END
Change Signature CTRL-R,S

 Coding Assistance

Symbol Code Completion CTRL-SPACE
Smartcode Completion CTRL-ALT-SPACE
Import Symbol Completion ALT-SHIFT-SPACE

Coding Backwards CTRL-R,V
Complete Statements CTRL-SHIFT-ENTER
Duplicate Line/Selection CTRL-D
Comment/Uncomment Line CTRL-ALT-/
Comment/Uncomment Block CTRL-SHIFT-/
Surround With CTRL-E,U

Parameter Info CTRL-SHIFT-SPACE
Quick Docs CTRL-SHIFT-F1
Solution Wide Analysis Gray dot in right bottom corner

 Micro Code Generation & Templating

Generate Code ALT-INSERT
Implement delegating members
New file template - Resharper - Templates Explorer - File Templates
Insert Live Template CTRL-E,L
Create Live Template ALT-R,T,R
$END$, $PROP_TYPE$, $PROP_NAME$, $CLASS$, $SELSTART$, $SELEND$, $SELECTION$, ...
Users - User - AppData - Roaming - JetBrains - ReSharper - v7.1 - vs10.0 - UserSettings.xml

 Grab Bag of Useful Extras

Explore Stack Trace CTRL-E,T (copy stack message to clipboard first)
Todo-List CTRL-ALT-D

Run all tests ALT-R,U,N
Run test in context ALT-R,U,R
Run test in session ALT-R,U,C

Patterns Catalog
Download from JetBrains : Sample pattern catalog for Structural Search and Replace
ReSharper | Options | Code Inspection | Custom Patterns and click Import.

MSBuild and Nant helpers CTRL-ALT-F (only for .csproj)

Introduction to IIS Certificates - Notes 

Categories: IIS Notes

by Paul Lemmers

Ok, this must have been the most confusing 44m of my IT life. I clearly do have almost no knowledge about certificates. (edit: finally starting to understand, and yes it is very important and also a total mess selfsll, opensll, bouncycastle, certutil, pvk2pfx, makecert, ...) and I actually wonder if there are people who really know this... let alone really understand the specifications.

Alice & Bob Story - Certificate is name of Alice + Public key signed with private key if self-signed.
Object Identifier (OID)
Certificate: Subject CN = name to trust, Issuer eg. Go Daddy, Valid from, Valid to, Public Key

Exclamation mark means it is a critical extension and client should only use it when they really know how.

Formats

  • DER (binary format *.cer over network in ssl handshake)
  • Base-64 (xml, email)
  • Export with hierarchy of certificates can be included (.P7B)
  • PKCS#12 : Export user certificate with private key. (.PFX)

MMC - Certificates
To make all stores visible, select Certificates in treeview > View - Options - Check Physical certificate stores. All hidden notes of trusted root certification authorities will be visible. Certificates that are at enterprise level will come back in your store after deletion if set in the group policy.

When using a machine for signing, you should always delete the private key on export.

Distinguished Name

E = foo@bar.com
CN = foo bar
CN = foo
DC = local

Subject Alternative Name

Other Name:
       Principal Name = foo@bar.com (upn name)
RFC822 Name = Foo@Bar.com (email name)

Key Usage (8bit field flags)
Enhanced Key Usage
SSL certificate should have Server Authentication as enhanced, Digital Signature and Key Encipherment as usage. Command name should be dns.

Where are the keys stored?

CSP - Cryptical Service Providers (eg. when using a smartcard to sign, the private key will 'never' leave the smart card) In the properties (all tasks - manage private keys) you can set which computer accounts should have access to the certificates.

certutil (eg. when using windows 2003)
certutil -dump -v abc.cer
certutil -url abc.cer
certutil -store My
  • Windows - dir ProgramData /As - Microsoft - Crypt - RSA - MachineKeys
  • Firefox - Tools - Options - Encryption - View Certificates
  • Microsoft Active Directory Certificate Services - psResCA

IIS - Machine Name - Server Certificates
Create Domain Certificate (testing)
Create Certificate Request (from external)
Complete Certificate Request

Self-Signed Certificates
if key usage and enhanced key usage is not filled in you can use the certificate for anything
if you install a self-signed certificate of someone else in your trusted root store then they can do remote to your machine!

Certificate Revocation

Certificate - Details - CRL Distribution Point -> url -> Certificate Revocation List -> Serial number by date and reason. (eg. http://crl.godaddy.com/gds3-4.crl)

Authority Information Access (eg. http://ocsp.godaddy.com) will just return valid or not for this certificate instead of complete list of revoked certificates.

Certificate Chain building
Root Certificate then Issuer = Subject

Legal
When you create a CA you are changing the burden of proof (certificate policies)
Usage of certificates has legal consequences.

More

Azure - The Big Picture - Notes 

Categories: Azure Notes

by David Chappell
http://www.davidchappell.com

Execution Models

Virtual Machines (IaaS)
VHDs from Gallery or User-Supplied (by the hour used or unused)
Azure Management Portal
Rest API for scripting and creating VMs in batch
One OS disk and one or more data disks (all stored as blobs)
You can move the image in and out the platform
eg. App + Sql cluster, Sharepoint farm, on demand vm for testing, disaster recovery
Only failed hardware will be fixed.
Requires the most management.

Web Sites
Shared IIS or Dedicated IIS
Static Websites
Popular Web Applications eg. Drupal, ...
Custom Web Applications eg. ASP.Net, Node.js, ...
Upload through ftp, WebDeploy, Repository (TFS, Git)

Cloud Services (PaaS)
Platform as a service
Web Roles - run iis
Worker Roles
The environment is created for you using code configuration
Detect failed applications and starts new one
So you can not store state in your VM file systems!
eg. app must be very reliable and very scalable
Low admin cost.
Needed when not possible with other options
eg. Admin access to VMs, to install arbitrary software
Background processing with workerroles
Connect to Azure Virtual Network
Combining technologies is possible.

Data Management

Sql Database Service
Disks are stored as blogs
Multi tenant virtual servers
Automatic data replication (setup 5 min)
Limited to some hunderd of gigabytes, else you need Sql Federation.
An application can work with two or more federation members that can have separate dbs and schema
Sql Data Sync between different datacenters in cloud or on-premise (with some latency)

Table Storage - NoSql
Key Value storage
Across multiple machines
Tables are partitioned with entities
Entities have properties of various types
Entities have row keys unique in their partition
Partitions have keys
eg. simple, fast access to loosly structured data
eg. very large about of data (up to 100 terabyte)
Much cheaper then sql but no query options

Blob Storage
Named containers
Large amounts of data such as video
For backup eg. whole VHDs

Business Analytics

Sql reporting
BI Studio & RDL-Files

Hadoop
Open source
Big data analysis
Map reduce over different systems
Large amount of unstructured data
Assumes data is in blobs
hdfs data api
Hive (with excel import), Pig, ...
eg. Log files, sensors like RFID, clickstream data, ...

Networking

Virtual Network
Connect your on-premise network with cloud network of VMs
Setup a segment of VMs as VNET
VPN Gateway Device with IPsec Connection needed
eg. Single sign-on with active directory, Dev/Test environments

Connect
Direct connection from application to group of on-premise servers
Windows Azure ConnectSoftware with IPsec Connection
No need to setup a full VPN

Traffic Manager
Routes users to datacenters that are most close to them
1. User lookup application dns name
2. DNS server redirects the query
3. AWTM applies policies
3a. Performance: to closest
3b. Failover: to specific unless down
3c. Round Robin: spread equaly across datacenters
4. Return chosen datacenter
5. Access application in datacenter

Messaging

Queues
In cloud communication
Web role(front-end) instances to/from worker role(back-end) instances
1. Web role receives work
2. Web role sends message
3. Worker reads message
4. Worker does work
5. Worker delete message (or it will re-appear in the queue)

Service Bus
In cloud, on-premise, anywhere communication
Multi tenant, each user has its own namespace
Queues: one to one queued messaging (one way communication)
message with body and properties (key-value)
Topics: one to many publish and subscribe messaging using filters
Relays: two way bi-directional messaging (eg. servers behind firewalls)
each application opens outbound to relay, inbound communication is seen as incoming on outgoing tcp/ip
construction a stable ip

Caching

  • Caching: on the VM or distributed on an array of VMs (supports MemCached api)
  • CDN: Video stored in blob and distributed globally

Identity

  • Active Directory
  • Running Windows Server AD in Azure VMs eg. Sharepoint on a web farm
  • Using Azure Active Directory eg. Saas (software as a service) apps 
  • ACS for single sign on with FB, Google, ...

High-Performance Computing

  • HPC Scheduler

Media

  • Media Services
  • Media Ingest - copy video into cloud blogs
  • Encoding - translate formats
  • Content Protection
  • Ad Insertion
  • Streaming
  • Partner Components
  • Using CDN to distribute if you feel like

Commerce

  • Windows Azure Marketplace
  • Sell your azure application in the cloud
  • Selling datasets

SDKs

  • .Net, Java, PHP, Python, Node.js, C++
  • Commandline tools for deployment from and to Linux and Macintosh

IIS for developers - Notes 

Categories: IIS Notes

by Steve Evans

1. IIS Setup

  • Windows 2000/IIS 5 (sample page allowed code red to attack the machine)
  • Windows 2003/IIS 6 (you had to activate on server)
  • Windows 2008/IIS 7 (choose with bits you want to install)
  • Windows 2008R2/IIS7.5

Server Manager - Roles - Add IIS

Web Platform Installer
Allows to install plugins like WordPress, Orchard CMS, MVC, IIS: FTP Publishing Service, IIS Smooth Streaming Client, ...

Remove default website

Keep binding IP address 'all unassigned' because webservers can have multiple ip addresses.

Remember to also bind www

SSL-Certificate
Root - Server Certificates
Create Certificate Request (for testing use self-signed certificate, issued to name of the box)
Add additional binding of type https
One ssl for one ip address, cause hostname is encrypted.
Browser will check that
Date is in range
Certificate created by authority it trusts
Does the hostname match what is in the certificate

Wildcard certificate (for testing make one with makecert.exe in windows SDK)
Root - Server Certificates - Import the pfx file (eg. issues to *.site2.com)
Bindings - Select certificate - Fill in subdomain host name (eg. www.site2.com)

Extended validation certificate is not available in wild card.

2. IIS Configuration

If not default document is defined you will get a 403.14 - Forbidden if the web server is configured to not list the contents of the directory.

web.config (can have other copies in subfolders)
<configuration>
  <defaultDocument>
    <files>
      <clear /> -> will break inheritance of parent folder
      <remove value="Default.htm" />
      <add value="Home.htm" />
   </files>
  </defaultDocument>
</configuration>

Feature Delegation
If you put on read only the developer will see the setting but not be able to change it in the web.config
Will throw a 500.19 if you keep the settings in the web.config
Remember to set them in IIS or you will get 403.14 again.
When going from read only to write it is best to revert to parent to avoid inconsistencies.

Application Pools (worker processes)
In production environment put the 'Idle Time-out' to 0.
Define your web garden by adjusting the maximum worker processes.
Ping enable will check if your application pool is healthy and if not recycle.
By default application gets recycled

  • idle timeout of 20min
  • every 29hours (you can add specific times instead)
  • whenever an unhandled exception occurs
  • whenever a ping gives an unhealthy response
  • whenever configuration changes

You can set the application pool defaults.
It is best to have only one site per application pool, unless very limited resources.
You can put part of a site in a separated application pool. (right-click folder, convert to application)

3. Manage IIS

Root - Worker Processes - Select pool and you will see all request that run longer then 0 seconds.

Server Manager - Add Role - Health - Tracing
Failed request tracing rules - Add
eg. trace requests that take longer than 30 seconds
eg. all pages that return a 500
Edit Site Tracing - Location where to store - open xml for report

Microsoft Log Parserhttp://www.microsoft.com/en-us/download/details.aspx?id=24659

Log Parser Lizardhttp://www.lizard-labs.net/log_parser_lizard.aspx

SELECT TOP 100 * 
FROM D:\Backups\date_libertinus_eu_logfiles_20121101\W3SVC4\*.log

SELECT cs-uri-stem, count(*)
FROM D:\Backups\date_libertinus_eu_logfiles_20121101\W3SVC4\*.log
WHERE sc-status = 404 AND date > '2012-10-01'
GROUP BY cs-uri-stem


Windows PowerShell will treat iis as a drive.

cd iis:\\
dir
cd .\AppPools
cd ..
cd sites

New-Item iis:\Sites\site3.com
-bindings @{protocol="http";bindingInformation="*:80:site3.com"}
-physicalPath C:\inetpub\site3.com

New-ItemProperty iis:\sites\site3.com
-name bindings
-value @{protocol="http";bindingInformation="*:80:www.site3.com"}

Web Deployment Tool 2.1

msdeploy 
-verb:sync
-source:webServer
-dest:webServer,computerName=xyz,username=rst,password=abc

-whatif
-presync:runcommand="%windir%\system32\inetsrv\appcmd stop apppool site2.com"

msdeploy
-verb:sync
-source:iisApp=site2.com
-dest:archiveDir=c:\temp

visual studio under administrator
right-click - publish - web deploy

4. IIS Extensions

http://iis.net - download
Media Services
URL Rewrite
You can specify user-friendly-urls and map them to old url.
You can also redirect, return custom response, ...

5. IIS Express

MyDocuments - IISExpress - Logs
MMC - Add certificate snap in - Computer Account - Personal Certificates - Copy certificate to trusted root certificates

6. IIS8 for 2012

Choose on which set of servers you want to install this. (so you can install on all your servers in the same time)

Application Initialisation Mode (app warmup)
IIs will perform the first request for you.
Application Pool - Advanced Settings - Start Mode - AlwaysRunning
Site - Advanced Settings - Preload Enabled - True

<applicationInitialization remapManagedRequestsTo="startup.htm" skipManagedModules="true">
    <add initializationPage="/default.aspx"/>
</applicationInitialization>

SNI - Server Name Indication
Allows multiple ssl certificates on one IP
Not support in Internet Explorer on windows XP !

SSL Management: Centralized Certificates for web farms with lots of certificates.
CPU ThrottleUnderLoad, allows to specify a percentage when others are also using else max possible.
Web Sockets support by adding WebSocket Protocol

Entity Framework 4.1 DbContext Data Access - Notes 

Categories: EF Notes

Entity Framework 4.1 DbContext Data Access
Julie Lerman

1. DbContext
  • .Add
  • .Attach is not an update but tells EF to track the entity.
  • .Remove
  • .Entry.State=Modified Added Deleted
var newPerson = context.People.Add(new Person { Name = "Julie"});
Assert.IsTrue(context.Entry(newPerson).State==System.Data.EnitityState.Added);
 
//context.Aliases.Attach(existingAlias); //line below willl do implicit
context.Entry(existingAlias).State = System.Data.EntityState.Modified;
Assert.IsTrue(context.Entry(exisitingAlias).State == System.Data.EntityState.Modified);
 
var query = from p in context.Person where p.Id == 3 select p;
var person = query.FirstOrDefault();
//use instead ->
var person = context.People.Find(3); //uses context cach as a bonus
 
//objects managed by the cache
ObservableCollection<Person> = context.People.Local 
Proxies, Change Tracking & Lazy Loading
[TestMethod]
public void ObjectsGetDynamicProxies()
{
var context = new TwitterContext();
var alias = context.Aliases.FirstOrDefault();
Assert.IsTrue(alias.GetType().FullName.StartsWith("System.Data.Entity.DynamicProxies"));
}
 
[TestMethod]
public void ObjectsAreInstantlyChangeTracked()
{
var context = new TwitterContext();
var alias = context.Aliases.FirstOrDefault();
alias.Name = "abcde";
//context.ChangeTracker.DetectChanges(); when not using dynamic proxy
Assert.IsTrue(((context as IObjectContextAdapter).ObjectContext).ObjectStateManager.GetObjectStateEntries(EntityState.Modified).Count() == 1);
}
 
public class Alias
{
public virtual int AuthorKey { get; set; } //will create lazy loading dynamic proxy
public virtual ICollection<Tweet> Tweets { get; set; } //one marked as virtual will enable lazy loading
public string Email { get; set; } //must be virual if you want change tracking
public string AliasPlusName //no setter so will be skipped
{
get { return Name + "(" + UserName + ")"; }
}
}
Change Tracker
  • DetectChanges called by:
  • DbSet .Find .Local .Remove .Add .Attach
  • DbContext .SaveChanges .GetValidationErrors .Entry
  • DbChangeTracker.Entries
//if you do NOT want DetectChanges to get called
context.Configuration.AutoDetectChangesEnabled = false;
Get To ObjectContext
  • var oContext = (myDbContext as ObjectContextAdapter).ObjectContext;
  • Linq to Entities CompiledQuery: No DbContext, No Adapter.ObjectContext
  • EF5 : http://blogs.msdn.com/b/stuartleeks/archive/2012/06/12/entity-framework-5-controlling-automatic-query-compilation.aspx
[TestMethod]
public void CanGetDatabaseValuesFromEntry()
{
var context = new TwitterContext();
var alias = context.Aliases.FirstOrDefault();
DbPropertyValues dbValues = context.Entry(alias).GetDatabaseValues();
Assert.IsNotNull(dbValues);
}
 
//when savechanges and an optimistic concurrency error was thrown
var entry = context.Entry(alias);
entry.OriginalValues.SetValues(entry.GetDatabaseValues()); //client win
entry.Reload(); //or use for server win
From existing database
  • edmx file -> DbContext T4 Template -> Simple POCO Classes and DbContext
  • ADO.Net DbContext Generation 
2. Code First Database Initialization
  • Connectionstring Available (else use buildstring) -> Database Exists (else create database) -> Use Database
  • Buildstring: SQL Server Express using Context Strong Name
  • eg. namespace DAL class myContext -> DAL.myContext will be the database name
public class MyContext : DbContext
{
  public MyContext() : base("MyOwnDatabaseName") {}
 
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
modelBuilder.Ignore<Privacy>();
modelBuilder.Configurations.Add(new AliasConfiguration());
}
}
  1. Read classes & configurations
  2. Build in-memory Model & mappings
  3. Compare model to EdmMetadata table
  4. Changes? Follow init strategy (default: throw exception)
//on application_start()
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
IDatabaseInitializer
  • CreateDataseIfNotExists
  • DropCreateDatabaseIfModelChanges
  • DropCreateDatabaseAlways
  • YourCustomDBInitialize
 
Code First Migrations
public class MyInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
  protected override void Seed(TwitterContext context)
  {
  new List<Alias> { ... }.ForEach(b => context.Aliases.Add(b));
base.Seed(context); //calls SaveChanges, so you don't have to
  }
}
Database.SetInitializer(new MyInitializer());
Specify the Database (new or existing)
<connectionStrings>
<add name="TwitterContext" 
connectionString="Data Source=.;Initial Catalog=TweetTweet;Integrated Security=True" 
providerName="System.Data.SqlCient" />
</connectionStrings> 
Make sure that initializer is on default CreateDataseIfNotExists, cause it will think you modified the database since EdmMetadata is missing!
 
  • DbModelBuilder.Conventions.Remove(IncludeMetadataConvention);
  • Database.SetInitialize<MyContext>(null);
  • <appSettings><add key="DatabaseInitializerForType DAL.MyContext, DataAccessAssembly" value="Disabled" /></appSettings>
 
Generic Types in XML configuration
  • IList<T> will be IList`1 and IList[]
  • IDictionary<K,V> will be IDictionary`2 and IDictionary[,]
 
System.Data.Entity.Database
  • Create, CreateIfNotExists, Delete, Exists
  • GetHashCode
  • ExecuteSqlCommand, SqlQuery
  • CompatibleWithModel
  • Initialize, SetInitializer(TContext)
  • Connection, DefaultConnectionFactory
3. More on Entity Framework
Page 3 of 5 << < 1 2 3 4 5 > >>