Now I am creating a simple banking project for learning purpose where I need to do a lot of search, update and insert operations for a simple action. For example, if I want to create a transaction from a sample user id, in the "Create Trasaction" Screen, after inputting the details and pressing "submit" button, my application will do the following actions.
1) Insert a row in login session table with values: IP address, user id and timing.
2) To check if the particular user id has access to create a transaction option from user access table.
3) To check if the accounts being debited/credited belong to the same branch code as the home branch code of the creating user.
3) To check if the input inventory (if any) i.e. DD, Cheque is valid or not from inventory table.
4) To check if the account being debited/credited has freeze or not.
5) To check if the account being debited has enough available balance or not.
6) Check the account status Active/Inactive or Dormant.
7) Check and create service tax if applicable i.e. another search from S.Tax table and insert into accounts transaction table
and finally,
8) Insert a row into the accounts transaction table if the criteria pass.
Now I do not feel comfortable to write so many preparedstatement code in my Servlet for only creating a transactions. There will be other operations in my application too. So I was wondering if there is a way we can simply write these SQL statements and pass the SQL file to the Servlet anyway. Or maybe we can write a function in PL/SQL and pass the function to the servelt. Are these ways possible?
Please note, I am using J2EE and Oracle database.
I did this once with a project I was doing some years back and I actually achieved something close to what you are looking for I created a properties file in this format:
trans.getTransactons=select * from whateverTable where onesqlquery
trans.getTranId=select tran_id from whatevertable where anothersqlquery
So that when you write your classes you just load the Properties from the file and the query is populated from the property: for example: This Loads the Property fle
public class QueriesLoader {
Properties prop;
public QueriesLoader() {
}
public Properties getProp() {
prop = new Properties();
ClassLoader classLoader = getClass().getClassLoader();
try {
InputStream url = classLoader.getResourceAsStream("path/to/your/propertiesFile/databasequeries.properties");
prop.load(url);
} catch (IOException asd) {
System.out.println(asd.getMessage());
}
return prop;
}
}
And then in you Database Access Objects
public ArrayList getAllTransactions() {
ArrayList arr = new ArrayList();
try {
String sql = que.getProp().getProperty("trans.getTransactons");
PreparedStatement ps = DBConnection.getDbConnection().prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
arr.add(rs.getString(1));
}
DBConnection.closeConn(DBConnection.getDbConnection());
} catch (IOException asd) {
log.debug(Level.FATAL, asd);
} catch (SQLException asd) {
log.debug(Level.FATAL, asd);
}
return arr;
}
And I ended up not writing a single Query Inside my classes. I hope this Helps you.
Related
The only data that should appear when I click the "view data button" should be the employee's personal data by searching its employee id.
This is my code:
public void viewAll() {
btnview.setOnClickListener(
new View.OnClickListener() {
#Override`enter code here`
public void onClick(View v) {
Cursor res = EmployeeData.getAllData();
if(res.getCount() == 0) {
// show message
showMessage("Error","Nothing found");
return;}
How can I get the specific data from the existing database?
You need to replace the getAllData with a method that SELECTs the appropriate data using a WHERE clause which is invoked with the employeeId being passed to it (after extracting the employeeId from the clicked item ).
You then need to process the Cursor by extracting the data from it, if any exists.
So you could have something like the following in your class that extends SQLiteOpenHelper :-
public Cursor getEmployeeDataById(long id) {
return this.getWritableDatabase().query("the_table",null,"employeeId=?",new String[]{String.valueOf(id)},null, null,null);
}
obviously "the_table" and "employeeId" should be replaced by the actual names.
see Query for an explanation of the method's parameters.
the Query (method which has 4 signatures) is a convenience method that returns a Cursor object.
-It generates the SQL on your behalf e.g. the above would generate the SQL SELECT * FROM the_table WHERE employeeId=?
- where the ? is bound (prevents SQL Injection) to the passed id value by SQLite.
When extracting the data from the Cursor, rather than checking the count, you can rely upon the fact that the Cursor's will return false if it cannot move to the first row (i.e. there is no first row). So extracting the data could be along the lines of:-
Cursor csr = EmployeeData.getEmployeeDataById(extracted_employee_id);
if (csr.moveToFirst()) {
.... extract the data from the cursor
} else {
showMessage("Error","Nothing found");
}
In my application I have two scenarios.
1. Create: Here we book a hotel room. After booking application returns a transaction ID.
2. Cancel: We need to pass the transaction Id to the application to cancel booking.
I want to test with jmeter in such a way that after a create call is made, the cancel call of the respective create is called with the generated transaction ID automatically.
So I have created two thread groups. One for create where I am calling create API, saving the transaction Id in a CSV file using Regular Expression Extractor & Bean Shell Post Processor. Another thread is for cancel where I am picking the transaction ID using CSV Dataset Config & calling the cancel API.
Problem is I want to delete that transaction ID from CSV file after calling the cancel API. I think Bean Shell Post Processor will do the job. This is my CSV Data Set Config:
Here is my Bean Shell Post Processor code:
File inputFile = new File("/home/demo/LocalFolder/CSV/result.csv");
File tempFile = new File("/home/demo/LocalFolder/CSV/myTempFile.csv");
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = vars.get("transactionId");
//String lineToRemove = "${transactionId}";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println("Completed");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But the transaction ID is not getting deleted from the file. I think that vars.get("transactionId") is not returning anything or returning wrong value. If I hardcode a transation ID then the code works fine. Can anyone help me?
JMeter Variables are local to the current Thread Group only, in order to pass the data between Thread Groups you need to use JMeter Properties (props instead of vars). See Knit One Pearl Two: How to Use Variables in Different Thread Groups article for more detailed explanation and usage example.
P.S. Maybe it would be easier to use HTTP Simple Table Server instead?
Say I have something like a support ticket system (simplified as example). It has many users and organizations. Each user can be a member of several organizations, but the typical case would be one org => many users, and most of them belong only to this organization. Each organization has a "tag" which is to be used to construct "ticket numbers" for this organization. Lets say we have an org called StackExchange that wants the tag SES.
So if I open the first ticket of today, I want it to be SES140407-01. The next is SES140407-02 and so on. Doesn't have to be two digits after the dash.
How can I make sure this is generated in a way that makes sure it is 100% unique across the organization (no orgs will have the same tag)?
Note: This does not have to be the document ID in the database - that will probably just be a Guid or similar. This is just a ticket reference - kinda like a slug - that will appear in related emails etc. So it has to be unique, and I would prefer if we didn't "waste" the sequential case numbers hilo style.
Is there a practical way to ensure I get a unique ticket number even if two or more people report a new one at almost the same time?
EDIT: Each Organization is a document in RavenDB, and can easily hold a property like LastIssuedTicketId. My challenge is basically to find the best way to read this field, generate a new one, and store this back in a way that is "race condition safe".
Another edit: To be clear - I intend to generate the ticket ID in my own software. What I am looking for is a way to ask RavenDB "what was the last ticket number", and then when I generate the next one after that, "am I the only one using this?" - so that I give my ticket a unique case id, not necessarily related to what RavenDB considers the document id.
I use for that generic sequence generator written for RavenDB:
public class SequenceGenerator
{
private static readonly object Lock = new object();
private readonly IDocumentStore _docStore;
public SequenceGenerator(IDocumentStore docStore)
{
_docStore = docStore;
}
public int GetNextSequenceNumber(string sequenceKey)
{
lock (Lock)
{
using (new TransactionScope(TransactionScopeOption.Suppress))
{
while (true)
{
try
{
var document = GetDocument(sequenceKey);
if (document == null)
{
PutDocument(new JsonDocument
{
Etag = Etag.Empty,
// sending empty guid means - ensure the that the document does NOT exists
Metadata = new RavenJObject(),
DataAsJson = RavenJObject.FromObject(new { Current = 0 }),
Key = sequenceKey
});
return 0;
}
var current = document.DataAsJson.Value<int>("Current");
current++;
document.DataAsJson["Current"] = current;
PutDocument(document);
{
return current;
}
}
catch (ConcurrencyException)
{
// expected, we need to retry
}
}
}
}
}
private void PutDocument(JsonDocument document)
{
_docStore.DatabaseCommands.Put(
document.Key,
document.Etag,
document.DataAsJson,
document.Metadata);
}
private JsonDocument GetDocument(string key)
{
return _docStore.DatabaseCommands.Get(key);
}
}
It generates incremental unique sequence based on sequenceKey. Uniqueness is guaranteed by raven optimistic concurrency based on Etag. So each sequence has its own document which we update when generate new sequence number. Also, there is lock which reduced extra db calls if several threads are executing at the same moment at the same process (appdomain).
For your case you can use it this way:
var sequenceKey = string.Format("{0}{1:yyMMdd}", yourCompanyPrefix, DateTime.Now);
var nextSequenceNumber = new SequenceGenerator(yourDocStore).GetNextSequenceNumber(sequenceKey);
var nextSequenceKey = string.Format("{0}-{1:00}", sequenceKey, nextSequenceNumber);
I am using Visual Basic 2008 and Sql Server 2000.
On all Forms I m saving a followup date user select a date and it saved in a relevant table, now at stored follow up date I need to pop up a bar or a notification inside application to tell user that this is you follow up date for this specific record.
Which are the ways I can do it.
any idea will be appreciated
Thanks
I don't understand your question completely. I don't know its for Windows form or Web form (Asp.net) Still I am trying to answer it
You can use SELECT IDENT_CURRENT(‘MyTable’) after your insert command in your stored procedure to get the last inserted id or to verify that it inserted data into table or not.
public int InsertDate(string pid, string followUpDt)
{
Try
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("#pid", pid);
param[1] = new SqlParameter("#isScraped", isScraped);
int identityId = (Int32)SqlHelper.ExecuteScalar(CommonCS.ConnectionString, CommandType.StoredProcedure, "Sproc_FollowUpDate_Insert", param);
if(identityId != null)
{
// it means Values has been inserted to the table
// Call a Java Script function to Show popup & message
ScriptManager.RegisterStartupScript(Page,GetType(),"showConfirmPopup","<script>disp_confirm()</script>",false)
}
else
{
//Operation not successful
}
}
}
}
Catch(exception ex)
{
//Log Exception to DB OR Send Error Email
}
///In Aspx
<script type="text/javascript">
function showConfirmPopup() {
var msg = "Successful "
//Show Popup code here
</script>
============================UPDATED ANS====================================
Alright You need to create a SQL Job make it occurring daily at specific time. SQL Job will call a Web service url(Invoke) through Stored Procedure
Check this
Now you can check database dates against current date in that web service.
Being rather new to MVC 3 and EF, I'm trying to understand the best architectural approach to developing an application for my company. The application will be a large-scale application that potentially handles hundreds of users at the same time, so I want to make sure I understand and am following proper procedures. So far, I've determined that a simple repository pattern (such as Controller -> Repository -> EF) approach is the best and easiest to implement, but I'm not sure if that is definitely the best way to do things. The application will basically return data that is shown to a user in a devexpress grid and they can modify this data/add to it etc.
I found this article and it is rather confusing for me at this time, so I'm wondering if there is any reason to attempt to work with a disconnected EF and why you would even want to do so: http://www.codeproject.com/Articles/81543/Finally-Entity-Framework-working-in-fully-disconne?msg=3717432#xx3717432xx
So to summarize my question(s):
Is the code below acceptable?
Should it work fine for a large-scale MVC application?
Is there a better way?
Will unnecessary connections to SQL remain open from EF? (SQL Profiler makes it look like it stays open a while even after the using statement has exited)
Is the disconnected framework idea a better one and why would you even want to do that? I don't believe we'll need to track data across tiers ...
Note: The repository implements IDisposable and has the dispose method listed below. It creates a new instance of the entity context in the repository constructor.
Example Usage:
Controller (LogOn using Custom Membership Provider):
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
User newUser = new User();
using (AccountRepository repo = new AccountRepository())
{
newUser = repo.GetUser(model.UserName);
...
}
}
Membership Provider ValidateUser:
public override bool ValidateUser(string username, string password)
{
using (AccountRepository repo = new AccountRepository())
{
try
{
if (string.IsNullOrEmpty(password.Trim()) || string.IsNullOrEmpty(username.Trim()))
return false;
string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Trim(), "md5");
bool exists = false;
exists = repo.UserExists(username, hash);
return exists;
}catch{
return false;
}
}
}
Account Repository Methods for GetUser & UserExists:
Get User:
public User GetUser(string userName)
{
try
{
return entities.Users.SingleOrDefault(user => user.UserName == userName);
}
catch (Exception Ex)
{
throw new Exception("An error occurred: " + Ex.Message);
}
}
User Exists:
public bool UserExists(string userName, string userPassword)
{
if (userName == "" || userPassword == "")
throw new ArgumentException(InvalidUsernamePassword);
try
{
bool exists = (entities.Users.SingleOrDefault(u => u.UserName == userName && u.Password == userPassword) != null);
return exists;
}
catch (Exception Ex)
{
throw new Exception("An error occurred: " + Ex.Message);
}
}
Repository Snippets (Constructor, Dispose etc):
public class AccountRepository : IDisposable
{
private DbContext entities;
public AccountRepository()
{
entities = new DbContext();
}
...
public void Dispose()
{
entities.Dispose();
}
}
What's acceptable is pretty subjective, but if you want to do proper data access I suggest you do NOT use the repository pattern, as it breaks down as your application gets more complex.
The biggest reason is minimizing database access. So for example look at your repository and notice the GetUser() method. Now take a step back from the code and think about how your application is going to be used. Now think about how often you are going to request data from the user table without any additional data. The answer is almost always going to be "rarely" unless you are creating a basic data entry application.
You say it your application will show a lot of grids. What data is in that Grid? I'm assuming (without knowing your application domain) that the grids will combine user data with other information that's relevant for that user. If that's the case, how do you do it with your repositories?
One way is to call on each repository's method individually, like so:
var user = userRepository.GetUser("KallDrexx");
var companies = companyRepository.GetCompaniesForUser(user.Id);
This now means you have 2 database calls for what really should be just one. As your screens get more and more complex, this will cause the number of database hits to increase and increase, and if your application gets significant traffic this will cause performance issues. The only real way to do this in the repository pattern is to add special methods to your repositories to do that specific query, like:
public class UserRepository
{
public User GetUser(string userName)
{
// GetUser code
}
public User GetUserWithCompanies(string userName)
{
// query code here
}
}
So now what happens if you need users and say their contact data in one query. Now you have to add another method to your user repository. Now say you need to do another query that also returns the number of clients each company has, so you need to add yet another method (or add an optional parameter). Now say you want to add a query that returns all companies and what users they contain. Now you need a new query method but then comes the question of do you put that in the User repository or the Company repository? How do you keep track of which one it's in and make it simple to choose between GetUserWithCompany and GetCompanyWithUsers when you need it later?
Everything gets very complex from that point on, and it's those situations that have made me drop the repository pattern. What I do now for data access is I create individual query and command classes, each class represents 1 (and only 1) query or data update command to the database. Each query class returns a view model that only contains the data I need for one specific user usage scenario. There are other data access patterns that will work too (specification pattern, some good devs even say you should just do your data access in your controllers since EF is your data access layer).
The key to doing data access successfully is good planning. Do you know what your screens are going to look like? Do you know how users are going to use your system? Do you know all the data that is actually going to be on each screen? If the answer to any of these is no, then you need to take a step back and forget about the data layer, because the data layer is (or should be for a good application) determined based on how the application is actually going to be used, the UI and the screens should not be dependent on how the data layer was designed. If you don't take your UI needs and user usage scenarios into account when developing the data access, your application will not scale well and will not be performant. Sometimes that's not an issue if you don't plan on your site being big, but it never hurts to keep those things in mind.
No matter what you do, you may consider moving instantiation and disposing of your context to your controller like this:
public class MyController : Controller
{
private Entities context = new Entities();
...
public override void Dispose()
{
context.Dispose();
}
}
You can then pass that context into any method that needs it without duplicating the overhead of creating it.
I disagree that the repository pattern is necessarily bad for the same reason. You create multiple classes to break up your code to make it manageable and still reuse the same context. That could look something like this:
repository.Users.GetUser(userName);
In this case "Users" is a lazy loaded instance of your user repository class which reuses the context from your repository. So the code for that Users property in your repository would look something like this:
private UserRepository users;
public UserRepository Users
{
get
{
If (users == null)
{
users = new UserRepository(this);
}
return users;
}
}
You can then expose your context to these other lazy loaded classes via a property.
I don't think this necessarily conflicts with KallDrexx's pattern. His method simply flips this so instead of
repository.Users.GetUser(userName);
You would have something like
UserQuery query = new UserQuery(repository.Users);
This then becomes an issue of syntax. Do you want this:
repository.Area.Query(value1, value2, ...);
Or this:
AreaQuery query = new AreaQuery { Property1 = value1, ... };
The latter actually works nicer with model binding but obviously is more verbose when you actually have to code it.
Best advice KallDrexx gave is to just put your code I your actions and then figure it out. If you are doing simple CRUD, then let MVC instantiate and populate your model, then all you have to do is attach and save. If you find you can reuse code, move it to where it can be reused. If your application starts getting too complicated, try some of these recommendations until you find what works for you.