Exemple #1
0
        public async Task <IActionResult> GetAllLocations()
        {
            try
            {
                var locations = await locationsRepository.GetAllLocations();

                if (locations == null || !locations.Any())
                {
                    var error = new NotFoundException("No locations data found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var resource = mapper.Map <IEnumerable <Location>, IEnumerable <LocationResource> >(locations);
                var response = new OkResponse <IEnumerable <LocationResource> >(resource, "Everything is good");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #2
0
        public async Task <IActionResult> DeleteALocation([FromRoute] int locationID)
        {
            if (locationID == 0)
            {
                var error = new BadRequestException("The given location ID is invalid");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var deleted = await locationsRepository.DeleteALocation(locationID);

                if (deleted == null)
                {
                    var error = new NotFoundException("The given location cannot be found on database");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var response = new DeletedResponse <int>(deleted.Id, $"Successfully deleted location '{deleted.Id}'");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #3
0
        public async Task <IActionResult> DeleteAProject([FromRoute] string projectNumber)
        {
            if (String.IsNullOrEmpty(projectNumber))
            {
                var error = new BadRequestException("The given project number is null/empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var deletedCount = await projectsRepository.DeleteAProject(projectNumber);

                if (deletedCount != 1)
                {
                    var error = new NotFoundException("The given project number cannot be found on database");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var response = new DeletedResponse <string>(projectNumber, $"Successfully deleted project with number '{projectNumber}'");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #4
0
        public async Task <IActionResult> UpdateUtilizationOfAllUsers()
        {
            try
            {
                IEnumerable <User> allUsers = await usersRepository.GetAllUsers();

                foreach (User user in allUsers)
                {
                    IEnumerable <Position> allPositionsOfUser = await positionsRepository.GetAllPositionsOfUser(user.Id);

                    IEnumerable <OutOfOffice> allOutOfOfficeOfUser = await outOfOfficeRepository.GetAllOutOfOfficeForUser(user.Id);

                    int userUtil = await utilizationRepository.CalculateUtilizationOfUser(allPositionsOfUser, allOutOfOfficeOfUser);

                    await usersRepository.UpdateUtilizationOfUser(userUtil, user.Id);
                }

                var response = new OkResponse <string>(null, "Successfully updated all Users");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
        public void HandleException(InternalServerException ise)
        {
            MessageBox.Show("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(InternalServerException).");

            if (ise is ConnectionException)
            {
                MessageBox.Show("\nThe server returned an connection error.\n" + ise.Message
                                + "\nDo you wish to retry the last service request?[y/n]");
            }
            else if (ise is ProtocolException)
            {
                MessageBox.Show("\nThe server returned an protocol error.\n" + ise.Message
                                + "\nThis is most likely the result of a programming error."
                                + "\nDo you wish to retry the last service request?[y/n]");
            }
            else
            {
                MessageBox.Show("\nThe server returned an internal server error.\n"
                                + ise.Message
                                + "\nThis is most likely the result of a programming error."
                                + "\nA RuntimeException will be thrown.");

                throw new SystemException(ise.Message);
            }
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception exception)
            {
                if (context.Response.HasStarted)
                {
                    _logger.LogWarning("The response has already started, the problem details middleware will not be executed.");
                    throw;
                }

                Log(exception);

                context.ClearResponse(StatusCodes.Status500InternalServerError);

                if (exception is ProblemDetailsException problem)
                {
                    if (!IsNullOrWhiteSpace(_options.DefaultTypeBaseUri))
                    {
                        problem.ProblemDetails.Type = $"{_options.DefaultTypeBaseUri.TrimEnd('/')}/{problem.ProblemDetails.Type}";
                    }

                    await context.WriteProblemDetailsAsync(problem.ProblemDetails);

                    return;
                }

                var internalServerException = new InternalServerException(exception, _options.DisplayUnhandledExceptionDetails(context));
                await context.WriteProblemDetailsAsync(internalServerException);
            }
        }
        public void HandleException(InternalServerException ise) {
            Console.WriteLine("");
            Console.WriteLine("*****");
            Console.WriteLine("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(InternalServerException).");

            if (ise is ConnectionException) {
                Console.Write("\nThe Server returned a connection error.\n" + ise.Message +
                              "\nDo you wish to retry the last service request?[y/n]");
            } else
            if (ise is ProtocolException) {
                Console.Write("\nThe server ereturned a protocol error.\n" + ise.Message +
                              "\nThis is most likely the result of a programming error." +
                              "\nDo you wish to retry the last service request?[y/n]");
            } else {
                Console.WriteLine("\nThe server returned an internal server error.\n" + ise.Message +
                                  "\nThis is most likely the result of a programming error." +
                                  "\nA runtimeException will be thrown.");
                throw new SystemException(ise.Message);
            }

            try {
                String retry = Console.ReadLine();

                if (retry.ToLower().Equals("y") || retry.ToLower().Equals("yes")) {
                    return;
                }

                throw new SystemException("The user has opted not to retry the last request"); 
            } catch (IOException e ) {
                Console.Error.WriteLine("Failed to read user response.\nA RuntimeException will be thrown.");
                throw new SystemException(e.Message);
            }
        }
Exemple #8
0
        public async Task <IActionResult> DeleteAProvince([FromRoute] string province)
        {
            if (String.IsNullOrEmpty(province))
            {
                var error = new BadRequestException("Province cannot be null or empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var deleted = await locationsRepository.DeleteAProvince(province);

                if (deleted == null)
                {
                    var error = new NotFoundException("The given province cannot be found on database");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var response = new DeletedResponse <string>(deleted, $"Successfully deleted location '{deleted}'");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #9
0
        public async Task <IActionResult> GetALocation([FromRoute] int locationId)
        {
            try
            {
                var location = await locationsRepository.GetALocation(locationId);

                if (location == null)
                {
                    var error = new NotFoundException($"No location at city '{locationId}' found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var resource = mapper.Map <Location, LocationResource>(location);
                var response = new OkResponse <LocationResource>(resource, "Everything is good");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #10
0
        CustomException HandleStatusCode(HttpStatusCode code, string message, string serverMessage = "", Exception innerException = null)
        {
            CustomException result;

            switch (code)
            {
            case HttpStatusCode.Unauthorized:
                result = new AutorizationException(message);
                break;

            case HttpStatusCode.PaymentRequired:
                result = new LicenseException();
                break;

            case HttpStatusCode.PreconditionFailed:
                result = new InvalidVersionException(message);
                break;

            case HttpStatusCode.Conflict:
                result        = new InternalServerException(message, D.SERVER_CONFIG_WAS_CHANGED);
                result.Report = null;
                break;

            case HttpStatusCode.NotAcceptable:
                result = new InvalidVersionException(message);
                break;

            default:
                result = new InternalServerException(serverMessage, innerException);
                break;
            }
            return(result);
        }
Exemple #11
0
        public async Task <IActionResult> GetAllProjects([FromQuery] string searchWord, [FromQuery] string orderKey, [FromQuery] string order, [FromQuery] int page)
        {
            orderKey = (orderKey == null) ? "startDate" : orderKey;
            order    = (order == null) ? "asc" : order;
            page     = (page == 0) ? 1 : page;
            try
            {
                var rowsPerPage = 50;
                IEnumerable <ProjectResource> projects;
                if (String.IsNullOrEmpty(searchWord))
                {
                    projects = await projectsRepository.GetAllProjectResources(orderKey, order, page, rowsPerPage);
                }
                else
                {
                    projects = await projectsRepository.GetAllProjectResourcesWithTitle(searchWord, orderKey, order, page, rowsPerPage);
                }

                if (projects == null || !projects.Any())
                {
                    var error = new NotFoundException("No projects data found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                bool isLastPage = (projects.Count() <= rowsPerPage);
                if (!isLastPage)
                {
                    var projectsList = projects.ToList();
                    projectsList.RemoveAt(rowsPerPage);
                    projects = projectsList;
                }
                var resource = mapper.Map <IEnumerable <ProjectResource>, IEnumerable <ProjectSummary> >(projects);
                var extra    = new
                {
                    searchWord = searchWord,
                    page       = page,
                    size       = resource.Count(),
                    order      = order,
                    orderKey   = orderKey,
                    isLastPage = isLastPage,
                    maxPages   = projects.Select(u => u.MaxPages).FirstOrDefault()
                };
                var response = new OkResponse <IEnumerable <ProjectSummary> >(resource, "Everything is good", extra);
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #12
0
        public async Task <IActionResult> UpdateAProject([FromBody] ProjectProfile projectProfile, string projectNumber)
        {
            if (projectProfile == null)
            {
                var error = new BadRequestException("The given project profile is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (
                projectProfile.ProjectManager == null || String.IsNullOrEmpty(projectProfile.ProjectManager.UserID) ||
                projectProfile.ProjectSummary == null ||
                String.IsNullOrEmpty(projectProfile.ProjectSummary.ProjectNumber) || String.IsNullOrEmpty(projectNumber) ||
                projectProfile.ProjectSummary.Location == null
                )
            {
                var error = new BadRequestException("The Project (Manager(ID) / Summary / Number / Location) cannot be null or empty string!");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (projectProfile.ProjectSummary.ProjectNumber != projectNumber)
            {
                var errMessage = $"The project number on URL '{projectNumber}'" +
                                 $" does not match with '{projectProfile.ProjectSummary.ProjectNumber}' in Request Body's Project Summary";
                var error = new BadRequestException(errMessage);
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var location = await locationsRepository.GetALocation(projectProfile.ProjectSummary.Location.City);

                var updatedProjectNumber = await projectsRepository.UpdateAProject(projectProfile, location.Id);

                var response = new UpdatedResponse <string>(updatedProjectNumber, "Successfully updated");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                if (err is CustomException <InternalServerException> )
                {
                    return(StatusCode(StatusCodes.Status500InternalServerError, ((CustomException <InternalServerException>)err).GetException()));
                }
                else
                {
                    var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                    if (err is SqlException)
                    {
                        var error = new InternalServerException(errMessage);
                        return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                    }
                    else
                    {
                        var error = new BadRequestException(errMessage);
                        return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                    }
                }
            }
        }
Exemple #13
0
        public async Task <IActionResult> ConfirmResource([FromRoute] int openingId)
        {
            if (openingId == 0)
            {
                var error = new BadRequestException($"The given opening {openingId} is invalid");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }
            try
            {
                Position position = await positionsRepository.GetAPosition(openingId);

                if (position == null)
                {
                    var error = new NotFoundException($"Invalid positionId {openingId}.");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }

                if (position.ResourceId == null || position.ResourceId == "")
                {
                    var error = new BadRequestException($"Position {position.Id} does not have a resource assigned.");
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }

                position.IsConfirmed = true;
                var updatedPosition = await positionsRepository.UpdateAPosition(position);

                IEnumerable <Position> positionsOfUser = await positionsRepository.GetAllPositionsOfUser(position.ResourceId);

                IEnumerable <OutOfOffice> outOfOfficesOfUser = await outOfOfficeRepository.GetAllOutOfOfficeForUser(position.ResourceId);

                var utilization = await utilizationRepository.CalculateUtilizationOfUser(positionsOfUser, outOfOfficesOfUser);

                await usersRepository.UpdateUtilizationOfUser(utilization, position.ResourceId);

                RequestProjectAssign response = new RequestProjectAssign
                {
                    OpeningId            = openingId,
                    UserID               = position.ResourceId,
                    ConfirmedUtilization = utilization
                };
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #14
0
        public async Task <IActionResult> GetMasterlists()
        {
            try
            {
                var disciplineResources = await disciplinesRepository.GetAllDisciplinesWithSkills();

                if (disciplineResources == null || !disciplineResources.Any())
                {
                    var error = new NotFoundException("No disciplines data found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var disciplines = MapDisciplines(disciplineResources);

                var locationResources = await locationsRepository.GetAllLocationsGroupByProvince();

                if (locationResources == null || !locationResources.Any())
                {
                    var error = new NotFoundException("No locations data found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var locations = MapLocations(locationResources);

                var yearsOfExp = await resourceDisciplineRepository.GetAllYearsOfExp();

                if (yearsOfExp == null || !yearsOfExp.Any())
                {
                    var error = new NotFoundException("No yearsOfExp data found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }

                var resource = new MasterResource
                {
                    Disciplines = disciplines,
                    Locations   = locations,
                    YearsOfExp  = yearsOfExp
                };

                var response = new OkResponse <MasterResource>(resource, "Everything is good");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #15
0
 public override async Task Invoke(HttpContext context)
 {
     try
     {
         await Next(context);
     }
     catch (Exception exception)
     {
         var apiException = new InternalServerException(exception);
         await HandleException(context, apiException);
     }
 }
Exemple #16
0
        /*
         * (non-Javadoc)
         *
         * @see com.teamcenter.soa.client.ExceptionHandler#handleException(com.teamcenter.schemas.soa._2006_03.exceptions.InternalServerException)
         */
        public void HandleException(InternalServerException ise)
        {
            //Console.WriteLine("");
            //Console.WriteLine("*****");
            //Console.WriteLine("Exception caught in com.teamcenter.clientx.AppXExceptionHandler.handleException(InternalServerException).");


            if (ise is ConnectionException)
            {
                // ConnectionException are typically due to a network error (server
                // down .etc) and can be recovered from (the last request can be sent again,
                // after the problem is corrected).
                //Console.Write("\nThe server returned an connection error.\n" + ise.Message
                //+ "\nDo you wish to retry the last service request?[y/n]");
            }
            else if (ise is ProtocolException)
            {
                // ProtocolException are typically due to programming errors
                // (content of HTTP
                // request is incorrect). These are generally can not be
                // recovered from.
                //Console.Write("\nThe server returned an protocol error.\n" + ise.Message
                //+ "\nThis is most likely the result of a programming error."
                //+ "\nDo you wish to retry the last service request?[y/n]");
            }
            else
            {
                //Console.WriteLine("\nThe server returned an internal server error.\n"
                //+ ise.Message
                //+ "\nThis is most likely the result of a programming error."
                //+ "\nA RuntimeException will be thrown.");
                throw new SystemException(ise.Message);
            }

            try
            {
                String retry = Console.ReadLine();
                // If yes, return to the calling SOA client framework, where the
                // last service request will be resent.
                if (retry.ToLower().Equals("y") || retry.ToLower().Equals("yes"))
                {
                    return;
                }

                throw new SystemException("The user has opted not to retry the last request");
            }
            catch (IOException e)
            {
                Console.Error.WriteLine("Failed to read user response.\nA RuntimeException will be thrown.");
                throw new SystemException(e.Message);
            }
        }
Exemple #17
0
        public async Task <IActionResult> SearchUsers([FromBody] RequestSearchUsers req)
        {
            if (req == null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, new BadRequestException("The given user is null / Request Body cannot be read")));
            }

            try
            {
                var rowsPerPage = 50;
                var users       = await usersRepository.GetAllUserResourcesOnFilter(req, rowsPerPage);

                if (users == null || !users.Any())
                {
                    var error = new NotFoundException("No users data found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                bool isLastPage = (users.Count() <= rowsPerPage);
                if (!isLastPage)
                {
                    var usersList = users.ToList();
                    usersList.RemoveAt(rowsPerPage);
                    users = usersList;
                }
                var usersSummary = mapper.Map <IEnumerable <UserResource>, IEnumerable <UserSummary> >(users);
                var extra        = new
                {
                    requestBody = req,
                    size        = usersSummary.Count(),
                    isLastPage  = isLastPage,
                    maxPages    = users.Select(u => u.MaxPages).FirstOrDefault()
                };
                var response = new OkResponse <IEnumerable <UserSummary> >(usersSummary, "Everything is Ok", extra);
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #18
0
        private async Task <int> UpdateAProject(
            SqlConnection connection, int locationId,
            ProjectSummary projectSummary, ProjectManager projectManager
            )
        {
            string currentManagerId = await GetCurrentManagerIdOfProject(connection, projectSummary.ProjectNumber);

            if (!String.Equals(currentManagerId, projectManager.UserID))
            {
                var updatedUserCount = await UpdateOneUser(connection, projectManager.UserID);

                if (updatedUserCount != 1)
                {
                    var error = new InternalServerException("New Manager is not updated! Please check server!");
                    throw new CustomException <InternalServerException>(error);
                }
            }

            var sql = @"
                UPDATE Projects 
                SET 
                    Title = @Title,
                    LocationId = @LocationId,
                    ManagerId = @ManagerId,
                    ProjectStartDate = @ProjectStartDate,
                    ProjectEndDate = @ProjectEndDate
                WHERE
                    Number = @Number
            ;";

            connection.Open();
            int updatedCount = await connection.ExecuteAsync(sql, new
            {
                Number           = projectSummary.ProjectNumber,
                Title            = projectSummary.Title,
                LocationId       = locationId,
                ManagerId        = projectManager.UserID,
                ProjectStartDate = projectSummary.ProjectStartDate,
                ProjectEndDate   = projectSummary.ProjectEndDate
            });

            connection.Close();

            return(updatedCount);
        }
Exemple #19
0
        public async Task <IActionResult> DeleteASkill([FromRoute] int disciplineID, [FromRoute] string skillName)
        {
            if (String.IsNullOrEmpty(skillName))
            {
                var error = new BadRequestException("Skill Name cannot be null or empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (disciplineID == 0)
            {
                var error = new BadRequestException("The given discipline ID is invalid");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var deleted = await skillsRepository.DeleteASkill(skillName, disciplineID);

                if (deleted == null)
                {
                    var error = new NotFoundException("The given skill cannot be found on database");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }

                var response = new DeletedResponse <int>(deleted.Id, $"Successfully deleted skill '{deleted.Id}'");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #20
0
        public async Task <IActionResult> CreateASkill([FromBody] DisciplineSkillResource req, int disciplineID)
        {
            if (req == null)
            {
                var error = new BadRequestException("The given request body is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (disciplineID == 0 || disciplineID != req.DisciplineId)
            {
                var error = new BadRequestException("The given discipline ID is invalid");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (String.IsNullOrEmpty(req.Name))
            {
                var error = new BadRequestException("Skill Name cannot be null or empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var createdSkillID = await skillsRepository.CreateASkill(req);

                var response = new CreatedResponse <int>(createdSkillID, $"Successfully created skill '{createdSkillID}' associated with discipline '{disciplineID}'");
                return(StatusCode(StatusCodes.Status201Created, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #21
0
        public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
        {
            ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);

            if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException"))
            {
                InternalServerException ex = new InternalServerException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);

                return(ex);
            }

            if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException"))
            {
                InvalidRequestException ex = new InvalidRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);

                return(ex);
            }

            return(new AmazonElasticMapReduceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode));
        }
Exemple #22
0
        public async Task <IActionResult> CreateAProvince([FromBody] LocationResource location)
        {
            if (location == null)
            {
                var error = new BadRequestException("The given request body is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (String.IsNullOrEmpty(location.Province))
            {
                var error = new BadRequestException("Province cannot be null or empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var createdProvinceName = await locationsRepository.CreateAProvince(location.Province);

                var response = new CreatedResponse <string>(createdProvinceName, $"Successfully created province '{createdProvinceName}'");
                // Log.Information("@{a}", response);
                return(StatusCode(StatusCodes.Status201Created, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    // Log.Information("second bad request");
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #23
0
        public async Task <IActionResult> CreateADiscipline([FromBody] DisciplineResource discipline)
        {
            if (discipline == null)
            {
                var error = new BadRequestException("The given discipline is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (String.IsNullOrEmpty(discipline.Name))
            {
                var error = new BadRequestException("Discipline Name cannot be null or empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var createdDisciplineID = await disciplinesRepository.CreateADiscipline(discipline);

                var response = new CreatedResponse <int>(createdDisciplineID, $"Successfully created discipline '{createdDisciplineID}'");
                return(StatusCode(StatusCodes.Status201Created, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #24
0
        public async Task <IActionResult> CreateALocation([FromBody] LocationResource location)
        {
            if (location == null)
            {
                var error = new BadRequestException("The given request body is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (String.IsNullOrEmpty(location.Province) || String.IsNullOrEmpty(location.City))
            {
                var error = new BadRequestException("Province and City cannot be null or empty");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                var createdLocationID = await locationsRepository.CreateALocation(location);

                var response = new CreatedResponse <int>(createdLocationID, $"Successfully created location '{createdLocationID}'");
                return(StatusCode(StatusCodes.Status201Created, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
        private ClientException ParseError(IRestResponse response)
        {
            if (response == null)
            {
                return new ConnectionException();
            }
            if (HttpStatusCode.Redirect.Equals(response.StatusCode) || HttpStatusCode.TemporaryRedirect.Equals(response.StatusCode) || HttpStatusCode.MovedPermanently.Equals(response.StatusCode))
            {
                return new RedirectionException();
            }

            if (string.IsNullOrWhiteSpace(response.Content))
            {
                if (HttpStatusCode.Forbidden.Equals(response.StatusCode) || HttpStatusCode.NotFound.Equals(response.StatusCode) ||
                    HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode) || HttpStatusCode.NotImplemented.Equals(response.StatusCode))
                {
                    ClientException e = null;
                    ErrorResponse errorResponse = new ErrorResponse();

                    foreach (Parameter parameter in response.Headers)
                    {
                        if (parameter.Name.Equals("x-amz-id-2", StringComparison.CurrentCultureIgnoreCase))
                        {
                            errorResponse.XAmzID2 = parameter.Value.ToString();
                        }
                        if (parameter.Name.Equals("x-amz-request-id", StringComparison.CurrentCultureIgnoreCase))
                        {
                            errorResponse.RequestID = parameter.Value.ToString();
                        }
                    }

                    errorResponse.Resource = response.Request.Resource;

                    if (HttpStatusCode.NotFound.Equals(response.StatusCode))
                    {
                        int pathLength = response.Request.Resource.Split('/').Count();
                        if (pathLength > 1)
                        {
                            errorResponse.Code = "NoSuchKey";
                            e = new ObjectNotFoundException();
                        }
                        else if (pathLength == 1)
                        {
                            errorResponse.Code = "NoSuchBucket";
                            e = new BucketNotFoundException();
                        }
                        else
                        {
                            e = new InternalClientException("404 without body resulted in path with less than two components");
                        }
                    }
                    else if (HttpStatusCode.Forbidden.Equals(response.StatusCode))
                    {
                        errorResponse.Code = "Forbidden";
                        e = new AccessDeniedException();
                    }
                    else if (HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode))
                    {
                        errorResponse.Code = "MethodNotAllowed";
                        e = new MethodNotAllowedException();
                    }
                    else
                    {
                        errorResponse.Code = "MethodNotAllowed";
                        e = new MethodNotAllowedException();
                    }
                    e.Response = errorResponse;
                    return e;
                }
                throw new InternalClientException("Unsuccessful response from server without XML error: " + response.StatusCode);
            }

            var contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content);
            var stream = new MemoryStream(contentBytes);
            ErrorResponse errResponse = (ErrorResponse)(new XmlSerializer(typeof(ErrorResponse)).Deserialize(stream));
            string code = errResponse.Code;

            ClientException clientException;

            if ("NoSuchBucket".Equals(code)) clientException = new BucketNotFoundException();
            else if ("NoSuchKey".Equals(code)) clientException = new ObjectNotFoundException();
            else if ("InvalidBucketName".Equals(code)) clientException = new InvalidKeyNameException();
            else if ("InvalidObjectName".Equals(code)) clientException = new InvalidKeyNameException();
            else if ("AccessDenied".Equals(code)) clientException = new AccessDeniedException();
            else if ("InvalidAccessKeyId".Equals(code)) clientException = new AccessDeniedException();
            else if ("BucketAlreadyExists".Equals(code)) clientException = new BucketExistsException();
            else if ("ObjectAlreadyExists".Equals(code)) clientException = new ObjectExistsException();
            else if ("InternalError".Equals(code)) clientException = new InternalServerException();
            else if ("KeyTooLong".Equals(code)) clientException = new InvalidKeyNameException();
            else if ("TooManyBuckets".Equals(code)) clientException = new MaxBucketsReachedException();
            else if ("PermanentRedirect".Equals(code)) clientException = new RedirectionException();
            else if ("MethodNotAllowed".Equals(code)) clientException = new ObjectExistsException();
            else if ("BucketAlreadyOwnedByYou".Equals(code)) clientException = new BucketExistsException();
            else clientException = new InternalClientException(errResponse.ToString());

            clientException.Response = errResponse;
            clientException.XmlError = response.Content;
            return clientException;
        }
        protected override IEnumerator Routine()
        {
            string url = Material.Url;

            if (Material.Parameters != null)
            {
                foreach (string param in Material.Parameters)
                {
                    url += "/" + param;
                }
            }

            Debug.Log(url);

            WWW www;

            if (Material.Fields != null)
            {
                WWWForm form = new WWWForm();

                foreach (string key in Material.Fields.Keys)
                {
                    form.AddField(key, Material.Fields[key]);
                }

                www = new WWW(url, form);
            }
            else
            {
                www = new WWW(url);
            }

            yield return(www);

            Debug.Log(www.text);

            if (www.error != null)
            {
                Exception ex = null;

                if (www.error.Contains("java.net.UnknownHostException"))
                {
                    ex = new NoConnectionException();
                }
                else if (www.error.Contains("Failed to connect to"))
                {
                    ex = new ServerException();
                }
                else if (www.error.Contains("Recv failure: Connection was reset"))
                {
                    ex = new ConnectionDropException();
                }
                else
                {
                    try
                    {
                        string status = www.responseHeaders["STATUS"];

                        if (status.Contains("404 Not Found"))
                        {
                            ex = new NotFoundException();
                        }
                        else if (status.Contains("500 Internal Server Error"))
                        {
                            ex = new InternalServerException();
                        }
                    }
                    catch (Exception)
                    {
                        ex = new Exception(www.error);

                        Debug.LogAssertion(www.error);
                    }
                }

                if (OnFail != null)
                {
                    OnFail(ex);
                }
                else
                {
                    Events.Exception(ex);
                }
            }
            else
            {
                try
                {
                    if (www.text == "not recognized")
                    {
                        OnFail(new InstanceException());
                    }
                    else
                    {
                        OnSuccess(www);
                    }
                }
                catch (Exception ex)
                {
                    if (OnFail != null)
                    {
                        OnFail(ex);
                    }
                    else
                    {
                        Events.Exception(ex);
                    }
                }
            }

            Dispose();
        }
Exemple #27
0
        public async Task <IActionResult> GetAUser(string userId)
        {
            try
            {
                var user = await usersRepository.GetAUserResource(userId);

                if (user == null)
                {
                    var error = new NotFoundException($"No users with userId '{userId}' found");
                    return(StatusCode(StatusCodes.Status404NotFound, new CustomException <NotFoundException>(error).GetException()));
                }
                var userSummary = mapper.Map <UserResource, UserSummary>(user);

                var projects = await projectsRepository.GetAllProjectResourcesOfUser(userId);

                var positionsResource = await positionsRepository.GetPositionsOfUser(userId);

                var positions   = mapper.Map <IEnumerable <PositionResource>, IEnumerable <PositionSummary> >(positionsResource);
                var disciplines = await disciplinesRepository.GetUserDisciplines(userId);

                var skills = await skillsRepository.GetUserSkills(userId);

                var outOfOffice = await outOfOfficeRepository.GetAllOutOfOfficeForUser(userId);

                IEnumerable <ResourceDisciplineResource> disciplineResources = Enumerable.Empty <ResourceDisciplineResource>();
                foreach (var discipline in disciplines)
                {
                    var discSkills = skills.Where(x => x.ResourceDisciplineName == discipline.Name);
                    var disc       = new ResourceDisciplineResource
                    {
                        DisciplineID = discipline.DisciplineId,
                        Discipline   = discipline.Name,
                        YearsOfExp   = discipline.YearsOfExperience,
                        Skills       = discSkills.Select(x => x.Name).ToHashSet()
                    };
                    disciplineResources = disciplineResources.Append(disc);
                }
                var userProfile = new UserProfile
                {
                    UserSummary     = userSummary,
                    Availability    = mapper.Map <IEnumerable <OutOfOffice>, IEnumerable <OutOfOfficeResource> >(outOfOffice),
                    CurrentProjects = mapper.Map <IEnumerable <ProjectResource>, IEnumerable <ProjectSummary> >(projects),
                    Disciplines     = disciplineResources,
                    Positions       = positions
                };

                var response = new OkResponse <UserProfile>(userProfile, "Everything is good");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #28
0
        public async Task <IActionResult> UpdateUser([FromBody] UserProfile userProfile, string userId)
        {
            if (userProfile == null)
            {
                var error = new BadRequestException("The given user is null / Request Body cannot be read");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (
                userProfile.UserSummary == null || String.IsNullOrEmpty(userProfile.UserSummary.UserID) ||
                userProfile.UserSummary.Location == null ||
                userProfile.Availability == null || userProfile.Disciplines == null
                )
            {
                var error = new BadRequestException("The User (Summary(ID) / Location / Availability / Disciplines) cannot be null or empty string!");
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            if (!String.Equals(userProfile.UserSummary.UserID, userId))
            {
                var errMessage = $"The user ID on URL '{userId}'" +
                                 $" does not match with '{userProfile.UserSummary.UserID}' in Request Body's Project Summary";
                var error = new BadRequestException(errMessage);
                return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
            }

            try
            {
                UserSummary summary  = userProfile.UserSummary;
                Location    location = await locationsRepository.GetALocation(userProfile.UserSummary.Location.City);

                var changedUser = await usersRepository.UpdateAUser(summary, location);

                if (changedUser == "-1")
                {
                    var error = new InternalServerException($"Cannot Update User with id: {userId}");
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                var disciplines = await processDisciplineSkillChanges(userProfile.Disciplines, userId);

                var avails = await processOutOfOfficeChanges(userProfile.Availability, userId);

                var tmp      = new { changedUser, disciplines, avails };
                var response = new OkResponse <string>(userId, "Successfully updated");
                return(StatusCode(StatusCodes.Status200OK, response));
            }
            catch (Exception err)
            {
                var errMessage = $"Source: {err.Source}\n  Message: {err.Message}\n  StackTrace: {err.StackTrace}\n";
                if (err is SqlException)
                {
                    var error = new InternalServerException(errMessage);
                    return(StatusCode(StatusCodes.Status500InternalServerError, new CustomException <InternalServerException>(error).GetException()));
                }
                else
                {
                    var error = new BadRequestException(errMessage);
                    return(StatusCode(StatusCodes.Status400BadRequest, new CustomException <BadRequestException>(error).GetException()));
                }
            }
        }
Exemple #29
0
        public async Task <string> UpdateAProject(ProjectProfile projectProfile, int locationId)
        {
            using var connection = new SqlConnection(connectionString);

            var projectSummary = projectProfile.ProjectSummary;
            var projectManager = projectProfile.ProjectManager;
            var updatedCount   = await this.UpdateAProject(connection, locationId, projectSummary, projectManager);

            if (updatedCount != 1)
            {
                var errMessage = $"Query returns failure status on updating project number '{projectProfile.ProjectSummary.ProjectNumber}'";
                var error      = new InternalServerException(errMessage);
                throw new CustomException <InternalServerException>(error);
            }

            else
            {
                var projectId = await this.GetProjectId(connection, projectSummary.ProjectNumber);

                var currentOpeningIds = await this.GetCurrentOpeningIdsForProject(connection, projectId);

                if (
                    (currentOpeningIds != null && currentOpeningIds.Any()) &&
                    (projectProfile.Openings == null || !projectProfile.Openings.Any())
                    )
                {
                    var deletedCount = await this.DeleteAllOpeningPositions(connection, projectId);

                    if (deletedCount != currentOpeningIds.Count())
                    {
                        var error = new InternalServerException(
                            $@"Deleted opening counts ({deletedCount}) is not the same as Current opening counts ({currentOpeningIds.Count()})"
                            );
                        throw new CustomException <InternalServerException>(error);
                    }
                }
                else
                {
                    var request     = projectProfile.Openings.Select(opening => opening.PositionID);
                    var toDeleteIds = currentOpeningIds.Except(request);
                    if (toDeleteIds != null && toDeleteIds.Count() > 0)
                    {
                        var deletedCount = await this.DeleteOpeningPositions(connection, toDeleteIds);

                        if (deletedCount != toDeleteIds.Count())
                        {
                            var error = new InternalServerException(
                                $@"Deleted opening counts ({deletedCount}) is not the same as To Be Deleted opening counts ({toDeleteIds.Count()})"
                                );
                            throw new CustomException <InternalServerException>(error);
                        }
                    }

                    foreach (var opening in projectProfile.Openings)
                    {
                        if (!currentOpeningIds.Contains(opening.PositionID))
                        {
                            var newOpeningId = await this.CreateAnOpeningPosition(connection, opening, projectId);

                            if (opening.Skills.Count != 0)
                            {
                                foreach (var skill in opening.Skills)
                                {
                                    await this.CreatePositionSkill(connection, newOpeningId, skill);
                                }
                            }
                        }
                        else
                        {
                            var updateOpeningSuccess = await this.UpdateAnOpeningPosition(connection, opening, projectId);

                            if (updateOpeningSuccess == 1)
                            {
                                if (opening.Skills.Count != 0)
                                {
                                    var currentSkillIds = await GetCurrentPositionSkillIds(connection, opening.PositionID);

                                    var openingSkillIds = await GetSkillIds(connection, opening.Skills, opening.Discipline);

                                    foreach (var id in openingSkillIds)
                                    {
                                        if (!currentSkillIds.Contains(id))
                                        {
                                            await this.CreatePositionSkill(connection, opening.PositionID, id);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return(projectSummary.ProjectNumber);
            }
        }
        protected override IEnumerator Routine()
        {
            string url = Material.Url;

            if (Material.Parameters != null)
            {
                foreach (string param in Material.Parameters)
                {
                    url += "/" + param;
                }
            }

            WWW www = new WWW(url);

            if (Material.UI_Text != null)
            {
                MonoBridge.StartCoroutine(Progress(www));
            }

            yield return(www);

            while (!www.isDone)
            {
            }

            if (Material.UI_Text != null)
            {
                Material.UI_Text.text = "";
            }

            if (www.error != null)
            {
                Exception ex = null;

                if (www.error.Contains("java.net.UnknownHostException"))
                {
                    ex = new NoConnectionException();
                }
                else if (www.error.Contains("Failed to connect to"))
                {
                    ex = new ServerException();
                }
                else if (www.error.Contains("Recv failure: Connection was reset"))
                {
                    ex = new ConnectionDropException();
                }
                else
                {
                    try
                    {
                        string status = www.responseHeaders["STATUS"];

                        if (status.Contains("404 Not Found"))
                        {
                            ex = new NotFoundException();
                        }
                        else if (status.Contains("500 Internal Server Error"))
                        {
                            ex = new InternalServerException();
                        }
                    }
                    catch (Exception)
                    {
                        ex = new Exception(www.error);

                        Debug.LogAssertion(www.error);
                    }
                }

                if (OnFail != null)
                {
                    OnFail(ex);
                }
                else
                {
                    Events.Exception(ex);
                }
            }
            else
            {
                try
                {
                    OnSuccess(www);
                }
                catch (Exception ex)
                {
                    if (OnFail != null)
                    {
                        OnFail(ex);
                    }
                    else
                    {
                        Events.Exception(ex);
                    }
                }
            }

            Dispose();
        }
Exemple #31
0
        private ClientException ParseError(IRestResponse response)
        {
            if (response == null)
            {
                return(new ConnectionException());
            }
            if (HttpStatusCode.Redirect.Equals(response.StatusCode) || HttpStatusCode.TemporaryRedirect.Equals(response.StatusCode) || HttpStatusCode.MovedPermanently.Equals(response.StatusCode))
            {
                return(new RedirectionException());
            }

            if (string.IsNullOrWhiteSpace(response.Content))
            {
                if (HttpStatusCode.Forbidden.Equals(response.StatusCode) || HttpStatusCode.NotFound.Equals(response.StatusCode) ||
                    HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode) || HttpStatusCode.NotImplemented.Equals(response.StatusCode))
                {
                    ClientException e             = null;
                    ErrorResponse   errorResponse = new ErrorResponse();

                    foreach (Parameter parameter in response.Headers)
                    {
                        if (parameter.Name.Equals("x-amz-id-2", StringComparison.CurrentCultureIgnoreCase))
                        {
                            errorResponse.HostID = parameter.Value.ToString();
                        }
                        if (parameter.Name.Equals("x-amz-request-id", StringComparison.CurrentCultureIgnoreCase))
                        {
                            errorResponse.RequestID = parameter.Value.ToString();
                        }
                    }

                    errorResponse.Resource = response.Request.Resource;

                    if (HttpStatusCode.NotFound.Equals(response.StatusCode))
                    {
                        int pathLength = response.Request.Resource.Split('/').Count();
                        if (pathLength > 1)
                        {
                            errorResponse.Code = "NoSuchKey";
                            e = new ObjectNotFoundException();
                        }
                        else if (pathLength == 1)
                        {
                            errorResponse.Code = "NoSuchBucket";
                            e = new BucketNotFoundException();
                        }
                        else
                        {
                            e = new InternalClientException("404 without body resulted in path with less than two components");
                        }
                    }
                    else if (HttpStatusCode.Forbidden.Equals(response.StatusCode))
                    {
                        errorResponse.Code = "Forbidden";
                        e = new AccessDeniedException();
                    }
                    else if (HttpStatusCode.MethodNotAllowed.Equals(response.StatusCode))
                    {
                        errorResponse.Code = "MethodNotAllowed";
                        e = new MethodNotAllowedException();
                    }
                    else
                    {
                        errorResponse.Code = "MethodNotAllowed";
                        e = new MethodNotAllowedException();
                    }
                    e.Response = errorResponse;
                    return(e);
                }
                throw new InternalClientException("Unsuccessful response from server without XML error: " + response.StatusCode);
            }

            var           contentBytes = System.Text.Encoding.UTF8.GetBytes(response.Content);
            var           stream       = new MemoryStream(contentBytes);
            ErrorResponse errResponse  = (ErrorResponse)(new XmlSerializer(typeof(ErrorResponse)).Deserialize(stream));
            string        code         = errResponse.Code;

            ClientException clientException;

            if ("NoSuchBucket".Equals(code))
            {
                clientException = new BucketNotFoundException();
            }
            else if ("NoSuchKey".Equals(code))
            {
                clientException = new ObjectNotFoundException();
            }
            else if ("InvalidBucketName".Equals(code))
            {
                clientException = new InvalidKeyNameException();
            }
            else if ("InvalidObjectName".Equals(code))
            {
                clientException = new InvalidKeyNameException();
            }
            else if ("AccessDenied".Equals(code))
            {
                clientException = new AccessDeniedException();
            }
            else if ("InvalidAccessKeyId".Equals(code))
            {
                clientException = new AccessDeniedException();
            }
            else if ("BucketAlreadyExists".Equals(code))
            {
                clientException = new BucketExistsException();
            }
            else if ("ObjectAlreadyExists".Equals(code))
            {
                clientException = new ObjectExistsException();
            }
            else if ("InternalError".Equals(code))
            {
                clientException = new InternalServerException();
            }
            else if ("KeyTooLong".Equals(code))
            {
                clientException = new InvalidKeyNameException();
            }
            else if ("TooManyBuckets".Equals(code))
            {
                clientException = new MaxBucketsReachedException();
            }
            else if ("PermanentRedirect".Equals(code))
            {
                clientException = new RedirectionException();
            }
            else if ("MethodNotAllowed".Equals(code))
            {
                clientException = new ObjectExistsException();
            }
            else if ("BucketAlreadyOwnedByYou".Equals(code))
            {
                clientException = new BucketExistsException();
            }
            else
            {
                clientException = new InternalClientException(errResponse.ToString());
            }


            clientException.Response = errResponse;
            clientException.XmlError = response.Content;
            return(clientException);
        }