Operating system patch
i want to get list of install patch of my operation system with version details in dot net,
i am trying using wmi
string Software = null;
string SoftwareKey = #"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
Software += "\r\nWINDOWS X64 Software\r\n\r\n\r\n ";
using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(SoftwareKey))
{
if (rk == null)
{
return Software;
}
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
try
{
if (!(sk.GetValue("DisplayName") == null))
{
if (sk.GetValue("InstallLocation") == null)
Software += sk.GetValue("DisplayName") + " - Install path not known \r\n ";
else
Software += sk.GetValue("DisplayName") + " - " + sk.GetValue("InstallLocation") + "\r\n ";
}
}
catch (Exception ex)
{
}
}
}
}
return Software;
I have written the following code in a Timer's Tick event to checking if the file modification time of an image has changed then copy that image and save it to another directory. Sometimes GetLastWrittenTime() doesn't change even though the file has already been overwritten.
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp"))
{
DateTime filetime=File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
if (!filetime.Equals(lastmMdifiedTime))
{
if (txtkapan.Text != "" && txtlot.Text != "")
{
if (reg.Read("AUTOPATH") == null || reg.Read("AUTOPATH").Equals(""))
{
Directory.CreateDirectory("D:\\" + txtkapan.Text + "\\" + txtlot.Text);
}
else
{
Directory.CreateDirectory(reg.Read("AUTOPATH")+"\\" + txtkapan.Text + "\\" + txtlot.Text);
}
string image_name;
if (txtlot.Text.Length <= 3 || txtparty.Text.Length <= 3 || txtkapan.Text.Length <= 3)
{
image_name = txtparty.Text.Substring(0, txtparty.Text.Length) + "_" + txtkapan.Text.Substring(0, txtkapan.Text.Length) + "_" + txtlot.Text.Substring(0, txtlot.Text.Length) + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH_mm") + ".jpg";
}
else
{
image_name = txtparty.Text.Substring(0, 3) + "_" + txtkapan.Text.Substring(0, 3) + "_" + txtlot.Text.Substring(0, 3) + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH_mm") + ".jpg";
}
try
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
img.Save(reg.Read("AUTOPATH") + "\\" + txtkapan.Text + "\\" + txtlot.Text + "\\" + image_name, ImageFormat.Jpeg);
lastmMdifiedTime = File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
}
catch (Exception ex)
{
MessageBox.Show("Exception:" + ex.ToString());
}
}
else { }
}
}
Please tell me what is wrong in my code.
when i run this code after 30 second give me error 'time out expire' . error comming exactly after fill dataset . by the way i add connection time out = 0 to my app config but still the problem is the same . so how i can set connection time out for this dataset
public void ExportInvoicesAccount()
{
var q = from h in hmsdb.TransHdrs
where h.Account.AccountsContracts.First().AccountsMain.ID == _mainaccid
&& h.PayMethod == "R"
&& h.CancelDate == null
&& h.TransDate >= _fromdate
&& h.TransDate <= _todate
group h by new
{
amID = h.Account.AccountsContracts.First().AccountsMain.ID,
amcode = h.Account.AccountsContracts.First().AccountsMain.Code,
amName = h.Account.AccountsContracts.First().AccountsMain.EngName,
acccode = h.AccountCode,
accid = h.AccountID,
accname = h.Account.EngName
} into qg
select new
{
amID = qg.Key.amID,
amCode = qg.Key.amcode,
amName = qg.Key.amName,
acccode = qg.Key.acccode,
accid = qg.Key.accid,
accname = qg.Key.accname
};
if (_facccode != "" && _taccccode == "")
{
q = q.Where(f => f.acccode == _facccode);
}
if (_facccode != "" && _taccccode != "")
{
q = q.Where(f => Convert.ToInt32(f.acccode) >= Convert.ToInt32(_facccode) && Convert.ToInt32(f.acccode) <= Convert.ToInt32(_taccccode) && f.acccode != "C" && f.acccode != "10281501مكرر ");
}
foreach (var x in q)
{
try
{
ClaimDS ds = new ClaimDS();
SP_EClaims_StatmentOfAccountGeneralTableAdapter adapt = new SP_EClaims_StatmentOfAccountGeneralTableAdapter();
ds.EnforceConstraints = false;
adapt.Fill(ds.SP_EClaims_StatmentOfAccountGeneral, x.amID, x.accid, 0, _fromdate, _todate, _inout,0,0,0, 0);
if (ds.SP_EClaims_StatmentOfAccountGeneral.Rows.Count != 0)
{
InvoicesByAcc rptinv = new InvoicesByAcc();
rptinv.SetDataSource(ds);
ExportOptions expop = new ExportOptions();
DiskFileDestinationOptions dfdo = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions pdfop = new PdfRtfWordFormatOptions();
FolderPath = _path + x.amCode + " - " + x.amName + "\\";
bool exists = System.IO.Directory.Exists(FolderPath);
if (!exists)
System.IO.Directory.CreateDirectory(FolderPath);
fpath = FolderPath;
rptinv.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
rptinv.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
DiskFileDestinationOptions objDiskOpt = new DiskFileDestinationOptions();
if (_inout == "O")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-OUT" + ".pdf";
}
else if (_inout == "I")
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-IN" + ".pdf";
}
else
{
objDiskOpt.DiskFileName = FolderPath + "\\" + x.acccode + "-" + "0000" + "-0000" + "-" + "001" + "-ALL" + ".pdf";
}
rptinv.ExportOptions.DestinationOptions = objDiskOpt;
rptinv.Export();
rptinv.Dispose();
rptinv.Close();
}
GC.Collect();
ds.Dispose();
ds.Clear();
}
catch (Exception ex)
{
string logpath = FolderPath + "E_Claim_ErrorLog.txt";
// This text is added only once to the file.
if (!File.Exists(logpath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logpath))
{
//sw.WriteLine(ex.Message + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - "+ "ConsID: " + x.consid + " - " + "MRN: " + x.mrn + " )");
}
}
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(logpath))
{
sw.WriteLine(ex.Message + " SP_EClaims_StatmentOfAccountGeneral" + "ExportInvoicesAccount" + "( " + "AccountMainID: " + x.amID + " - " + "AccountID: " + x.accid + " - " + "ConsID: " + "0" + " - " + "MRN: " + "0" + " )");
}
//MessageBox.Show(ex.Message + "AccountMainID: " + x.amID + "-"+ "AccountID: " + x.accid + "ConsID: " + x.consid + "MRN: " + x.mrn );
}
}
}
I need help here.I don't know how to tell to labels from different stringBuilder to go on different .doc files.In my if() statements in need to tell to write labels from first stringBuilder and in another if() statement should write labels from another stingBuilder in another .doc file. Below is my code:
StringBuilder strBody = new StringBuilder();
StringBuilder strBody1 = new StringBuilder();
strBody.Append(#"<html " +
"xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>" +
"<head><title>Time</title>");
strBody1.Append(#"<html " +
"xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>" +
"<head><title>Time</title>");
strBody.Append("<body lang=EN-US style='tab-interval:.5in'>" +
"<p style='color:red; font-size:13px'>" +
Label47.Text +"<br/>" +
Label45.Text +"X "+
Label48.Text +" " +
Label54.Text +"</p>" +
"</div></body></html>").Append(strBody1.ToString());
strBody1.Append("<body lang=EN-US style='tab-interval:.5in'>" +
"<p style='color:red; font-size:13px'>" +
Label12.Text +"<br/>" +
Label11.Text +"X "+
Label13.Text +" " +
Label17.Text +"</p>" +
"</div></body></html>");
if (Session["one"] != null && Session["two"] != null && Session["three"] != null)
{
{
string path = #"c:\Backup\kitchen.doc";
string path2 = #"c:\Backup\bar.doc";
if (!File.Exists(path) && !File.Exists(path2))
{
using (StreamWriter sw = File.CreateText(path))
{
using (StreamWriter sw2 = File.CreateText(path2))
{
if (Label53.Text == "4")
{
sw.WriteLine(strBody);
}
else if (Label53.Text == "1")
{
sw2.WriteLine(strBody);
if (Label44.Text == "4")
{
sw.WriteLine(strBody1);
}
else if (Label44.Text == "1")
{
sw2.WriteLine(strBody1);
}
}
I think there is a missing closing } in your if conditions. The
else if (Label53.Text == "1")
did not have a closing }
Updated if conditions
if (Label53.Text == "4")
{
sw.WriteLine(strBody);
}
else if (Label53.Text == "1")
{
sw2.WriteLine(strBody);
}
if (Label44.Text == "4")
{
sw.WriteLine(strBody1);
}
else if (Label44.Text == "1")
{
sw2.WriteLine(strBody1);
}
So this is what I have (full add-in code):
using Microsoft.SystemCenter.VirtualMachineManager;
using Microsoft.SystemCenter.VirtualMachineManager.UIAddIns;
using Microsoft.SystemCenter.VirtualMachineManager.UIAddIns.ContextTypes;
using Microsoft.VirtualManager.Remoting;
using System;
using System.AddIn;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Forms;
namespace Microsoft.VirtualManager.UI.AddIns.BackupAddIn
{
[AddIn("Make Backup")]
public class BackupAddIn : ActionAddInBase
{
protected const string PowershellPath = "%WINDIR%\\System32\\WindowsPowershell\\v1.0\\powershell.exe";
protected const string DefaultDirectory = "C:\\ClusterStorage\\Volume2";
protected const string WildcardVMName = "{{VMName}}";
protected const string WildcardError = "{{Error}}";
protected const string BackupDirectoryBase = "{{Base}}";
protected const string BackupDirectoryName = "{{Name}}";
protected const string BackupDirectoryDate = "{{Date}}";
public enum JobState { Initialized, Success, Fail };
protected const string BackupDirectoryTemplate = BackupDirectoryBase + "\\" + BackupDirectoryName + "\\" + BackupDirectoryDate + "\\";
protected static readonly ReadOnlyCollection<string> AllowedBackupStates = new ReadOnlyCollection<string>(new string[] { "PowerOff", "Paused"/*, "Saved"*/});
public override bool CheckIfEnabledFor(IList<ContextObject> contextObjects)
{
if (contextObjects != null && contextObjects.Count > 0)
{
foreach (var host in contextObjects.OfType<HostContext>())
{
if (host.ComputerState != ComputerState.Responding)
{
return false;
}
}
return true;
}
return false;
}
public override void PerformAction(IList<ContextObject> contextObjects)
{
if (contextObjects != null)
{
// check if we have VMs selected
var VMs = contextObjects.OfType<VMContext>();
if (VMs != null && VMs.Count() > 0)
{
// check if VMs are in a good state
var badVMs = VMs.Where(vm => AllowedBackupStates.Contains(vm.Status.ToString()) == false).ToArray();
if (badVMs != null && badVMs.Length > 0)
{
MessageBox.Show("Backup not possible!\r\nThe following VMs are still running:\r\n\r\n" + string.Join(", ", badVMs.Select(vm => vm.Name)));
}
else
{
// ask for backup directory
string backupDir = Microsoft.VisualBasic.Interaction.InputBox("Enter a path on the host to export the selected virtual machine(s) to.", "Export path", DefaultDirectory);
if (string.IsNullOrEmpty(backupDir) == false)
{
if (backupDir.EndsWith("\\"))
{
backupDir = backupDir.Substring(0, backupDir.Length - 1);
}
// go
/*foreach (var vm in VMs)
{
exportVM(vm, backupDir);
}*/
// testing to export multiple vms in one invoke
exportVMs(VMs, backupDir);
}
}
}
}
}
public string getDate()
{
var date = DateTime.Now;
return date.Year.ToString()
+ (date.Month < 10 ? "0" : "") + date.Month.ToString()
+ (date.Day < 10 ? "0" : "") + date.Day.ToString()
+ "_"
+ (date.Hour < 10 ? "0" : "") + date.Hour.ToString()
+ (date.Minute < 10 ? "0" : "") + date.Minute.ToString();
}
public void ManageJob(string name, JobState state, string message = null)
{
string command;
if (state == JobState.Initialized)
{
command = string.Format("New-SCExternalJob -Name \"{0}\"", name);
}
else if (state == JobState.Success)
{
command = string.Format("Set-SCExternalJob -Job (Get-SCJob -Name \"{0}\")[0] -Complete -InfoMessage \"" + (string.IsNullOrEmpty(message) ? "Backup successfully started." : message.Replace("\"", "'")) + "\"", name);
}
else
{
command = string.Format("Set-SCExternalJob -Job (Get-SCJob -Name \"{0}\")[0] -Failed -InfoMessage \"" + (string.IsNullOrEmpty(message) ? "Backup FAILED." : message.Replace("\"", "'")) + "\"", name);
}
//MessageBox.Show(command);
PowerShellContext.ExecuteScript<Host>(
command,
(profiles, error) =>
{
if (error != null)
{
MessageBox.Show("Cannot modify job state\r\nError: " + error.Problem);
}
}
);
}
public void exportVMs(IEnumerable<VMContext> VMs, string backupDir)
{
string date = getDate();
string VMS = "";
string fullBackupDirS = BackupDirectoryTemplate.Replace(BackupDirectoryBase, backupDir).Replace(BackupDirectoryName, "_VMBackups").Replace(BackupDirectoryDate, date);
VMS = "'" + string.Join("', '", VMs.Select(vm => vm.Name).ToArray()) + "'";
string command = string.Format("Export-VM -Name {0} -Path '{1}'", VMS, fullBackupDirS);
MessageBox.Show(command);
// We need to manager jobs in another thread probably --------------------------------------------------------------!!!
string jobname = "Starting_backup_of_multiple_machines";
mkShortcuts(backupDir, date, VMs.Select(vm => vm.Name).ToArray(), VMs.First());
//! execPSScript(jobname, scvmmPsCommand(command, VMs.First()), VMs.First(), WildcardVMName + ": Backup successful.", WildcardVMName + ": Backup FAILED!\r\nError: " + WildcardError, backupDir, date, VMs.Select(vm => vm.Name).ToArray());
}
public String scvmmPsCommand(string command, VMContext vm, string appPath = PowershellPath)
{
return string.Format("Invoke-SCScriptCommand -Executable {0} -VMHost (Get-SCVMHost -ID \"{1}\") -CommandParameters \"{2}\" -RunAsynchronous -TimeoutSeconds 360000", appPath, vm.VMHostId.ToString(), command);
}
// Make a shortcut from the machines backup directory to the backup in the "_VMBackups"-folder
public void mkShortcuts(string path, string date, string[] names, VMContext vm)
{
string command = "$shell = New-Object -ComObject WScript.Shell;";
foreach (var n in names)
{
command = command + string.Format(" $shortc = $shell.CreateShortcut('{0}\\{1}\\{2}.lnk'); $shortc.TargetPath = '{0}\\_VMBackup\\{2}\\{1}'; $shortc.Save();", path, n, date);
}
string fullCommand = scvmmPsCommand(command, vm);
MessageBox.Show(fullCommand);
execPSScript("Create_ShortcutS", fullCommand, vm, "Shortcut(s) created.", "FAILED to create Shortcut(s)!");
}
public void execPSScript(string jobname, string command, VMContext vm, string successMessage, string errorMessage, string path = "", string date = "", string[] names = null)
{
ManageJob(jobname, JobState.Initialized);
PowerShellContext.ExecuteScript<Host>(
command,
(vms, error) =>
{
if (error != null)
{
ManageJob(jobname, JobState.Fail, errorMessage.Replace(WildcardVMName, vm.Name).Replace(WildcardError, error.Problem));
}
else
{
ManageJob(jobname, JobState.Success, successMessage.Replace(WildcardVMName, vm.Name));
if (string.IsNullOrEmpty(path) == false)
{
//mkShortcuts(path, date, names, vm);
}
}
}
);
}
}
}
When I run the plugin I get an error Box that says sth like: "Unknown script-error. Expression not closed - ")" missing.
+ ... andard'; .Save();
+ ~
An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordEx
ception
+ FullyQualifiedErrorId : ExpectedExpression". Weitere Informationen finden Sie im Standardfehlerprotokoll "C:\Windows\TEMP\gce_stderrord07b04547c74493caa6bdba9087df444.log".
But I can't find the error in my code since it worked when typed manually into the powershell on the host and .Save() takes no arguments. Do you have any idea?
OK, Instead of
command2 = command2 + string.Format(" ${1} = $shell.CreateShortcut(\"C:\\ClusterStorage\\Volume2\\test.lnk\"); ${1}.TargetPath = \"{0}\\_VMBackup\\{2}\\{1}\"; ${1}.Save();", backupDir, vm.Name, date);
Try
command2 = command2 + string.Format(" $shortc = $shell.CreateShortcut(\"C:\\ClusterStorage\\Volume2\\test.lnk\"); $shortc.TargetPath = \"{0}\\_VMBackup\\{2}\\{1}\"; $shortc.Save();", backupDir, vm.Name, date);
command2 = "'" + command2 + "'"
This did not work and neither did a lot of other things.
Basically, the problem is the way the command string is passed to PowerShell to execute.
PowerShell will examine the sting and attempt to enumerate all variables. This is not the desired behaviour. Tried to enclose the entire string in single quotes, however this did not help.
In the end the solution was to use the PowerShell escape character “`” to mask all variable names.
command2 = command2 + string.Format(" `$shortc = `$shell.CreateShortcut(\"C:\\ClusterStorage\\Volume2\\test.lnk\"); `$shortc.TargetPath = \"{0}\\_VMBackup\\{2}\\{1}\"; `$shortc.Save();", backupDir, vm.Name, date);