How To Make More Functional? - c#

I'm a c# guy who has learned JavaScript recently and thinking of going down the f# path. I love the functional nature of JavaScript but have trouble bring it into my c# code. I look at the below block of code and it really feels ugly. For those that are naturally bent towards functional programming, what would be a better way to do this block in either c# (or even f#).
(or am I barking up the wrong tree looking to improve it)
/// <summary>
/// Get the current Tenant based on tenantNameOverride if present,
/// otherwise uses urlHost to figure it out
/// case independent
/// if urlHost and tenantNameOverride empty then
/// throws exception
/// if tenantNameOverride specified and not found
/// throw exception
/// if tenantNameOverride not specified and there
/// is no default tenant, then throw exception
/// </summary>
/// <param name="tenants"></param>
/// <param name="urlHost"></param>
/// <param name="tenantNameOverride"></param>
/// <returns></returns>
private static Tenant GetTenantBasedOnUrlHost(
List<Tenant> tenants, string urlHost=null,
string tenantNameOverride=null)
{
if (String.IsNullOrEmpty(urlHost) &&
String.IsNullOrEmpty(tenantNameOverride))
{
throw new ApplicationException(
"urlHost or tenantName must be specified");
}
Tenant tenant;
if (String.IsNullOrEmpty(tenantNameOverride))
{
tenant = tenants.
FirstOrDefault(a => a.DomainName.ToLower().Equals(urlHost)) ??
tenants.FirstOrDefault(a => a.Default);
if (tenant == null)
{
throw new ApplicationException
("tenantName must be specified, no default tenant found");
}
}
else
{
tenant = tenants.FirstOrDefault
(a => a.Name.ToLower() == tenantNameOverride.ToLower());
if (tenant == null)
{
throw new ApplicationException
("tenantNameOverride specified and not found");
}
}
return tenant;
}
/********************* update below *****************/
Per Jon Skeet's suggestion, I've made two methods. With the exception of the error check at the top for empty string violations which I'm not sure we can easily avoid in c#. Throwing an exception also feels a little odd on not found but for my purposes, these methods should always find a tenant and if not that is unexpected and an exception seems reasonable.
This does seem cleaner and sticks better to the design guideline of single responsibility. Maybe that is what I did not like about my solution and it had nothing to do with functional or non-functional.
/// <summary>
/// Return tenant based on URL (or return default tenant if exists)
/// </summary>
/// <param name="tenants"></param>
/// <param name="urlHost"></param>
/// <returns></returns>
private static Tenant GetTenantBasedOnUrl(
List<Tenant> tenants, string urlHost)
{
if (String.IsNullOrEmpty(urlHost))
{
throw new ApplicationException(
"urlHost must be specified");
}
var tenant = tenants.
FirstOrDefault(a => a.DomainName.ToLower().Equals(urlHost)) ??
tenants.FirstOrDefault(a => a.Default);
if (tenant == null)
{
throw new ApplicationException
("tenant not found based on URL, no default found");
}
return tenant;
}
/// <summary>
/// Get exact tenant name match and do not return default even
/// if exists.
/// </summary>
/// <param name="tenants"></param>
/// <param name="tenantNameOverride"></param>
/// <returns></returns>
private static Tenant GetTenantByName(List<Tenant> tenants,
string tenantNameOverride)
{
if (String.IsNullOrEmpty(tenantNameOverride))
{
throw new ApplicationException(
"tenantNameOverride or tenantName must be specified");
}
var tenant = tenants.FirstOrDefault
(a => a.Name.ToLower() == tenantNameOverride.ToLower());
if (tenant == null)
{
throw new ApplicationException
("No tenant Found (not checking for default)");
}
return tenant;
}
}

Here's how I would approach the problem in F#.
First, if I understand the requirements correctly, the caller of the function must supply either a domain name, or a tenant name to search for. In C#, such an exclusive rule is difficult to model, which leads to the rule that at least one must be specified, but if both are specified, one of the arguments take precedence.
While such a rule is difficult to define using C#'s type system, it's trivial to declare in F#, using a Discriminated Union:
type TenantCriterion =
| DomainName of Uri
| Name of string
This means that a criterion searching for a tenant can be either a DomainName or a Name, but never both.
In my definition of DomainName, I changed the type to System.Uri. When you're dealing with URLs, it's generally safer to use Uri values than string values.
Instead of converting string values to lower case, it's safer to compare them using StringComparison.OrdinalIgnoreCase, if that's what you want, since there are all sorts of subtle localization issues if you convert e.g. Turkish strings to lower case (that conversion is lossy).
Finally, I changed the query to return Tenant option instead of throwing exceptions. In Functional Programming, we prefer to avoid exceptions. If you want more detailed exception handling than option you can use the Either monad.
All that said, here's a possible implementation of the function to find a tenant:
let findTenant tenants = function
| DomainName u ->
let t = tenants |> List.tryFind (fun x -> x.DomainName = u)
match t with
| Some t -> Some t
| None -> tenants |> List.tryFind (fun x -> x.IsDefault)
| Name n ->
tenants
|> List.tryFind
(fun x -> n.Equals(x.Name, StringComparison.OrdinalIgnoreCase))
This function has the type Tenant list -> TenantCriterion -> Tenant option. If you want more lazy evaluation, you can replace List.tryFind with Seq.tryFind.

Related

How to determine whether a branch contains a commit with TFS WebApi client library?

Basically I'd like to find an API alternative to git branch --contains with TFS WebApi client libraries:
var commitId = "123456789abcdef";
var branchName = "branch";
var tpc = new TfsTeamProjectCollection(new Uri(""));
var git = tpc.GetClient<GitHttpClient>();
var isInBranch = git.?????(branchName, commitId);
Is there a way to accomplish it?
Or should I rather operate on a local clone with git.exe/libgit instead (the repository in question is a bit too large and, if possible, I'd much prefer to avoid cloning it)?
There is not any WebApi Client library corresponding to git branch-- contains command.
However as a workaround, you could directly run git command in your C# code.
string gitCommand = "git";
string gitAddArgument = #"add -A" ;
string gitCommitArgument = #"commit ""explanations_of_changes"" "
string gitPushArgument = #"push our_remote"
Process.Start(gitCommand, gitAddArgument );
Process.Start(gitCommand, gitCommitArgument );
Process.Start(gitCommand, gitPushArgument );
You could contain your certification, more details please refer Run git commands from a C# function
Another way is using powershell script to run the git command and call TFS API.
The best way to do it now is with GetBranchStatsBatchAsync.
The GetCommits solution is not really reliable - we had some cases where API failed to find specific commits in the range falsely declaring that a commit wasn't in the branch (we then replaced the logic with GetBranchStatsBatchAsync as it became available and had no problems since).
Old/unreliable solution
There is a way to achieve it without GetBranchStatsBatchAsync - get commit time, then check whether such commit is in the branch at that time interval, though it requires two separate calls and may have some issues with:
Committer date vs Author date - I use committer date, but didn't spend enough time trying to truly check it.
The usage is:
GitHttpClient git = ...;
var isInBranch = git.BranchContains(
project: "project",
repositoryId: "repository",
branch: "master",
commitId: "12345678910...")
The code is:
public static class GitHttpClientExt
{
/// <summary>
/// Gets a value indicating whether a branch with name <paramref name="branch"/> (like 'master', 'dev') contains the commit with specified <paramref name="commitId"/>.
/// Just like the <code>git branch --contains</code> it doesn't take possible reversions into account.
/// </summary>
public static Boolean BranchContains(this GitHttpClient git, String project, String repositoryId, String branch, String commitId)
{
var commitToFind = git.TryGetCommit(project: project, repositoryId: repositoryId, commitId: commitId);
if (commitToFind == null)
{
return false;
}
var committedDate = commitToFind.Committer.Date; // TODO: It will usually be the same as the author's, but I have failed to check what date TFS actually uses in date queries.
var criteria = new GitQueryCommitsCriteria
{
ItemVersion = new GitVersionDescriptor
{
Version = branch,
VersionType = GitVersionType.Branch
},
FromDate = DateToString(committedDate.AddSeconds(-1)), // Zero length interval seems to work, but just in case
ToDate = DateToString(committedDate.AddSeconds(1)),
};
var commitIds = git
.GetAllCommits(
project: project,
repositoryId: repositoryId,
searchCriteria: criteria)
.Select(c => c.CommitId);
return commitIds.Contains(commitId);
}
/// <summary>
/// Gets the string representation of <paramref name="dateTime"/> usable in query objects for <see cref="GitHttpClient"/>.
/// </summary>
public static String DateToString(DateTimeOffset dateTime)
{
return dateTime.ToString(CultureInfo.InvariantCulture);
}
/// <summary>Tries to retrieve git commit with specified <paramref name="commitId"/> for a project.</summary>
public static GitCommitRef TryGetCommit(this GitHttpClient git, String project, String repositoryId, String commitId)
{
return git
.GetAllCommits(
project: project,
repositoryId: repositoryId,
searchCriteria: new GitQueryCommitsCriteria
{
Ids = new List<String>
{
commitId
}
})
.SingleOrDefault();
}
/// <summary>Retrieve all(up to <see cref="Int32.MaxValue"/>) git (unless <paramref name="top"/> is set) commits for a project</summary>
public static List<GitCommitRef> GetAllCommits(
this GitHttpClient git,
String project,
String repositoryId,
GitQueryCommitsCriteria searchCriteria,
Int32? skip = null,
Int32? top = (Int32.MaxValue - 1)) // Current API somehow fails (silently!) on Int32.MaxValue;
{
return git
.GetCommitsAsync(
project: project,
repositoryId: repositoryId,
searchCriteria: searchCriteria,
skip: skip,
top: top)
.GetAwaiter()
.GetResult();
}
}
P.S.: The code currently is a sync wrapper over async methods, as it is what was unfortunately required in the current project. Rework it into a proper async version if it suits you.

How to get a list of all forks of a GitHub repo?

I would like to get a list of all forks of a GitHub repo (e.g. https://github.com/eternicode/bootstrap-datepicker), however I am unable to find out how to do it using octokit.net.
I want also get a renamed repositories, I could not just search a name of a repository.
Any hints?
CLARIFICATION: The rest api is described here https://developer.github.com/v3/repos/forks/, but how to do it with octokit.net?
You can achieve that by visiting:
https://api.github.com/repos/<Author>/<Repo>/forks
Make sure to replace Author and Repo with suitable values.
The functionality has been added to octokit.net recently:
https://github.com/octokit/octokit.net/blob/b07ce6e11a1b286dda0a65ee427bda3b8abcefb8/Octokit.Reactive/Clients/ObservableRepositoryForksClient.cs#L31
/// <summary>
/// Gets the list of forks defined for a repository
/// </summary>
/// <remarks>
/// See API documentation for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
public IObservable<Repository> GetAll(string owner, string name)
{
Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
Ensure.ArgumentNotNullOrEmptyString(name, "name");
return GetAll(owner, name, ApiOptions.None);
}
Similar functions exist for other ways to specify repository.
Please feel free to edit in the full code for this use case here.
Threads a bit old but in case someone else ends up here from google thought Id necro it.
private static IReadOnlyList<Octokit.Repository> retrieveGitHubRepos()
{
Task<IReadOnlyList<Octokit.Repository>> getRepoList = null;
string appname = System.AppDomain.CurrentDomain.FriendlyName;
Octokit.GitHubClient client = new Octokit.GitHubClient(new Octokit.ProductHeaderValue(ConnectionDetails.appName));
client.Credentials = new Octokit.Credentials(ConnectionDetails.username, ConnectionDetails.password);
Task.Run(() => getRepoList = client.Repository.GetAllForUser(ConnectionDetails.username)).Wait();
return getRepoList.Result;
}

Write to Windows Application Event Log without event source registration

Is there a way to write to this event log:
Or at least, some other Windows default log, where I don't have to register an event source?
Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.
*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.
I used this code to write directly to the event log Application:
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "Application";
eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1);
}
As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources # Windows Dev Center (I bolded the part which refers to source name):
Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.
You can using the EventLog class, as explained on How to: Write to the Application Event Log (Visual C#):
var appLog = new EventLog("Application");
appLog.Source = "MySource";
appLog.WriteEntry("Test log message");
However, you'll need to configure this source "MySource" using administrative privileges:
Use WriteEvent and WriteEntry to write events to an event log. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source.
As stated in MSDN (eg. https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog(v=vs.110).aspx ), checking an non existing source and creating a source requires admin privilege.
It is however possible to use the source "Application" without.
In my test under Windows 2012 Server r2, I however get the following log entry using "Application" source:
The description for Event ID xxxx from source Application cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
{my event entry message}
the message resource is present but the message is not found in the string/message table
I defined the following method to create the source:
private string CreateEventSource(string currentAppName)
{
string eventSource = currentAppName;
bool sourceExists;
try
{
// searching the source throws a security exception ONLY if not exists!
sourceExists = EventLog.SourceExists(eventSource);
if (!sourceExists)
{ // no exception until yet means the user as admin privilege
EventLog.CreateEventSource(eventSource, "Application");
}
}
catch (SecurityException)
{
eventSource = "Application";
}
return eventSource;
}
I am calling it with currentAppName = AppDomain.CurrentDomain.FriendlyName
It might be possible to use the EventLogPermission class instead of this try/catch but not sure we can avoid the catch.
It is also possible to create the source externally, e.g in elevated Powershell:
New-EventLog -LogName Application -Source MyApp
Then, using 'MyApp' in the method above will NOT generate exception and the EventLog can be created with that source.
This is the logger class that I use. The private Log() method has EventLog.WriteEntry() in it, which is how you actually write to the event log. I'm including all of this code here because it's handy. In addition to logging, this class will also make sure the message isn't too long to write to the event log (it will truncate the message). If the message was too long, you'd get an exception. The caller can also specify the source. If the caller doesn't, this class will get the source. Hope it helps.
By the way, you can get an ObjectDumper from the web. I didn't want to post all that here. I got mine from here: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\1033\CSharpSamples.zip\LinqSamples\ObjectDumper
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Xanico.Core.Utilities;
namespace Xanico.Core
{
/// <summary>
/// Logging operations
/// </summary>
public static class Logger
{
// Note: The actual limit is higher than this, but different Microsoft operating systems actually have
// different limits. So just use 30,000 to be safe.
private const int MaxEventLogEntryLength = 30000;
/// <summary>
/// Gets or sets the source/caller. When logging, this logger class will attempt to get the
/// name of the executing/entry assembly and use that as the source when writing to a log.
/// In some cases, this class can't get the name of the executing assembly. This only seems
/// to happen though when the caller is in a separate domain created by its caller. So,
/// unless you're in that situation, there is no reason to set this. However, if there is
/// any reason that the source isn't being correctly logged, just set it here when your
/// process starts.
/// </summary>
public static string Source { get; set; }
/// <summary>
/// Logs the message, but only if debug logging is true.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="debugLoggingEnabled">if set to <c>true</c> [debug logging enabled].</param>
/// <param name="source">The name of the app/process calling the logging method. If not provided,
/// an attempt will be made to get the name of the calling process.</param>
public static void LogDebug(string message, bool debugLoggingEnabled, string source = "")
{
if (debugLoggingEnabled == false) { return; }
Log(message, EventLogEntryType.Information, source);
}
/// <summary>
/// Logs the information.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="source">The name of the app/process calling the logging method. If not provided,
/// an attempt will be made to get the name of the calling process.</param>
public static void LogInformation(string message, string source = "")
{
Log(message, EventLogEntryType.Information, source);
}
/// <summary>
/// Logs the warning.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="source">The name of the app/process calling the logging method. If not provided,
/// an attempt will be made to get the name of the calling process.</param>
public static void LogWarning(string message, string source = "")
{
Log(message, EventLogEntryType.Warning, source);
}
/// <summary>
/// Logs the exception.
/// </summary>
/// <param name="ex">The ex.</param>
/// <param name="source">The name of the app/process calling the logging method. If not provided,
/// an attempt will be made to get the name of the calling process.</param>
public static void LogException(Exception ex, string source = "")
{
if (ex == null) { throw new ArgumentNullException("ex"); }
if (Environment.UserInteractive)
{
Console.WriteLine(ex.ToString());
}
Log(ex.ToString(), EventLogEntryType.Error, source);
}
/// <summary>
/// Recursively gets the properties and values of an object and dumps that to the log.
/// </summary>
/// <param name="theObject">The object to log</param>
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Xanico.Core.Logger.Log(System.String,System.Diagnostics.EventLogEntryType,System.String)")]
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
public static void LogObjectDump(object theObject, string objectName, string source = "")
{
const int objectDepth = 5;
string objectDump = ObjectDumper.GetObjectDump(theObject, objectDepth);
string prefix = string.Format(CultureInfo.CurrentCulture,
"{0} object dump:{1}",
objectName,
Environment.NewLine);
Log(prefix + objectDump, EventLogEntryType.Warning, source);
}
private static void Log(string message, EventLogEntryType entryType, string source)
{
// Note: I got an error that the security log was inaccessible. To get around it, I ran the app as administrator
// just once, then I could run it from within VS.
if (string.IsNullOrWhiteSpace(source))
{
source = GetSource();
}
string possiblyTruncatedMessage = EnsureLogMessageLimit(message);
EventLog.WriteEntry(source, possiblyTruncatedMessage, entryType);
// If we're running a console app, also write the message to the console window.
if (Environment.UserInteractive)
{
Console.WriteLine(message);
}
}
private static string GetSource()
{
// If the caller has explicitly set a source value, just use it.
if (!string.IsNullOrWhiteSpace(Source)) { return Source; }
try
{
var assembly = Assembly.GetEntryAssembly();
// GetEntryAssembly() can return null when called in the context of a unit test project.
// That can also happen when called from an app hosted in IIS, or even a windows service.
if (assembly == null)
{
assembly = Assembly.GetExecutingAssembly();
}
if (assembly == null)
{
// From http://stackoverflow.com/a/14165787/279516:
assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
}
if (assembly == null) { return "Unknown"; }
return assembly.GetName().Name;
}
catch
{
return "Unknown";
}
}
// Ensures that the log message entry text length does not exceed the event log viewer maximum length of 32766 characters.
private static string EnsureLogMessageLimit(string logMessage)
{
if (logMessage.Length > MaxEventLogEntryLength)
{
string truncateWarningText = string.Format(CultureInfo.CurrentCulture, "... | Log Message Truncated [ Limit: {0} ]", MaxEventLogEntryLength);
// Set the message to the max minus enough room to add the truncate warning.
logMessage = logMessage.Substring(0, MaxEventLogEntryLength - truncateWarningText.Length);
logMessage = string.Format(CultureInfo.CurrentCulture, "{0}{1}", logMessage, truncateWarningText);
}
return logMessage;
}
}
}
try
System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
appLog.Source = "This Application's Name";
appLog.WriteEntry("An entry to the Application event log.");

Shadow copy error using Alphavss

iI am trying to use the sample code provided on the site alphavss. I am trying to include the class VssBackup.cs and then use this in my program. Most likely I am missing a dll reference but I am not getting any errors on the using components. Anyone knows what the problem could be?
I am getting 3 errors:
The type or namespace name 'Snapshot' could not be found (are you missing a using directive or an assembly reference?)
Snapshot _snap;
The type or namespace name 'IVssAsync' could not be found (are you missing a using directive or an assembly reference?
using (IVssAsync async = _backup.GatherWriterMetadata())
{.......
The type or namespace name 'Snapshot' could not be found (are you missing a using directive or an assembly reference?)
_snap = new Snapshot(_backup);
Class **VssBackup.cs C# Sample Code that the site provides**
/* Copyright (c) 2008-2012 Peter Palotas
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#region Copyright Notice
/*
* AlphaVSS Sample Code
* Written by Jay Miller
*
* This code is hereby released into the public domain, This applies
* worldwide.
*/
#endregion
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Alphaleonis.Win32.Vss;
using Alphaleonis.Win32.Filesystem;
namespace VssSample
{
/// <summary>
/// This class encapsulates some simple VSS logic. Its goal is to allow
/// a user to backup a single file from a shadow copy (presumably because
/// that file is otherwise unavailable on its home volume).
/// </summary>
/// <example>
/// This code creates a shadow copy and copies a single file from
/// the new snapshot to a location on the D drive. Here we're
/// using the AlphaFS library to make a full-file copy of the file.
/// <code>
/// string source_file = #"C:\Windows\system32\config\sam";
/// string backup_root = #"D:\Backups";
/// string backup_path = Path.Combine(backup_root,
/// Path.GetFilename(source_file));
///
/// // Initialize the shadow copy subsystem.
/// using (VssBackup vss = new VssBackup())
/// {
/// vss.Setup(Path.GetPathRoot(source_file));
/// string snap_path = vss.GetSnapshotPath(source_file);
///
/// // Here we use the AlphaFS library to make the copy.
/// Alphaleonis.Win32.Filesystem.File.Copy(snap_path, backup_path);
/// }
/// </code>
/// This code creates a shadow copy and opens a stream over a file
/// on the new snapshot volume.
/// <code>
/// string source_file = #"C:\Windows\system32\config\sam";
///
/// // Initialize the shadow copy subsystem.
/// using (VssBackup vss = new VssBackup())
/// {
/// vss.Setup(Path.GetPathRoot(filename));
///
/// // We can now access the shadow copy by either retrieving a stream:
/// using (Stream s = vss.GetStream(filename))
/// {
/// Debug.Assert(s.CanRead == true);
/// Debug.Assert(s.CanWrite == false);
/// }
/// }
/// </code>
/// </example>
public class VssBackup : IDisposable
{
/// <summary>
/// Setting this flag to true will enable 'component mode', which
/// does not, in this example, do much of any substance.
/// </summary>
/// <remarks>
/// VSS has the ability to selectively disable VSS-compatible
/// components according to the specifics of the current backup. One
/// might, for example, only quiesce Outlook if only the Outlook PST
/// file is intended to be backed up. The ExamineComponents() method
/// provides a framework for this sort of mode if you're interested.
/// Otherwise, this example code quiesces all VSS-compatible components
/// before making its shadow copy.
/// </remarks>
bool ComponentMode = false;
/// <summary>A reference to the VSS context.</summary>
IVssBackupComponents _backup;
/// <summary>Some persistent context for the current snapshot.</summary>
Snapshot _snap;
/// <summary>
/// Constructs a VssBackup object and initializes some of the necessary
/// VSS structures.
/// </summary>
public VssBackup()
{
InitializeBackup();
}
/// <summary>
/// Sets up a shadow copy against the specified volume.
/// </summary>
/// <remarks>
/// This methods is separated out from the constructor because if it
/// throws, we still want the Dispose() method to be called.
/// </remarks>
/// <param name="volumeName">Name of the volume to copy.</param>
public void Setup(string volumeName)
{
Discovery(volumeName);
PreBackup();
}
/// <summary>
/// The disposal of this object involves sending completion notices
/// to the writers, removing the shadow copies from the system and
/// finally releasing the BackupComponents object. This method must
/// be called when this class is no longer used.
/// </summary>
public void Dispose()
{
try { Complete(true); } catch { }
if (_snap != null)
{
_snap.Dispose();
_snap = null;
}
if (_backup != null)
{
_backup.Dispose();
_backup = null;
}
}
/// <summary>
/// This stage initializes both the requester (this program) and
/// any writers on the system in preparation for a backup and sets
/// up a communcation channel between the two.
/// </summary>
void InitializeBackup()
{
// Here we are retrieving an OS-dependent object that encapsulates
// all of the VSS functionality. The OS indepdence that this single
// factory method provides is one of AlphaVSS's major strengths!
IVssImplementation vss = VssUtils.LoadImplementation();
// Now we create a BackupComponents object to manage the backup.
// This object will have a one-to-one relationship with its backup
// and must be cleaned up when the backup finishes (ie. it cannot
// be reused).
//
// Note that this object is a member of our class, as it needs to
// stick around for the full backup.
_backup = vss.CreateVssBackupComponents();
// Now we must initialize the components. We can either start a
// fresh backup by passing null here, or we could resume a previous
// backup operation through an earlier use of the SaveXML method.
_backup.InitializeForBackup(null);
// At this point, we're supposed to establish communication with
// the writers on the system. It is possible before this step to
// enable or disable specific writers via the BackupComponents'
// Enable* and Disable* methods.
//
// Note the 'using' construct here to dispose of the asynchronous
// comm link once we no longer need it.
using (IVssAsync async = _backup.GatherWriterMetadata())
{
// Because allowing writers to prepare their metadata can take
// a while, we are given a VssAsync object that gives us some
// status on the background operation. In this case, we just
// wait for it to finish.
async.Wait();
}
}
/// <summary>
/// This stage involes the requester (us, again) processing the
/// information it received from writers on the system to find out
/// which volumes - if any - must be shadow copied to perform a full
/// backup.
/// </summary>
void Discovery(string fullPath)
{
if (ComponentMode)
// In component mode, we would need to enumerate through each
// component and decide whether it should be added to our
// backup document.
ExamineComponents(fullPath);
else
// Once we are finished with the writer metadata, we can dispose
// of it. If we were in component mode, we would want to keep it
// around so that we could notify the writers of our success or
// failure when we finish the backup.
_backup.FreeWriterMetadata();
// Now we use our helper class to add the appropriate volume to the
// shadow copy set.
_snap = new Snapshot(_backup);
_snap.AddVolume(Path.GetPathRoot(fullPath));
}
/// <summary>
/// This method is optional in this implementation, and in fact does
/// nothing of substance. It does demonstrate how one might parse
/// through the various writers on the system and add them to the
/// backup document if necessary.
/// </summary>
/// <param name="fullPath">The full path of the file to back up.</param>
void ExamineComponents(string fullPath)
{
// At this point it is the requester's duty to examine what the
// writers have prepared for us. The WriterMetadata property
// (in place of the C API's 'GetWriterMetadata' function) collects
// metadata from each writer behind a list interface.
IList<IVssExamineWriterMetadata> writer_mds = _backup.WriterMetadata;
// If you receive a "bad state" error when enumerating, you might
// have a registry inconsistency from a program that improperly
// uninstalled itself. If your event log is showing an error like,
// "ContentIndexingService called routine RegQueryValueExW which
// failed," you'll want to read Microsoft's KB article #907574.
foreach (IVssExamineWriterMetadata metadata in writer_mds)
{
// We can see the name of the writer, if we like.
Trace.WriteLine("Examining metadata for " + metadata.WriterName);
// The important bit of the writers' metadata is the list of
// components each writer is broken into. These components are
// responsible for some number of files, so going through this
// data allows us to construct an initial list of files for our
// shadow copies.
foreach (IVssWMComponent cmp in metadata.Components)
{
// Print out some info for each component.
Trace.WriteLine(" Component: " + cmp.ComponentName);
Trace.WriteLine(" Component info: " + cmp.Caption);
// If a component is available for backup, it's then up to us to
// decide whether it is relevant to the current backup. To do
// this, we may examine the files each component manages.
foreach (VssWMFileDescription file in cmp.Files)
{
// The idea here is to find out whether these files are
// relevant to whatever purpose your application holds. If
// they are, you should a) add this component to your backup
// set so VSS involves it in the shadow copy operation, and
// b) record the files' volume names so you know later which
// volumes need to be shadow copied.
// I'm not worried about that stuff for this example, though,
// so instead I'm printing out the stuff you might need to
// examine if you have requirements of that sort.
Trace.WriteLine(" Path: " + file.Path);
Trace.WriteLine(" Spec: " + file.FileSpecification);
// Here we might insert some logic to:
//
// 1. Check whether the AlternateLocation property is valid.
// 2. Expand environment vairables in either Path.or
// AlternateLocation, as appropriate.
// 3. Considering the FileSpecification and the IsRecursive
// properties, decide whether this component manages
// the file(s) you wish to backup (in this case, the
// fullPath argument).
//
// If this component is relevant, add it with AddComponent().
// (The FileToPathSpecification method below might help with
// some of these steps.)
}
}
}
}
/// <summary>
/// This phase of the backup is focused around creating the shadow copy.
/// We will notify writers of the impending snapshot, after which they
/// have a short period of time to get their on-disk data in order and
/// then quiesce writing.
/// </summary>
void PreBackup()
{
Debug.Assert(_snap != null);
// This next bit is a way to tell writers just what sort of backup
// they should be preparing for. The important parts for us now
// are the first and third arguments: we want to do a full,
// backup and, depending on whether we are in component mode, either
// a full-volume backup or a backup that only requires specific
// components.
_backup.SetBackupState(ComponentMode,
true, VssBackupType.Full, false);
// From here we just need to send messages to each writer that our
// snapshot is imminent,
using (IVssAsync async = _backup.PrepareForBackup())
{
// As before, the 'using' statement automatically disposes of
// our comm link. Also as before, we simply block while the
// writers to complete their background preparations.
async.Wait();
}
// It's now time to create the snapshot. Each writer will have to
// freeze its I/O to the selected volumes for up to 10 seconds
// while this process takes place.
_snap.Copy();
}
/// <summary>
/// This simple method uses a bit of string manipulation to turn a
/// full, local path into its corresponding snapshot path. This
/// method may help users perform full file copies from the snapsnot.
/// </summary>
/// <remarks>
/// Note that the System.IO methods are not able to access files on
/// the snapshot. Instead, you will need to use the AlphaFS library
/// as shown in the example.
/// </remarks>
/// <example>
/// This code creates a shadow copy and copies a single file from
/// the new snapshot to a location on the D drive. Here we're
/// using the AlphaFS library to make a full-file copy of the file.
/// <code>
/// string source_file = #"C:\Windows\system32\config\sam";
/// string backup_root = #"D:\Backups";
/// string backup_path = Path.Combine(backup_root,
/// Path.GetFilename(source_file));
///
/// // Initialize the shadow copy subsystem.
/// using (VssBackup vss = new VssBackup())
/// {
/// vss.Setup(Path.GetPathRoot(source_file));
/// string snap_path = vss.GetSnapshotPath(source_file);
///
/// // Here we use the AlphaFS library to make the copy.
/// Alphaleonis.Win32.Filesystem.File.Copy(snap_path, backup_path);
/// }
/// </code>
/// </example>
/// <seealso cref="GetStream"/>
/// <param name="localPath">The full path of the original file.</param>
/// <returns>A full path to the same file on the snapshot.</returns>
public string GetSnapshotPath(string localPath)
{
Trace.WriteLine("New volume: " + _snap.Root);
// This bit replaces the file's normal root information with root
// info from our new shadow copy.
if (Path.IsPathRooted(localPath))
{
string root = Path.GetPathRoot(localPath);
localPath = localPath.Replace(root, String.Empty);
}
string slash = Path.DirectorySeparatorChar.ToString();
if (!_snap.Root.EndsWith(slash) && !localPath.StartsWith(slash))
localPath = localPath.Insert(0, slash);
localPath = localPath.Insert(0, _snap.Root);
Trace.WriteLine("Converted path: " + localPath);
return localPath;
}
/// <summary>
/// This method opens a stream over the shadow copy of the specified
/// file.
/// </summary>
/// <example>
/// This code creates a shadow copy and opens a stream over a file
/// on the new snapshot volume.
/// <code>
/// string source_file = #"C:\Windows\system32\config\sam";
///
/// // Initialize the shadow copy subsystem.
/// using (VssBackup vss = new VssBackup())
/// {
/// vss.Setup(Path.GetPathRoot(filename));
///
/// // We can now access the shadow copy by either retrieving a stream:
/// using (Stream s = vss.GetStream(filename))
/// {
/// Debug.Assert(s.CanRead == true);
/// Debug.Assert(s.CanWrite == false);
/// }
/// }
/// </code>
/// </example>
public System.IO.Stream GetStream(string localPath)
{
// GetSnapshotPath() returns a very funky-looking path. The
// System.IO methods can't handle these sorts of paths, so instead
// we're using AlphaFS, another excellent library by Alpha Leonis.
// Note that we have no 'using System.IO' at the top of the file.
// (The Stream it returns, however, is just a System.IO stream.)
return File.OpenRead(GetSnapshotPath(localPath));
}
/// <summary>
/// The final phase of the backup involves some cleanup steps.
/// If we're in component mode, we're supposed to notify each of the
/// writers of the outcome of the backup. Once that's done, or if
/// we're not in component mode, we send the BackupComplete event to
/// all of the writers.
/// </summary>
/// <param name="succeeded">Success value for all of the writers.</param>
void Complete(bool succeeded)
{
if (ComponentMode)
{
// As before, we iterate through all of the writers on the system.
// A more efficient method might only iterate through those writers
// that were actually involved in this backup.
IList<IVssExamineWriterMetadata> writers = _backup.WriterMetadata;
foreach (IVssExamineWriterMetadata metadata in writers)
{
foreach (IVssWMComponent component in metadata.Components)
{
// The BackupSucceeded call should mirror the AddComponent
// call that was called during the discovery phase.
_backup.SetBackupSucceeded(
metadata.InstanceId, metadata.WriterId,
component.Type, component.LogicalPath,
component.ComponentName, succeeded);
}
}
// Finally, we can dispose of the writer metadata.
_backup.FreeWriterMetadata();
}
try
{
// The BackupComplete event must be sent to all of the writers.
using (IVssAsync async = _backup.BackupComplete())
async.Wait();
}
// Not sure why, but this throws a VSS_BAD_STATE on XP and W2K3.
// Per some forum posts about this, I'm just ignoring it.
catch (VssBadStateException) { }
}
/// <summary>
/// This method takes the information in a file description and
/// converts it to a full path specification - with wildcards.
/// </summary>
/// <remarks>
/// Using the wildcard-to-regex library found at
/// http://www.codeproject.com/KB/string/wildcmp.aspx on the
/// output of this method might be very helpful.
/// </remarks>
/// <param name="file">Object describing a component's file.</param>
/// <returns>
/// Returns a full path, potentially including DOS wildcards. Eg.
/// 'c:\windows\config\*'.
/// </returns>
string FileToPathSpecification(VssWMFileDescription file)
{
// Environment variables (eg. "%windir%") are common.
string path = Environment.ExpandEnvironmentVariables(file.Path);
// Use the alternate location if it's present.
if (!String.IsNullOrEmpty(file.AlternateLocation))
path = Environment.ExpandEnvironmentVariables(
file.AlternateLocation);
// Normalize wildcard usage.
string spec = file.FileSpecification.Replace("*.*", "*");
// Combine the file specification and the directory name.
return Path.Combine(path, file.FileSpecification);
}
}
}
I ran into the same issues when attempting to use that sample code. You should note that in addition to linking, and adding references to the references you need for AlphaVss, that this code also uses AlphaFS. In particular, you should link and reference AlphaFS.dll from that package.
The Snapshot class could not be found...you should bring in the Snapshot.cs file from the sample to your project.
But wait...there's more...
This was a bit frustrating til I found a few clever notes in the change log from version 1.1.
"* BREAKING CHANGE: The class VssWMFileDescription has been renamed to VssWMFileDescriptor
BREAKING CHANGE: The IVssAsync interface has been removed. Any methods previously returning
IVssAsync are now synchronous and returns void. Asynchronous versions of these
methods have been added with the standard APM naming scheme of BeginXXX, EndXXX
where the Begin method returns an IVssAsyncResult instance which implements
the standard IAsyncResult interface.
"
Replacing "VssWMFileDescription" with "VssWMFileDescriptor" will get you half the way there.
To get this code to compile and function, change the messages in the following pattern of:
using (IVssAsync async = _backup.GatherWriterMetadata())
{
// Because allowing writers to prepare their metadata can take
// a while, we are given a VssAsync object that gives us some
// status on the background operation. In this case, we just
// wait for it to finish.
async.Wait();
}
to
_backup.GatherWriterMetadata();
In short, the methods are now synchronous, so calling them differently will do the trick.
I hope this helps. I have my VssSample code working with these changes.
You've added references to all the AlphaVSS files? AlphaVSS.Common loads the correct assembly for the OS via IVssImplementation vss = VssUtils.LoadImplementation();.
The list for AlphaVSS 1.1 (add references to all of them):
AlphaVSS.Common
AlphaVSS.51.x86
AlphaVSS.52.x64
AlphaVSS.52.x86
AlphaVSS.60.x64
AlphaVSS.60.x86

Creating a class for an interface at runtime, in C#

I'm looking at taking a set of objects, let's say there's 3 objects alive at the moment, which all implement a common interface, and then wrap those objects inside a fourth object, also implementing the same interface.
The fourth object's implementations of methods and properties would simply call the relevant bits on those 3 underlying objects. I know that there will be cases here where it won't make sense to do that, but this is for a service multicast architecture so there's already a good set of limitations in place.
My question is where to start. The generation of that fourth object should be done in memory, at runtime, so I'm thinking Reflection.Emit, unfortunately I don't have enough experience with that to even know where to begin.
Do I have to construct an in-memory assembly? It sure looks that way, but I'd just like a quick pointer to where I should start.
Basically I'm looking at taking an interface, and a list of object instances all implementing that interface, and constructing a new object, also implementing that interface, which should "multicast" all method calls and property access to all the underlying objects, at least as much as possible. There will be heaps of problems with exceptions and such but I'll tackle those bits when I get to them.
This is for a service-oriented architecture, where I would like to have existing code that takes, as an example, a logger-service, to now access multiple logger services, without having to change the code that uses the services. Instead, I'd like to runtime-generate a logger-service-wrapper that internally simply calls the relevant methods on multiple underlying objects.
This is for .NET 3.5 and C#.
I'll post my own implementation here, if anyone's interested.
This is heavily influenced and copied from Marc's answer, which I accepted.
The code can be used to wrap a set of objects, all implementing a common interface, inside a new object, also implementing said interface. When methods and properties on the returned object is accessed, the corresponding methods and properties on the underlying objects are accessed in the same way.
Here there be dragons: This is for a specific usage. There's potential for odd problems with this, in particular since the code does not ensure that all underlying objects are given the exact same objects as the callee is passing (or rather, it does not prohibit one of the underlying objects from messing with the arguments), and for methods that returns a value, only the last return value will be returned. As for out/ref arguments, I haven't even tested how that works, but it probably doesn't. You have been warned.
#region Using
using System;
using System.Linq;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using LVK.Collections;
#endregion
namespace LVK.IoC
{
/// <summary>
/// This class implements a service wrapper that can wrap multiple services into a single multicast
/// service, that will in turn dispatch all method calls down into all the underlying services.
/// </summary>
/// <remarks>
/// This code is heavily influenced and copied from Marc Gravell's implementation which he
/// posted on Stack Overflow here: http://stackoverflow.com/questions/847809
/// </remarks>
public static class MulticastService
{
/// <summary>
/// Wrap the specified services in a single multicast service object.
/// </summary>
/// <typeparam name="TService">
/// The type of service to implement a multicast service for.
/// </typeparam>
/// <param name="services">
/// The underlying service objects to multicast all method calls to.
/// </param>
/// <returns>
/// The multicast service instance.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="services"/> is <c>null</c>.</para>
/// <para>- or -</para>
/// <para><paramref name="services"/> contains a <c>null</c> reference.</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para><typeparamref name="TService"/> is not an interface type.</para>
/// </exception>
public static TService Wrap<TService>(params TService[] services)
where TService: class
{
return (TService)Wrap(typeof(TService), (Object[])services);
}
/// <summary>
/// Wrap the specified services in a single multicast service object.
/// </summary>
/// <param name="serviceInterfaceType">
/// The <see cref="Type"/> object for the service interface to implement a multicast service for.
/// </param>
/// <param name="services">
/// The underlying service objects to multicast all method calls to.
/// </param>
/// <returns>
/// The multicast service instance.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="serviceInterfaceType"/> is <c>null</c>.</para>
/// <para>- or -</para>
/// <para><paramref name="services"/> is <c>null</c>.</para>
/// <para>- or -</para>
/// <para><paramref name="services"/> contains a <c>null</c> reference.</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para><typeparamref name="TService"/> is not an interface type.</para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// <para>One or more of the service objects in <paramref name="services"/> does not implement
/// the <paramref name="serviceInterfaceType"/> interface.</para>
/// </exception>
public static Object Wrap(Type serviceInterfaceType, params Object[] services)
{
#region Parameter Validation
if (Object.ReferenceEquals(null, serviceInterfaceType))
throw new ArgumentNullException("serviceInterfaceType");
if (!serviceInterfaceType.IsInterface)
throw new ArgumentException("serviceInterfaceType");
if (Object.ReferenceEquals(null, services) || services.Length == 0)
throw new ArgumentNullException("services");
foreach (var service in services)
{
if (Object.ReferenceEquals(null, service))
throw new ArgumentNullException("services");
if (!serviceInterfaceType.IsAssignableFrom(service.GetType()))
throw new InvalidOperationException("One of the specified services does not implement the specified service interface");
}
#endregion
if (services.Length == 1)
return services[0];
AssemblyName assemblyName = new AssemblyName(String.Format("tmp_{0}", serviceInterfaceType.FullName));
String moduleName = String.Format("{0}.dll", assemblyName.Name);
String ns = serviceInterfaceType.Namespace;
if (!String.IsNullOrEmpty(ns))
ns += ".";
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName,
AssemblyBuilderAccess.RunAndSave);
var module = assembly.DefineDynamicModule(moduleName, false);
var type = module.DefineType(String.Format("{0}Multicast_{1}", ns, serviceInterfaceType.Name),
TypeAttributes.Class |
TypeAttributes.AnsiClass |
TypeAttributes.Sealed |
TypeAttributes.NotPublic);
type.AddInterfaceImplementation(serviceInterfaceType);
var ar = Array.CreateInstance(serviceInterfaceType, services.Length);
for (Int32 index = 0; index < services.Length; index++)
ar.SetValue(services[index], index);
// Define _Service0..N-1 private service fields
FieldBuilder[] fields = new FieldBuilder[services.Length];
var cab = new CustomAttributeBuilder(
typeof(DebuggerBrowsableAttribute).GetConstructor(new Type[] { typeof(DebuggerBrowsableState) }),
new Object[] { DebuggerBrowsableState.Never });
for (Int32 index = 0; index < services.Length; index++)
{
fields[index] = type.DefineField(String.Format("_Service{0}", index),
serviceInterfaceType, FieldAttributes.Private);
// Ensure the field don't show up in the debugger tooltips
fields[index].SetCustomAttribute(cab);
}
// Define a simple constructor that takes all our services as arguments
var ctor = type.DefineConstructor(MethodAttributes.Public,
CallingConventions.HasThis,
Sequences.Repeat(serviceInterfaceType, services.Length).ToArray());
var generator = ctor.GetILGenerator();
// Store each service into its own fields
for (Int32 index = 0; index < services.Length; index++)
{
generator.Emit(OpCodes.Ldarg_0);
switch (index)
{
case 0:
generator.Emit(OpCodes.Ldarg_1);
break;
case 1:
generator.Emit(OpCodes.Ldarg_2);
break;
case 2:
generator.Emit(OpCodes.Ldarg_3);
break;
default:
generator.Emit(OpCodes.Ldarg, index + 1);
break;
}
generator.Emit(OpCodes.Stfld, fields[index]);
}
generator.Emit(OpCodes.Ret);
// Implement all the methods of the interface
foreach (var method in serviceInterfaceType.GetMethods())
{
var args = method.GetParameters();
var methodImpl = type.DefineMethod(method.Name,
MethodAttributes.Private | MethodAttributes.Virtual,
method.ReturnType, (from arg in args select arg.ParameterType).ToArray());
type.DefineMethodOverride(methodImpl, method);
// Generate code to simply call down into each service object
// Any return values are discarded, except the last one, which is returned
generator = methodImpl.GetILGenerator();
for (Int32 index = 0; index < services.Length; index++)
{
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldfld, fields[index]);
for (Int32 paramIndex = 0; paramIndex < args.Length; paramIndex++)
{
switch (paramIndex)
{
case 0:
generator.Emit(OpCodes.Ldarg_1);
break;
case 1:
generator.Emit(OpCodes.Ldarg_2);
break;
case 2:
generator.Emit(OpCodes.Ldarg_3);
break;
default:
generator.Emit((paramIndex < 255)
? OpCodes.Ldarg_S
: OpCodes.Ldarg,
paramIndex + 1);
break;
}
}
generator.Emit(OpCodes.Callvirt, method);
if (method.ReturnType != typeof(void) && index < services.Length - 1)
generator.Emit(OpCodes.Pop); // discard N-1 return values
}
generator.Emit(OpCodes.Ret);
}
return Activator.CreateInstance(type.CreateType(), services);
}
}
}
(I'm justifying an answer here by adding extra context/info)
Yes, at the moment Reflection.Emit is the only way to solve this.
In .NET 4.0, the Expression class has been extended to support both loops and statement blocks, so for single method usage, a compiled Expression would be a good idea. But even this won't support multi-method interfaces (just single-method delegates).
Fortunately, I've done this previously; see How can I write a generic container class that implements a given interface in C#?
Did you really need to create the assembly at runtime?
Probably you don't need it.
c# give you Action<T>, the is operator and lambda/delegates...

Categories