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.");
Related
In my application, a toast message(pop up) appears when i try to enter invalid cell phone number and i want to assert the text of that toast message.
Below is the image of my HTML.I am unable to copy paste here.
Below is the code tried but no such element error occurs.
String actual_error = driver.FindElement(By.XPath("//div[#class='toast-message']")).Text;
String expected_error = "CellphoneNumber:Please enter a valid cellphone number. :";
Assert.AreEqual(actual_error, expected_error);
Console.WriteLine("Phone Number error message validated successfully");
Kindly suggest the right way to assert the toast message.
I think you can do like this:
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using Serilog;
using System;
using System.IO;
using System.Reflection;
namespace StackOverFlow.Answer.Selenium.AssertMessageText
{
class AssertMessagePhone
{
public static IWebDriver driver;
public static WebDriverWait wait;
public static int timeOut = 30;
[Test]
[Category("ClickPartilLink")]
public void AssertMessagePhoneTest()
{
string messageError = "CellphoneNumber:Please enter a valid cellphone number. :";
Log.Information("Get instance Chrome Browser");
driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), OptionsChrome());
Console.WriteLine("Acess your url site");
driver.Navigate().GoToUrl("http://YourUrlSite/index.aspx");
// Steps until to fill and submit phone
Log.Information("Wait notificantion message error");
WaiElement(By.CssSelector(".toast-message"));
Log.Information("Check message");
Assert.True(GetText(By.CssSelector(".toast-message")).ToUpper().Contains(messageError.ToUpper()));
Log.Information("Click on message to disaper");
Click(By.CssSelector("div[class='noty_bar noty_type_success'] > div > span"));
}
/// <summary>
/// Wait elements
/// </summary>
/// <param name="locator"></param>
private void WaiElement(By locator)
{
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut));
wait.Until(condition: ExpectedConditions.PresenceOfAllElementsLocatedBy(locator));
}
/// <summary>
/// click on elements
/// </summary>
/// <param name="locator"></param>
private void Click(By locator)
{
WaiElement(locator);
driver.FindElement(locator).Click();
}
/// <summary>
/// return text from element
/// </summary>
/// <param name="locator"></param>
/// <returns></returns>
private string GetText(By locator)
{
WaiElement(locator);
return driver.FindElement(locator).Text;
}
}
}
Your verification seems fine. You need to make sure that:
- your tests are in proper order if page is opened in another one
- make sure you wait for all elements, i.e use method:
ExpectedConditions.PresenceOfAllElementsLocatedBy(/*element to test*/)
I agree with lukbl that I would create a bool to verify the element it present but I believe the issue is that your text is in a div tag and not in a span.
Try this:
String expected_error = driver.FindElement(By.XPath("//div[#class='toast-message']/text()[1]")).Text;
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.
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;
}
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
I am using a xml web service on my web app and sometimes remote server fails to respond in time. I came up with the idea of re-request if first attempt fails. To prevent loop I want to limit concurrent request at 2. I want to get an opinion if what I have done below is ok and would work as I expect it.
public class ScEngine
{
private int _attemptcount = 0;
public int attemptcount
{
get
{
return _attemptcount;
}
set
{
_attemptcount = value;
}
}
public DataSet GetStat(string q, string job)
{
try
{
//snip....
attemptcount += attemptcount;
return ds;
}
catch
{
if (attemptcount>=2)
{
return null;
}
else
{
return GetStat(q, job);
}
}
}
}
public class ScEngine
{
public DataSet GetStat(string q, string job)
{
int attemptCount;
while(attemptCount < 2)
{
try
{
attemptCount++;
var ds = ...//web service call
return ds;
}
catch {}
}
//log the error
return null;
}
}
You forgot to increment the attemptcount. Plus, if there's any error on the second run, it will not be caught (thus, becomes an unhandled exception).
I wouldn't recurse in order to retry. Also, I wouldn't catch and ignore all exceptions. I'd learn which exceptions indicate an error that should be retried, and would catch those. You will be ignoring serious errors, as your code stands.
You don't want to solve it this way. You will just put more load on the servers and cause more timeouts.
You can increase the web service timeout via httpRuntime. Web services typically return a lot of data in one call, so I find myself doing this pretty frequently. Don't forget to increase how long the client is willing to wait on the client side.
Here's a version that doesn't use recursion but achieves the same result. It also includes a delay so you can give the server time to recover if it hiccups.
/// <summary>
/// The maximum amount of attempts to use before giving up on an update, delete or create
/// </summary>
private const int MAX_ATTEMPTS = 2;
/// <summary>
/// Attempts to execute the specified delegate with the specified arguments.
/// </summary>
/// <param name="operation">The operation to attempt.</param>
/// <param name="arguments">The arguments to provide to the operation.</param>
/// <returns>The result of the operation if there are any.</returns>
public static object attemptOperation(Delegate operation, params object[] arguments)
{
//attempt the operation using the default max attempts
return attemptOperation(MAX_ATTEMPTS, operation, arguments);
}
/// <summary>
/// Use for creating a random delay between retry attempts.
/// </summary>
private static Random random = new Random();
/// <summary>
/// Attempts to execute the specified delegate with the specified arguments.
/// </summary>
/// <param name="operation">The operation to attempt.</param>
/// <param name="arguments">The arguments to provide to the operation.</param>
/// <param name="maxAttempts">The number of times to attempt the operation before giving up.</param>
/// <returns>The result of the operation if there are any.</returns>
public static object attemptOperation(int maxAttempts, Delegate operation, params object [] arguments)
{
//set our initial attempt count
int attemptCount = 1;
//set the default result
object result = null;
//we've not succeeded yet
bool success = false;
//keep trying until we get a result
while (success == false)
{
try
{
//attempt the operation and get the result
result = operation.DynamicInvoke(arguments);
//we succeeded if there wasn't an exception
success = true;
}
catch
{
//if we've got to the max attempts and still have an error, give up an rethrow it
if (attemptCount++ == maxAttempts)
{
//propogate the exception
throw;
}
else
{
//create a random delay in milliseconds
int randomDelayMilliseconds = random.Next(1000, 5000);
//sleep for the specified amount of milliseconds
System.Threading.Thread.Sleep(randomDelayMilliseconds);
}
}
}
//return the result
return result;
}