Throw DirectoryServicesCOMException (0x80072020) when try to RefreshCache for DirectoryEntry - active-directory

I write a very sample test program and run it as local system account in a domain machine. Here is the code look like:
static void Main(string[] args)
{
try
{
System.Console.Out.WriteLine("Test Start");
List<string> temp = new List<string>();
temp.Add(Environment.UserDomainName);
temp.Add("test");
temp.Add("test.com");
temp.Add("dc.test.com");
temp.Add("gc.test.com");
foreach (var i in temp)
{
using (HostingEnvironment.Impersonate())
{
System.Console.WriteLine("LDAP://{0}", i);
DirectoryEntry entry = new DirectoryEntry("LDAP://" + i);
try
{
entry.RefreshCache();
string nativeGuid = entry.NativeGuid;
string path = entry.Path;
string server = entry.Options.GetCurrentServerName();
System.Console.WriteLine("{0} success!", i);
}
catch (Exception e)
{
System.Console.WriteLine("{0}\n {1}", i, e);
}
}
}
System.Console.Out.WriteLine("Test End");
}
catch (Exception e)
{
System.Console.Out.WriteLine("e:Main{0}", e.Message);
}
System.Console.In.ReadLine();
}
The NetBIOS name for the domain is "test", full domain name is "test.com". "dc.test.com" is the DC FQDN and "gc.test.com" is the GC FQDN.
It works fine for "test.com", "dc.test.com"" and "gc.test.com", but it throws DirectoryServicesCOMException (0x80072020) for "test" and "Environment.UserDomainName".
The detail running result is:
Test Start
LDAP://TEST
TEST
System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operati
ons error occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.RefreshCache()
at ConsoleApplication1.Program.Main(String[] args)
LDAP://test
test
System.DirectoryServices.DirectoryServicesCOMException (0x80072020): An operati
ons error occurred.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.RefreshCache()
at ConsoleApplication1.Program.Main(String[] args)
LDAP://test.com
test.com success!
LDAP://dc.test.com
dc.test.com success!
LDAP://gc.test.com
gc.test.com success!
Test End
It works all fine if I run it as domian admin account. Any idea what cause this? Thanks a lots!

What are you actually trying to do? If you're on a machine joined to the domain, you should just do new DirectoryEntry().
As for your error, when you log on to Windows with a local account, the UserDomainName environment variable is set to the local computer name. If that machine's name is the same as the domain's NetBIOS name, then I wouldn't be surprised if Windows gets confused.

Related

What is the use of System.getProperty() while taking Screenshot in Selenium?

I'm running a program for adding screenshot in extent report automatically using selenium. Program is running perfectly,but I want to know the meaning of System.getProperty line in below program .
public class SST
{
public static String getScreenshot(WebDriver driver)
{
TakesScreenshot ts=(TakesScreenshot) driver;
File src=ts.getScreenshotAs(OutputType.FILE);
String path = System.getProperty("user.dir")+"/Screenshot/"+System.currentTimeMillis()+".png";
File destination=new File(path);
try
{
FileUtils.copyFile(src, destination);
} catch (IOException e)
{
System.out.println("Capture Failed "+e.getMessage());
}
return path;
}
}
It is getting the user home directory, for example, C:\Users\user10796675.

Selenium-Extent_Reports: Not able to view the failure screenshots on other Computer/Machine

-Failure Screenshot are visible in Extent_Reports on my local machine. But not able to view the failure screenshot in Extent_Reports on other Computer/Machine.
-When i trigger build from Jenkins, After build successful, Sending email to:Recipient List
To Capture Screenshot
public String captureScreen(String fileName) {
if(fileName =="") {
fileName="Screenshot"; }
File destFile=null;
Calendar calendar =Calendar.getInstance() ;
SimpleDateFormat formater= new SimpleDateFormat("dd_MM_yyy_hh_mm_ss");
File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
String reportDirectory = "/src/main/java/com/test/automation/Demo/screenshot/";
//String reportDirectory= new File(System.getProperty("user.dir")).getAbsolutePath()+"./src/main/java/com/test/automation/Demo/screenshot/";
destFile= new File((String)reportDirectory + fileName +"-" + formater.format(calendar.getTime())+ ".png");
FileUtils.copyFile(srcFile,destFile );
//This will help us to link screen shot in Extent report
Reporter.log("<a href='"+destFile+ "'><img src='" +destFile+"' height='100' width='100'/></a>");
//Reporter.log("<a href='"+destFile.getAbsolutePath()+ "'><img src='" +destFile.getAbsolutePath()+"' height='100' width='100'/></a>");
}
catch(IOException e) {
e.printStackTrace();
}
return destFile.toString();
}
For generating Extent reports with screenshots for Failure test cases
public void getresult(ITestResult result) {
if(result.getStatus()==ITestResult.FAILURE)
{
test.log(LogStatus.ERROR, result.getName()+" Test case FAILED due to below issues: "+result.getThrowable());
String screen = captureScreen("");
test.log(LogStatus.FAIL," Failure Screenshot : "+ test.addScreenCapture(screen));
}}
If You're using remoteWebDriver than it must be augmented before you can use the screenshot capability. Did You try to
WebDriver driver = new RemoteWebDriver();
driver = new Augmenter().augment(driver);
// or for mobile driver
androidDriver.setFileDetector(new LocalFileDetector());
//this is needed when using remoteDriver
Here is how I take screenshot for ExtentReport
File scrFile = driver.getScreenshotAs(OutputType.FILE);
String dest = System.getProperty("user.dir") + "/resources/screenshots/" + dataMethod.getAndroidDriver().getSessionId() + ".png";
File destination = new File(dest);
try {
FileUtils.copyFile(scrFile, destination);
// this is just utility which takes screenshot and copy it to desired destination
dataMethod.setScreenshotPath(destination.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
And on code failure:
#Override
public synchronized void onTestFailure(ITestResult result) {
setTestEndTime(result);
ExtentTest extentTest = methodData.getExtentTest();
extentTest.addScreenCaptureFromPath(methodData.getScreenshotPath());
}
Hope this will help.
I didn't used Extent reports, i have my own implementation for reports. But i am expecting is there is issue with src
<img src='" +destFile+"' height='100' width='100'/></a>");
Here, destFile brings location of image or screenshot which is related to your machine. the same should not be works for others. We have to use relative path, see this
https://www.w3schools.com/html/html_filepaths.asp
And also make sure that when sharing reports, it should contains all requires files and folders also.
Normally, the issue happens as the local files are not allowed to be loaded. So even we put relative or absolute path, that seems not work for many cases.
So I try to take base64screenshot instead, and it displays quite good in Extent Report.
To have the screenshot in folder report, just need to take screenshot as usual.
public static String getBase64Screenshot(WebDriver driver, String screenshotName) throws IOException {
String encodedBase64 = null;
FileInputStream fileInputStream = null;
TakesScreenshot screenshot = (TakesScreenshot) driver;
File source = screenshot.getScreenshotAs(OutputType.FILE);
String destination = windowsPath + "\\FailedTestsScreenshots\\"+screenshotName+timeStamp+".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, finalDestination);
try {
fileInputStream =new FileInputStream(finalDestination);
byte[] bytes =new byte[(int)finalDestination.length()];
fileInputStream.read(bytes);
encodedBase64 = new String(Base64.encodeBase64(bytes));
}catch (FileNotFoundException e){
e.printStackTrace();
}
return encodedBase64;
}
Call it in failure cases:
public synchronized void onTestFailure(ITestResult result) {
System.out.println("==="+methodDes + "=== failed!");
try {
WebDriver driver = (WebDriver) result.getTestContext().getAttribute("driver");
String base64Screenshot = ExtentManager.getBase64Screenshot(driver, result.getName());
MediaEntityModelProvider mediaModel = MediaEntityBuilder.createScreenCaptureFromBase64String(base64Screenshot).build();
test.get().fail("image:", mediaModel);
} catch (IOException e) {
e.printStackTrace();
}
test.get().fail(result.getThrowable().getMessage());
}

How to make a connection localhost and my database

I'm using NetBeans to make a web application and using pgadmin4 for my database. The problem is when I'm making a connection pool.
This is my database http://prntscr.com/hzwn9h and I think the problem is because I want something like that http://prntscr.com/hzwnj2 but I have this http://prntscr.com/hzwnrw. I have tried a lot of solutions but it doesn't work and I don't know what else I have to do. One of the things I have tried was this https://rivaso.wordpress.com/2012/02/19/how-to-setup-a-new-database-in-postgresql-and-glassfish/ but unfortunately unsuccessful
Following code snippet shows how to establish connection for PostgreSQL using jdbc driver. Make sure to add jdbc driver to libraries.
public Connection DBConnect() {
try {
String host = "localhost";//host
String port = "5432";//db port
String db = "exp";//database name
String user = "root";//database username
String pass = "1234";//password
//connection url
String url = "jdbc:postgresql://" + host + ":" + port + "/" + db;
//initialize jdbc driver for postger sql
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
//return connection
return conn;
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
return null;
}
}
reference : jdbc.postgresql.org
public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/yourdatabasename";
Connection conn = DriverManager.getConnection(url, user,password);
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}

How to access sqlite database from webserver and insert record using web services in codenameone

I am developing one application in CN1 that has to do with database, I want the user to enter a pin generated for them. once the user entered the valid pin, the apps will be activated for usage. The problem am having now is how to access the database using webservices. I have followed the webservices wizard tutorial, but all my effort was futile.
This is my snippet code.
private static final String DESTINATION_URL = "http://localhost:8085/CBT_PINS/folder/PINS.db";
ConnectionRequest req = new ConnectionRequest(DESTINATION_URL) {
#Override
protected void handleException(Exception err) {
Log.e(err);
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("An error occured while connecting to the server: " + err);
});
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("Error code from the server: " + code + "\n" + message);
});
}
};
req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);
Please help me out. I dont know what to do next. Thanks
This is because you aren't accessing a webservice. You are trying to open a database with an http URL:
SQLException: path to 'C:\Users\EMMY_OLUWASEGUN.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db'
Triggered by:
Database myDataBase = com.codename1.db.Database.openOrCreate(DESTINATION_URL);
The Database API is local to the device and not remote a webservice is something completely different.
Thanks for your response, Author of CN1. This is the full code below. I am using tomcat server on the local machine to test on the simulator. I am very sure if it works for me on the local machine's server, it will definitely work on the web server
private static final String DESTINATION_URL = "http://localhost:8085/CBT_PINS/folder/PINS.db";
ConnectionRequest req = new ConnectionRequest(DESTINATION_URL) {
#Override
Database myDataBase = com.codename1.db.Database.openOrCreate(DESTINATION_URL);
Cursor c = myDataBase.executeQuery("select pin from PIN_TABLE where id = 1" );
if (c.next()) {
Row r = c.getRow();
String pin = r.getString(0);
Dialog.show("valid pin", pin, "Ok", "Ok");
} else if (!c.next()) {
Dialog.show("Invalid pin", "keep off", "ok", "ok");
}
protected void handleException(Exception err) {
Log.e(err);
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("An error occured while connecting to the server: " + err);
});
}
#Override
protected void handleErrorResponseCode(int code, String message) {
Display.getInstance().callSerially(() -> {
ToastBar.showErrorMessage("Error code from the server: " + code + "\n" + message);
});
}
};
req.setPost(false);
NetworkManager.getInstance().addToQueueAndWait(req);
This is the error code generated for me when I ran the code:
WARNING: Apple will no longer accept http URL connections from applications you tried to connect to http://localhost:8085/CBT_PINS/folder/PINS.db to learn more check out https://www.codenameone.com/blog/ios-http-urls.html
java.sql.SQLException: path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
[Network Thread] 0:0:0,0 - Codename One revisions: 375ed2c938445450f0983f0d18235f61e793a7ee2004
[Network Thread] 0:0:0,0 - Exception: java.io.IOException - path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
Rendering frame took too long 187 milliseconds
at org.sqlite.SQLiteConnection.open(SQLiteConnection.java:156)
at org.sqlite.SQLiteConnection.<init>(SQLiteConnection.java:105)
at org.sqlite.JDBC.createConnection(JDBC.java:113)
at org.sqlite.JDBC.connect(JDBC.java:87)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at com.codename1.impl.javase.JavaSEPort.openOrCreateDB(JavaSEPort.java:7548)
at com.codename1.ui.Display.openOrCreate(Display.java:3690)
at com.codename1.db.Database.openOrCreate(Database.java:59)
at com.mycompany.myapp.MyApplication$1.readResponse(MyApplication.java:283)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:483)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.io.IOException: path to 'C:\Users\EMMY_OLUWASEGUN\.cn1/database/http://localhost:8085/CBT_PINS/folder/PINS.db': 'C:\Users\EMMY_OLUWASEGUN\.cn1\database\http:' does not exist
at com.codename1.impl.javase.JavaSEPort.openOrCreateDB(JavaSEPort.java:7554)
at com.codename1.ui.Display.openOrCreate(Display.java:3690)
at com.codename1.db.Database.openOrCreate(Database.java:59)
at com.mycompany.myapp.MyApplication$1.readResponse(MyApplication.java:283)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:483)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

cannot create new object in ActiveDirectory

I'm trying to add new object to existing organisational unit in Active Directory. Following code is used to do this.
It runs without errors. But new object is not created after this. Please advise what I'm doing wrong here.
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
namespace TestAdObjectCreation
{
class Program
{
static void Main(string[] args)
{
DirectoryEntry root = new DirectoryEntry("LDAP://servername/OU=Services,OU=PCX,DC=q2q,DC=xenyq,DC=com", "Administrator", "pass");
DirectoryEntry newItem = root.Children.Add("test_node", "valid_schema_class_name");
root.CommitChanges();
root.Close();
root.Dispose();
}
}
}
What kind of object are you trying to create??
First of all, all LDAP object always have a prefix, DC= for domain component, OU= for organizational unit, CN= for common name.
Also, many LDAP objects have minimal requirements for what they need to be considered valid; e.g. a user or a group must have a unique samAccountName.
So again - what are you trying to create??
If you wrap your creation code into a try..catch - do you get any exceptions? If so - what are they??
static void Main(string[] args)
{
DirectoryEntry root = new DirectoryEntry("LDAP://servername/OU=Services,OU=PCX,DC=q2q,DC=xenyq,DC=com", "Administrator", "pass");
try
{
DirectoryEntry newItem = root.Children.Add("CN=test_node", "valid_schema_class_name");
root.CommitChanges();
}
catch(Exception exc)
{
string error = exc.GetType().FullName + ": " + exc.Message;
}
}

Resources