Friday, April 30, 2010

Visual Studio 2010 - Keyboard Shortcuts


  • VSTS 2010 is supporting Multimonitor's - drag and drop documents or toolboxes out of your VS onto other monitors.

  • Navigation to - upon "ctrl+comma" it's easy to navigate around




File Menu Primary Secondary
New Project: Ctrl + Shift + N / Alt F + N + P
New Website: Shift + Alt + N / Alt F + N + W
Open Project: Ctrl + Shift + O / Alt F + O + P
Open Website: Shift + Alt + O / Alt F + O + E
Open File: Ctrl + O / Alt F + O + F
Convert: / Alt F + O + C
Close: / Alt F + C
Close Solution: / Alt F + T
Save: Ctrl + S
Save As: Alt F + A
Save Option: Alt F + V
Save All: Ctrl + Shift + S / Alt F + L
Export Template: / Alt F + E
Page Setup: / Alt F + U
Print: Ctrl + P
Recent Files: / Alt F + F
Recent Project/Solution: / Alt F + J
Exit: / Alt F + X

Edit Menu Primary Secondary
Undo: Ctrl + Z / Alt E + U
Redo: Ctrl + Y / Alt E + R
Undo Last Global Action: / Alt E + N
Redo Last Global Action: / Alt E + L
Cut: Ctrl + X / Alt E + T
Copy: Ctrl + C / Alt E + C
Paste: Ctrl + P / Alt E + P
Delete: DEL (Button) Alt E + D
Select All: Ctrl + A / Alt E + A
Find and Replace Options: / Alt E + F
Quick Find: Ctrl + F / Alt E + F + F
Quick Replace: Ctrl + H / Alt E + F + R
Find in Files: Ctrl + Shift + F / Alt E + F + I
Replace in Files: Ctrl + Shift + H / Alt E + F + S
Find Symbol: Alt + F12 / Alt E + F + Y
Go To: Ctrl + G / Alt E + G
Navigate To: Ctrl + , / Alt E + .
Insert File as Text: / Alt E + X
Advance: / Alt E + V
Format Document: Ctrl K + D / Alt E + V + A
Format Selection: Ctrl K + F / Alt E + V + F
Tabify Selected Lines: / Alt E + V + T
Untabify Selected Lines: / Alt E + V + B
Make Uppercase: Ctrl + Shift + U / Alt E + V + U
Make Lowercase: Ctrl + U / Alt E + V + L
Delete Horizontal White Space: Ctrl + K + \ / Alt E + V + H
View White Space: Ctrl + R + W / Alt E + V + W
Word Wrap: Ctrl + E + W / Alt E + V + R
Incremental Search: Ctrl + I / Alt E + V + S
Comment Selection: Ctrl + K + C / Alt E + V + M
Uncomment Selection: Ctrl + K + U / Alt E + V + E
Increase Line Indent: / Alt E + V + I
Decrease Line Indent: / Alt E + V + D
Bookmarks: / Alt E + K
Toggle Bookmark: Ctrl + K + K / Alt E + K + T
Enabled All Bookmarks: / Alt E + K + A
Previous Bookmark: Ctrl + K + P / Alt E + K + P
Next Bookmark: Ctrl + K + N / Alt E + K + B
Clear Bookmarks: Ctrl + K + L / Alt E + K + C
Previous Bookmark in Folder: Ctrl + Shift + K + P
Next Bookmark in Folder: Ctrl + Shift + K + N
Previous Bookmark in Document: / Alt E + K + R
Next Bookmark in Document: / Alt E + K + E
Add Task List Shortcut: Ctrl + K + H
Outlining: / Alt E + O
Toggle Outlining Expansion: Ctrl + M + M / Alt E + O + T
Toggle All Outlining: Ctrl + M + L / Alt E + O + L
Stop Outlining: Ctrl + M + P / Alt E + O + P
Stop Hiding Current: Ctrl + M + U / Alt E + O + I
Collapse to Definition: Ctrl + M + O / Alt E + O + O
Intellisence: / Alt E + I
Generate: / Alt E + I + G
Generate Method Stub: Ctrl + K + M / Alt E + I + G + G
Constructor: / Alt E + I + G + C
Property: / Alt E + I + G + P
Field: / Alt E + I + G + F
Enum Member: / Alt E + I + G + E
Type...: / Alt E + I + G + Y
Implement Interface: / Alt E + I + I
Implicitly: / Alt E + I + I + Right Arrow + M
Explicitly: / Alt E + I + I + Right Arrow + X
Implement Abstract Class: / Alt + E + I + A
Organize Using: / Alt + E + I + O
Remove Unused Using: / Alt + E + I + O + R
Sort Using: / Alt + E + I + O + U
Remove and Sort: / Alt + E + I + O + A
List Members: Ctrl + J / Alt + E + I + L
Parameter Info: Ctrl + Shift + Space / Alt + E + I + P
Quick Info: Ctrl + K + I / Alt + E + I + Q
Complete Word: Alt + Right Arrow / Alt + E + I + W
Toggle Consume First Completion Mode: Ctrl + Alt + Space/ Alt + E + I + T
Insert Snippet…: Ctrl + K + X / Alt + E + I + I
Surround With…: Ctrl + K + S / Alt + E + I + S

View Menu Primary Secondary
Code: / Alt + V + C
Open: / Alt + V + O
Open With…: / Alt + V + N
Server Explorer: Ctrl + Alt + S / Alt + V + V
Solution Explorer: Ctrl + Alt + L / Alt + V + P
Bookmark Window: Ctrl + K + W / Alt + V + B
Call Hierarchy: Ctrl + Alt + K / Alt + V + H
Class View: Ctrl + Shift + C / Alt + V + A
Code Definition Window: Ctrl + \ + D / Alt + V + D
Object Browser: Ctrl + Alt + J / Alt + V + J
Error List: Ctrl + \ + E / Alt + V + L
Toolbox: Ctrl + Alt + X / Alt + V + X
Start Page: / Alt + V + G
Find Results: / Alt + V + N
Find Results 1: / Alt + V + 1
Find Results 2: / Alt + V + 2
Find Symbol Results: Ctrl + Alt + F12 / Alt + V + Y
Other Windows: / Alt + V + E
Command Window: Ctrl + Alt + A / Alt + V + E + C
Resource View: Ctrl + Shift + E / Alt + V + E + R
F# Interactive: Ctrl + Alt + F
Macro Explorer: Alt + F8 / Alt + V + E + M
Web Browser: Ctrl + Alt + R / Alt + V + E + B
Toolbars: / Alt + V +T
Full Screen: Shift + Alt + Enter / Alt + V + U
Navigate Backward: Ctrl + - / Alt + V +B
Navigate Forward: Ctrl + Shift + - / Alt + V + F
Next Task: / Alt + V + X
Previous Task: / Alt + V + R
Property Pages: Shift + F4 / Alt + V + Y

Refactor Menu Primary Secondary
Rename: Ctrl + R + R / Alt + R + R
Extract Method: Ctrl + R + M / Alt + R + M
Encapsulate Field: Ctrl + R + E / Alt + R + F
Extract Interface: Ctrl + R + I / Alt + R + I
Remove Parameters: Ctrl + R + V / Alt + R + V
Reorder Parameters: Ctrl + R + O / Alt + R + O

Project Menu Primary Secondary
Add Class: / Alt + P + C
Add New Item: Ctrl + Shift + A / Alt + P + W
Add Existing Item: Shift + Alt + A / Alt + P + G
Add ASP.Net Folder: / Alt + P + S
App_Global Resources: / Alt + P + S + R
App_Local Resources: / Alt + P + S + C
App_Data: / Alt + P + S + A
App_Browsers: / Alt + P + S + W
Theme: / Alt + P + S + E
Package: / Alt + P + K
Create Package: / Alt + P + P
Package Settings: / Alt + P + S
Exclude From Project: / Alt + P + J
Show All Files: / Alt + P + O
Add Reference: / Alt + P + R
Add Service Reference: / Alt + P + S
Set as StartUp Project: / Alt + P + A
Refresh Project Toolbox Items: / Alt + P + T
Properties: / Alt + P + P
ASP.NET Configuration: / Alt + P + T

Build Menu Primary Secondary
Build Solution: Ctrl + Shift + B / Alt + B + B
Rebuild Solution: / Alt + B + R
Clean Solution: / Alt + B + C
Build: / Alt + B + U
Rebuild: / Alt + B + E
Clean: / Alt + B + N
Publish: / Alt + B + H
Batch Build: / Alt + B + T
Configuration Manager: / Alt + B + O

Debug Menu Primary Secondary
Window: / Alt + D + W
Breakpoints: Ctrl + Alt + B / Alt + D + W + B
Output: / Alt + D + W + O
Immediate: Ctrl + Alt + I / Alt + D + W + I
Start Debugging: F5 / Alt + D + S
Start Without Debugging: Ctrl + F5 / Alt + D + H
Attach to Process: / Alt + D + P
Exceptions: Ctrl + Alt + E / Alt + D + X
Step Info: F11 / Alt + D + I
Step Over: F10 / Alt + D + O
Toggle Breakpoint: F9 / Alt + D + G
New Breakpoint: Alt + D + B
Break at Function: Ctrl + B / Alt + D + B + F
New Data Breakpoint: / Alt + D + B + D
Delete All Breakpoints: Ctrl + Shift + F9/ Alt + D + D

Tools Menu Primary Secondary
Attach to Process: Ctrl + Alt + P / Alt + T + P
Connect to Database: / Alt + T + D
Connect to Server: / Alt + T + S
Code Snippets Manager: Ctrl + K + B / Alt + T + T
Choose Toolbox Item: / Alt + T + X
Add-In Manager: / Alt + T + A
Macros: / Alt + T + M
Run TemporaryMacro: Ctrl + Shift + P / Alt + T + M + R
Record TemporaryMacro: Ctrl + Shift + R / Alt + T + M + C
Save TemporaryMacro: / Alt + T + M + V
Macro Explorer: Alt + F8 / Alt + T + M + M
Macros IDE: Alt + F11 / Alt + T + M + I
Load Macro Project: / Alt + T + M + L
Unload Macro Project: / Alt + T + M + U
New Macro Project: / Alt + T + M + W
Extension Manager: / Alt + T + R
Create GUID: / Alt + T + G
Dotfuscator Software Services: / Alt + T + F
WCF Service Configuration Editor: / Alt + T + W
External Tools: / Alt + T + E
Import and Export Settings: / Alt + T + I
Customize: / Alt + T + C
Options: / Alt + T + O

Test Menu Primary Secondary
New Test: / Alt + S + T
Load MetaData File: / Alt + S + F
Create New Test List: / Alt + S + C
Run: / Alt + S + R
Test in Current Context: Ctrl + R, T / Alt + S + R + T
All Test in Solution: Ctrl + R, A / Alt + S + R + A
Debug: / Alt + S + D
Test in Current Context: Ctrl + R + T / Alt + S + D + T
All Test in Solution: Ctrl + R + T / Alt + S + D + A
Select Active Test Settings: / Alt + S + G
Edit Test Settings: / Alt + S + S
Windows: / Alt + S + W
Test View: / Alt + S + W + T
Test List Editor: / Alt + S + W + L
Test Results: / Alt + S + W + R
Test Runs: / Alt + S + W + E

Window Menu Primary Secondary
New Window / Alt + W + N
Split / Alt + W + P
Dock / Alt + W + K
Auto Hide / Alt + W + A
Hide / Alt + W + H
Auto Hide All / Alt + W + U
New Horizontal Tab Group / Alt + W + Z
New Vertical Tab Group / Alt + W + V
Close All Documents / Alt + W + L
Reset Window Layout / Alt + W + R

Help Menu Primary Secondary
Visual Studio Documentation Ctrl + Alt + F1 / Alt + H + V
MSDN Forums / Alt + H + M
Report a Bug / Alt + H + B
Samples / Alt + H + L
Customer Feedback Options / Alt + H + F
Register Product / Alt + H + R
Check for Updates / Alt + H + K
Technical Support / Alt + H + T
Online Privacy Statement / Alt + H + O
About Microsoft Visual Studio / Alt + H + A

how to make web deployments with .net C# and VSTS 2010

visual studio 2010 introduce finally a solution for the paradigma of test / live config files. the solution is a config transformation per xsl.

Step 1:


Once you have executed this you get 2 web.config files:

- web.debug.config
- web.release.config

if you want you have also the ability to add additional config files as long as you support the naming convention: web.integration.config. The files area actually only contain the changes and are not copies of you main config files.

Step 2:
so here an example how to manage that:

<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/configuration/appSettings">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
<xsl:element name="add">
<xsl:attribute name="key">NewSetting</xsl:attribute>
<xsl:attribute name="value">New Setting Value</xsl:attribute>
</xsl:element>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>


more infos and samples can be found here.

Whats new in Visual Studio 2010 (VSTS 2010)

Visual Studio 2010 is released and a bunch of new stuff is available. This post is describes certain things i could gather on the web.

From MSDN:

C# 4.0 Language and Compiler

Dynamic Support
Visual C# 2010 provides support for late binding to dynamic types by introducing a new type, dynamic. This addition enables many new scenarios, including simplified access to COM APIs such as the Office Automation APIs, to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM). For more information, see Using Type dynamic (C# Programming Guide) and dynamic (C# Reference).

Office Programmability
Access to COM interfaces, including the Office Automation APIs, is greatly enhanced by the addition of named and optional arguments, the dynamic type, indexed properties and optional ref modifiers.

For more information, see Named and Optional Arguments (C# Programming Guide), Using Type dynamic (C# Programming Guide), How to: Use Indexed Properties in COM Interop Programming (C# Programming Guide), and How to: Access Office Interop Objects by Using Visual C# 2010 Features (C# Programming Guide).

Type Equivalence Support
You can now deploy an application that has embedded type information instead of type information that is imported from a Primary Interop Assembly (PIA). With embedded type information, your application can use types in a runtime without requiring a reference to the runtime assembly. If various versions of the runtime assembly are published, the application that contains the embedded type information can work with the various versions without having to be recompiled. For more information, see /link (C# Compiler Options). For an example, see Walkthrough: Embedding Types from Managed Assemblies (C# and Visual Basic).

Covariance and Contravariance
Covariance enables you to use a more derived type than that specified by the generic parameter, whereas contravariance enables you to use a less derived type. This allows for implicit conversion of classes that implement variant interfaces and provides more flexibility for matching method signatures with variant delegate types. Variant interfaces and delegates can be created by using the new in and out language keywords. The .NET Framework also introduces variance support for several existing generic interfaces and delegates, including the IEnumerable(Of T) interface and the Func(Of TResult) and Action(Of T) delegates. For more information, see Covariance and Contravariance (C# and Visual Basic).

New Command-Line Options
The /langversion command-line option causes the compiler to accept only syntax that is valid in the specified version of C#.

The /appconfig compiler option enables a C# application to specify the location of an assembly's application configuration file to the compiler.

Visual C# Integrated Development Environment
--------------------------------------------------------------------------------

The following sections describe enhancements to the Visual Studio integrated development environment (IDE).

Call Hierarchy
Call Hierarchy enables you to navigate through your code by displaying the following:


  • All calls to and from a selected method, property, or constructor

  • All implementations of an interface member

  • All overrides of a virtual or abstract member



This enables you to better understand how code flows and to evaluate the effects of changes to code. For more information, see Call Hierarchy.




Navigate To
You can use the Navigate To feature to search for a symbol or file in source code. You can search for keywords that are contained in a symbol by using Camel casing and underscore characters to divide the symbol into keywords.

For more information, see How to: Search for Objects, Definitions, and References (Symbols).

Highlighting References
When you click a symbol in source code, all instances of that symbol are highlighted in the document. To move to the next or previous highlighted symbol, you can use CTRL+SHIFT+DOWN ARROW or CTRL+SHIFT+UP ARROW. For more information, see How to: Use Reference Highlighting.

Generate From Usage
The Generate From Usage feature enables you to use classes and members before you define them. Without leaving your current location in code, you can generate a stub for a class, constructor, method, property, field, or enum that you want to use but have not yet defined. This minimizes interruption to your workflow.

Generate From Usage supports programming styles such as test-first development. For more information, see Generate From Usage and Walkthrough: Test-First Support with the Generate From Usage Feature.

IntelliSense Suggestion Mode
IntelliSense now provides two alternatives for IntelliSense statement completion: completion mode and suggestion mode. Suggestion mode is used when classes and members are used before they are defined. For more information, see List Members.

Live Semantic Errors
The Live Semantic Errors feature has been enhanced in Visual C# 2010. The use of wavy underlines to signal errors and warnings as you type has been extended to include constructs that are outside of method bodies, such as return types, parameter types, and default values in method declarations.

Thursday, April 22, 2010

MOSS 2007 reading from list including attachments

The following code sample display how to read from a Sharepoint 2007 list which includes also attachments. I haven't used this code for MOSS 2010!

    

private ICredentials GetCredentials()
{
return new NetworkCredential("username", "password", "domain");
}

private DataRowCollection LoadSharepointData(string viewFields, string listName)
{
WebServiceRef.Lists sp = new WebServiceRef.Lists();
sp.Url = "http://your.sharepoint.com/_vti_bin/Lists.asmx";
sp.Credentials = GetCredentials();

// this part is needed to receive the link to document attachments and all specified fields
XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
ndQueryOptions.InnerXml = "<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>";
ndViewFields.InnerXml = viewFields;
ndQuery.InnerXml = ""; // <Query />

XmlNode allLists = sp.GetListCollection();
XmlNode lists = sp.GetListItems(listName, "", ndQuery, ndViewFields, "10000", ndQueryOptions, "");

XmlNodeReader r = new XmlNodeReader(lists);
DataSet ds = new DataSet();
ds.ReadXml(r, XmlReadMode.Auto);

return ds.Tables[1].Rows;
}


WebServiceRef is a normal Web Service reference to Sharepoints List Webservice:
- http://your.sharepoint.com/_vti_bin/lists.asmx

The following code blocks contain various helper classes to extract data row by row, download attachments and saving data to a local folder.

Here we have the class to download files from Sharepoint:


public class AttchmentHandler
{
private static CookieContainer _cookieContainer;
public static CookieContainer CookieContainer
{
get
{
if (_cookieContainer == null)
{
_cookieContainer = new CookieContainer();
}
return _cookieContainer;
}
}

public class CookieAwareWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = AttchmentHandler.CookieContainer;
(request as HttpWebRequest).KeepAlive = false;
}
return request;
}
}

public string DownloadSharepointAttachment(string url, string filename, ICredentials credentials)
{
string localFolder = @"D:\\LocalFolder\\";

// ensure we do not overwrite files with the same name.
string uniqueGuid = Guid.NewGuid().ToString();
//now the code that will download the file
try
{
using (WebClient client = new CookieAwareWebClient())
{
client.Credentials = credentials;
// client.DownloadFile("http://address.com/somefile.pdf", @"c:\\temp\savedfile.pdf");
client.DownloadFile(url, localFolder + uniqueGuid + "_-_" + filename);
client.Dispose();
}
return localFolder + uniqueGuid + "_-_" + filename;
}
catch (Exception ex)
{
Console.WriteLine("DownloadSharepointAttachment: " + ex.Message);
return string.Empty;
}
}
}


To extract data from the DataRowCollection we have to Parse each row. For that i had to write 2 methods, one which retrieves the row and another one which extract the data from the column.



public void ParseAndExtractRow(System.Data.DataRow data, ICredentials credentials)
{
this.ContentTypeId = this.GetRowValue(data, "ows_ContentTypeId");
this.Title = this.GetRowValue(data, "ows_Title");
this.Date = this.GetRowValue(data, "ows_Date");

if (string.IsNullOrEmpty(this.Date))
this.Date = DateTime.Now.ToString();

DateTime.TryParse(this.Date, out this.DateTimeSorting);

this.Attribute_01 = this.GetRowValue(data, "Attribute_01");
// add here all other attributes
// ....
// ...
// ...
}

private string GetRowValue(System.Data.DataRow data, string columnName)
{
try
{
if (data[columnName] != null)
return data[columnName].ToString();
else
return string.Empty;
}
catch (Exception ex)
{
// Console.WriteLine(ex.Message);
return string.Empty;
}
}


Finally a method which uses all this code:

    private List<Data> ExtractList()
{
string listname = "SharepointListName";

string viewFields = "";
DataRowCollection rows = LoadSharepointData(viewFields, listname);
List<Data> data = new List<Data>();
int i = 0;
foreach (DataRow row in rows)
{
Data b = new Data();
try
{
b.ParseAndExtractRow("Name", row, GetCredentials());
data.Add(b);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
b = null;
}
}
return data;
}


enjoy

Sharepoint MOSS 2007 distribute announcement over several site collections

The following lines of code iterate over all site collections within a Sharepoint / MOSS 2007 Farm and it's adding an announcement to each site collection.

To use this code i had to impersonate the user to the application pool user. This is the only user which allows me to access all content databases.

// connect to sharepoint and read all site collections under "default web site"
foreach (var application in SPWebService.ContentService.WebApplications)
{
siteCollectionMax = application.Sites.Count;

this.UpdateProcess(string.Format("Connecting to: {0}", application.Name));
this.UpdateProcess(string.Format("Total Amount of #{0} site collections", siteCollectionMax));

this.UpdateProcess("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");

string currentUrl = string.Empty;
this.UpdateProcess(
"Connecting to Sharepoint this can take some seconds!"
);
System.Threading.Thread.Sleep(500);

foreach (SPSite site in application.Sites)
{
try
{
currentUrl = site.Url;
siteCollectionCounter++;

using (SPSite s = new SPSite(site.Url))
{

using (SPWeb web = s.OpenWeb())
{
SPList list = web.GetList(s.Url + "/Lists/Announcements");
if (list != null)
{
SPListItemCollection items = list.Items;
SPListItem item = items.Add();
item["Title"] = title.Trim();
item["Body"] = body.Trim();
item["Expires"] = expiries;
item.Update();
this.UpdateProcess(
string.Format("#{0} of {1} - Announcement added to 'Site Collection': {2}", siteCollectionCounter.ToString(), siteCollectionMax.ToString(), currentUrl)
);
}
else
{
string txt = string.Format("Following 'Site Collection' does not contain an Announcement List: {0}", currentUrl);
this.UpdateProcess(
txt
);
errors.Add(txt);
}
}
}
System.Threading.Thread.Sleep(250);
}
catch (Exception ex)
{
this.UpdateProcess(
string.Format("An error occured: {0}", ex.Message)
);
}
}
}


The this.UpdateProcess(...) method is a helper method which writes into a log file. You can simply replace it and write to the Console.

Wednesday, April 21, 2010

Prozess Innovation - notes

ein paar notes zu prozess innovationen....

Standard
- Schlanke und wiederholbare Prozesse
- Prozesse müssen sich internen Bedürfnissen anpassen

Effizänz durch wiederholte Anwendungen
- Mit Wiederholungen steigert sich die Effizienz
- Lernkurve ist sichtbar: Skepsis, Euphorie, Frustration, Beherschung

Payback Effekt



- Breakeven wird schneller erreicht mit effizienten Leistungssteigerungen

Sicherheit / weniger Risiko

- Standardtisiertes vorgehen
- Verlässliche Angaben - Machbarkeit / Kosten / Projektdauer
- Beherschte Prozesse reduzieren das Risiko einzelner Mitarbeiter

Transparanz
- Probleme können frühzeitig erkannt werden
- Vorgesetze können durch Transparenz schnellere Entscheide fällen
- Es kann mehr Eigenverantwortung übernommen werden

Mitarbeiterzufriedenheit
- Industriestandards motivieren Mitarbeiter
- Steigert die Bereitschaft für Veränderungen
- Ausbau der persöhnlichen Fahigkeiten
- Plan - und Steuerbare Mitarbeiterentwicklung
- Bessere Zusammenarbeit im Team
- Steigerung des Marktwertes von Mitarbeitern

Benchmarking
- Priorisierung von Massnahmen

Projekt-Masterplan (Iterationsvorgehen)


Coaching
- Tell me and I forget, teach me and I remember, involve me and I learn (Benjamin Frenkel)

Performance
- Eingespielte Verhaltensweisen bringen Sicherheit und Erfolg

Erfolg = Wissen x Verhalten2

- Nur wenn Mitarbeiter verstehen, und Prozesse vorgelebt werden nehmen Sie den Lernaufwand auf sich

Performance II

Mitarbeiter:

  • Sichere Arbeitsplätze
  • Persöhnliche Weiterbildung
  • Erreichen von Zielvorgaben
  • Interessante Tätigkeiten
  • Teamkultur
  • Annerkennung
  • Eigener Marktwert
  • Moderne Infrastruktur
Akzeptanz Stärken (Transparenz)
  • Frühzeitige und glaubwürdige Informationen von Veränderungen
  • Berücksichtung der Mitarbeiterbedürfnisse und Erwartungen
  • Kommunikation / Feedback
  • Einbezug von Mitarbeitern
  • Erfahrungsaustausch
  • Meilensteine Feiern!!!!
Templates
  • jeder Mitarbeiter muss Informationen in 5 min finden
Metriken

Prozess

  • Periodische geprüfte und auswärtungstand
  • Projektreifegrad
Produkt
  • Anzahl Defekte (pro Woche)
  • Anzahl Use Cases
  • Anzahl der Change Requests
  • Anzahl der Templates
  • Anzahl der Versionen

Tuesday, April 20, 2010

ASP.NET MVC 2: Ninja Black Belt Tips by Scott Hanselman

Having the customer on your back to deliver features on time and under budget with thight deadlines can make you feel you're being chased by ninjas on fire. Join Scott Hanselman and he'll walk through lots of tips and tricks to get the most out of the ASP.NET MVC's better productivity features as we make the most of several key features.

This session is presented by Scott Hanselman during Microsoft DevDays 2010 in The Hague in The Netherlands.

http://channel9.msdn.com/posts/matthijs/ASPNET-MVC-2-Ninja-Black-Belt-Tips-by-Scott-Hanselman/

The security validation for this page is invalid. Click Back in your Web

While i was developing certain Sharepoint MOSS 2007 maintenance stuff I received the following error:

"The security validation for this page is invalid. Click Back in your Web..."

I developed the code against MOSS API and not on the website and was a kind of irritated about it!

The solution to solve this can be one of the following ways:

Option A)
turn off the security validation over your central administration:
- Central Administration
- Application Management
- Web Application Aettings
- "turn security validation off"

Option B)
You can modify the setting also within you coding:

SPSecurity.RunWithElevatedPrivileges(new SPSecurity.CodeToRunElevated(
delegate()
{
using (SPSite oSite = new SPSite("http://your.website.com/"))
{
using (SPWeb web = oSite.OpenWeb())
{
SPWebApplication webApp = web.Site.WebApplication;
webApp.FormDigestSettings.Enabled = false;
web.AllowUnsafeUpdates = true;


web.AllowUnsafeUpdates = false;
webApp.FormDigestSettings.Enabled = true;
web.close();
}
}
}
)
);

Monday, April 19, 2010

Development often requires impersonation with Sharepoint (MOSS) 2007


public class Impersonator
{
public string CurrentUser
{
get
{
return this.username;
}
}

public string Domain
{
get
{
return this.domain;
}
}

// private members for holding domain user account credentials
private string username = String.Empty;
private string password = String.Empty;
private string domain = String.Empty;
// this will hold the security context for reverting back to the client after impersonation operations are complete
private WindowsImpersonationContext impersonationContext = null;

// disable instantiation via default constructor
private Impersonator()
{ }

public Impersonator(string username, string domain, string password)
{
// set the properties used for domain user account
this.username = username;
this.domain = domain;
this.password = password;
}

private WindowsIdentity Logon()
{
IntPtr handle = new IntPtr(0);
handle = IntPtr.Zero;

// This stuff required for impersonation
//const int LOGON32_LOGON_NETWORK = 3;
//const int LOGON32_LOGON_SERVICE = 3;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;

// attempt to authenticate domain user account
// bool logonSucceeded = LogonUser(this.username, this.domain, this.password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ref handle);
bool logonSucceeded = LogonUser(this.username, this.domain, this.password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref handle);

if (!logonSucceeded)
{
// if the logon failed, get the error code and throw an exception
int errorCode = Marshal.GetLastWin32Error();
throw new Exception("User logon failed. Error Number: " + errorCode);
}

// if logon succeeds, create a WindowsIdentity instance
WindowsIdentity winIdentity = new WindowsIdentity(handle);

// close the open handle to the authenticated account
CloseHandle(handle);

return winIdentity;
}


public void Impersonate()
{
// authenticates the domain user account and begins impersonating it
this.impersonationContext = this.Logon().Impersonate();
}


public void Undo()
{
// rever back to original security context which was store in the WindowsImpersonationContext instance
this.impersonationContext.Undo();
}

[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern bool CloseHandle(IntPtr handle);

}

Sunday, April 18, 2010

Advanced Logging by Microsoft

Monitoring and measuring media experiences is critical for understanding how users engage with content and how to more profitably deploy media. IIS Media Services’ Advanced Logging extension provides access to both real-time client and server side logs for media experiences delivered over HTTP. Advanced Logging also allows third-party analytics providers to easily access data in real-time as well as extend the set of metrics that are captured from either the client or the server.

Data Collection and Real-time Logging
Advanced Logging provides rich, flexible data collection and real-time logging capabilities. Log any of the HTTP request/response headers, IIS server variables and client-side fields to track end-user engagement. Generate logs per IIS application, create custom logging for modules, or implement hierarchical logging. Set up a central log farm to collect and log client-side metrics and create multiple logs per request, with each log containing purpose-specific data.

Custom Media Metrics
Advanced Logging generates completely customizable W3C-standard log files. Site administrators can generate real-time client and server logs and tailor logs to track as many or as few metrics as necessary across multiple log files. Filter out information relevant to a specific purpose. Advanced Logging can create multiple logs per request, with each log contains data relevant to the purpose of the log. Capture quality of service data and audience engagement in separate logs to simplify analysis.

Analytics Integration
Silverlight applications can use an upcoming Silverlight analytics control to automatically track and report data to the IIS Advanced Logging extension. The Advanced Logging module parses the data and writes it to a file on the IIS server and also exposes this data in real-time to an analytics service. The analytics service provider can take advantage of this data to generate reports for their customers in real-time.

http://www.iis.net/download/AdvancedLogging

Thursday, April 15, 2010

Sharepoint MOSS 2007: AllUsers vs. SiteUsers vs Users

According WSS SDK's definition:
*******************************

SPWeb.AllUsers – Gets the collection of user objects that represents all users who are either members of the site or who have browsed to the site as authenticated members of a domain group in the site

SPWeb.SiteUsers – Gets the collection of all users that belong to the site collection

SPWeb.Users – Gets the collection of user objects that are explicitly assigned permissions on the Web site

very confusing how microsoft decided to manage users and profile in Sharepoint 2007

Monday, April 12, 2010

Outlook Personal Folders File Format

Intellectual Property Rights Notice for Open Specifications Documentation

* Technical Documentation. Microsoft publishes Open Specifications documentation for protocols, file formats, languages, standards as well as overviews of the interaction among each of these technologies.

* Copyrights. This documentation is covered by Microsoft copyrights. Regardless of any other terms that are contained in the terms of use for the Microsoft website that hosts this documentation, you may make copies of it in order to develop implementations of the technologies described in the Open Specifications and may distribute portions of it in your implementations using these technologies or your documentation as necessary to properly document the implementation. You may also distribute in your implementation, with or without modification, any schema, IDL’s, or code samples that are included in the documentation. This permission also applies to any documents that are referenced in the Open Specifications.

* No Trade Secrets. Microsoft does not claim any trade secret rights in this documentation.

* Patents. Microsoft has patents that may cover your implementations of the technologies described in the Open Specifications. Neither this notice nor Microsoft's delivery of the documentation grants any licenses under those or any other Microsoft patents. However, a given Open Specification may be covered by Microsoft's Open Specification Promise (available here: http://www.microsoft.com/interop/osp) or the Community Promise (available here: http://www.microsoft.com/interop/cp/default.mspx). If you would prefer a written license, or if the technologies described in the Open Specifications are not covered by the Open Specifications Promise or Community Promise, as applicable, patent licenses are available by contacting iplg@microsoft.com.

* Trademarks. The names of companies and products contained in this documentation may be covered by trademarks or similar intellectual property rights. This notice does not grant any licenses under those rights.

* Fictitious Names. The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted in this documentation are fictitious. No association with any real company, organization, product, domain name, email address, logo, person, place, or event is intended or should be inferred.

Reservation of Rights. All other rights are reserved, and this notice does not grant any rights other than specifically described above, whether by implication, estoppel, or otherwise.

Tools. The Open Specifications do not require the use of Microsoft programming tools or programming environments in order for you to develop an implementation. If you have access to Microsoft programming tools and environments you are free to take advantage of them. Certain Open Specifications are intended for use in conjunction with publicly available standard specifications and network programming art, and assumes that the reader either is familiar with the aforementioned material or has immediate access to it.

http://msdn.microsoft.com/en-us/library/ff385210.aspx

.Net C#: Binary Tree

needed using's are the following onces:

In computer science, a binary tree is a tree data structure in which each node has at most two children. Typically the first node is known as the parent and the child nodes are called left and right. In type theory, a binary tree with nodes of type A is defined inductively as TA = μα. 1 + A × α × α. Binary trees are commonly used to implement binary search trees and binary heaps.

if you need more information about binary tree please check-out the following link on Wikipedia: http://en.wikipedia.org/wiki/Binary_tree


using System;
using System.Collections.Generic;

    /// <summary>
/// Binary tree
/// </summary>
/// <typeparam name="T">The type held by the nodes</typeparam>
public class BinaryTree<T> : ICollection<T>,IEnumerable<T> where T : IComparable<T>
{
#region Constructor

/// <summary>
/// Constructor
/// </summary>
public BinaryTree()
{
NumberOfNodes = 0;
}

public BinaryTree(TreeNode<T> Root)
{
this.Root = Root;
NumberOfNodes = 0;
}

#endregion

#region Properties
/// <summary>
/// The root value
/// </summary>
public TreeNode<T> Root { get; set; }

/// <summary>
/// The number of nodes in the tree
/// </summary>
protected int NumberOfNodes { get; set; }

/// <summary>
/// Is the tree empty
/// </summary>
public bool IsEmpty { get { return Root == null; } }

/// <summary>
/// Gets the minimum value of the tree
/// </summary>
public T MinValue
{
get
{
if (IsEmpty)
throw new Exception("The tree is empty");
TreeNode<T> TempNode = Root;
while (TempNode.Left != null)
TempNode = TempNode.Left;
return TempNode.Value;
}
}

/// <summary>
/// Gets the maximum value of the tree
/// </summary>
public T MaxValue
{
get
{
if (IsEmpty)
throw new Exception("The tree is empty");
TreeNode<T> TempNode = Root;
while (TempNode.Right != null)
TempNode = TempNode.Right;
return TempNode.Value;
}
}

#endregion

#region IEnumerable<T> Members

public IEnumerator<T> GetEnumerator()
{
foreach (TreeNode<T> TempNode in Traversal(Root))
{
yield return TempNode.Value;
}
}

#endregion

#region IEnumerable Members

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
foreach (TreeNode<T> TempNode in Traversal(Root))
{
yield return TempNode.Value;
}
}

#endregion

#region ICollection<T> Members

public void Add(T item)
{
if (Root == null)
{
Root = new TreeNode<T>(item);
++NumberOfNodes;
}
else
{
Insert(item);
}
}

public void Clear()
{
Root = null;
}

public bool Contains(T item)
{
if(IsEmpty)
return false;

TreeNode<T> TempNode=Root;
while (TempNode != null)
{
int ComparedValue = TempNode.Value.CompareTo(item);
if (ComparedValue == 0)
return true;
else if (ComparedValue < 0)
TempNode = TempNode.Left;
else
TempNode = TempNode.Right;
}
return false;
}

public void CopyTo(T[] array, int arrayIndex)
{
T[] TempArray = new T[NumberOfNodes];
int Counter = 0;
foreach (T Value in this)
{
TempArray[Counter] = Value;
++Counter;
}
Array.Copy(TempArray, 0, array, arrayIndex, this.NumberOfNodes);
}

public int Count
{
get { return NumberOfNodes; }
}

public bool IsReadOnly
{
get { return false; }
}

public bool Remove(T item)
{
TreeNode<T> Item = Find(item);
if (Item == null)
return false;
List<T> Values = new List<T>();
foreach (TreeNode<T> TempNode in Traversal(Item.Left))
{
Values.Add(TempNode.Value);
}
foreach (TreeNode<T> TempNode in Traversal(Item.Right))
{
Values.Add(TempNode.Value);
}
if (Item.Parent.Left == Item)
{
Item.Parent.Left = null;
}
else
{
Item.Parent.Right = null;
}
Item.Parent = null;
foreach (T Value in Values)
{
this.Add(Value);
}
return true;
}

#endregion

#region Private Functions

/// <summary>
/// Finds a specific object
/// </summary>
/// <param name="item">The item to find</param>
/// <returns>The node if it is found</returns>
protected TreeNode<T> Find(T item)
{
foreach (TreeNode<T> Item in Traversal(Root))
if (Item.Value.Equals(item))
return Item;
return null;
}

/// <summary>
/// Traverses the list
/// </summary>
/// <param name="Node">The node to start the search from</param>
/// <returns>The individual items from the tree</returns>
protected IEnumerable<TreeNode<T>> Traversal(TreeNode<T> Node)
{
if (Node.Left != null)
{
foreach (TreeNode<T> LeftNode in Traversal(Node.Left))
yield return LeftNode;
}
yield return Node;
if (Node.Right != null)
{
foreach (TreeNode<T> RightNode in Traversal(Node.Right))
yield return RightNode;
}
}

/// <summary>
/// Inserts a value
/// </summary>
/// <param name="item">item to insert</param>
protected void Insert(T item)
{
TreeNode<T> TempNode = Root;
bool Found=false;
while (!Found)
{
int ComparedValue = TempNode.Value.CompareTo(item);
if(ComparedValue<0)
{
if(TempNode.Left==null)
{
TempNode.Left=new TreeNode<T>(item,TempNode);
++NumberOfNodes;
return;
}
else
{
TempNode=TempNode.Left;
}
}
else if(ComparedValue>0)
{
if(TempNode.Right==null)
{
TempNode.Right=new TreeNode<T>(item,TempNode);
++NumberOfNodes;
return;
}
else
{
TempNode=TempNode.Right;
}
}
else
{
TempNode=TempNode.Right;
}
}
}

#endregion
}

/// <summary>
/// Node class for the Binary tree
/// </summary>
/// <typeparam name="T">The value type</typeparam>
public class TreeNode<T>
{
#region Constructors

/// <summary>
/// Constructor
/// </summary>
public TreeNode()
{
}

/// <summary>
/// Constructor
/// </summary>
/// <param name="Value">Value of the node</param>
public TreeNode(T Value)
{
this.Value = Value;
}

/// <summary>
/// Constructor
/// </summary>
/// <param name="Value">Value of the node</param>
/// <param name="Parent">Parent node</param>
public TreeNode(T Value, TreeNode<T> Parent)
{
this.Value = Value;
this.Parent = Parent;
}

/// <summary>
/// Constructor
/// </summary>
/// <param name="Value">Value of the node</param>
/// <param name="Parent">Parent node</param>
/// <param name="Left">Left node</param>
/// <param name="Right">Right node</param>
public TreeNode(T Value, TreeNode<T> Parent, TreeNode<T> Left, TreeNode<T> Right)
{
this.Value = Value;
this.Right = Right;
this.Left = Left;
this.Parent = Parent;
}

#endregion

#region Properties

/// <summary>
/// Value of the node
/// </summary>
public T Value { get; set; }

/// <summary>
/// Parent node
/// </summary>
public TreeNode<T> Parent { get; set; }

/// <summary>
/// Left node
/// </summary>
public TreeNode<T> Left { get; set; }

/// <summary>
/// Right node
/// </summary>
public TreeNode<T> Right { get; set; }

/// <summary>
/// Is this the root
/// </summary>
public bool IsRoot { get { return Parent == null; } }

/// <summary>
/// Is this a leaf
/// </summary>
public bool IsLeaf { get { return Left == null && Right == null; } }

internal bool Visited { get; set; }

#endregion

#region Public Overridden Functions

public override string ToString()
{
return Value.ToString();
}

#endregion
}

.Net C#: Simple way to receive various information about the current system (Environment)

needed usings:

using System;
using System.Management;


/// <summary>
/// Name of the machine running the app
/// </summary>
public static string MachineName
{
get { return System.Environment.MachineName; }
}

/// <summary>
/// Gets the user name that the app is running under
/// </summary>
public static string UserName
{
get { return System.Environment.UserName; }
}

/// <summary>
/// Name of the domain that the app is running under
/// </summary>
public static string DomainName
{
get { return System.Environment.UserDomainName; }
}

/// <summary>
/// Name of the OS running
/// </summary>
public static string OSName
{
get { return System.Environment.OSVersion.Platform.ToString(); }
}

/// <summary>
/// Version information about the OS running
/// </summary>
public static string OSVersion
{
get { return System.Environment.OSVersion.Version.ToString(); }
}

/// <summary>
/// The service pack running on the OS
/// </summary>
public static string OSServicePack
{
get { return System.Environment.OSVersion.ServicePack; }
}

/// <summary>
/// Full name, includes service pack, version, etc.
/// </summary>
public static string OSFullName
{
get { return System.Environment.OSVersion.VersionString; }
}

/// <summary>
/// Gets the current stack trace information
/// </summary>
public static string StackTrace
{
get { return System.Environment.StackTrace; }
}

/// <summary>
/// Returns the number of processors on the machine
/// </summary>
public static int NumberOfProcessors
{
get { return System.Environment.ProcessorCount; }
}

/// <summary>
/// The total amount of memory the GC believes is used
/// by the app in bytes
/// </summary>
public static long TotalMemoryUsed
{
get { return GC.GetTotalMemory(false); }
}

/// <summary>
/// The total amount of memory that is available in bytes
/// </summary>
public static long TotalMemory
{
get
{
ObjectQuery TempQuery = new ObjectQuery("SELECT * FROM Win32_LogicalMemoryConfiguration");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(TempQuery);
long ReturnValue = 0;
foreach (ManagementObject TempObject in Searcher.Get())
{
ReturnValue = long.Parse(TempObject["TotalPhysicalMemory"].ToString()) * 1024;
}
Searcher.Dispose();
return ReturnValue;
}
}

.Net C#: Compress / Decompress Methods

Utility Methods for data compression and data decompress.

using System.IO;
using System.IO.Compression;

public static byte[] Compress(byte[] bytes)
{
byte [] retValue;
using (MemoryStream stream = new MemoryStream())
{
using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Compress, true))
{
zipStream.Write(bytes, 0, bytes.Length);
retValue = stream.ToArray();
zipStream.Close();
stream.Close();
}
}
return retValue;
}


public static byte[] Decompress(byte[] bytes)
{
byte[] retValue;
using (MemoryStream stream = new MemoryStream())
{
using (GZipStream zipStream = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress, true))
{
byte[] buffer = new byte[4096];
int size;
while (true)
{
size = zipStream.Read(buffer, 0, buffer.Length);
if (size > 0)
stream.Write(buffer, 0, size);
else
break;
}
zipStream.Close();
retValue = stream.ToArray();
stream.Dispose();
zipStream.Dispose();
return retValue;
}
}


Friday, April 02, 2010

Sharepoint MOSS 2007 enum all site collections

unfortunate I don't remember from where I have takeover the following code - if you find it let me know - i would like to update a link to your site.

copy and paste following code into a enum.aspx and than save the file on your sharepoint 2007 / MOSS 2007 under the following path:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\enum.aspx

once you're done with that you can invoke it under the following url: http://your.sharepoint.com/_vti_bin/Enum.aspx

NOTE: to use this you have to call it with a user which have enough privileges for all site collections - best would be to call it with the app-pool user.

<%@ Page Language="C#" ContentType="application/xml"%> 
<%@ Import Namespace="Microsoft.SharePoint.Administration" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="System.Xml" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<script runat="server">
protected override void OnLoad(EventArgs e){
// Get references to the farm and farm WebService object
// the SPWebService object contains the SPWebApplications
SPFarm thisFarm = SPFarm.Local;
SPWebService service = thisFarm.Services.GetValue<SPWebService>("");

// Prepare the XML Writer
XmlTextWriter xmlWriter = new XmlTextWriter(Response.OutputStream,
Encoding.UTF8);

//Start the XML Document
xmlWriter.WriteStartDocument();

//Create a Web Applications Element
xmlWriter.WriteStartElement("webapplications");

//**********************************************
// NOTE: From here on everything is executed in
// "try catch" blocks. This is done to
// facilitate troubelshooting in case any
// errors surface. The error is caught and
// rendered in an xml "error" element.
// since the pages MIME type has been
// changed to XML, allowing the error
// to surface would render the xml document
// unreadable in IE.
//***********************************************
try
{
//Iterate through each web application
foreach (SPWebApplication webApp in service.WebApplications)
{
//Create an XML Element for each web application
//and include the name in the "name" attribute
xmlWriter.WriteStartElement("webapplication");
xmlWriter.WriteAttributeString("name", webApp.DisplayName);

try
{

//Create a sites element for the site collections
xmlWriter.WriteStartElement("sites");

//Iterate through each site collection
foreach (SPSite siteCollection in webApp.Sites)
{

//Create an XML Element for each site collection
//and include the url in the "url" attribute
xmlWriter.WriteStartElement("site");
xmlWriter.WriteAttributeString("url", siteCollection.Url);

//call the recursive method to get all the sites(webs)
GetWebs(siteCollection.AllWebs, xmlWriter);

//close the site element
xmlWriter.WriteEndElement();

}
//close the site collection element
xmlWriter.WriteEndElement();


}
catch (Exception siteError)
{
//if an error occurs write the error message to
//an error element
xmlWriter.WriteElementString("error", siteError.Message);
}

//close the web application element
xmlWriter.WriteEndElement();

}
}
catch (Exception webAppError)
{
//if an error occurs write the error message to
//an error element
xmlWriter.WriteElementString("error", webAppError.Message);
}

// close the web applications element and document
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}

//*************************************************
// This method is used recursively to display all
// webs in a site collection. The Web Collection
// from the site collection is passed in along with
// the XML writer to continue writing the XML Document
// where the calling method left off
public void GetWebs(SPWebCollection allWebs, XmlTextWriter xmlWriter)
{
//create a webs element to contain all sites(webs)
xmlWriter.WriteStartElement("webs");
try
{

//iterate through each site(web)
foreach (SPWeb web in allWebs)
{
if (web.Permissions.DoesUserHavePermissions(SPRights.FullMask));
{
//Create an XML Element for each site(web)
//and include attributes for the url, title,
//and template information
xmlWriter.WriteStartElement("web");
xmlWriter.WriteAttributeString("url",web.Url);
xmlWriter.WriteAttributeString("title", web.Title);
xmlWriter.WriteAttributeString("WebTemplateID", web.WebTemplateId.ToString());
xmlWriter.WriteAttributeString("WebTemplateName", web.WebTemplate);


//close the site(web) element
xmlWriter.WriteEndElement();
}
}

}

catch (Exception webError)
{
//if an error occurs write the error message to
//an error element
xmlWriter.WriteElementString("error", webError.Message);
}

//close the webs element
xmlWriter.WriteEndElement();
}
</script>

format my source code for blogger.com

Format My Source Code for Blogging

A javascript web application application that will format source code text into html for inserting into your blog.


http://formatmysourcecode.blogspot.com/

Extract Data from MOSS 2007 (Sharepoint)

The following classes shows how easy it can be to extract data from MOSS 2007 (Sharepoint) and fill the values into properties. The class also checks if there are attachments if so, then it will download attached files to a local path.

the sample below assumes that you have created a Web References to your sharepoint list web service: https://your.sharepoint.com/_vti_bin/lists.asmx

please notice that i have copy and pasted methods from various classes into one class without running it, so don't be surprised if you get any compilation error.

the main aim behind it is to extract data from a bug tracker list and import it over the tfs api 2010 into team foundation server.

public class Sharepoint2007Wrapper
{
public string Title { get; set; }
public string Date { get; set; }
public string CreatedBy { get; set; }

[System.Diagnostics.DebuggerStepThrough]
private ICredentials GetCredentials()
{
return new NetworkCredential("username", "password", "domain");
}

private DataRowCollection LoadSharepointData(string viewFields, string listName)
{
sharepoint.Lists sp = new MigrationToolExportImport.sharepoint.Lists();
sp.Url = "http://url.ToYourSiteCollection.com/_vti_bin/Lists.asmx";
sp.Credentials = this.GetCredentials();

// this part is needed to receive the link to document attachments and all specified fields
XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

// receive links to the attachments
ndQueryOptions.InnerXml = "<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>";
ndViewFields.InnerXml = viewFields;
ndQuery.InnerXml = ""; // <Query />

XmlNode allLists = sp.GetListCollection();
// ensure the number is big enough because without this value sharepoint returns configured amount which is 100 per view!
// listsgetlistitems method lists only 100
XmlNode lists = sp.GetListItems(listName, "", ndQuery, ndViewFields, "10000", ndQueryOptions, "");

XmlNodeReader r = new XmlNodeReader(lists);
DataSet ds = new DataSet();
ds.ReadXml(r, XmlReadMode.Auto);

return ds.Tables[1].Rows;
}

public void Extract(string listname)
{
if(string.IsNullOrEmpty(listname))
listname = "Your Sharepoint 2007 List Name";
// if nothing is provided then it returns all rows otherwise
// uese fieldRef tags to retrieve only requested columns
// <FieldRef Name="LinkTitle" /> <FieldRef Name="Title" />
string viewFields = "";
DataRowCollection rows = LoadSharepointData(viewFields, listname);

int i = 0;
foreach (DataRow row in rows)
{
try
{
if ((++i % 10) == 0)
Console.Write('.');
this.ParseAndExtractRow(row, GetCredentials());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

private List<string> Attachments { get; set; }

private void ParseAndExtractRow(System.Data.DataRow data, ICredentials credentials)
{
// this helps to identify which text we need to retrieve the column value
this.PrintColNames(data);

this.Title = this.GetRowValue(data, "ows_Title");
this.Date = this.GetRowValue(data, "ows_Date");
this.CreatedBy = this.GetRowValue(data, "ows_CreatedBy");
}

private void DownloadAttachments(string urls, ICredentials credentials)
{
this.Attachments = new List<string>();
string[] fileUrls = urls.Split('#');
if (fileUrls != null && fileUrls.Length > 0)
{
foreach (string file in fileUrls)
{
string uri = file.Replace(";", "");
if (!string.IsNullOrEmpty(uri) && uri.Length > 1)
this.Attachments.Add(uri);
}
}

List<string> filepaths = new List<string>();

if (this.Attachments.Count > 0)
{
foreach (string url in this.Attachments)
{
try
{
string file = System.IO.Path.GetFileName(url);
string filepath = new Attchments().DownloadSharepointAttachment(url, file, credentials);
if (System.IO.File.Exists(filepath))
filepaths.Add(filepath);
else
Console.WriteLine("File does not exists!!");
}
catch (Exception ex)
{
Console.WriteLine("Error upon file download: " + ex.Message);
}
}
this.Attachments.Clear();
this.Attachments.AddRange(filepaths);
}
}

private void PrintColNames(System.Data.DataRow data)
{
for (int i = 0; i < data.Table.Columns.Count; ++i)
{
Console.WriteLine(data.Table.Columns[i].ToString());
}
}

private string GetRowValue(System.Data.DataRow data, string columnName)
{
try
{
if (data[columnName] != null)
return data[columnName].ToString();
else
return string.Empty;
}
catch (Exception ex)
{
return string.Empty;
}
}

private class Attchments
{
private static CookieContainer _cookieContainer;
public static CookieContainer CookieContainer
{
get
{
if (_cookieContainer == null)
{
_cookieContainer = new CookieContainer();
}
return _cookieContainer;
}
}

public class CookieAwareWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = AttchmentHandler.CookieContainer;
(request as HttpWebRequest).KeepAlive = false;
}
return request;
}
}

public string DownloadSharepointAttachment(string url, string filename, ICredentials credentials)
{
string localFolder = @"Z:\\YourRequestedLocationOnYourHardDrive\\";
// ensure we do not overwrite files with the same name.
string uniqueGuid = Guid.NewGuid().ToString();

//now the code that will download the file
try
{
using (WebClient client = new CookieAwareWebClient())
{
client.Credentials = credentials;
// client.DownloadFile("http://address.com/abc.pdf", @"c:\\temp\abc_local.pdf");
client.DownloadFile(url, localFolder + uniqueGuid + "_-_" + filename);
client.Dispose();
}
return localFolder + uniqueGuid + "_-_" + filename;
}
catch (Exception ex)
{
Console.WriteLine("Download Sharepoint Attachment Error: " + ex.Message);
return string.Empty;
}
}
}
}

TFS API: Creating recursive TFS areas

The following code has been founded at Shai Raiten's blog:

TFS API Part 9: Get Area/Iteration Programmatically

TFS API Part 11: Get Area/Iteration Security Settings Using IAuthorizationService

He created a fantastic serie how to work with the API!!!
Thanks Shai



Simple Call:
NodeInfo nodeInfo = this.GetAddNode("\\new area name1", "YourProject", StructureType.Area);
NodeInfo nodeInfo = this.GetAddNode("\\new area name2", "YourProject", StructureType.Area);

Recursive Calls:
NodeInfo nodeInfo = this.GetAddNode("\\new area name\\area 1", "YourProject", StructureType.Area);
NodeInfo nodeInfo = this.GetAddNode("\\new area name\\area 2", "YourProject", StructureType.Area);





public enum StructureType
{
Iteration = 0,
Area = 1
}

private NodeInfo GetAddNode(string ElementPath, string projectName, StructureType nodeType)
{
NodeInfo retVal;
string rootNodePath = "\\" + projectName + "\\" + nodeType.ToString();

//Check if this path already exsist
string newPath = rootNodePath + ElementPath;
try
{
retVal = css.GetNodeFromPath(newPath);
if (retVal != null)
{
// return existing node
return retVal;
}
}
catch (Exception ex)
{
if (ex.Message.Contains("The following node does not exist"))
{
//just means that this path is not exist and we can continue.
}
else
{
throw ex;
}
}

int BackSlashIndex = ElementPath.LastIndexOf("\\");
string Newpathname = ElementPath.Substring(BackSlashIndex + 1);
string NewPath = (BackSlashIndex == 0 ? string.Empty : ElementPath.Substring(0, BackSlashIndex));
string PathRoot = rootNodePath + NewPath;
NodeInfo previousPath = null;
try
{
previousPath = css.GetNodeFromPath(PathRoot);
}
catch (Exception ex)
{
// had to update the string from shai's original code
if (ex.Message.Contains("TF200014: The following node does not exist:"))
{
//just means that this path is not exist and we can continue.
previousPath = null;
}
else
{
throw ex;
}
}
if (previousPath == null)
{
//call this method to create the parent paths.
previousPath = GetAddNode(NewPath, projectName, nodeType);
}

string newPathUri = css.CreateNode(Newpathname, previousPath.Uri);
NodeInfo ni = css.GetNode(newPathUri);

Console.WriteLine("Creating Area: " + ni.Path.ToString());
return ni;
}

TFS API: Get Team Project

The following method retrieves the TeamProject over TFS API:

    private TeamProject GetTeamProject()
{
VersionControlServer versionControl = (VersionControlServer)server.GetService(typeof(VersionControlServer));
TeamProject teamProject = versionControl.GetTeamProject("ProjectName");
return teamProject;
}

TFS API: List all TFS Users

The following code lists all TFS users over the API.

[System.Diagnostics.DebuggerStepThrough]
private ICredentials GetCredentials()
{
return new NetworkCredential("user", "pwd", "domain");
}


    public TfsWrapper()
{
server = new TeamFoundationServer("https://your.tfs.com/tfs/store", GetCredentials());
server.Authenticate();
css = (ICommonStructureService)server.GetService(typeof(ICommonStructureService));
gss = (IGroupSecurityService)server.GetService(typeof(IGroupSecurityService));
tfsIdentities = new List<Identity>();
}


public void ReadTfsUsers()
{
TeamProject tp = this.GetTeamProject();
Identity[] appGroups = gss.ListApplicationGroups(tp.ArtifactUri.AbsoluteUri);

foreach (Identity group in appGroups)
{
Identity[] groupMembers = gss.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Expanded);
foreach (Identity member in groupMembers)
{
Console.WriteLine(member.DisplayName);
if (member.Members != null)
{
foreach (string memberSid in member.Members)
{
Identity memberInfo = gss.ReadIdentity(SearchFactor.Sid, memberSid, QueryMembership.None);

if (memberInfo.Type == IdentityType.WindowsUser)
{
if (!this.tfsIdentities.Contains(memberInfo))
this.tfsIdentities.Add(memberInfo);

// Console.WriteLine(" {0}", memberInfo.DisplayName);
//Console.WriteLine("AccountName :" + memberInfo.AccountName);
//Console.WriteLine("Deleted :" + memberInfo.Deleted);
//Console.WriteLine("Description :" + memberInfo.Description);
//Console.WriteLine("DisplayName :" + memberInfo.DisplayName);
//Console.WriteLine("DistinguishedName :" + memberInfo.DistinguishedName);
//Console.WriteLine("Domain :" + memberInfo.Domain);
//Console.WriteLine("MailAddress :" + memberInfo.MailAddress);
//Console.WriteLine("Sid :" + memberInfo.Sid);
//Console.WriteLine("Type :" + memberInfo.Type.ToString());
//Console.WriteLine("*********************************");
}
}
}
}
}
}

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge