TypeInitializationException with separate Class - oracle

i have a little program to monitor my oracle DB's.
So i have a Class DBConn: (extremely shortened)
class DBConn
{
private OracleConnection conn_oraconn = new OracleConnection();
OracleCommand cmd_oracmd;
static string str_oraconn;
OracleDataReader dr;
Logger log = new Logger();
private String str_cname;
public DBConn(String str_connname)
{
str_cname = str_connname;
}
}
In the main Form i initialize this by: (extremely shortened)
public partial class frm_main : Form
{
TNSEntries availtns = new TNSEntries();
bool gettns = false;
Logger applog = new Logger();
//List<DBConn> dbconn = new List<DBConn>();
DBConn mydb;
String std_user, std_password, std_db;
private void btn_connect_Click(object sender, EventArgs e)
{
mydb = new DBConn(cmb_dbs.SelectedItem.ToString());
}
}
So i start the programm and if i click the button i get the error in the line
private OracleConnection conn_oraconn = new OracleConnection(); in CLass DBConn. I don't understand why.
If i put this member directly under public partial class frm_main : Form it works.

i found the error.
The "OracleDataAccess.ddl" was the reason. I switched the version and all is fine.
Thanks!

Related

How to refresh tableview after adding the new data in JavaFx

I am currently working on JAVA FX application to fetch the user's information from JIRA REST API. I want to have a refresh button and on clicking it,the table view must be shown with the newly added data.
Please have a look at the code.
My POJO class
public class Issues {
private String jiraKey;
private String jiraSummary;
private String jiraPriority;
private String jiraAssignee;
private String jiraIssueType;
private Hyperlink hyperLink;
private String loghours;
private String commentLogHours;
public Issues(String jiraKey, String jiraSummary, String jiraPriority, String jiraAssignee, String jiraIssueType) {
super();
this.hyperLink = new Hyperlink(jiraKey);
this.jiraSummary = jiraSummary;
this.jiraPriority = jiraPriority;
this.jiraAssignee = jiraAssignee;
this.jiraIssueType = jiraIssueType;
this.hyperLink = hyperLink;
this.loghours = loghours;
this.commentLogHours = commentLogHours;
}
public String getJiraKey() {
return jiraKey;
}
public void setJiraKey(String jiraKey) {
this.jiraKey = jiraKey;
}
//getters and setters
}
My Observable list method which populates the data to table
Class ABC{
public ObservableList<Issues> issueJsonList(){
// A processed arraylist
ObservableList<Issues> data = FXCollections.observableList(list);
return data;
}
}
Here's my tableview code.
#SuppressWarnings({ "unchecked", "rawtypes" })
public TableView<Issues> initTable() throws IOException, URISyntaxException {
TableView<Issues> table = new TableView<Issues>();
table.setEditable(true);
TableColumn<Issues, Hyperlink> jiraKey = new TableColumn<>(keyField);
jiraKey.setCellValueFactory(new PropertyValueFactory("hyperLink"));
jiraKey.setCellFactory(new HyperlinkCell());
TableColumn jiraPriority = new TableColumn(priorityField);
TableColumn jiraIssueType = new TableColumn(issueTypeField);
TableColumn jiraSummary = new TableColumn(summaryField);
TableColumn jiraAssignee = new TableColumn(assigneeField);
TableColumn workLogCol = new TableColumn(workLogField);
TableColumn timeSpent = new TableColumn(timeSpentField);
TableColumn commentTimeLog = new TableColumn(commentField);
workLogCol.getColumns().addAll(timeSpent, commentTimeLog);
jiraSummary.setCellValueFactory(new PropertyValueFactory("jiraSummary"));
jiraIssueType.setCellValueFactory(new PropertyValueFactory("jiraIssueType"));
jiraPriority.setCellValueFactory(new PropertyValueFactory("jiraPriority"));
jiraAssignee.setCellValueFactory(new PropertyValueFactory("jiraAssignee"));
timeSpent.setCellValueFactory(new PropertyValueFactory("getTimeSpent"));
timeSpent.setCellFactory(TextFieldTableCell.forTableColumn());
commentTimeLog.setCellValueFactory(new PropertyValueFactory("getComment"));
commentTimeLog.setCellFactory(TextFieldTableCell.forTableColumn());
timeSpent.setOnEditCommit(new EventHandler<CellEditEvent<JiraAuth, String>>() {
public void handle(CellEditEvent<JiraAuth, String> t) {
JiraAuth.setTimeSpent(t.getNewValue());
}
});
commentTimeLog.setCellFactory(TextFieldTableCell.forTableColumn());
commentTimeLog.setOnEditCommit(new EventHandler<CellEditEvent<JiraAuth, String>>() {
public void handle(CellEditEvent<JiraAuth, String> t) {
JiraAuth.setWorkLogComment(t.getNewValue());
int i = t.getTablePosition().getRow();
String abc = table.getColumns().get(0).getCellData(i).toString();
String finalStr = abc.substring(abc.indexOf("]") + 1);
JiraAuth.setWorkLogJiraKey(finalStr);
}
});
table.getColumns().setAll(jiraKey, jiraSummary, jiraPriority, jiraAssignee, jiraIssueType);
IssuesJsonParser issueObject = new IssuesJsonParser();
ObservableList<Issues> data = issueObject.issueJsonList();
table.setItems(data);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
return table;
}
upon calling the refresh button,
buttons[0] = new Button("Refresh");
buttons[0].setOnAction(event->{
initTable().refresh();
});
nothing happens. Please help!!

Can CRM OrgService and Context be static?

This is design question/query so I hope it's Ok to post...
Pretty much every CRM OrgService and Context example you see is not static. Normally uses a using block. Which works of course, but could this be a static class rather than creating/destroying this over and over and over with using blocks everywhere? Is there any issue doing this?
Thanks for your advice :-)
Edit: Here's the code. Do you see any issue with this?...
CrmServiceContext is created by the early-bound entities generator.
static public class CRMOrgService
{
static private IOrganizationService _orgService = null;
static private CrmServiceContext _context = null;
static public IOrganizationService OrgService {
get
{
if (_orgService == null)
{
var reader = new AppSettingsReader();
Uri crmUri = new Uri(reader.GetValue("CRMOrgSvc", typeof(string)).ToString());
string crmUser = reader.GetValue("CRMUser", typeof(string)).ToString();
string crmPass = reader.GetValue("CRMPass", typeof(string)).ToString();
// Your client credentials
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = crmUser;
clientCredentials.UserName.Password = crmPass;
// Create your Organization Service Proxy
var proxy = new OrganizationServiceProxy(crmUri, null, clientCredentials, null);
proxy.EnableProxyTypes();
_orgService = (IOrganizationService)proxy;
}
return _orgService;
}
}
static public CrmServiceContext Context
{
get
{
if (_context == null)
{
_context = new CrmServiceContext(OrgService);
}
return _context;
}
}
static public void CloseCleanUp()
{
_context.ClearChanges();
_context.Dispose();
_context = null;
_orgService = null;
}
} // end class
Yes, it can be static. However, you have to keep in mind this instance will not be thread safe. This means, the connection instance can not be used simultaneous by multiple threads.

Added DataColumns not being saving in Access Database

I would like to write code to add a DataColumn to a DataTable, but when I save the DataTable, it does not include the new DataColumn.
It saves any new DataRows I add, but not the DataColumns.
Can somebody please tell me what I am doing wrong?
public partial class Form1 : Form
{
MyDatabase DB;
DataTable Products;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DB = new MyDatabase();
DB.Open(#"C:\Users\Grant\Documents\Database.accdb");
Products = DB.GetTable("Products");
AddColumn();
AddRow();
DB.Save(Products);
}
private void AddColumn()
{
DataColumn Column = new DataColumn();
Column.DataType = Type.GetType("System.String");
Column.ColumnName = "TestColumn";
Products.Columns.Add(Column);
}
private void AddRow()
{
DataRow Row;
Row = Products.Rows.Add(1, "B", "C");
}
}
class MyDatabase
{
// The following program has to be installed on the computer
// http://www.microsoft.com/downloads/en/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en
private String provider = "Microsoft.ACE.OLEDB.12.0";
private String source;
private OleDbConnection connection;
private String connectionString;
private DataSet dataSet = new DataSet();
private OleDbDataAdapter adapter;
private OleDbCommandBuilder commandBuilder;
public String Provider
{
get { return provider; }
set { provider = value; }
}
public String Source
{
get { return Source; }
set { source = value; }
}
public void Open(String Filename)
{
connectionString = #"Provider=" + provider + #";Data Source=" + Filename;
connection = new OleDbConnection(connectionString);
connection.Open();
adapter = new OleDbDataAdapter();
}
public void BuildStrings()
{
commandBuilder = new OleDbCommandBuilder(adapter);
adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
adapter.InsertCommand = commandBuilder.GetInsertCommand();
adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
}
public DataTable GetTable(String TableName)
{
adapter.SelectCommand = new OleDbCommand("SELECT * From " + TableName, connection);
BuildStrings();
adapter.Fill(dataSet, TableName);
return dataSet.Tables[TableName];
}
public void Save(DataTable Table)
{
adapter.Update(Table);
adapter.Update(dataSet, "Products");
}
}
Got an answer from a different forum.
You can not add new column/field to database table using dataset or datatable you might need to use "ALTER TABLE" with ADO.NET commands. Check below links
How Can I Insert New Column Into A Database Table Using SqlDataAdapter and DataTable?[^]
adding a column to a SQL table in VB using ADO.NET commands[^]

IO streams to JPanel, GUI with InputStream and OutputStream in a JPanels JTextField and JTextArea

I'm trying to write a GUI where the user sees the System output in a JTextArea and where he writes the input in a JTextField, both object inside a JPanel.
How do I do to connect the System output stream to the JTextArea and the System input stream to the JTextField? I have googled and searched these forums but havnt found the solution. I would be very happy if someone could help me with this.
I have a Master class that calls the JPanel with the GUI, and I will have work executed in different threads later on, but right now I struggle with the basic issue of connecting IO streams to the JPanel. Down below is the 2 classes:
public class MainTest {
public static void main(String[] args) throws IOException {
JPanelOUT testpanel = new JPanelOUT();
JFrame frame = new JFrame();
frame.add(testpanel);
frame.setVisible(true);
frame.pack();
/*
System.setOut(CONVERT TEXTAREA TO AN OUTPUTSTREAM SOMEHOW??(JPanelOUT.textArea)));
System.setIn(CONVERT STRING TO AN INPUTSTREAM SOMEHOW?? JPanelOUT.textField);
*/
String text = Sreadinput();
System.out.println(text);
}
public static String Sreadinput() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(JPanelOUT.is));
String input=in.readLine();
return input;
}
}
public class JPanelOUT extends JPanel implements ActionListener {
protected static JTextField textField;
protected static JTextArea textArea;
public static InputStream is;
private final static String newline = "\n";
public JPanelOUT() throws UnsupportedEncodingException, FileNotFoundException {
super(new GridBagLayout());
JLabel label1 = new JLabel("OUTPUT:");;
JLabel label2 = new JLabel("INPUT:");;
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
textArea.setBackground(Color.black);
textArea.setForeground(Color.white);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(500,200));
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(label1, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
c.weightx = 0;
c.weighty = 0;
c.fill = GridBagConstraints.HORIZONTAL;
add(label2, c);
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
String WelcomeText1 = "Hello and welcome to the TEST";
String WelcomeText2 = "Trying to get the input field below to become the System.in and this output";
String WelcomeText3 = "field to become the System.out (preferrably both with UTF-8 encoding where";
String WelcomeText4 = "the scrollpane automatically scrolls down to the last output line)!";
textArea.append(WelcomeText1 + newline + newline + WelcomeText2 + newline + WelcomeText3 + newline + WelcomeText4 + newline + newline);
String text = textField.getText();
is =new ByteArrayInputStream(text.getBytes("UTF-8"));
}
public void actionPerformed(ActionEvent evt) {
String text2 = textField.getText();
textArea.append(text2 + newline);
textField.selectAll();
textArea.setCaretPosition(textArea.getDocument().getLength());
}
}
i am new to java, trying to deal with the streams, too :)
Sorry for bad English I am from Russia.
May be this code will help you.
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public MyPrintStream myPrintStream;
public NewJFrame()throws FileNotFoundException{
initComponents();
this.myPrintStream = new MyPrintStream("string");
}
private class MyPrintStream extends PrintStream {
MyPrintStream(String str)throws FileNotFoundException{
super(str);
}
public void println(String s){
textArea1.append(s+'\n');
}
} .. continuation class code
Main method:
public static void main(String args[]){
/* Set the Nimbus look and feel... */
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run(){
try{
NewJFrame myJFrame = new NewJFrame();
myJFrame.setVisible(true);
System.setOut(myJFrame.myPrintStream);
System.out.println("its work");
System.out.println("its work2");
System.out.print("str"); //does not work, need to override
}catch (FileNotFoundException e){System.out.println (e.getMessage());}
}
});

Wicket serving images from File System

I am pretty new to Wicket and i have some difficulties with using resource references. I am using wicket 1.5.4 and have following problem: I store images on the file system. I have class ImageElement which holds part of the file path relative to configured rootFilePath (i.e dir1/dir2/img1.png). On the page I add Image as follows:
new Image("id",ImagesResourceReference.get(), pageParameters)
where page parameters includes image path parameter (path="/dir1/dir2/img1.png"). My questions are:
Is it the simplest way of serving images from the file system?
Is it ok to use ResourceReference with static method? or I should construct each time new ResourceReference? I saw that in previous version it was possible to use new ResourceReference(globalId), but it seems not to be the case anymore. If so what is the global resource reference for? So far as I understand resource reference is supposed to be factory for resources so it would be rather strange to create new factory for each resource request.
The last question is, how can i pass the path to the image in a better way so that i do not have to concatenate indexed parameters to build the path once respond method is invoked on ImageResource.
What would be the best scenario to get it working in efficient and simple way, i saw the example in 'Wicket in action', but this is meant for dynamic image generation from db and am not sure if it suites for my case
My implementation of ResourceReference which I mounted in Application under "/images" path, looks as follows:
public class ImagesResourceReference extends ResourceReference {
private static String rootFileDirectory;
private static ImagesResourceReference instance;
private ImagesResourceReference() {
super(ImagesResourceReference.class, "imagesResourcesReference");
}
public static ImagesResourceReference get() {
if(instance == null) {
if(StringUtils.isNotBlank(rootFileDirectory)) {
instance = new ImagesResourceReference();
} else {
throw new IllegalStateException("Parameter configuring root directory " +
"where images are saved is not set");
}
}
return instance;
}
public static void setRootFileDirectory(String rootFileDirectory) {
ImagesResourceReference.rootFileDirectory = rootFileDirectory;
}
private static final long serialVersionUID = 1L;
#Override
public IResource getResource() {
return new ImageResource(rootFileDirectory);
}
private static class ImageResource implements IResource {
private static final long serialVersionUID = 1L;
private final String rootFileDirectory;
public ImageResource(String rootFileDirectory) {
this.rootFileDirectory = rootFileDirectory;
}
#Override
public void respond(Attributes attributes) {
PageParameters parameters = attributes.getParameters();
List<String> indexedParams = getAllIndexedParameters(parameters);
if(!indexedParams.isEmpty() && isValidImagePath(indexedParams)) {
String pathToRequestedImage = getImagePath(indexedParams);
FileResourceStream fileResourceStream = new FileResourceStream(new File(pathToRequestedImage));
ResourceStreamResource resource = new ResourceStreamResource(fileResourceStream);
resource.respond(attributes);
}
}
private boolean isValidImagePath(List<String> indexedParams) {
String fileName = indexedParams.get(indexedParams.size() -1);
return !FilenameUtils.getExtension(fileName).isEmpty();
}
private List<String> getAllIndexedParameters(PageParameters parameters) {
int indexedparamCount = parameters.getIndexedCount();
List<String> indexedParameters = new ArrayList<String>();
for(int i=0; i<indexedparamCount ;i++) {
indexedParameters.add(parameters.get(i).toString());
}
return indexedParameters;
}
private String getImagePath(List<String> indexedParams) {
return rootFileDirectory + File.separator + StringUtils.join(indexedParams, File.separator);
}
}
Any help and advices appreciated! Thanks in advance.
You could use it as a shared resource:
public class WicketApplication extends WebApplication {
#Override
public Class<HomePage> getHomePage() {
return HomePage.class;
}
#Override
public void init() {
super.init();
getSharedResources().add("downloads", new FolderContentResource(new File("C:\\Users\\ronald.tetsuo\\Downloads")));
mountResource("downloads", new SharedResourceReference("downloads"));
}
static class FolderContentResource implements IResource {
private final File rootFolder;
public FolderContentResource(File rootFolder) {
this.rootFolder = rootFolder;
}
public void respond(Attributes attributes) {
PageParameters parameters = attributes.getParameters();
String fileName = parameters.get(0).toString();
File file = new File(rootFolder, fileName);
FileResourceStream fileResourceStream = new FileResourceStream(file);
ResourceStreamResource resource = new ResourceStreamResource(fileResourceStream);
resource.respond(attributes);
}
}
}
You can still use ResourceReferences with global IDs. You just have to use a SharedResourceReference. This is probably better, too.
add(new Image("image", new SharedResourceReference("mySharedResourceRef", parameters));
I would try to avoid building paths from URL parameters. This can easily end up in security leaks.

Resources