get the description from an WMI class using vbscript - windows

How can I get the description from an WMI class using vbscript?
I found this example but it's in C#:
// Gets the class description.
try
{
// Gets the property qualifiers.
ObjectGetOptions op = new ObjectGetOptions(null, System.TimeSpan.MaxValue, true);
ManagementClass mc = new ManagementClass(namespace,
classname, op);
mc.Options.UseAmendedQualifiers = true;
foreach (QualifierData dataObject in
mc.Qualifiers)
{
if(dataObject.Name.Equals("Description"))
{
classdesc =
dataObject.Value.ToString();
}
}
}
catch (ManagementException mErr)
{
if(mErr.Message.Equals("Not found "))
MessageBox.Show("WMI class or not found.");
else
MessageBox.Show(mErr.Message.ToString());
}
This image shows what I need.

Here's the VBScript equivalent of your C# code (only without error handling):
Const wbemFlagUseAmendedQualifiers = &H20000
strComputer = "."
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set oClass = oWMI.Get("Win32_LogicalDisk", wbemFlagUseAmendedQualifiers)
strDesc = oClass.Qualifiers_("Description").Value
WScript.Echo strDesc

Related

Sub Form of Visual Basic .Net isn't opened correctly

I designed a Form and it use to the sub Form
The Mainform is correctly display, but I use some action to show the sub Form and set Visible property of Mainform to false
The sub Form is displayed incorrectly
^^ Sub Form
^^ displayed
MainForm code:
Imports SearcherScreen = Osu_Offline_Searcher.My.SearcherScreen
Public Class SearcherOfOsu
Private ReadOnly SS As New SearcherScreen()
Private ReadOnly DOF As New DownloadOsuForm()
Private Sub Downloader_OnDownloadData(sender As OsuDownload.OsuDownloader, e As OsuDownload.OsuDownloader.DownloadDataEventArgs) Handles Downloader.DownloadData
If DOF.Created Then
DOF.ChangeProgressBar(e.Present)
Else
DOF.Icon = New Icon("osu!.ico")
DOF.Show()
Visible = False
End If
End Sub
Private Sub DetectButton_Click(sender As Object, e As EventArgs) Handles DetectButton.Click
Dim Detecter As New OsuDetect.DetectClass()
Dim UserDirectoryName = Detecter.DetectUserDirectory()
If UserDirectoryName = "No User" Then
MsgBox("I can't find any User.")
Else
Dim OsuDirectoryName = Detecter.DetectOsuDirectory(UserDirectoryName)
If OsuDirectoryName = "No Osu" Then
MsgBox("You don't download the Osu in defalut directory.")
Dim Result = MsgBox("Download Osu now?", MsgBoxStyle.YesNo, "Download Osu")
If Result = MsgBoxResult.Yes Then
OsuDirectoryPath.Text = Downloader.DownloadOsu(UserDirectoryName)
Visible = True
DOF.Close()
End If
Else
OsuDirectoryPath.Text = OsuDirectoryName
End If
End If
End Sub
Friend WithEvents Downloader As New OsuDownload.OsuDownloader()
End Class
Sub Form:
Public Class DownloadOsuForm
Sub ChangeProgressBar(Value As Integer)
OsuDownloadProgressBar.Value = Value
OsuDownloadLabel.Text = "Osu Downloading..."
End Sub
End Class
This the code of forms
and after here is the designer code
Sub Designer Code:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class DownloadOsuForm
Inherits System.Windows.Forms.Form
'Form 覆寫 Dispose 以清除元件清單。
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'為 Windows Form 設計工具的必要項
Private components As System.ComponentModel.IContainer
'注意: 以下為 Windows Form 設計工具所需的程序
'可以使用 Windows Form 設計工具進行修改。
'請勿使用程式碼編輯器進行修改。
<System.Diagnostics.DebuggerStepThrough()>
Private Sub InitializeComponent()
Me.OsuDownloadProgressBar = New System.Windows.Forms.ProgressBar()
Me.OsuDownloadLabel = New System.Windows.Forms.Label()
Me.SuspendLayout()
'
'OsuDownloadProgressBar
'
Me.OsuDownloadProgressBar.Location = New System.Drawing.Point(60, 205)
Me.OsuDownloadProgressBar.Minimum = 0
Me.OsuDownloadProgressBar.Maximum = 100
Me.OsuDownloadProgressBar.Value = 0
Me.OsuDownloadProgressBar.Name = "OsuDownloadProgressBar"
Me.OsuDownloadProgressBar.Size = New System.Drawing.Size(280, 30)
Me.OsuDownloadProgressBar.TabIndex = 0
'
'OsuDownloadLabel
'
Me.OsuDownloadLabel.AutoSize = True
Me.OsuDownloadLabel.Font = New System.Drawing.Font("新細明體", 12.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(136, Byte))
Me.OsuDownloadLabel.Location = New System.Drawing.Point(105, 155)
Me.OsuDownloadLabel.Name = "OsuDownloadLabel"
Me.OsuDownloadLabel.Size = New System.Drawing.Size(190, 24)
Me.OsuDownloadLabel.TabIndex = 1
Me.OsuDownloadLabel.Text = "Osu Downloading..."
'
'DownloadOsuForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(9.0!, 18.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(400, 400)
Me.Controls.Add(Me.OsuDownloadLabel)
Me.Controls.Add(Me.OsuDownloadProgressBar)
Me.Margin = New System.Windows.Forms.Padding(1, 3, 1, 3)
Me.Name = "DownloadOsuForm"
Me.Text = "Downloading Osu"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents OsuDownloadProgressBar As ProgressBar
Friend WithEvents OsuDownloadLabel As Label
End Class

Unable to get property 'get_contentArea' of undefined or null reference

Here am using Dynamic Rad Editor
oEditor.OnClientLoad = "OnClientLoad()"
on calling this method my Rad Editor is not working it is disable,tools and Content area also disabled.
here is my javascript function
function OnClientLoad(editor) {
editor.get_contentArea().style.height = "417px";
// editor.getContentAreaElement().style.height = (417) + "px";
}
Am getting this error
Unable to get property 'get_contentArea' of undefined or null reference
Dim oEditor As New Telerik.Web.UI.RadEditor()
oEditor.ID = sField
If bUnique = False Then oEditor.ID = sField & "[" & GetNextSeqNo.ToString & "]"
oEditor.Height = iHeight * 20
oEditor.Width = System.Web.UI.WebControls.Unit.Pixel(iUltimateWidth)
SetEditorProperties(oEditor)
Private Sub SetEditorProperties(ByVal oEditor As Telerik.Web.UI.RadEditor)
oEditor.OnClientLoad = "OnClientLoad"
'oEditor.ContentAreaMode = EditorContentAreaMode.Iframe
'oEditor.ContentAreaCssFile = "~/Scripts/thumb-scroller.css"
oEditor.ToolbarMode = EditorToolbarMode.Default
oEditor.EditModes = EditModes.Design
oEditor.NewLineMode = EditorNewLineModes.Br
Dim uploadImages As String() = New String() {"~/Temp/MMRImages"}
oEditor.ImageManager.ViewPaths = uploadImages
oEditor.ImageManager.UploadPaths = uploadImages
oEditor.ImageManager.MaxUploadFileSize = 2000000
oEditor.ImageManager.AllowMultipleSelection = False
oEditor.ImageManager.EnableAsyncUpload = True
oEditor.ImageManager.EnableImageEditor = False
oEditor.EnsureToolsFileLoaded()
how to add this reference
please help me
oEditor.OnClientLoad = "OnClientLoad()" should be
oEditor.OnClientLoad = "OnClientLoad"
Note the removed () at the end of the function name.

Why AJAX doesn't work once I add these code?

I have a page for deleting ORDER record. This page was called from AJAX, which work perfectly. However once I added some code that I made for updating inventory table at the same time. It seemed that AJAX function became malfunction and I can't figure out what is wrong with them. Please suggest me. Thanks in advance.
My AJAX function (order_edit.asp)
<script language="JavaScript">
var HttPRequest = false;
function doCallAjax(ID) { // delete order
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = '../engine/delorder_edit.asp';
var pmeters = "tID="+ID;
var bill_id = document.getElementById('bill_id').value; // additional for delorder_edit.asp
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4) // Return Request
{
if(HttPRequest.responseText == 'Y')
{
document.getElementById("tr"+ID).style.display = 'none';
}
}
}
}
</script>
My delorder_edit.asp Page
<%
Option Explicit
Dim strID
strID = Request.Form("tID")
Dim Conn,strSQL,objExec
Set Conn = Server.Createobject("ADODB.Connection")
Conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("../database/TKP.mdb"),"" , ""
'********** *****************************
'Open recorset in order to add od_qty back to tbl_inventory before this record was removed
'****** Once I added these code, my ajax became malfunction ******
Set rsOrder = conn.Execute("SELECT * FROM tbl_order WHERE od_id = "&strID&"" )
pd_id = rsOrder.fields.item("pd_id")
od_qty = rsOrder.fields.item("od_qty")
od_qty = DzToPcs(od_qty)
strSQL1 = "UPDATE tbl_inventory SET inv_qty_act = inv_qty_act + " & od_qty & ", inv_date = date() WHERE pd_id = '" & pd_id & "'"
Set objExec = Conn.Execute(sql1)
'*******************************************
strSQL = ""
strSQL = strSQL&"DELETE * FROM tbl_order "
strSQL = strSQL&"WHERE od_id = "&strID&" "
Set objExec = Conn.Execute(strSQL)
If Err.Number = 0 Then
Response.write("Y")
Else
Response.write("N")
End IF
Conn.Close()
Set Conn = Nothing
%>
First of all i will suggest to use the jQuery.ajax method to call the server method, so your code will be less and also more convenience to understand. And second thing, debug :
"HttPRequest.onreadystatechange = function()",
and check what value is being returned. Until unless we didn't get a exact error we can not suggest you a solution.

Microsoft Interop Outlook c# - invalidcastexception?

Suddenly getting a System.invalidcastexception: unable to cast COM object of type 'system._object' to interface type 'Microsoft.office.interop.outlook.mailitem' ... to a program I wrote that was working fine and now BAM! Exception.
Not sure why... please note I'm a novice programmer.
Here's a snippet of coding where I'm using the Outlook things :
using Microsoft.Office.Interop.Outlook;
static Microsoft.Office.Interop.Outlook.Application app = null;
static _NameSpace ns = null;
static MailItem item = null;
static MAPIFolder inboxFolder = null;
static MAPIFolder dest = null;
static void SendMail(string mailSubject, string htmlMailBody, string mailTo)
{
Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
NameSpace outlookNS = outlookApp.GetNamespace("MAPI");
outlookNS.Logon(Missing.Value, Missing.Value, true, true);
MailItem oMsg = (MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
oMsg.To = mailTo;
oMsg.Recipients.ResolveAll();
StreamReader sr = new StreamReader(#"C:\Users\" + WindowsIdentity.GetCurrent().Name.Split('\\')[1] + #"\AppData\Roaming\Microsoft\Signatures\Default.htm");
string signature = sr.ReadToEnd();
oMsg.Subject = mailSubject;
oMsg.HTMLBody = htmlMailBody + "<br><br>" + signature + "</font>";
oMsg.Save();
((Microsoft.Office.Interop.Outlook._MailItem)oMsg).Send();
oMsg = null;
outlookNS = null;
outlookApp = null;
}
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null, null, false, false);
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
#region match - convert - extract
foreach (string tifFile in Directory.GetFiles(workFolder, "*.tif", SearchOption.TopDirectoryOnly))
{
string currentFile = Path.GetFileNameWithoutExtension(tifFile);
for (int i = 1; i <= inboxFolder.Items.Count; i++)
{
//##############CODE CRASHES HERE##############
item = (MailItem)inboxFolder.Items[i];
// item = inboxFolder.Items[i];
if (item.Body != "")
{
if ((item.Body.Contains("Box Number =")) && (item.Body.Contains("Contract ID = ")) && (item.Body.Contains("Branch = ")) && (item.Body.Contains(currentFile.Replace('_', '/'))))
{
// matchFound = true;
MailStack current = new MailStack();
Console.WriteLine("________________________");
Console.WriteLine("File matched \t\t:\t" + currentFile + ".tif");
I've looked around but can't make much sense of the answers available.
any help appreciated.
Try this...
item = inboxFolder.Items[i] as MailItem;
if (item != null)
{
// ...
}

Print to a network printer in C#

I am attempting to print to a network servia via C# in VS2010 but have run into difficulties getting it to work. If I use the "print" Verb insted it prints fine but only to the default printer. I am using the PrintTo Verb to try and specify a printer. In my case using print verb I successfully can print to the same network printer that I am trying to print to using the printto verb after I change my default printer to a different printer. Here is the code I am currently using. Any help would be greatly appreciated.
private string FindPrinter(string printerName)
{
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection printers = searcher.Get();
foreach (ManagementObject printer in printers)
{
if (!String.IsNullOrEmpty(printer.Properties["PortName"].Value.ToString()))
{
return printerName = string.Format(#"\\{0}\{1}", printer.Properties["PortName"].Value.ToString(), printerName);
}
}
return printerName;
}
private void Print(string fileName, string printerName)
{
PrinterSettings ps = new PrinterSettings();
ps.PrinterName = printerName;
if (ps.IsValid)
{
try
{
ProcessStartInfo processStartInfo = new ProcessStartInfo(fileName);
using (PrintDialog pd = new PrintDialog())
{
pd.ShowDialog();
printerName = this.FindPrinter(pd.PrinterSettings.PrinterName);
if (printerName.IndexOf(#"\\") == 0)
{
processStartInfo.Verb = "PrintTo";
processStartInfo.Arguments = printerName;
}
else
{
processStartInfo.Verb = "print";
}
}
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process printProcess = new Process();
printProcess.StartInfo = processStartInfo;
bool printStarted = printProcess.Start();
MessageBox.Show(string.Format("{0} printed to {1}", fileName, printerName), "Report Print", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Report Print", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show(string.Format("{0} printer does not exist. Please contact technical support.", printerName), "Report Print", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
only use verb PrintTo and
use the double quotes to quote the printerName
processStartInfo.Verb = "PrintTo";
processStartInfo.Arguments = "\"" + printerName + "\"";

Resources