Not all code paths return value while using Try Catch - asp.net-mvc-4

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);
}
}

Related

Azure.Documents.Document - Method not found

The error I got when I run below code
Method not found:
'System.Threading.Tasks.Task1<Microsoft.Azure.Documents.Client.ResourceResponse1>
Microsoft.Azure.Documents.IDocumentClient.ReadDocumentAsync(System.String,
Microsoft.Azure.Documents.Client.RequestOptions)'.
Before this I was able to run the code with
Microsoft.WindowsAzure.Storage, Microsoft.WindowsAzure.Storage.Table trying to migrate to Microsoft.Azure.CosmosDB.Table;, Microsoft.Azure.Storage
this is my code, I believe is nothing to do with code, but not sure how to fix this, and I've downgrade the Microsoft.Azure.Storage.Common to version 9.0.0.1-preview according to this
public static async Task<CloudTable> CreateTableAsync(string tableName)
{
CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference(tableName);
try
{
await table.CreateIfNotExistsAsync();
}
catch (StorageException ex)
{
Console.WriteLine(ex.Message);
throw;
}
Console.WriteLine();
return table;
}
public static CloudStorageAccount CreateStorageAccountFromConnectionString(string storageConnectionString)
{
CloudStorageAccount storageAccount;
try
{
storageAccount = CloudStorageAccount.Parse(storageConnectionString);
}
catch (FormatException fex)
{
Console.WriteLine(fex);
throw;
}
catch (ArgumentException aux)
{
throw;
}
return storageAccount;
}
Appreciate if anyone could advise. Thanks

Selenium Testing : If element is not present then exception is not handled by Exception of type NoSuchElementException in Selenium

If any element doesnot exists in Selenium Testing, then I am unable to handle it. I have tried this code.
public static bool IsElementPresent(IWebDriver driver, By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
It shows timeout exception takes too much time more than 1 min and finally handled by main Exception class, but my automation testing stops, And I dont want to stop my testing.
I have tried this code snippet also.
public bool IsElementPresent(IWebDriver driver, By by, TimeSpan? timeSpan)
{
bool isElementPresent = false;
try
{
if (timeSpan == null)
{
timeSpan = TimeSpan.FromMilliseconds(2000);
}
var driverWait = new WebDriverWait(driver, (TimeSpan)timeSpan);
driverWait.IgnoreExceptionTypes(typeof(WebDriverTimeoutException));
isElementPresent=driverWait.Until(x => x.FindElements(by).Any());
return isElementPresent;
}
catch (NoSuchElementException nex)
{
return false;
}
catch (Exception ex)
{
return false;
}
}
What should I do so that in small span of time it returns true or false.
Another option would be something like
return driver.FindElements(by).length > 0;
I generally use the Displayed property. I use the page object model with pre-determined IWebElements in the example below:
public bool IsPageObjectPresent(IWebElement PageObject)
{
try
{
if (PageObject.Displayed)
{
Console.WriteLine("Element is displayed");
return true;
}
else
{
Console.WriteLine("Element present but not visible");
return true;
}
}
catch (NoSuchElementException)
{
Console.WriteLine("Element not present");
return false;
}
catch (StaleElementReferenceException)
{
Console.WriteLine("Stale element present");
return false;
}
}
try{
// Add your complete portion of code here //
System.out.println("Portion of code executed Successfully");
}
catch(Exception name)
{
System.out.println("Portion of code failed");
}
Please try and let me know.......

Why is Entity Framework inserting duplicating records into table

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;
}
}

Extract result of sql request in a rest webservice

I am using this code to create a login webservice to database
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){};
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = '+name+' and prenom = '+lastname+' ";
st.close();
cn.close();
System.out.println("success");
return "login";
}
}
My code is working but I don't know how to extract the result of the sql request ( here id )
Are there any suggestions to this issue? Please help!
public class classeConnection {
#GET
#Path (value="log/{a}/{b}")
#Produces(MediaType.APPLICATION_JSON)
public String execMAJ(#PathParam("a")String name,#PathParam("b")String lastname )throws SQLException {
String req;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e ){
e.printStackTrace();
}
try {
Connection cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
Statement st=cn.createStatement();
req="select id from utilisateur where nom = "+name+" and prenom = "+lastname+" LIMIT 1";
ResultSet res = st.executeQuery(req);
if(res.first()) {
String id = res.getString("id");
System.out.println("id = "+id);
} else {
System.out.println("not found foo!");
}
}
catch (SQLException s){
s.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
st.close();
cn.close();
}
return "login";
}
}

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.