Why is Entity Framework inserting duplicating records into table - asp.net-mvc-4

For some reason .Net Entity Framework is inserting multiple duplicate records into a table called groups in my database. It seems to be occurring when a user logs in and access group index page.
Here are code snippets of my Index page controller code, as well as the DataContext get method and update method for Groups.
I'm not seeing whats wrong here as I'm only building a model and returning it to Index view. Anyone have any suggestions? I'm using MVC 4, Entity Framework 6.
Screenshot of records: It goes on for 50 rows like this.
Index View Controller
[Authorize(Roles = "Standard, Administrator")]
public ActionResult Index()
{
int _userId = WebSecurity.CurrentUserId;
var model = new GroupIndexModel();
if (Roles.GetRolesForUser().Contains("Administrator"))
{
ViewBag.Role = "Administrator";
var modelList = model.BuildIndexModel(_ctx.Groups.GetAllGroups());
modelList.CampaignTemplates = _ctx.Templates.GetAllCampaignTemplateList();
modelList.ProcedureTemplates = _ctx.Templates.GetAllProcedureTemplateList();
return View(modelList);
}
else
{
ViewBag.Role = "Standard";
var userGroups = _ctx.ManyToManyRelationShips.GetUserGroups(_userId);
var modelList = model.BuildIndexModel(_ctx.ManyToManyRelationShips.GetGroupsEntitiesForUser(userGroups));
foreach( var group in modelList.GroupObjects)
{
modelList.CampaignTemplates = _ctx.Templates.GetAllCampaignTemplateList().FindAll(p => p.GroupID == group.GroupId);
}
var tempProcTemplateList = _ctx.Templates.GetAllProcedureTemplateList();
foreach (var cTemplate in modelList.CampaignTemplates)
{
modelList.ProcedureTemplates.AddRange(tempProcTemplateList.FindAll(p => p.CampaignTemplateID == cTemplate.CampaignTemplateId));
}
return View(modelList);
}
}
Groups Manager (Get, GetAll, Add, Update Functions)
public Group Get(int groupId)
{
try
{
var group = new Group();
var temp = _ctx.Groups.First(p => p.GroupId == groupId);
if (temp != null)
{
group.GroupId = temp.GroupId;
group.CompanyName = temp.CompanyName;
group.Email = temp.Email;
group.PhoneNumber = temp.PhoneNumber;
group.CreatedDate = temp.CreatedDate;
group.LastModifiedDate = temp.LastModifiedDate;
}
return group;
}
catch (Exception ex)
{
logger.Error("An Error occured getting a group", ex);
// Console.WriteLine("An Error occured getting a group" + System.Environment.NewLine + ex);
return null;
}
}
public List<Group> GetAllGroups()
{
try
{
var groupList = _ctx.Groups.OrderBy(p => p.CompanyName).ToList<Group>();
return groupList;
}
catch (Exception ex)
{
logger.Error("An Error occured getting groups", ex);
//Console.WriteLine("An Error occured getting groups" + System.Environment.NewLine + ex);
return null;
}
}
public int Add(Group eGroup)
{
int newGroupId;
try
{
_ctx.Groups.Add(eGroup);
_ctx.SaveChanges();
newGroupId = eGroup.GroupId;
return newGroupId;
}
catch (Exception ex)
{
logger.Error("An Error occured adding group", ex);
//Console.WriteLine("An Error occured adding group" + System.Environment.NewLine + ex);
return -1;
}
}
public void UpdateGroup(Group eGroup)
{
try
{
var updev = _ctx.Groups.First(p => p.GroupId == eGroup.GroupId);
if (updev.CompanyName != eGroup.CompanyName)
updev.CompanyName = eGroup.CompanyName;
if (updev.Email != eGroup.Email)
updev.Email = eGroup.Email;
if (updev.PhoneNumber != eGroup.PhoneNumber)
updev.PhoneNumber = eGroup.PhoneNumber;
updev.LastModifiedDate = DateTime.Now;
_ctx.SaveChanges();
}
catch (Exception ex)
{
logger.Error("An Error occured updating group", ex);
// Console.WriteLine("An Error occured updating group" + System.Environment.NewLine + ex);
return;
}
}

Related

org.apache.fop.fo.flow.ExternalGraphic catches and logs ImageException I want to handle myself

I am transforming an Image into pdf for test purposes.
To ensure that the Image is compatible with the printing process later on, I'm running a quick test print during the upload.
I'm creating a simple Test-PDF with a transformer. When I try to print an image with an incompatible format, the ImageManager of the transformer throws an ImageException, starting in the preloadImage() function:
public ImageInfo preloadImage(String uri, Source src)
throws ImageException, IOException {
Iterator iter = registry.getPreloaderIterator();
while (iter.hasNext()) {
ImagePreloader preloader = (ImagePreloader)iter.next();
ImageInfo info = preloader.preloadImage(uri, src, imageContext);
if (info != null) {
return info;
}
}
throw new ImageException("The file format is not supported. No ImagePreloader found for "
+ uri);
}
throwing it to:
public ImageInfo needImageInfo(String uri, ImageSessionContext session, ImageManager manager)
throws ImageException, IOException {
//Fetch unique version of the URI and use it for synchronization so we have some sort of
//"row-level" locking instead of "table-level" locking (to use a database analogy).
//The fine locking strategy is necessary since preloading an image is a potentially long
//operation.
if (isInvalidURI(uri)) {
throw new FileNotFoundException("Image not found: " + uri);
}
String lockURI = uri.intern();
synchronized (lockURI) {
ImageInfo info = getImageInfo(uri);
if (info == null) {
try {
Source src = session.needSource(uri);
if (src == null) {
registerInvalidURI(uri);
throw new FileNotFoundException("Image not found: " + uri);
}
info = manager.preloadImage(uri, src);
session.returnSource(uri, src);
} catch (IOException ioe) {
registerInvalidURI(uri);
throw ioe;
} catch (ImageException e) {
registerInvalidURI(uri);
throw e;
}
putImageInfo(info);
}
return info;
}
}
throwing it to :
public ImageInfo getImageInfo(String uri, ImageSessionContext session)
throws ImageException, IOException {
if (getCache() != null) {
return getCache().needImageInfo(uri, session, this);
} else {
return preloadImage(uri, session);
}
}
Finally it gets caught and logged in the ExternalGraphic.class:
/** {#inheritDoc} */
public void bind(PropertyList pList) throws FOPException {
super.bind(pList);
src = pList.get(PR_SRC).getString();
//Additional processing: obtain the image's intrinsic size and baseline information
url = URISpecification.getURL(src);
FOUserAgent userAgent = getUserAgent();
ImageManager manager = userAgent.getFactory().getImageManager();
ImageInfo info = null;
try {
info = manager.getImageInfo(url, userAgent.getImageSessionContext());
} catch (ImageException e) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageError(this, url, e, getLocator());
} catch (FileNotFoundException fnfe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageNotFound(this, url, fnfe, getLocator());
} catch (IOException ioe) {
ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
getUserAgent().getEventBroadcaster());
eventProducer.imageIOError(this, url, ioe, getLocator());
}
if (info != null) {
this.intrinsicWidth = info.getSize().getWidthMpt();
this.intrinsicHeight = info.getSize().getHeightMpt();
int baseline = info.getSize().getBaselinePositionFromBottom();
if (baseline != 0) {
this.intrinsicAlignmentAdjust
= FixedLength.getInstance(-baseline);
}
}
}
That way it isn't accessible for me in my code that uses the transformer.
I tried to use a custom ErrorListener, but the transformer only registers fatalErrors to the ErrorListener.
Is there any way to access the Exception and handle it myself without changing the code of the library?
It was easier than I thought. Before I call the transformation I register a costum EventListener to the User Agent of the Fop I'm using. This Listener just stores the Information what kind of Event was triggered, so I can throw an Exception if it's an ImageError.
My Listener:
import org.apache.fop.events.Event;
import org.apache.fop.events.EventListener;
public class ImageErrorListener implements EventListener
{
private String eventKey = "";
private boolean imageError = false;
#Override
public void processEvent(Event event)
{
eventKey = event.getEventKey();
if(eventKey.equals("imageError")) {
imageError = true;
}
}
public String getEventKey()
{
return eventKey;
}
public void setEventKey(String eventKey)
{
this.eventKey = eventKey;
}
public boolean isImageError()
{
return imageError;
}
public void setImageError(boolean imageError)
{
this.imageError = imageError;
}
}
Use of the Listener:
// Start XSLT transformation and FOP processing
ImageErrorListener imageListener = new ImageErrorListener();
fop.getUserAgent().getEventBroadcaster().addEventListener(imageListener);
if (res != null)
{
transformer.transform(xmlDomStreamSource, res);
}
if(imageListener.isImageError()) {
throw new ImageException("");
}
fop is of the type Fop ,xmlDomStreamSource ist the xml-Source I want to transform and res is my SAXResult.

my javafx project doesn't read data from the database

So i created a database table in intellij and i made a javafx project and it's connected to my server(localhost)
now i'm getting errors here
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
it says I'm unable to access the table
this is the method
public boolean isLogin(String user,String pass) throws SQLException
{
PreparedStatement preparedStatement = null ;
ResultSet resultSet = null;
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
try
{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,user);
preparedStatement.setString(2,pass);
resultSet = preparedStatement.executeQuery();
if (resultSet.next())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
//TODO: handle exception
}
finally {
preparedStatement.close();
resultSet.close();
}
}
and the other error here
if (loginModel.isLogin(userAction.getText(), passAction.getText()))
and this line too
resultSet.close();
and I guess they are related and i don't know how to fix this
this is the other code
#FXML
public void Login(ActionEvent event) {
try {
if (loginModel.isLogin(userAction.getText(), passAction.getText())) {
isConnected.setText("Username & password is correct");
}
else
{
isConnected.setText("Check your username or password");
}
} catch (SQLException e)
{
isConnected.setText("Check your username or password");
//TODO Auto-generated catch block
e.printStackTrace();
}
}

Not all code paths return value while using Try Catch

I have been getting "not all code paths return value" in the following code. I have the code below. I think I am returning appropriately but still there is an error.
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
You forgot a return statement in the first if statement.
[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
try
{
Employee incomingEmployee = employee;
if (incomingEmployee == null)
{
-->return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
}
else if (UserManager.AddUser(employee) > 0)
{
return Request.CreateResponse(HttpStatusCode.Created);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}

Having Trouble with ObjectInputStream/OutputStream

I am having trouble with my programs ability to save my Maps to a file. Here are my two methods for writing and reading my maps and arraylist.
Here is my read method:
private void getData() throws IOException, ClassNotFoundException {
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
if (f_Instructors.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Instructors)))) {
//Add theList back in
if (in.readObject() != null) {
TreeMap<Instructor, Set<Student>> read = null;
while(in.available() > 0) {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
}
if (read != null) {
for (Instructor key : read.keySet()) {
System.out.println(key);
Set<Student> values = read.get(key);
PSLTrackerInfo.addInstructor(key, values);
}
System.out.println("Instructors Found! Reading...");
} else {
System.out.println("No instructor data saved.1");
}
} else {
System.out.println("No instructor data saved.2");
}
in.close();
}
}
//Add times back in
if (f_Times.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Times)))) {
if (in.readObject() != null) {
TreeMap<Student, ArrayList<Date>> readTimes = null;
while(in.available() > 0) {
readTimes = (TreeMap<Student, ArrayList<Date>>) in.readObject();
}
if (readTimes != null) {
for (Student key : readTimes.keySet()) {
System.out.println(key);
ArrayList<Date> values = readTimes.get(key);
PSLTrackerInfo.addTimes(key, values);
}
System.out.println("Dates Found! Reading...");
} else {
System.out.println("No dates saved.");
}
} else {
System.out.println("No dates saved.");
}
in.close();
}
}
//Add newStudents back in
if (f_Students.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new
BufferedInputStream(new FileInputStream(f_Students)))) {
if (in.readObject() != null) {
ArrayList<Student> readStudents = null;
while (in.available() > 0) {
readStudents = (ArrayList<Student>) in.readObject();
}
if (readStudents != null) {
PSLTrackerInfo.setTheList(readStudents);
}
System.out.println("New students found! Reading...");
} else {
System.out.println("No new students data saved.");
}
in.close();
}
}
}
And Here is my Writing method:
private void saveData() {
System.out.println("Saving Data...");
File f_Instructors = new File(PSLTrackerInfo.file + "instructors.brent");
File f_Students = new File(PSLTrackerInfo.file + "students.brent");
File f_Times = new File(PSLTrackerInfo.file + "times.brent");
ObjectOutputStream out_Instructors = null;
ObjectOutputStream out_Students = null;
ObjectOutputStream out_Times = null;
try {
out_Instructors = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Instructors)));
out_Students = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Students)));
out_Times = new ObjectOutputStream(new
BufferedOutputStream(new FileOutputStream(f_Times)));
out_Instructors.writeObject(PSLTrackerInfo.getMap());
out_Times.writeObject(PSLTrackerInfo.getTimes());
out_Students.writeObject(PSLTrackerInfo.getList());
out_Instructors.flush();
out_Students.flush();
out_Times.flush();
out_Instructors.close();
out_Students.close();
out_Times.close();
} catch (IOException ex) {
Logger.getLogger(PrivateLessonsTrackerGUI.class.getName())
.log(Level.SEVERE, null, ex);
}
System.exit(0);
}
Sorry if it is a little confusing I have 3 files to save 3 different objects, if there is a way to save it into one file let me know but I just was getting a lot of errors that I couldn't figure out how to solve so this is what I ended up doing. Thanks for any help given.
To EJP: I tried this
TreeMap<Instructor, Set<Student>> read = null;
try {
read = (TreeMap<Instructor, Set<Student>>)
in.readObject();
} catch (EOFException e) {
System.out.println("Caught EOFException!");
}
And even when there was data in it when it was written to the file, I got an EOFException everytime.
readObject() doesn't return null unless you wrote a null. If you're using that as a test for end of stream, it is invalid. The correct technique is to catch EOFException.
You are calling it and throwing away the result if it isn't null, and then calling it again. The second call will throw EOFException if there isn't another object in the file. It won't give you the same result as the first call. It's a stream.
available() is also not a valid test for end of stream. That's not what it's for. See the Javadoc. Again, the correct technique with readObject() is to catch EOFException.

java mail keeping Transport object connected

How do i keep the java mail transport object alive or connected.
I have written this in my code in a simple class file inside a web application : -
#Resource(name = "myMailServer")
private Session mailSession;
Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
System.out.println("" + transport.isConnected());
if(!transport.isConnected()) {
transport.connect(username, password);
}
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
the full code here
Now everytime i run this code it takes some time to connect with the mail server
and the line
System.out.println("" + transport.isConnected());
prints a false
How do i retain the object transport as it does gets null and into the block
if(transport == null) {
or the transport object remains connected...
Thanks
Pradyut
the code should be....
with a static initialization of transport object
without any problems but can be good with a function
static Transport getTransport() method
#Resource(name = "myMailServer")
private Session mailSession;
static Transport transport ;
public boolean sendMail(String recipient, String subject, String text) {
boolean exe = false;
Properties p = new Properties();
String username = "someone#gmail.com";
String password = "password";
InitialContext c = null;
try
{
c = new InitialContext();
mailSession = (javax.mail.Session) c.lookup("java:comp/env/myMailServer");
}
catch(NamingException ne)
{
ne.printStackTrace();
}
try
{
Message msg = new MimeMessage(mailSession);
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(recipient, false));
msg.setSubject(subject);
msg.setText(text);
msg.setHeader("MIME-Version" , "1.0" );
msg.setHeader("Content-Type" , "text/html" );
msg.setHeader("X-Mailer", "Recommend-It Mailer V2.03c02");
msg.saveChanges();
//Transport.send(msg);
if(transport == null) {
transport = mailSession.getTransport("smtps");
}
if(!transport.isConnected()) {
transport.connect(username, password);
}
transport.sendMessage(msg, msg.getAllRecipients());
exe = true;
}
catch (AddressException e)
{
e.printStackTrace();
exe = false;
}
catch (MessagingException e)
{
e.printStackTrace();
exe = false;
}
finally {
/*try {
if(transport != null)
transport.close();
}
catch(MessagingException me) {
me.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}*/
}
return exe;
}
Thanks
Regards
Pradyut