I want to list all users of a Windows domain with WMI in C#.
Can someone help me?
Here is my code:
try
{
ConnectionOptions connection = new ConnectionOptions();
connection.Username = user;
connection.Authority = "ntlmdomain:" + domain;
connection.Password = pwd;
SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");
ManagementScope scope = new ManagementScope(#"\\FullComputerName\\root\\CIMV2", connection);
scope.Connect();
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Account Type: " + queryObj["AccountType"]);
Console.WriteLine("Caption: " + queryObj["Caption"]);
Console.WriteLine("Description: " + queryObj["Description"]);
Console.WriteLine("Disabled: " + queryObj["Disabled"]);
Console.WriteLine("Domain: " + queryObj["Domain"]);
Console.WriteLine("Full Name: " + queryObj["FullName"]);
Console.WriteLine("Local Account: " + queryObj["LocalAccount"]);
Console.WriteLine("Lockout: " + queryObj["Lockout"]);
Console.WriteLine("Name: " + queryObj["Name"].ToString());
Console.WriteLine("Password Changeable: " + queryObj["PasswordChangeable"]);
Console.WriteLine("Password Expires: " + queryObj["PasswordExpires"]);
Console.WriteLine("Password Required: " + queryObj["PasswordRequired"]);
Console.WriteLine("SID: " + queryObj["SID"]);
Console.WriteLine("SID Type: " + queryObj["SIDType"]);
Console.WriteLine("Status: " + queryObj["Status"]);
Console.WriteLine("");
}
}
catch (ManagementException err)
{
Console.WriteLine("An error occured while querying for WMI data: " + err.Message);
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
Console.WriteLine("Connection error " + "(user name or password might be incorrect): " + unauthorizedErr.Message);
}
There's a typo in the namespace path in your ManagementScope constructor:
ManagementScope scope = new ManagementScope(#"\\FullComputerName\\root\\CIMV2", connection);
The string should be either #"\\FullComputerName\root\CIMV2" or "\\\\FullComputerName\\root\\CIMV2".
Note that you cannot specify the user account for local connections. So if FullComputerName is a local computer, use this instead:
ManagementScope scope = new ManagementScope("root\\CIMV2");
Related
I am trying to send a mail using google.Apis.Gmail.v1 and MimeKit, but the issue is that when I use Arabic characters, the receiver receives gibberish text.
My code is below:
var mail = new MimeMessage();
mail.From.Add(new MailboxAddress("From Name", "DoNotReply#someDomain.com"));
mail.To.Add(new MailboxAddress("To Name","customerAddress#someDomain.com"));
mail.Subject = "كشف حساب من تاريخ " + dateTimePicker1.Text + " حتى تاريخ " + dateTimePicker2.Text;
var text_part = new TextPart(MimeKit.Text.TextFormat.Plain);
string body = #"<table border='1'><table style='background-color:#E5E4E2;'><tr><tr style='background-color:#1e90ff;color:#ffffff;'><td>تراكمي</td><td>دائن</td><td>مدين</td><td>البيان</td><td>المرجع</td><td>التاريخ</td></tr>";
foreach (ListViewItem lstitem in listView1.Items)
{
body += #"<tr><td>" + lstitem.SubItems[1].Text + "</td><td>" + lstitem.SubItems[2].Text + "</td><td>" + lstitem.SubItems[3].Text + "</td><td>" + lstitem.SubItems[4].Text + "</td><td>" + lstitem.SubItems[5].Text + "</td><td>" + lstitem.SubItems[6].Text + "</td></tr>";
}
body += #"</table></style></style>";
body += #"<br /><br /> المبلغ المطلوب " + sum1s.Text;
body += #"<br /><br /> Thank You";
mail.Body = new TextPart("html") { Text = body };
byte[] bytes = Encoding.UTF8.GetBytes(mail.ToString());
string raw_message = Convert.ToBase64String(bytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
UserCredential credential;
//read your credentials file
using (FileStream stream = new FileStream(Application.StartupPath + #"/credentials.json", FileMode.Open, FileAccess.Read))
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
path = Path.Combine(path, ".credentials/gmail-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Program.Scopes, "user", CancellationToken.None, new FileDataStore(path, true)).Result;
}
//call your gmail service
var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = Program.ApplicationName });
var msg = new Google.Apis.Gmail.v1.Data.Message();
msg.Raw = raw_message;
service.Users.Messages.Send(msg, "me").Execute();
MessageBox.Show("تم ارسال التقرير بنجاح", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
And what I receive is:
تراكمي دائن مدين البيان المرجع التاريخ
985.00 58228.00 57243.00 رصيد منقول - 01/03/2022 00:00:00 AM
985 58228 -57243 المجموع الكلي - 11/03/2022 09:49:42 AM
المبلغ المطلوب + 985 شيكل
Thank You
The UI Editor in Dynamics CRM won't allow system admins to directly edit status/statecode picklists on the Activity Entity. How can the order be edited programatically?
In another question, information is provided about how to get metadata about statuscodes and statecodes:
Dynamics Crm: Get metadata for statuscode/statecode mapping
Microsoft provides a class for sorting order of picklists:
https://learn.microsoft.com/en-us/previous-versions/dynamicscrm-2016/developers-guide/gg327607(v%3dcrm.8)
I have successsfully coded and can retrieve metadata for both standard picklists and for statuscodes picklists (both the statecode and statuscode). I can programatically update the sort order on standard picklists, but when attempting to do so on a statuscode optionset, no errors are thrown and no changes are published to the system.
How can the sort order on the activity statuscode field be updated?
Example code follows, complete with both tests:
namespace ConsoleApps
{
class EditAptStatusCodeOptionSetOrder
{
static void Main()
{
//Connect to Database
string CRMConnectionString = #"AuthType = Office365; URL = https://URLOFSERVER; Username=USERNAME; Password=PASSWORD;";
Console.WriteLine("Connecting to Auric Solar Sandbox Environment Using Ryan Perry's Credentials. ");
CrmServiceClient crmServiceClient = new CrmServiceClient(CRMConnectionString);
IOrganizationService crmService = crmServiceClient.OrganizationServiceProxy;
//Test Retrieving Stage (Statuscode) from Test Entity.
//Get the Attribute
RetrieveAttributeRequest retrieveStatusCodeAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "new_testentity",
LogicalName = "statuscode",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse retrieveStatusCodeAttributeResponse =
(RetrieveAttributeResponse)crmService.Execute(retrieveStatusCodeAttributeRequest);
Console.WriteLine("Retreived Attribute:" +
retrieveStatusCodeAttributeResponse.AttributeMetadata.LogicalName);
Console.WriteLine("Retreived Attribute Description:" +
retrieveStatusCodeAttributeResponse.AttributeMetadata.Description);
StatusAttributeMetadata statusCodeMetaData =
(StatusAttributeMetadata)retrieveStatusCodeAttributeResponse.AttributeMetadata;
Console.WriteLine("Metadata Description:" +
statusCodeMetaData.Description);
Console.WriteLine("Metadata IsValidForUpdate:" +
statusCodeMetaData.IsValidForUpdate.ToString());
Console.WriteLine("OptionSet Type:" +
statusCodeMetaData.OptionSet.Name.ToString());
Console.WriteLine("OptionSet Name:" +
statusCodeMetaData.OptionSet.OptionSetType.ToString());
Console.WriteLine("Retrieved Options:");
foreach (OptionMetadata optionMeta in statusCodeMetaData.OptionSet.Options)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Save Options in an array to reorder.
OptionMetadata[] optionList = statusCodeMetaData.OptionSet.Options.ToArray();
Console.WriteLine("Option Array:");
foreach (OptionMetadata optionMeta in optionList)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
var sortedOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();
Console.WriteLine("Sorted Option Array:");
foreach (OptionMetadata optionMeta in sortedOptionList)
{
Console.WriteLine(((StatusOptionMetadata)optionMeta).State.Value + " : " + optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Create the request.
OrderOptionRequest orderStatusCodeOptionRequest = new OrderOptionRequest
{
AttributeLogicalName = "statuscode",
EntityLogicalName = "new_testentity",
Values = sortedOptionList.Select(X => X.Value.Value).ToArray()
};
Console.WriteLine("orderStatusCodeOptionRequest Created.");
//Execute Request. //////THIS DOESN'T THROW ERRORS, BUT DOESN'T UPDATE SYSTEM.
OrderOptionResponse orderStatusCodeResponse = (OrderOptionResponse)crmService.Execute(orderStatusCodeOptionRequest);
Console.WriteLine("Request Executed");
////////////////////////////////////////PICKLIST TEST//////////////////////////////////
Console.WriteLine("\n\nTestingPickList");
RetrieveAttributeRequest retrieveTestPicklistAttributeRequest = new RetrieveAttributeRequest
{
EntityLogicalName = "new_testentity",
LogicalName = "new_testpicklist",
RetrieveAsIfPublished = true
};
RetrieveAttributeResponse retrieveTestPicklistAttributeResponse =
(RetrieveAttributeResponse)crmService.Execute(retrieveTestPicklistAttributeRequest);
PicklistAttributeMetadata pickListMetaData =
(PicklistAttributeMetadata)retrieveTestPicklistAttributeResponse.AttributeMetadata;
Console.WriteLine("Retrieved Picklist Options:");
foreach (OptionMetadata optionMeta in pickListMetaData.OptionSet.Options)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Save Options in an array to reorder.
OptionMetadata[] picklistOptionList = pickListMetaData.OptionSet.Options.ToArray();
Console.WriteLine("Picklist Option Array:");
foreach (OptionMetadata optionMeta in picklistOptionList)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
var sortedPicklistOptionList = picklistOptionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();
Console.WriteLine("Picklist Sorted Option Array:");
foreach (OptionMetadata optionMeta in sortedPicklistOptionList)
{
Console.WriteLine(optionMeta.Value + " : " + optionMeta.Label.UserLocalizedLabel.Label);
}
//Create the request.
OrderOptionRequest orderPicklistOptionRequest = new OrderOptionRequest
{
AttributeLogicalName = "new_testpicklist",
EntityLogicalName = "new_testentity",
Values = sortedPicklistOptionList.Select(X => X.Value.Value).ToArray()
};
Console.WriteLine("orderPicklistOptionRequest Created.");
//Execute Request.
OrderOptionResponse orderPicklistResponse = (OrderOptionResponse)crmService.Execute(orderPicklistOptionRequest);
Console.WriteLine("Order Picklist Request Executed");
//Publish All.
Console.WriteLine("Publishing. Please Wait...");
PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
crmService.Execute(publishRequest);
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}
I am getting below error in my function.
Error: FROM keyword not found where expected
And here is my Function:
private int BauteilLieferzeit(string Materianummer)
{
try
{
OracleCommand cmd = new OracleCommand(
" Select MATNR, AVG_DAUER" +
" AVG " +
" (DATEDIFF " +
" (mi, Z.APL_ANFDATUM, " +
" Z.STA_LIEFERDATUM)) " +
" as AVG_DAUER " +
" from ZDATA AS Z " +
" where MATNR = '" + Materianummer + "'"
, OraVerbindung._conn);
OracleDataReader r = cmd.ExecuteReader();
if (r.HasRows)
{
int Restminuten = OraVerbindung.Lieferzeit;
while (r.Read())
{
Restminuten = r.GetInt32(1);
}
return Restminuten;
}
else
{
return OraVerbindung.Lieferzeit;
}
}
catch
{
return OraVerbindung.Lieferzeit;
}
}
In Oracle this is not a valid syntax
from ZDATA AS Z
use
from ZDATA Z
instead (remove "AS")
Additionally consider the use of bind variables instead of string concatenation:
" where MATNR = '" + Materianummer + "'"
search for "SQL Injection".
Use this. Included the issue highlighted by Marmite also. But the error FROM keyword not found where expected would be due to missing comma in select statement.
Edit: Removed AVG_DAUER column as it is getting derived later.
private int BauteilLieferzeit(string Materianummer)
{
try
{
OracleCommand cmd = new OracleCommand(
" Select MATNR," +
" AVG " +
" (DATEDIFF " +
" (mi, Z.APL_ANFDATUM, " +
" Z.STA_LIEFERDATUM)) " +
" as AVG_DAUER " +
" from ZDATA Z " +
" where MATNR = '" + Materianummer + "'"
, OraVerbindung._conn);
OracleDataReader r = cmd.ExecuteReader();
if (r.HasRows)
{
int Restminuten = OraVerbindung.Lieferzeit;
while (r.Read())
{
Restminuten = r.GetInt32(1);
}
return Restminuten;
}
else
{
return OraVerbindung.Lieferzeit;
}
}
catch
{
return OraVerbindung.Lieferzeit;
}
}
I am using BaseX (XML based datastore) for its performance benchmarking. For testing it with ,
TestBeds
I) 10,000 users, 10 friends, 10 resources
II) 100,000 users , 10 friends, 10 resources
I faced below issues:
1) Loading of data is too slow. Gets slowed with eh increase in the number of threads.
2) Plus point - Reading/retriving values from BaseX is faster (17k operation per second)
3) Updating the data in BaseX is very slow. Throughput is ~10 operations per second.
Am I correct to say BaseX is 'TOO' slow for write/update operations (20/sec) compared to read/retrieve (10k/sec)?
Please advice me to make it more efficient for the write and update :
I have a function insertEntity (update or insert function) in to the BaseX datastore as follows -
public int insertEntity(String entitySet, String entityPK,
HashMap<String, ByteIterator> values, boolean insertImage) {
String parentTag ="",childTag ="", key="", entryTag="";
StringBuffer insertData = new StringBuffer();
Set<String> keys = values.keySet();
Iterator<String> iterator = keys.iterator();
while(iterator.hasNext()) {
String entryKey = iterator.next();
if(!(entryKey.equalsIgnoreCase("pic") || entryKey.equalsIgnoreCase("tpic")))
insertData.append("element " + entryKey + " {\"" + StringEscapeUtils.escapeXml(values.get(entryKey).toString()) + "\"},");
}
if(entitySet.equalsIgnoreCase("users")&& insertImage){
byte[] profileImage = ((ObjectByteIterator)values.get("pic")).toArray();
String encodedpImage = DatatypeConverter.printBase64Binary(profileImage);
insertData.append(" element pic {\"" + encodedpImage + "\"},");
profileImage = ((ObjectByteIterator)values.get("tpic")).toArray();
encodedpImage = DatatypeConverter.printBase64Binary(profileImage);
insertData.append(" element tpic {\"" + encodedpImage + "\"},");
}
if(entitySet.equalsIgnoreCase("users"))
{
parentTag = "users";
childTag = "members";
entryTag = "member";
key = "mem_id";
insertData.append("element confirmed_friends {}, element pending_friends {}");
}
if(entitySet.equalsIgnoreCase("resources"))
{
parentTag = "resources";
childTag = "resources";
entryTag = "resource";
key = "rid";
insertData.append("element manipulations {}");
}
try {
session.execute(new XQuery(
"insert node element " + entryTag
+ "{ attribute " + key + "{"
+ entityPK + "}, "
+ insertData.toString()
+ "} "
+ "into doc('" + databaseName + "/" + parentTag +".xml')/" + childTag
));
String q1 = "insert node element " + entryTag
+ "{ attribute " + key + "{"
+ entityPK + "}, "
+ insertData.toString()
+ "} "
+ "into doc('" + databaseName + "/" + parentTag +".xml')/" + childTag;
System.out.println(q1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
And the below function is acceptFriendship (update function)
public int acceptFriend(int inviterID, int inviteeID) {
// TODO Auto-generated method stub
String acceptFriendQuery1 = "insert node <confirmed_friend id = '"
+ inviterID + "'>"
+ " </confirmed_friend>"
+ "into doc('"+databaseName+"/users.xml')/members/member[#mem_id = '"+inviteeID+"']/confirmed_friends";
String acceptFriendQuery2 = "insert node <confirmed_friend id = '"
+ inviteeID + "'>"
+ " </confirmed_friend>"
+ "into doc('"+databaseName+"/users.xml')/members/member[#mem_id = '"+inviterID+"']/confirmed_friends";
String acceptFriendQuery3 = "delete node doc('"+databaseName+"/users.xml')/members/member[#mem_id = '"
+ inviteeID + "']/pending_friends/pending_friend[#id = '"+ inviterID +"']";
try {
session.execute(new XQuery(acceptFriendQuery1));
session.execute(new XQuery(acceptFriendQuery2));
session.execute(new XQuery(acceptFriendQuery3));
System.out.println("Inviter: "+inviterID +" AND Invitee: "+inviteeID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
I have a Spring MVC REST service that accepts two #RequestParams called from and to. These are parsed as java.util.Date and passed to the following method in my DAO class.
#Override
public List<ErrorsDTOEntity> getAllErrors(Date from, Date to) {
try {
Query query = getSession().createQuery(
"SELECT NEW com.mydomain.esb.jpa.dto.ErrorsDTOEntity(ee, ec.message) "
+ "FROM ErrorsEntity ee, EventCodeEntity ec "
+ "WHERE ee.responseTime > " + from.getTime() + " "
+ "AND ee.responseTime < " + to.getTime() + " "
+ "AND ee.serviceResponseCode = ec.code "
+ "GROUP BY ee.domainName, ee.serviceName, ec.message, ee.serviceErrorCount, ee.errorTimestamp, "
+ "ee.deviceName, ee.servErrId, ee.serviceResponseCode, ee.elapsedTime, ee.forwardTime, "
+ "ee.responseCompletionTime, ee.responseSizeAverage, ee.requestSizeAverage, ee.responseTime "
+ "ORDER BY ee.domainName, ee.serviceName, ec.message, ee.errorTimestamp");
#SuppressWarnings("unchecked")
List<ErrorsDTOEntity> services = (List<ErrorsDTOEntity>) query.list();
return services;
} catch (HibernateException hex) {
hex.printStackTrace();
}
return null;
}
This is throwing the following SQL error:
org.hibernate.exception.SQLGrammarException: ORA-00932: inconsistent datatypes: expected TIMESTAMP got NUMBER
What's the proper way to structure this query so I can only fetch results between the from and to dates?
I figured it out, this works:
#Override
public List<ErrorsDTOEntity> getAllErrors(Date from, Date to) {
try {
Query query = getSession().createQuery(
"SELECT NEW com.mydomain.esb.jpa.dto.ErrorsDTOEntity(ee, ec.message) "
+ "FROM ErrorsEntity ee, EventCodeEntity ec "
+ "WHERE ee.responseTime > :from "
+ "AND ee.responseTime < :to "
+ "AND ee.serviceResponseCode = ec.code "
+ "GROUP BY ee.domainName, ee.serviceName, ec.message, ee.serviceErrorCount, ee.errorTimestamp, "
+ "ee.deviceName, ee.servErrId, ee.serviceResponseCode, ee.elapsedTime, ee.forwardTime, "
+ "ee.responseCompletionTime, ee.responseSizeAverage, ee.requestSizeAverage, ee.responseTime "
+ "ORDER BY ee.domainName, ee.serviceName, ec.message, ee.errorTimestamp");
query.setTimestamp("from", from);
query.setTimestamp("to", to);
#SuppressWarnings("unchecked")
List<ErrorsDTOEntity> services = (List<ErrorsDTOEntity>) query.list();
return services;
} catch (HibernateException hex) {
hex.printStackTrace();
}
return null;
}