Rename a snapshot in Hyper-V WMI V2 from C# - rename

I am trying to rename a Hyper-V snapshot (checkpoint) using root\virtualization\v2. None of the standard methods like ModifySystemSettings or ModifyVirtualSystem of Msvm_VirtualSystemSnapshotService or Msvm_VirtualSystemManagementService has been helpful so far.
Powershell Rename-VMSnapshot can do the job however I am not sure it is using WMI.
Any idea?

Here is what worked for me:
//
// Rename last snapshot to desired name
//
using (ManagementBaseObject inParams = vmms.GetMethodParameters("ModifySystemSettings"))
{
ManagementObject setting = null;
ManagementObjectCollection settings = vm.GetRelated(
"Msvm_VirtualSystemSettingData",
"Msvm_MostCurrentSnapshotInBranch",
null,
null,
"Dependent",
"Antecedent",
false,
null
);
foreach (ManagementObject instance in settings)
{
// Usually only one, but loop through to the end to get latest one
if (setting != null)
{
if (string.Compare(
(string)instance["CreationTime"],
(string)setting["CreationTime"],
true) > 0
)
{
// Get latest one since there could be duplicates
setting = instance;
}
}
else
{
setting = instance;
}
}
setting["ElementName"] = snapshotName;
inParams["SystemSettings"] = setting.GetText(TextFormat.WmiDtd20);
using (ManagementBaseObject outParams = vmms.InvokeMethod("ModifySystemSettings", inParams, null))
{
// What this does is get Job managementObject and check JobState to be JobCompleted.
this.ProcessSnapshotMethodResult(outParams, "rename");
}
}

Related

How do you show multiple locations on a map with .NET MAUI?

I have been able to open the default map application and display a single location:
var location = new Location(latitude, longitude);
var options = new MapLaunchOptions { Name = locationName };
try
{
await Map.Default.OpenAsync(location, options);
}
catch (Exception ex)
{
// No map application available to open
}
Wondering if the ability to open with multiple locations pinned exists?
You will first need to load in the location data, whether that is from an embedded resource or API call. Once you have the lat/lng data pulled in (mine is in a List) you can go ahead and add them. You will need map.Layers.Add(CreatePointLayer()); to call the code below:
private MemoryLayer CreatePointLayer()
{
return new MemoryLayer
{
Name = "Points",
IsMapInfoLayer = true,
Features = GetLocsFromList(),
Style = SymbolStyles.CreatePinStyle()
};
}
private IEnumerable<IFeature> GetLocsFromList()
{
var locs = Locs; //<- Locs is the List<Locations>
return locs.Select(l => {
var feature = new PointFeature(SphericalMercator.FromLonLat(l.lng, l.lat).ToMPoint());
return feature;
});
}

Unable to access an error message corresponding to your field name -while uploading file in fuel cms in MY_Form_validation

I have written an validation rule on MY_Form_validation class under application -> library folder
as follow ..
public function doc_uploaded($field,$types)
{
$types=explode(',',$types);
$upload = $this->CI->lang->line('upload');
if(isset($_FILES[$field]) && !empty($_FILES[$field]['name']))
{
if(!function_exists('file_upload')){ $this->CI->load->helper('MY_file_helper'); }
$status = file_upload(($field),$_FILES[$field], captcha_path(),$types);
if($status >0 or strlen($status) > 2 )
{
return TRUE;
}
elseif(is_array($status))
{
$this->CI->_error_array[$field] = $status[0];
$this->CI->_error_array[$field] = $status[0];
$this->_error_array[$field]=sprintf( $upload,$this->_translate_fieldname($this->_field_data[$field]['label']));
// echo $field, print_r($this->_error_array);
// print_r($this->CI->_error_array);die();
return FALSE;
}
else
{
$this->_error_array[$field] = $status[0];
return FALSE;
}
}
else
{
return FALSE;
}
}
i am setting the validation rule from controller as follow
$this->form_validation->set_rules('resume', 'Resume', 'required|doc_uploaded[pdf,doc,docx,odt,txt,ppt,pptx]');
$_POST['resume'] ='resume';
now this one working fine except that error massage :
Unable to access an error message corresponding to your field name
Resume.(doc_uploaded)
must be an way to fix it please help . iam using 1.4
instead of
$this->_error_array[$field] = $status[0];
using
$this->CI->form_validation->set_message('doc_uploaded',$status[0]);
resolved the issue

Activated Solution on Sharepoint 2010 is not visible

I have activated a WSP file which includes a website template. This works and I can see the solution int he solution gallery. When I try to create a website, based on that template, its not showing up. But it says "Status: Activated".
Then I tried to deactivate it and activate it again manually. Out of a sudden, there is a new template showing up, which takes the name of my template appended by a "2".
So whats happening here exactly? The code to activate my solution is:
System.IO.MemoryStream input = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(rootDirectory + "\\Templates\\Project.wsp"), true);
SPDocumentLibrary solutionGallery = (SPDocumentLibrary)web.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
try
{
SPFile solutionFile = solutionGallery.RootFolder.Files.Add("Project.wsp", input);
SPUserSolution newUserSolution = web.Site.Solutions.Add(solutionFile.Item.ID);
}
catch { ... }
Ok, I found the answer myself and want to share it here. The solution is, not to provide the solution in the catalog, but also to enable the features! It works like this:
System.IO.MemoryStream input = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(rootDirectory + "\\Templates\\Project.wsp"), true);
SPDocumentLibrary solutionGallery = (SPDocumentLibrary)web.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
try
{
SPFile solutionFile = solutionGallery.RootFolder.Files.Add("Project.wsp", input);
SPUserSolution newUserSolution = web.Site.Solutions.Add(solutionFile.Item.ID);
Guid solutionId = newUserSolution.SolutionId;
SPFeatureDefinitionCollection siteFeatures = web.Site.FeatureDefinitions;
var features = from SPFeatureDefinition f
in siteFeatures
where f.SolutionId.Equals(solutionId) && f.Scope == SPFeatureScope.Site
select f;
foreach (SPFeatureDefinition feature in features)
{
try
{
web.Site.Features.Add(feature.Id, false, SPFeatureDefinitionScope.Site);
}
catch { }
}
SPWebTemplateCollection webTemplates = web.Site.RootWeb.GetAvailableWebTemplates(1033);
SPWebTemplate webTemplate = (from SPWebTemplate t
in webTemplates
where t.Title == "Projekt"
select t).FirstOrDefault();
if (webTemplate != null)
{
try
{
web.Site.RootWeb.ApplyWebTemplate(webTemplate.Name);
}
catch { }
}
}
catch { ... }

Orchard CMS- Get the current Data Migration Record version number

Given the name of a Migrations class as a string, how can I get the current version number as stored in Orchard_Framework_DataMigrationRecord?
I can see Version in IExtensionManager, but that appears to just be the module version as defined in module.txt.
OK, so I've solved this myself-
I knew that Orchard must already be executing similar code to what I require when it fires off migration methods, so I created a new migrations file, and put a breakpoint on the Create() method. When the breakpoint hit, I looked up through the call stack to find DataMigrationManager in Orchard.Data.Migration. Everything I needed was in there, and if anyone else has similar requirements, I suggest they have a look at that class as a starting point.
This is pretty much lifted straight out of that class:
string moduleName="Your.Module.Name";
var migrations = GetDataMigrations(moduleName);
// apply update methods to each migration class for the module
var current = 0;
foreach (var migration in migrations)
{
// copy the objet for the Linq query
var tempMigration = migration;
// get current version for this migration
var dataMigrationRecord = GetDataMigrationRecord(tempMigration);
if (dataMigrationRecord != null)
{
current = dataMigrationRecord.Version.Value;
}
// do we need to call Create() ?
if (current == 0)
{
// try to resolve a Create method
var createMethod = GetCreateMethod(migration);
if (createMethod != null)
{
//create method has been written, but not executed!
current = (int)createMethod.Invoke(migration, new object[0]);
}
}
}
Context.Output.WriteLine("Version: {0}", current);
A couple of methods you may need:
private DataMigrationRecord GetDataMigrationRecord(IDataMigration tempMigration)
{
return _dataMigrationRepository.Table
.Where(dm => dm.DataMigrationClass == tempMigration.GetType().FullName)
.FirstOrDefault();
}
private static MethodInfo GetCreateMethod(IDataMigration dataMigration)
{
var methodInfo = dataMigration.GetType().GetMethod("Create", BindingFlags.Public | BindingFlags.Instance);
if (methodInfo != null && methodInfo.ReturnType == typeof(int))
{
return methodInfo;
}
return null;
}
Don't forget to inject any dependencies that you may need.

Check Active directory Group membership

How do i go about iterating a group to find out if a given user is a member of a group?
I know i can use IsInRole on WindowsPrincipal object but for some reason it don't always work for me, it doesn't error out or throw exception but just return false.
i have put together following code from web, can some help me improve it in terms of reliability, it hasn't gave any wrong result in 3 weeks of testing.
Side notes: 1: I don't have access to AD username and password hence using GC. 2: Groups can be created in any domain but with in same forest. 3: Group can have users from various domains as well as groups.
thanks
KA
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
static extern int CheckTokenMembership(int TokenHandle, byte[] PSID, out bool IsMember);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
static extern bool IsValidSid(byte[] PSID);
private bool Authenticate(XmlNodeList XmlNodeGroups)
{
bool result = false;
try
{
Dictionary<string, List<string>> Groups = GetGroups(XmlNodeGroups);
//search global catalog and get SID of the group
Byte[] sid = null;
foreach (string groupName in Groups.Keys)
{
using (DirectoryEntry entry = new DirectoryEntry("GC:"))
{
IEnumerator ie = entry.Children.GetEnumerator();
ie.MoveNext();
using (DirectorySearcher ds = new DirectorySearcher((DirectoryEntry)ie.Current))
{
ds.Filter = string.Format("(&(|(sAMAccountName={0}))(objectClass=group))", groupName);
using (SearchResultCollection resColl = ds.FindAll())
{
if (resColl.Count > 0)
{
ResultPropertyCollection resultPropColl = resColl[0].Properties;
sid = (byte[])resultPropColl["objectsid"][0];
if (sid == null || !IsValidSid(sid))
{
// log message and continue to next group continue;
}
}
else
{
// log message and continue to next group continue;
}
}
bool bIsMember = false;
if (CheckTokenMembership(0, sid, out bIsMember) == 0)
{
// log message and initiate fall back....... use Legacy
result = CheckMemberOf(XmlNodeGroups, _CurrentIdentity);
break;
}
else
{
result = bIsMember ? true : false;
if (result)
{
// debug message break;
}
else
{
// debug message
}
}
}
}
}
}
catch (Exception ex)
{
// log exception message and initiate fall back....... use Legacy
result = CheckMemberOf(XmlNodeGroups, _CurrentIdentity);
}
return result;
}</code>
Are you on .NET 3.5 ? If so, check out the MSDN magazine article Managing Directory Security Principals in the .NET Framework 3.5. It shows just how much easier things have become when it comes to users and groups in AD.
As for your requirement - you could
find the group in question
enumerate all its members
find if your given user is a member in that group
and all this can be done quite easily with the help of the System.DirectoryServices.AccountManagement namespace:
// establish a context - define a domain (NetBIOS style name),
// or use the current one, when not specifying a specific domain
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the group in question
GroupPrincipal theGroup = GroupPrincipal.FindByIdentity(ctx, "nameOfGroup");
// recursively enumerate the members of the group; making the search
// recursive will also enumerate the members of any nested groups
PrincipalSearchResult<Principal> result = theGroup.GetMembers(true);
// find the user in the list of group members
UserPrincipal user = (result.FirstOrDefault(p => p.DisplayName == "Some Name") as UserPrincipal);
// if found --> user is member of this group, either directly or recursively
if(user != null)
{
// do something with the user
}
I tried to use your code snippet above for the 3.5 framework and this line my compiler says it's incorrect:
// find the user in the list of group members
UserPrincipal user = (result.FirstOrDefault(p => p.DisplayName == adUser) as UserPrincipal);
Specifically the result.FirstOfDefault, it says that's not a valid option.
Thanks!

Resources