C# Updating user details error - c#

I'm trying to update the user properties but I get an error :
The attribute syntax specified to the directory service is invalid
It happens when I do CommitChanges(), this code worked for me before so I don't know what is wrong.
This is the code:
DirectoryEntry de = new DirectoryEntry(_ldap);
DirectorySearcher ds = new DirectorySearcher(de) { Filter = "(&(objectClass=user)(SamAccountName=" + logon_tb.Text + "))" };
SearchResult sr = ds.FindOne();
DirectoryEntry userEntry = sr.GetDirectoryEntry();
try { userEntry.Properties["givenName"].Value = fn_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["sn"].Value = ln_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["displayName"].Value = dispName_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["description"].Value = description_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["physicalDeliveryOfficeName"].Value = office_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["telephoneNumber"].Value = telephone_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["mobile"].Value = mobile_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["title"].Value = jobTitle_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["department"].Value = department_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["postOfficeBox"].Value = poBox_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["homeDirectory"].Value = homeFolder_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute10"].Value = extAtt10_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute11"].Value = extAtt11_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute12"].Value = extAtt12_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute13"].Value = extAtt13_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute14"].Value = extAtt14_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["extensionAttribute15"].Value = extAtt15_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["SamAccountName"].Value = logon_tb.Text; }
catch (Exception) { }
try { userEntry.Properties["userPrincipalName"].Value = logonPrincipal_tb.Text; }
catch (Exception) { }
if (pwNeverExpire_cb.Checked)
userEntry.Properties["userAccountControl"].Value = 66048;
userEntry.CommitChanges();
userEntry.Close();

DirectoryEntry de = new DirectoryEntry(_ldap);
DirectorySearcher ds = new DirectorySearcher(de) { Filter = "(&(objectClass=user)(SamAccountName=" + logon_tb.Text + "))" };
SearchResult sr = ds.FindOne();
DirectoryEntry userEntry = sr.GetDirectoryEntry();
if (fn_tb.Text != "")
userEntry.Properties["givenName"].Value = fn_tb.Text;
else
userEntry.Properties["givenName"].Value = null;
if (ln_tb.Text != "")
userEntry.Properties["sn"].Value = ln_tb.Text;
else
userEntry.Properties["sn"].Value = null;
if (dispName_tb.Text != "")
userEntry.Properties["displayName"].Value = dispName_tb.Text;
else
userEntry.Properties["displayName"].Value = null;
if (description_tb.Text != "")
userEntry.Properties["description"].Value = description_tb.Text;
else
userEntry.Properties["description"].Value = null;
if (office_tb.Text != "")
userEntry.Properties["physicalDeliveryOfficeName"].Value = office_tb.Text;
else
userEntry.Properties["physicalDeliveryOfficeName"].Value = null;
if (telephone_tb.Text != "")
userEntry.Properties["telephoneNumber"].Value = telephone_tb.Text;
else
userEntry.Properties["telephoneNumber"].Value = null;
if (mobile_tb.Text != "")
userEntry.Properties["mobile"].Value = mobile_tb.Text;
else
userEntry.Properties["mobile"].Value = null;
if (jobTitle_tb.Text != "")
userEntry.Properties["title"].Value = jobTitle_tb.Text;
else
userEntry.Properties["title"].Value = null;
if (department_tb.Text != "")
userEntry.Properties["department"].Value = department_tb.Text;
else
userEntry.Properties["department"].Value = null;
if (poBox_tb.Text != "")
userEntry.Properties["postOfficeBox"].Value = poBox_tb.Text;
else
userEntry.Properties["postOfficeBox"].Value = null;
if (homeFolder_tb.Text != "")
userEntry.Properties["homeDirectory"].Value = homeFolder_tb.Text;
else
userEntry.Properties["homeDirectory"].Value = null;
if (extAtt10_tb.Text != "")
userEntry.Properties["extensionAttribute10"].Value = extAtt10_tb.Text;
else
userEntry.Properties["extensionAttribute10"].Value = null;
if (extAtt11_tb.Text != "")
userEntry.Properties["extensionAttribute11"].Value = extAtt11_tb.Text;
else
userEntry.Properties["extensionAttribute11"].Value = null;
if (extAtt12_tb.Text != "")
userEntry.Properties["extensionAttribute12"].Value = extAtt12_tb.Text;
else
userEntry.Properties["extensionAttribute12"].Value = null;
if (extAtt13_tb.Text != "")
userEntry.Properties["extensionAttribute13"].Value = extAtt13_tb.Text;
else
userEntry.Properties["extensionAttribute13"].Value = null;
if (extAtt14_tb.Text != "")
userEntry.Properties["extensionAttribute14"].Value = extAtt14_tb.Text;
else
userEntry.Properties["extensionAttribute14"].Value = null;
if (extAtt15_tb.Text != "")
userEntry.Properties["extensionAttribute15"].Value = extAtt15_tb.Text;
else
userEntry.Properties["extensionAttribute15"].Value = null;
if (logon_tb.Text != "")
userEntry.Properties["SamAccountName"].Value = logon_tb.Text;
else
userEntry.Properties["SamAccountName"].Value = null;
if (idNumber_tb.Text != "")
userEntry.Properties["userPrincipalName"].Value = idNumber_tb.Text;
else
userEntry.Properties["userPrincipalName"].Value = null;
userEntry.CommitChanges();
userEntry.Close();
I did it like that and it worked with no problems.

Related

Excel data reading from Stream and save to the database

In my asp.net MVC application, There is an option to upload data from an excel file. For that, I have used this on my controller.
public ActionResult ImportEmpDetails(HttpPostedFileBase excelFile)
{
try
{
if (excelFile.ContentLength == 0 || excelFile == null)
{
ViewBag.Error = "Please select the excel file";
return View("EmpDetails");
}
else
{
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/ExcelFile/" + excelFile.FileName);
if (System.IO.File.Exists(path)) System.IO.File.Delete(path);
excelFile.SaveAs(path);
ExcelPath = Server.MapPath("~/ExcelFile/") + path;
Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = application.Workbooks.Open(path);
Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;
Microsoft.Office.Interop.Excel.Range range = worksheet.UsedRange;
List<EmpDetailsVM> xcel = new List<EmpDetailsVM>();
for (int i = 2; i <= range.Rows.Count; i++)
{
try
{
EmpDetails emp = new EmpDetails();
int EmpNo = int.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 1]).Text);
var EmpId = (from c in db.CreateEmployee where c.EmpNo == EmpNo select c.Id).First();
emp.EmpID = EmpId;
emp.YearOfService = decimal.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 2]).Text);
emp.BasicSalary = decimal.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 3]).Text);
emp.EmpCatagory = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 4]).Text;
emp.EmpGrade = ((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 5]).Text;
int SupervisorId = int.Parse(((Microsoft.Office.Interop.Excel.Range)range.Cells[i, 6]).Text);
var SupId = (from h in db.CreateEmployee where h.EmpNo == SupervisorId select h.Id).First();
emp.SupervisorId = SupId;
EmpDetailsVM data = new EmpDetailsVM();
data.EmpID = emp.EmpID;
data.YearOfService = emp.YearOfService;
data.BasicSalary = emp.BasicSalary;
data.EmpCatagory = emp.EmpCatagory;
data.EmpGrade = emp.EmpGrade;
data.SupervisorId = emp.SupervisorId;
xcel.Add(data);
}
catch (Exception ex)
{
ViewBag.Error = "Error in " + i + " record";
return View("EmpDetails");
}
}
if (xcel != null)
{
try
{
foreach (var item in xcel)
{
int empID = item.EmpID;
decimal yearOfService = item.YearOfService;
decimal basicSalary = item.BasicSalary;
string catagory = item.EmpCatagory;
string grade = item.EmpGrade;
int supId = item.SupervisorId;
var isEmployeeExists = (from e in dbs.EmpDetails where e.EmpID == empID select e.Id).ToList();
int EmpCount = isEmployeeExists.Count();
if (EmpCount == 0)
{
EmpDetails e = new EmpDetails();
e.EmpID = empID;
e.YearOfService = yearOfService;
e.BasicSalary = basicSalary;
e.EmpCatagory = catagory;
e.EmpGrade = grade;
e.SupervisorId = supId;
dbs.EmpDetails.Add(e);
dbs.SaveChanges();
}
else
{
EmpDetails EmpDetails = dbs.EmpDetails.Where(x => x.EmpID == empID).First();
EmpDetails.YearOfService = yearOfService;
EmpDetails.BasicSalary = basicSalary;
EmpDetails.EmpCatagory = catagory;
EmpDetails.EmpGrade = grade;
EmpDetails.SupervisorId = supId;
db.SaveChanges();
}
}
}
catch (Exception ex)
{
ViewBag.Error = "Error " + ex;
}
TempData["msg"] = "success";
return View("EmpDetails", xcel);
}
else
{
}
return View("EmpDetails");
}
else
{
ViewBag.Error = "Selected excel file not supported";
return View("EmpDetails");
}
}
}
catch (Exception ex)
{
string message = string.Format("<b>Message:</b> {0}<br /><br />", "You do not have access to this view");
message += string.Format("<b>StackTrace:</b> {0}<br /><br />", ex.StackTrace.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>Source:</b> {0}<br /><br />", ex.Source.Replace(Environment.NewLine, string.Empty));
message += string.Format("<b>TargetSite:</b> {0}", ex.TargetSite.ToString().Replace(Environment.NewLine, string.Empty));
ModelState.AddModelError("Id", message);
}
return View("EmpDetails");
}
This is working properly when I debug the code and run from it using VS. When I applied to the live version, can't upload the excel file there is an exception triggering You do not have access to this view
Want to know how to prevent this or how to do same using stream ?

data getting moved instead of added

I am trying to create functionality to copy data from one order to another. Here is the code that copies the data:
protected void copySeminarIDButton_Click(object sender, EventArgs e)
{
try
{
//show some message incase validation failed and return
String seminarID = this.copySeminarIDText.Text;
Int32 id;
try
{
id = Convert.ToInt32(seminarID);
} catch (Exception e2)
{
return;
}
//copy over all the registration types now for the entered id
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
var seminars = db.seminars.Where(x => x.id == id);
if (seminars.Any())
{
var s = seminars.First();
//Load RegTypes
try
{
var regList = s.seminar_registration_type
.OrderBy(x => x.sort)
.ToList()
.Select(x => new seminarRegistrationTypeListing
{
id = x.id,
amount = x.amount,
description = x.description,
feeTypeId = x.feeTypeId,
method = x.method,
promoCodes = PromoCodesToString(x.xref_reg_type_promo.Select(z => z.promoId).ToList()),
title = x.title,
isPreorder = x.isPreorder,
sort = x.sort
});
this.dlTypes.DataSource = regList;
this.dlTypes.DataBind();
}
catch (Exception ex)
{
Response.Write("RegTypes: " + ex.Message);
}
} else
{
return;
}
}
}
catch (Exception m)
{
}
}
The user will enter a ID of the invoice they want to copy from. The above code copies pull the right data from the invoice and loads it on the page. When i click save the data is being saved.
The problem that is occurring is that the invoice that i copy data from will no longer have the data any more. So basically instead of copying the data its actually moving the data to the new invoice. I want to copy.
Here is my Save code.
private void SaveRegTypes(int seminarId)
{
//Reg Types
using (SeminarGroupEntities db = new SeminarGroupEntities())
{
try
{
var s = db.seminars.Where(x => x.id == seminarId).First();
var msg = "alert('Saving:" + seminarId + "');";
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", msg, true);
this.copySeminarIDText.Text = msg;
//s.seminar_registration_type.Clear();
foreach (DataListItem dli in this.dlTypes.Items)
{
String sId = ((HiddenField)dli.FindControl("hdnId")).Value;
var reg = new seminar_registration_type();
if ((sId != "") && (sId != "0"))
{
Int32 id = Convert.ToInt32(sId);
reg = db.seminar_registration_type.Where(x => x.id == id).Single();
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "Data Copied...", "alert('hidded field id is empty.');", true);
}
else
{
db.seminar_registration_type.Add(reg);
}
reg.feeTypeId = Convert.ToInt32(((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Value);
reg.amount = Convert.ToDecimal(((TextBox)dli.FindControl("txtPrice")).Text);
reg.title = ((DropDownList)dli.FindControl("ddlRegType")).SelectedItem.Text;
reg.description = ((TextBox)dli.FindControl("txtRegDesc")).Text;
reg.method = Convert.ToInt32(((DropDownList)dli.FindControl("ddlDeliveryMethod")).Text);
reg.promocode = null;
reg.isPreorder = Convert.ToBoolean(((CheckBox)dli.FindControl("chkPreorder")).Checked);
reg.sort = 1;
reg.seminarId = seminarId;
string sort = ((TextBox)dli.FindControl("txtRTSort")).Text;
try
{
reg.sort = Convert.ToInt32(sort);
}
catch (Exception ex) { }
//Do Promo Codes
Repeater rptPromocodes = (Repeater)dli.FindControl("rptPromoCodesList");
reg.xref_reg_type_promo.Clear();
foreach (RepeaterItem ri in rptPromocodes.Items)
{
try
{
Int32 id = Convert.ToInt32(((HiddenField)ri.FindControl("hdnCodeId")).Value);
DateTime? expires = null;
try
{
HiddenField exp = (HiddenField)ri.FindControl("hdnExpirationDate");
if (!String.IsNullOrWhiteSpace(exp.Value))
expires = Convert.ToDateTime(((HiddenField)ri.FindControl("hdnExpirationDate")).Value);
}
catch (Exception ex) { }
var code = db.promo_code.Where(x => x.id == id).First();
reg.xref_reg_type_promo.Add(new xref_reg_type_promo
{
expiration = expires,
promoId = code.id
});
}
catch (Exception ex) { }
}
db.SaveChanges();
((HiddenField)dli.FindControl("hdnId")).Value = reg.id.ToString();
}
}
catch (Exception ex)
{
String err = ex.Message;
}
}
}

The code is giving error at MultiSheetsPdf

This is my code which create PDF of a dwg file but it gives me error near MultiSheetPdf. Please give me the solution for same.
I thought that linking is the problem but I am not able to identify please suggest me the solution.
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdfPlot(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Here you go: (Try to note and understand the difference between your version and this version)
namespace Plottings
{
public class MultiSheetsPdf
{
private string dwgFile, pdfFile, dsdFile, outputDir;
private int sheetNum;
private IEnumerable<Layout> layouts;
private const string LOG = "publish.log";
public MultiSheetsPdf(){}
public MultiSheetsPdf(string pdfFile, IEnumerable<Layout> layouts)
{
Database db = HostApplicationServices.WorkingDatabase;
this.dwgFile = db.Filename;
this.pdfFile = pdfFile;
this.outputDir = Path.GetDirectoryName(this.pdfFile);
this.dsdFile = Path.ChangeExtension(this.pdfFile, "dsd");
this.layouts = layouts;
}
public void Publish()
{
if (TryCreateDSD())
{
Publisher publisher = AcAp.Publisher;
PlotProgressDialog plotDlg = new PlotProgressDialog(false, this.sheetNum, true);
publisher.PublishDsd(this.dsdFile, plotDlg);
plotDlg.Destroy();
File.Delete(this.dsdFile);
}
}
private bool TryCreateDSD()
{
using (DsdData dsd = new DsdData())
using (DsdEntryCollection dsdEntries = CreateDsdEntryCollection(this.layouts))
{
if (dsdEntries == null || dsdEntries.Count <= 0) return false;
if (!Directory.Exists(this.outputDir))
Directory.CreateDirectory(this.outputDir);
this.sheetNum = dsdEntries.Count;
dsd.SetDsdEntryCollection(dsdEntries);
dsd.SetUnrecognizedData("PwdProtectPublishedDWF", "FALSE");
dsd.SetUnrecognizedData("PromptForPwd", "FALSE");
dsd.SheetType = SheetType.MultiDwf;
dsd.NoOfCopies = 1;
dsd.DestinationName = this.pdfFile;
dsd.IsHomogeneous = false;
dsd.LogFilePath = Path.Combine(this.outputDir, LOG);
PostProcessDSD(dsd);
return true;
}
}
private DsdEntryCollection CreateDsdEntryCollection(IEnumerable<Layout> layouts)
{
DsdEntryCollection entries = new DsdEntryCollection();
foreach (Layout layout in layouts)
{
DsdEntry dsdEntry = new DsdEntry();
dsdEntry.DwgName = this.dwgFile;
dsdEntry.Layout = layout.LayoutName;
dsdEntry.Title = Path.GetFileNameWithoutExtension(this.dwgFile) + "-" + layout.LayoutName;
dsdEntry.Nps = layout.TabOrder.ToString();
entries.Add(dsdEntry);
}
return entries;
}
private void PostProcessDSD(DsdData dsd)
{
string str, newStr;
string tmpFile = Path.Combine(this.outputDir, "temp.dsd");
dsd.WriteDsd(tmpFile);
using (StreamReader reader = new StreamReader(tmpFile, Encoding.Default))
using (StreamWriter writer = new StreamWriter(this.dsdFile, false, Encoding.Default))
{
while (!reader.EndOfStream)
{
str = reader.ReadLine();
if (str.Contains("Has3DDWF"))
{
newStr = "Has3DDWF=0";
}
else if (str.Contains("OriginalSheetPath"))
{
newStr = "OriginalSheetPath=" + this.dwgFile;
}
else if (str.Contains("Type"))
{
newStr = "Type=6";
}
else if (str.Contains("OUT"))
{
newStr = "OUT=" + this.outputDir;
}
else if (str.Contains("IncludeLayer"))
{
newStr = "IncludeLayer=TRUE";
}
else if (str.Contains("PromptForDwfName"))
{
newStr = "PromptForDwfName=FALSE";
}
else if (str.Contains("LogFilePath"))
{
newStr = "LogFilePath=" + Path.Combine(this.outputDir, LOG);
}
else
{
newStr = str;
}
writer.WriteLine(newStr);
}
}
File.Delete(tmpFile);
}
[CommandMethod("PlotPdf")]
public void PlotPdf()
{
Database db = HostApplicationServices.WorkingDatabase;
short bgp = (short)Application.GetSystemVariable("BACKGROUNDPLOT");
try
{
Application.SetSystemVariable("BACKGROUNDPLOT", 0);
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<Layout> layouts = new List<Layout>();
DBDictionary layoutDict =
(DBDictionary)db.LayoutDictionaryId.GetObject(OpenMode.ForRead);
foreach (DBDictionaryEntry entry in layoutDict)
{
if (entry.Key != "Model")
{
layouts.Add((Layout)tr.GetObject(entry.Value, OpenMode.ForRead));
}
}
layouts.Sort((l1, l2) => l1.TabOrder.CompareTo(l2.TabOrder));
string filename = Path.ChangeExtension(db.Filename, "pdf");
MultiSheetsPdf plotter = new MultiSheetsPdf(filename, layouts);
plotter.Publish();
tr.Commit();
}
}
catch (System.Exception e)
{
Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
ed.WriteMessage("\nError: {0}\n{1}", e.Message, e.StackTrace);
}
finally
{
Application.SetSystemVariable("BACKGROUNDPLOT", bgp);
}
}
}
}
Heads up. The method, PostProcessDSD, tests are too generic. Client contacted me complaining that one of his files was not plotting. It was named "SOUTH". The test for "OUT" in the string caused the issue. No errors were thrown. Just a good ol' fashion mystery.
Change all tests to include the "=". ie else if (str.Contains("OUT=")) { ...

Request Win32_ComputerSystem class remote

Does somebody have some example C# code about how objects from the Win32_ComputerSystem WMI class can be retrieved from a remote system using hostname, username and password?
Connecting:
try
{
rcOptions = new ConnectionOptions();
rcOptions.Authentication = AuthenticationLevel.Packet;
rcOptions.Impersonation = ImpersonationLevel.Impersonate;
rcOptions.EnablePrivileges = true;
rcOptions.Username = servername + #"\" + username;
rcOptions.Password = password;
mScope = new ManagementScope(String.Format(#"\\{0}\root\cimv2", servername), rcOptions);
mScope.Connect();
if (mScope.IsConnected == true) { MessageBox.Show("Connection Succeeded", "Alert"); } else { MessageBox.Show("Connection Failed", "Alert"); }
if (mScope.IsConnected == true) { lblConnectionStateWarning.Text = "Connected"; } else { lblConnectionStateWarning.Text = "Disconnected"; } //I have a label that displays connectionstate, you can leave that out
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
Getting query with method, loading into dictonary & returning into listview
private void FindWMI(string servername, string classSelection, ConnectionOptions rcOptions, ListView listView)
{
try
{
var dct = new Dictionary<string, string>();
List<ListViewItem> itemsList = new List<ListViewItem>();
oQuery = new ObjectQuery("select * from " + classSelection);
moSearcher = new ManagementObjectSearcher(mScope, oQuery);
moCollection = moSearcher.Get();
Invoke(new MethodInvoker(() =>
{
listView.Items.Clear();
}));
foreach (ManagementObject mObject in moCollection)
{
if (mObject != null)
{
foreach (PropertyData propData in mObject.Properties)
{
if (propData.Value != null && propData.Value.ToString() != "" && propData.Name != null && propData.Name != "")
dct[propData.Name] = propData.Value.ToString();
//Don't forget this, when the result is an array, you want all the strings in that array..
if (propData.Value is Array) { dct[propData.Name] = ""; foreach (string stringArray in (string[])propData.Value) { dct[propData.Name] += stringArray + "\n"; } }
}
}
}
foreach (KeyValuePair<string, string> listItem in dct)
{
ListViewItem lstItem = new ListViewItem(listItem.Key);
lstItem.SubItems.Add(listItem.Value);
itemsList.Add(lstItem);
}
Invoke(new MethodInvoker(() =>
{
listView.Items.AddRange(itemsList.ToArray());
}));
}
catch (Exception) { }
}

Not all code paths return value

Here's my method:
public bool UserExistsActiveDir()
{
try
{
const int ADS_UF_ACCOUNTDISABLE = 0x00000002;
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://domainname;
DirectorySearcher objADSearcher = new DirectorySearcher(de);
de.AuthenticationType = AuthenticationTypes.Secure;
objADSearcher.SearchRoot = de;
objADSearcher.Filter = "(SAMAccountName=" + txtUserName.Text + ")";
SearchResult results = objADSearcher.FindOne();
if (results.ToString() != "")
{
int flags = Convert.ToInt32(results.Properties["userAccountControl"][0].ToString());
//results.Properties["userAccountControl"][0].ToString().Equals("514");
if (Convert.ToBoolean(flags & ADS_UF_ACCOUNTDISABLE))
{
return false;
}
else
{
return true;
}
}
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
return false;
}
}
Where am I going wrong? It says missing return but as far I know, all my return statements are there.
You need an else to this if statement:
if (results.ToString() != "")
What happens if the string is not empty? You need to return a value for that case.
there is no return in case
if (results.ToString() == "")
public bool UserExistsActiveDir()
{
try
{
const int ADS_UF_ACCOUNTDISABLE = 0x00000002;
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://domainname;
DirectorySearcher objADSearcher = new DirectorySearcher(de);
de.AuthenticationType = AuthenticationTypes.Secure;
objADSearcher.SearchRoot = de;
objADSearcher.Filter = "(SAMAccountName=" + txtUserName.Text + ")";
SearchResult results = objADSearcher.FindOne();
if (results.ToString() != "")
{
int flags = Convert.ToInt32(results.Properties["userAccountControl"][0].ToString());
//results.Properties["userAccountControl"][0].ToString().Equals("514");
if (Convert.ToBoolean(flags & ADS_UF_ACCOUNTDISABLE))
{
return false;
}
else
{
return true;
}
}
// <-here
}
catch (Exception ex)
{
lblError.Text = ex.Message.ToString();
return false;
}
}
There's no return value when if (results.ToString() != "") returns false.
All of your returns are inside this if statement:
if (results.ToString() != "")
{
int flags =
Convert.ToInt32(results.Properties["userAccountControl"][0].ToString());
//results.Properties["userAccountControl"][0].ToString().Equals("514");
if (Convert.ToBoolean(flags & ADS_UF_ACCOUNTDISABLE))
{
return false;
}
else
{
return true;
}
}
But what heppens if results.ToString() is ""...there's no return value.
There's no else for the if (results.ToString() != "") statement.
if (results.ToString() != "")
{
...
}
else
{
return false; // or whatever fits in your logic
}
Or without nesting:
if (results.ToString() != "")
{
...
}
return false; // or whatever fits in your logic

Categories

Resources