How to use extent reports for individual steps - extentreports

How can we use extent report logs for individual steps. My main test is as follows
#Test(testName = "Validate SinglePage and Multiple Page", enabled = true, priority = 1, groups = {"Section Formatting"})
public void SingleSection(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String SecItem1, String SecItem2, String DispStyle, String fType) throws InterruptedException {
extentTest = extent.startTest("SingleSection");
extentTest.log(LogStatus.INFO, "Login to the system");
login.loginToTenant(username, password);
extentTest.log(LogStatus.INFO, "Access the content menu");
// select view from content menu button
createContentMenuButton.setContentMenuButton();
extentTest.log(LogStatus.INFO, "Select the view");
// choose view
reportView.selectView(viewName);
extentTest.log(LogStatus.INFO, "Create the report");
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
extentTest.log(LogStatus.INFO, "Add fields to sections");
// Adds fields to sections
sections.dragAndDropToSections(SecItem1, SecItem2);
For example If I want to put steps for one of the methods ex- loginToTenant, the system throughs null value exception error.
the code for the method loginToTenant is as follows
public class loginPage extends ConfigReader {
WebDriver driver;
public ExtentReports extent;
public ExtentTest extentTest;
public loginPage(WebDriver driver) {
this.driver = driver;
}
// locators for login page
By userName = By.name("email");
By password = By.name("password");
By submitButton = By.id("logonButton");
By licenseWarning = By.partialLinkText("Click Here To Continue");
By plusButton = By.className("create-menu-container");
By banner = By.className("i4sidenav_width");
By logout = By.id("logoffBtn");
/**
* perform login to yellowfin and verify successful login
*
* #param uName
* #param passwd
* #return
*/
public String loginToTenant(String uName, String passwd) {
String loginmsg = null;
long d = 1000;
try {
extentTest.log(LogStatus.INFO, "Login to the system"); //I am getting an error on this line with null pointer exception
driver.findElement(userName).clear();
driver.findElement(userName).sendKeys(uName);
driver.findElement(password).clear();
driver.findElement(password).sendKeys(passwd);
driver.findElement(submitButton).click();

If you wants to create individual steps for loginToTenant method, you can create extentReport in loginPage class similarly. And it will create individual steps for it.

Related

Old ASP.NET code works on one computer, not on another?

So in my global.asax, I've got the following code:
Inventory.BusinessTier bt = new Inventory.BusinessTier();
string UserLogin = bt.ExtractLogin (Request.ServerVariables ["AUTH_USER"]);
Inventory.User myUser = new Inventory.User (UserLogin);
Session ["User"] = myUser;
It works just fine on one development PC, but using the same version of Visual Studio, it craps out on the third line with this error:
System.TypeInitializationException: 'The type initializer for
'Inventory.DataTier' threw an exception.'
Inner Exception
NullReferenceException: Object reference not set to an instance of an
object.
Other than a line adding impersonation in my web.config (it has to be there now), I haven't changed a single thing. Is there a way to get more info on this? I can't even trace it, because if I put a debug line in the User object constructor, it never hits it. I'm at a bit of a loss. Would appreciate any advice.
EDIT to answer questions below:
InventoryUser is a very simple user object that reads the current from the database and stores some basic user info in properties, such as UserID, Role, RoleID, and IsAdmin.
The DataTier class is a class that interacts with the database. It is used in multiple projects, so I'm quite sure it's not the problem. I tried to paste in the code anyway, but it exceeded the limit for a post.
I'm reasonably sure the problem is related to the user class. It's short, so I can paste it in here:
using System;
using System.Data;
// This is the user business object. It contains information pertaining to the current user of the application. Notably, it
// contains the department ID, which determines what inventory items the user will see when using the application. Only
// specified employees with admin access can see all items for all departments, and that is determined by a specific department ID.
namespace Inventory {
public class User {
private Guid _UserID;
private Guid _RoleID;
private Guid _UserDepartmentID;
private string _UserRole = "";
private string _UserName = "";
private bool _IsAuthorizedUser = false;
private bool _IsAdmin = false;
// Attribute declarations
public Guid UserID {
get {
return _UserID;
}
set {
_UserID = value;
}
}
public string UserRole {
get {
return _UserRole;
}
set {
_UserRole = value;
}
}
public Guid RoleID {
get {
return _RoleID;
}
set {
_RoleID = value;
}
}
public string UserName {
get {
return _UserName;
}
set {
_UserName = value;
}
}
public Guid UserDepartmentID {
get {
return _UserDepartmentID;
}
set {
_UserDepartmentID = value;
}
}
public bool IsAdmin {
get {
return _IsAdmin;
}
set {
_IsAdmin = value;
}
}
public bool IsAuthorizedUser {
get {
return _IsAuthorizedUser;
}
set {
_IsAuthorizedUser = value;
}
}
// -----------------
// - Constructor -
// -----------------
public User (string UserLogin) {
string ShortUserLogin = ExtractLogin (UserLogin);
GetUser (ShortUserLogin);
}
// ------------------
// - ExtractLogin -
// ------------------
public string ExtractLogin (string Login) {
// The domain and "\" symbol must be removed from the string, leaving only the user name.
int pos = Login.IndexOf (#"\");
return Login.Substring (pos + 1, Login.Length - pos - 1);
}
// -------------
// - GetUser -
// -------------
// This method is called to fill the user object based on the user's login. It ultimately gets authorized user data
// from the user table.
public void GetUser (string UserName) {
DataTier dt1 = new DataTier();
DataTable dt = dt1.GetUserInfo (UserName);
int RecordCount = dt.Rows.Count;
switch (RecordCount) {
case 1: // There is one user name match, as there should be. This is the likely situation.
DataRow dr = dt.Rows[0];
UserID = (Guid)dr ["UserID"];
UserRole = (string)dr ["UserRole"];
RoleID = (Guid)dr ["RoleID"];
this.UserName = UserName;
UserDepartmentID = (Guid)dr ["DepartmentID"];
IsAdmin = (bool)dr ["IsAdmin"];
IsAuthorizedUser = true;
break;
case 0: // There are no user name matches (unauthorized use).
IsAdmin = false;
IsAuthorizedUser = false;
break;
default: // There are multiple user name matches (problem!).
IsAdmin = false;
IsAuthorizedUser = false;
break;
}
}
}
}

Extent report logs for Test Steps is not working

I have a TestNG test that has multiple methods. The extent report works in the main class but when I try to write logs for the other methods I am getting null pointer exception. All the tutorials point to writing logs in the main method but not to the other methods. I have been struggling to find a solution for this for a week now. Can somebody help me please ? Thanks
My code is some thing like this
#Test
public void TestOne()
{
extentTest = extent.startTest("TestOne");
Login.LoginToClient();
Access.AccessMainPage();
-
-
}
Public void LoginToClient()
{
***How can write an extent report log here for example - "Enter Username"
driver.findElement(By.id("username")).SendKeys(username)
-
-
}
The following is written in the main test
#BeforeTest
public void setExtent(){
extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
extent.addSystemInfo("Host Name", "Calcutta");
extent.addSystemInfo("User Name", "Admin");
extent.addSystemInfo("Environment", "QA");
}
#AfterMethod
public void tearDown(ITestResult result) throws IOException {
if(result.getStatus()==ITestResult.FAILURE){
//to add name in extent report
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getName());
//to add error/exception in extent report
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getThrowable());
String screenshotPath = Screenshots.getScreenshot(driver, result.getName());
//to add screenshot in extent report
extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath));
}
else if(result.getStatus()==ITestResult.SKIP){
extentTest.log(LogStatus.SKIP, "Test Case SKIPPED IS " + result.getName());
}
else if(result.getStatus()==ITestResult.SUCCESS){
extentTest.log(LogStatus.PASS, "Test Case PASSED IS " + result.getName());
}
extent.endTest(extentTest);
}
My Full code is here
package yellowfin.bi.test;
import java.awt.AWTException;
import java.io.IOException;
import java.lang.reflect.Method;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import y.bi.create.reports.charts.ContentMenuButton;
import y.bi.create.reports.charts.ReportChartBuilder;
import y.bi.create.reports.charts.ReportFormattingPage;
import y.bi.create.reports.charts.ViewForReport;
import y.bi.login.loginPage;
import y.bi.logout.Logout;
import y.bi.screenshots.Screenshots;
import y.bi.utils.Printscreen;
import y.bi.utils.BrowserFactory;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ReportFormatting {
private EventFiringWebDriver driver;
private loginPage login;
private Logout logout;
private ContentMenuButton createContentMenuButton;
private ViewForReport reportView;
private ReportChartBuilder createChart;
Printscreen ps;
private ReportFormattingPage reportFormattingPage;
public ExtentReports extent;
public ExtentTest logger;
#BeforeSuite(enabled = true)
public void setUpTheTest() {
driver = (EventFiringWebDriver) BrowserFactory.selectBrowser("chrome");
}
#Parameters({ "yellowfinURL" })
#BeforeTest(enabled = true)
public void instantiatePages(String url) {
driver.get(url);
login = new loginPage(driver);
logout = new Logout(driver);
createContentMenuButton = new ContentMenuButton(driver);
reportView = new ViewForReport(driver);
createChart = new ReportChartBuilder(driver);
ps = new Printscreen(driver);
reportFormattingPage = new ReportFormattingPage(driver);
}
#BeforeTest
public void setExtent(){
extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
extent.addSystemInfo("Host Name", "Calcutta");
extent.addSystemInfo("User Name", "Admin");
extent.addSystemInfo("Environment", "QA");
}
#AfterMethod(alwaysRun=true)
public void TearDown_AM(ITestResult result) throws IOException
{
System.out.println("#After Method");
try
{
if(result.getStatus()==ITestResult.FAILURE)
{
String screenshotPath = Screenshots.getScreenshot(driver, result.getName());
String image= logger.addScreenCapture(screenshotPath);
System.out.println(image);
String TestCaseName = this.getClass().getSimpleName() + " Test Case Failure and Title/Boolean Value Failed";
logger.log(LogStatus.FAIL, TestCaseName + logger.addScreenCapture(screenshotPath));
}
else if(result.getStatus()==ITestResult.SUCCESS)
{
logger.log(LogStatus.PASS, this.getClass().getSimpleName() + " Test Case Success");
}
else if(result.getStatus()==ITestResult.SKIP)
{
logger.log(LogStatus.SKIP, this.getClass().getSimpleName() + " Test Case Skipped");
}
extent.endTest(logger);
extent.flush();
}
catch(Throwable t)
{
logger.log(LogStatus.ERROR,t.fillInStackTrace());
}
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "fontType" ,"fontSize"})
#Test(testName = "validateDataSection", enabled = true, groups = {"Report Formatting : Data"}, alwaysRun = true, priority=1)
public void ValidateDataSection(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String ftype, String fsize) {
logger = extent.startTest("ValidateDataSection");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
//Checks the style "Font Type, Font Size, Bold Italic"
reportFormattingPage.DataSection(ftype,fsize);
// Access Row Highlight
reportFormattingPage.RowHighlight();
logout.performLogout();
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "headerFontType", "headerFontSize", "borderWidth"})
#Test(testName = "Validate Column & Row Headings and Border", enabled = false, groups = {"Report Formatting : Column & Row Headings and Border"}, alwaysRun = true, priority=1)
public void ValidateColumnandRowHeadingsandBorder(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String headerFontType, String headerFontSize, String borderWidth) {
logger = extent.startTest("ValidateColumnandRowHeadingsandBorder");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
// validates the column and Row headings
reportFormattingPage.ColumnAndRowHandling(headerFontType, headerFontSize);
// Validates the border
reportFormattingPage.Border(borderWidth);
logout.performLogout();
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "displayTitleFontType", "displayTitleFontSize", "displayDescFontType", "displayDescFontSize"})
#Test(testName = "Validate Title and Description", enabled = false, groups = {"Report Formatting : Title and Description"}, alwaysRun = true, priority=1)
public void ValidateTitleandDescription(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String displayTitleFontType, String displayTitleFontSize, String displayDescFontType, String displayDescFontSize) {
logger = extent.startTest("ValidateTitleandDescription");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
//Validates Title and Description
reportFormattingPage.TitleAndDescription(displayTitleFontType,displayTitleFontSize,displayDescFontType,displayDescFontSize);
logout.performLogout();
}
#Parameters({ "userName", "passsword", "viewName", "rf1", "rf2", "rf3", "rf4", "rf5", "displayTitleFontType", "displayTitleFontSize", "displayDescFontType", "displayDescFontSize"})
#Test(testName = "Validate header / Footer and Table sort", enabled = false, groups = {"Report Formatting : header / Footer and Table sort"}, alwaysRun = true, priority=1)
public void ValidateHeaderFooterandTableSort(String username, String password, String viewName, String r1, String r2, String r3, String r4, String r5, String displayTitleFontType, String displayTitleFontSize, String displayDescFontType, String displayDescFontSize) {
logger = extent.startTest("ValidateHeaderFooterandTableSort");
login.loginToTenant(username, password);
// select view from content menu button
createContentMenuButton.setContentMenuButton();
// choose view
reportView.selectView(viewName);
// create the report in report builder
createChart.createReport(r1, r2, r3, r4, r5);
//Validates Header and Footer page
reportFormattingPage.HeaderAndFooter();
//Validates Table sort
reportFormattingPage.TableSort();
logout.performLogout();
}
#AfterTest
public void endReport(){
extent.flush();
extent.close();
driver.quit();
}
}
import java.awt.Robot;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.BeforeTest;
import org.testng.asserts.SoftAssert;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import yellowfin.bi.screenshots.Screenshots;
public class ReportFormattingPage {
static WebDriver driver;
static long d = 2000;
String xpathElements="//div[#class='toggleSwitchSliderInner']";
String workingDir = System.getProperty("user.dir");
ReportFormat rf = new ReportFormat();
SoftAssert sa= new SoftAssert();
Screenshots screenshot = new Screenshots();
public ExtentReports extent;
public ExtentTest logger;
#BeforeTest
public void setExtent(){
extent = new ExtentReports(System.getProperty("user.dir")+"/test-output/ExtentReport.html", true);
extent.addSystemInfo("Host Name", "Calcutta");
extent.addSystemInfo("User Name", "Admin");
extent.addSystemInfo("Environment", "QA");
}
#SuppressWarnings("static-access")
public ReportFormattingPage(WebDriver driver) {
this.driver = driver;
}
public void DataSection(String FontType, String FontSize)
{
try {
logger = extent.startTest("ValidateDataSection");
//Click on Report Format
logger.log(LogStatus.INFO, "Access Report Format Button");
rf.accessReportFormat(driver);
//Click on the Toggle switch
driver.findElement(By.cssSelector("div.toggleSwitchSliderInner")).click();
Thread.sleep(d);
//Select the font type
new Select(driver.findElement(By.cssSelector("div.fontDropDown > div.styledSelect.customSelect > select"))).selectByVisibleText(FontType);
Thread.sleep(d);
//Select the font size
driver.findElement(By.cssSelector("input.broadcastInput")).clear();
driver.findElement(By.cssSelector("input.broadcastInput")).sendKeys(FontSize);
//Click on Bold
driver.findElement(By.cssSelector("div.fontStyleOptions > div > img")).click();
Thread.sleep(d);
//Select italic and underline
driver.findElement(By.xpath("//img[#src='images/format_italic.png']")).click();
driver.findElement(By.xpath("//img[#src='images/format_underline.png']")).click();
//Changing the color of the text
driver.findElement(By.xpath("//div[#class='sp-preview-inner']")).click();
rf.dragAndDrop(driver);
driver.findElement(By.xpath("(//span[#id='chooseColourText'])")).click();
//Row shading Default
driver.findElement(By.xpath("//td[contains(text(), 'Default')]")).click();
// Row Shading Alternative ------------------------------------------------------------
driver.findElement(By.xpath("//td[contains(text(), 'Alternating')]")).click();
//click on the Alternate Row Color
driver.findElement(By.xpath("(//div[contains(text(), 'Define a color to be applied to every second row in the table.')]//following::div[#class='backboneColourPicker'])[1]")).click();
//Select the color
driver.findElement(By.xpath("(//span[#style='background-color:rgb(143, 80, 157);'])[3]")).click();
// Click on close and access the design page
rf.clickCloseAndAccessDesignPage(driver);
Thread.sleep(d);
screenshot.captureScreenShot(driver, "RowShadingAlternative");
//Click on Report Format
rf.accessReportFormat(driver);
//RowShading none ------------------------------------------------------------------------------------
driver.findElement(By.xpath("//td[contains(text(), 'None')]")).click();
// Click on close and access the design page
rf.clickCloseAndAccessDesignPage(driver);
screenshot.captureScreenShot(driver, "RowShadingNone");
//Click on Report Format
rf.accessReportFormat(driver);
rf.clickCloseAndAccessDesignPage(driver);
//Assertions
rf.DataSectionAssertions(driver);
Thread.sleep(d);
screenshot.captureScreenShot(driver, "RowShadingDefault");
}
catch (Exception e) {
e.printStackTrace();
}
}
public void RowHighlight()
{
try {
//Click on Report Format
rf.accessReportFormat(driver);
// Click on the toggle switch for the Row Highlight field
driver.findElement(By.cssSelector("div.controlContainer > div.toggleSwitchSlider > div.toggleSwitchSliderInner")).click();
// Click on Row Highlight color
driver.findElement(By.cssSelector("div.sp-preview-inner.no-colour")).click();
// Select the color
driver.findElement(By.xpath("(//span[#style='background-color:rgb(124, 187, 0);'])[3]")).click();
// Click on close and access the design page
rf.clickCloseAndAccessDesignPage(driver);
Robot robot = new Robot();
robot.mouseMove(200,600);
robot.delay(1500);
robot.mouseMove(200,900);
Thread.sleep(d);
screenshot.captureScreenShot(driver, "RowHighlight");
}
catch (Exception e) {
e.printStackTrace();
}
}
Please check these links for the answer:
How to print logs by using ExtentReports listener in java?
https://github.com/cbeust/testng/blob/master/src/main/java/org/testng/reporters/EmailableReporter2.java
If you have a Reporting Class say which Listens to the TestNG Listner and have ExtentReport code implemented in it you can get the TestCase Steps using Reporter Object
please see below.
Note that Reporter .log of TestNG does not have any definition for Type of Log like INFO, FATAL etc.. It just adds the Log Message.
Test case:
public class TC_1 extends BaseClass{
#Test (priority=0)
public void addNotes() throws Exception
{
if (super.search("VALUE"))
{
logger.info("Search is Successful");
Reporter.log("Search is Successful");
Assert.assertTrue(true);
}
}
Reporting:
public class Reporting extends TestListenerAdapter
{
public ExtentHtmlReporter htmlReporter;
public ExtentReports extent;
public ExtentTest logger;
public void onStart(ITestContext testContext)
{
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());//time stamp
String repName="Test-Report-"+timeStamp+".html";
htmlReporter=new ExtentHtmlReporter(System.getProperty("user.dir")+ "/test-output/"+repName);//specify location of the report
htmlReporter.loadXMLConfig(System.getProperty("user.dir")+ "/extent-config.xml");
extent=new ExtentReports();
extent.attachReporter(htmlReporter);
htmlReporter.config().setDocumentTitle("Test Project");
htmlReporter.config().setReportName("Functional Test Automation Report");
htmlReporter.config().setTestViewChartLocation(ChartLocation.TOP);
htmlReporter.config().setTheme(Theme.DARK);
}
public void onTestSuccess(ITestResult tr)
{
logger=extent.createTest(tr.getName());
logger.log(Status.PASS,MarkupHelper.createLabel(tr.getName(),ExtentColor.GREEN));
List<String> reporterMessages = Reporter.getOutput(tr);
for (int i = 0; i < reporterMessages.size(); i++)
{
System.out.println(reporterMessages.get(i));
logger.info(reporterMessages.get(i));
}
}
}
Firstly, I recommend to use Version 3 instead of Version 2,
As I can see in your Code, You have define Test definition but there is no such logs for that method in which you wants to generate,
Please Refer as Following, to generate logs:
You can use same way in any method,
extentTest.log(LogStatus.INFO, "Test Case Details");
Here object of ExtentTest need to declare as Class variable, So you can access it anywhere within class.
If you wants to create different Test section for Login.LoginToClient(); method, you can define it like:
Public void LoginToClient()
{
extentTest = extent.startTest("Login Test");
driver.findElement(By.id("username")).SendKeys(username);
extentTest.log(LogStatus.INFO, "User Name: " +username);
}
Hope it will works as you want to generate.

ActiveAndroid NPE from execute

I am following https://github.com/pardom/ActiveAndroid/wiki/Querying-the-database to incorporate activeandroid in my application like so:
#Table(name="Contact")
public class Contact extends Model implements Serializable, Comparable {
public Contact() {
super();
}
public Contact(String id, String n, String c, String p, String addr, String phone,
String fb, String twit, String yt) {
super();
candID = id;
name = n;
chamber = c;
party = p;
address = addr;
phoneNo = phone;
facebook = fb;
twitter = twit;
youtube = yt;
}
public static List<Contact> getCachedContactsByState(String stateAbbr) {
/*return new Select().from(Contact.class).where("state = ?",
stateAbbr).execute();*/
Select s = new Select();
From f = s.from(Contact.class);
f = f.where("state = ?", stateAbbr);
List<Contact> cachedContacts = f.execute();
return cachedContacts;
}
According to my debugger, the f.execute throws a null pointer exception, and f is not null.
just making sure, the tutorial didn't mention needing to install sqlite before using activeandroid, and it said the point of activeandroid was to use objects and their functions to do CRUD on sqlite, so I'm assuming I just needed to follow the tutorial to create and query my sqlite db?
Looks like you've forgotten to call ActiveAndroid.initialize() with a valid Context. See the Getting Started section from the documentation you linked to.

C# Error: Cannot read from a Closed reader...?

I have this code below. Gets data and sets data property to the values gathered.
public struct TrblShootData
{
public List<string> Logins;
public IEnumerable<Hieracrhy> Hierarchy;
public IEnumerable<EmployeeTeam> EmpTeam;
}
public TrblShootData TroubleShootData
{
get;
private set;
}
class DataGetter
{
public void GetData(string FirstName, string LastName, string Login, string Email, bool isFirstName, bool isLastName, bool isLogin, bool isEmail)
{
List<string> logins = null;
IEnumerable<Hieracrhy> hier = null;
IEnumerable<EmployeeTeam> tmemp = null;
TrblShootData tsData = new TrblShootData();
queries q = BuildQuery(FirstName, LastName, Login, Email, isFirstName, isLastName, isLogin, isEmail);
if (q.isValidQueries)
{
DataContext1 mscDB = new DataContext1 ();
using (DataContext2 opsDB = new DataContext2 ())
{
tmemp = opsDB.ExecuteQuery<EmployeeTeam>(q.qryEmployeeTeam);
}
using (DataContext3 rptDB = new DataContext3 ())
{
hier = rptDB.ExecuteQuery<Hieracrhy>(q.qryHierarchy);
if (hier != null)
{
logins = hier.Select(s => s.SalesRepLogin).Distinct().ToList();
}
}
tsData.EmpTeam = tmemp.Select(r=>r);
tsData.Hierarchy = hier.Select(r => r);
tsData.Logins = logins.Select(r => r).ToList();
TroubleShootData = tsData;
}//if
}
}
From another class I attempt to do this:
tshtr.GetData(txtFirstName.Text, txtLastName.Text, txtLogin.Text, txtEmail.Text, chkFirstName.Checked, chkLastName.Checked, chkLogin.Checked, chkEmail.Checked);
gvEmpTeams.DataSource = tshtr.TroubleShootData.EmpTeam;
gvHierarchy.DataSource = tshtr.TroubleShootData.Hierarchy;
gvEmpTeams.DataBind();
gvHierarchy.DataBind();
But at the DataBind() I get an error saying that I cannot read from a closed reader.
I'm not seeing why it would throw this error when I've set my property as above after I've assigned the values in the usings. So I'm not seeing how this is trying to use a closed reader.
Thanks for any help!
Because of deferred execution, your query only executes when the data-binding engine enumerates its results, after you close the DataContext.
You need to call .ToList() before closing the DataContext to force it to be evaluated immediately.

Not getting value in midlet from servlet

I'm trying to send data from a midlet to a servlet and recieve back a response from the servlet but I don't get any value in response. I've tried to print it on command window and it seems to be null yet I expect only two values "ok" or "error". Please help me check the code and let me know what I should do to get the response right on the midlet. My code is below:
import javax.microedition.midlet.*;//midlet class package import
import javax.microedition.lcdui.*;//package for ui and commands
import javax.microedition.io.*;//
import java.io.*;
/**
* #author k'owino
*/
//Defining the midlet class
public class MvsMidlet extends MIDlet implements CommandListener {
private boolean midletPaused = false;//variable for paused state of midlet
//defining variables
private Display display;// Reference to Display object
private Form welForm;
private Form vCode;//vote code
private StringItem welStr;
private TextField phoneField;
private StringItem phoneError;
private Command quitCmd;
private Command contCmd;
//constructor of the midlet
public MvsMidlet() {
display = Display.getDisplay(this);//creating the display object
welForm = new Form("THE MVS");//instantiating welForm object
welStr = new StringItem("", "Welcome to the MVS, Busitema's mobile voter."
+ "Please enter the your phone number below");//instantiating welStr string item
phoneError = new StringItem("", "");//intantiating phone error string item
phoneField = new TextField("Phone number e.g 0789834141", "", 10, 3);//phone number field object
quitCmd = new Command("Quit", Command.EXIT, 0);//creating quit command object
contCmd = new Command("Continue", Command.OK, 0);//creating continue command object
welForm.append(welStr);//adding welcome string item to form
welForm.append(phoneField);//adding phone field to form
welForm.append(phoneError);//adding phone error string item to form
welForm.addCommand(contCmd);//adding continue command
welForm.addCommand(quitCmd);//adding quit command
welForm.setCommandListener(this);
display.setCurrent(welForm);
}
//start application method definition
public void startApp() {
}
//pause application method definition
public void pauseApp() {
}
//destroy application method definition
public void destroyApp(boolean unconditional) {
}
//Command action method definition
public void commandAction(Command c, Displayable d) {
if (d == welForm) {
if (c == quitCmd) {
exitMidlet();//call to exit midlet
} else {//if the command is contCmd
//place a waiting activity indicator
System.out.println("ken de man");
Thread t = new Thread() {
public void run() {
try {
//method to connect to server
sendPhone();
} catch (Exception e) {
}//end of catch
}//end of ru()
};//end of thread
t.start();//starting the thread
}//end of else
}//end of first if
}//end of command action
//defining method to exit midlet
public void exitMidlet() {
display.setCurrent(null);
destroyApp(true);
notifyDestroyed();
}//end of exitMidlet()
//defining sendPhone method
public void sendPhone() throws IOException {
System.out.println("ken de man");//check
HttpConnection http = null;//HttpConnection variable
OutputStream oStrm = null;//OutputStream variable
InputStream iStrm = null;//InputStream variable
String url = "http://localhost:8084/MvsWeb/CheckPhone";//server url
try {
http = (HttpConnection) Connector.open(url);//opening connection
System.out.println("connection made");//checking code
oStrm = http.openOutputStream();//opening output stream
http.setRequestMethod(HttpConnection.POST);//setting request type
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//setting content type
byte data[] = ("phone=" + phoneField.getString()).getBytes();
oStrm.write(data);
iStrm = http.openInputStream();//openning input stream
if (http.getResponseCode() == HttpConnection.HTTP_OK) {
int length = (int) http.getLength();
String str;
if (length != -1) {
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
} else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) {
bStrm.write(ch);
}
str = new String(bStrm.toByteArray());
bStrm.close();
}
System.out.println("de man");
System.out.println(str);
if (str.equals("ok")) {
//change to vcode form
} else {
//add error message to phone_error stingItem
}
}
} catch (Exception e) {
}
}
}//end of class definition
//servlet
import java.io.*;//package for io classes
import javax.servlet.ServletException;//package for servlet exception classes
import javax.servlet.http.*;
import java.sql.*;//package for sql classes
/**
*
* #author k'owino
*/
public class CheckPhone extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//declaring variables
PrintWriter pw;//PrintWriter object
String pnum;//phone parameter sent from client
Connection con = null;//connection variable
String dbDriver = "com.jdbc.mysql.Driver";//the database driver
String dbUrl = "jdbc:mysql://localhost/mvs_db";//the database url
String dbUser = "root";//database user
String dbPwd = "";//database password
PreparedStatement pstmt = null;//Prepared statement variable
String query = "select * from student where stud_phone = ?;";
ResultSet rs = null;//resultset variable
String dbPhone=null;//phone from database
//getting the "phone" parameter sent from client
pnum = req.getParameter("phone");//getting the "phone" parameter sent from client
System.out.println(pnum);
//setting the content type of the response
res.setContentType("text/html");
//creating a PrintWriter object
pw = res.getWriter();
pw.println("ken");
try{//trying to load the database driver and establish a connection to the database
Class.forName(dbDriver).newInstance();//loading the database driver
con = DriverManager.getConnection(dbUrl,dbUser,dbPwd);//establishing a connection to the database
System.out.println("connection established");
}
catch(Exception e){
}
//trying to query the database
try{
pstmt = con.prepareStatement(query);//preparing a statement
pstmt.setString(1, pnum);//setting the input parameter
rs = pstmt.executeQuery();//executing the query assigning to the resultset object
//extracring data from the resultset
while(rs.next()){
dbPhone = rs.getString("stud_phone");//getting the phone number from database
}//end of while
if(pnum.equals(dbPhone)){
pw.print("ok");
pw.close();
}
else{
pw.print("error");
pw.close();
}
}
catch(Exception e){
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Resources