Exemplo n.º 1
0
        public virtual DataAccessResult <TEntity> Update(TEntity entityToUpdate,
                                                         EntityState newChildrenState = EntityState.Unchanged)
        {
            var result = new DataAccessResult <TEntity>();

            try
            {
                //If entityToUpdate is already being tracked, then we want to use a different method for updating the entity, so check that here
                if (MainEntity.Local.Any(e => e.Id.Equals(entityToUpdate.Id)))
                {
                    var existingEntity = GetEntity(entityToUpdate.Id);
                    DbContext.Entry(existingEntity).CurrentValues.SetValues(entityToUpdate);
                }
                else
                {
                    DbContext.Entry(entityToUpdate).State = EntityState.Modified;
                }

                SetExistingChildrenStateTo(newChildrenState, entityToUpdate);

                result.IsSuccessful = true;
                result.Data         = entityToUpdate;
            }
            catch (Exception ex)
            {
                result.IsSuccessful = false;
                result.Error        = ErrorValues.GENERIC_FATAL_BACKEND_ERROR;
                Logger.Error(GetFormattedGenericLogMessage(GENERIC_UPDATE_LOG_MESSAGE), ex);
            }

            return(result);
        }
Exemplo n.º 2
0
        protected override void zExecuteStep()
        {
            string command = DataUtils.ApplyStateVariablesToString(m_Step.Command, CurrentScope.DataScope, m_Step.TrimVariableValueWhitespace);

            using (IDataAccess dataAccess = DataAccessFactory.CreateDataAccess(m_Step.ConnectionType, m_Step.ConnectionString))
            {
                DataAccessResult result;
                if (m_Step.ResultMapping is ScalarResultMapping)
                {
                    DataAccessResult <object> scalarResult = dataAccess.ExecuteScalar(m_Step.CommandType, command, paramBuilder => zCreateInputParameters(paramBuilder));
                    zReadScalarResult(scalarResult.Value);
                    result = scalarResult;
                }
                else if (m_Step.ResultMapping is TableResultMapping)
                {
                    result = dataAccess.ExecuteQueryReader(m_Step.CommandType, command,
                                                           paramBuilder => zCreateInputParameters(paramBuilder),
                                                           reader => zReadTableResult(reader));
                }
                else
                {
                    result = dataAccess.ExecuteNonQuery(m_Step.CommandType, command, paramBuilder => zCreateInputParameters(paramBuilder));
                }
                zReadOutputParameters(result.OutputParameters);
            }

            zCompleteStep(StepResult.Success);
        }
Exemplo n.º 3
0
        public async virtual Task <DataAccessResult <TEntity> > GetWhereAsync(Expression <Func <TEntity, bool> > predicate,
                                                                              params string[] includes)
        {
            var result = new DataAccessResult <TEntity>();

            try
            {
                var subset = await
                             MainEntity.IncludeMany(includes)
                             .AsExpandable()
                             .Where(predicate)
                             .SingleOrDefaultAsync();

                result.Data         = subset;
                result.IsSuccessful = true;
            }
            catch (Exception ex)
            {
                result.IsSuccessful = false;
                result.Error        = ErrorValues.GENERIC_FATAL_BACKEND_ERROR;
                Logger.Error(GetFormattedGenericLogMessage(GENERIC_GET_WHERE_LOG_MESSAGE), ex);
            }

            return(result);
        }
Exemplo n.º 4
0
        private async Task <string> StartInitializeUserAsync(SignInContext signInContext, IAsyncCollector <EventGridEvent> collector, ILogger log)
        {
            string id                           = Guid.NewGuid().ToString();
            string location                     = $"{serviceBaseAddress}/UserInit/{id}";
            UserInitializeStatus status         = new UserInitializeStatus(id, false);
            DataAccessResult     entryAddResult = await dataService.SetUserInitializeStatusAsync(status);

            if (!entryAddResult.Success)
            {
                log.LogWarning("Cannot add user initialize status to database. Status {statusCode}", entryAddResult.StatusCode);
            }
            try
            {
                var eventGridEvent = new EventGridEvent(
                    id: $"UserInit-{Guid.NewGuid()}",
                    subject: signInContext.SignedInUser,
                    data: new Models.UserInitializeCommand(signInContext, id),
                    eventType: "DL444.Ucqu.UserInit",
                    eventTime: DateTime.UtcNow,
                    dataVersion: "1.0"
                    );
                await collector.AddAsync(eventGridEvent);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Cannot trigger user initialization.");
            }
            return(location);
        }
Exemplo n.º 5
0
        public virtual DataAccessResult <List <TEntity> > GetAllWhereOrdered(
            Expression <Func <TEntity, bool> > predicate,
            string orderBy, bool descending,
            params string[] includes)
        {
            var result = new DataAccessResult <List <TEntity> >();

            try
            {
                var builder = MainEntity.IncludeMany(includes).AsExpandable().Where(predicate);
                builder = @descending ? builder.OrderBy("it." + orderBy + " descending") : builder.OrderBy("it." + orderBy);

                var allOrderedEntities = builder.ToList();

                result.IsSuccessful = true;
                result.Data         = allOrderedEntities;
            }
            catch (Exception ex)
            {
                result.IsSuccessful = false;
                result.Error        = ErrorValues.GENERIC_FATAL_BACKEND_ERROR;
                Logger.Error(GetFormattedGenericLogMessage(GENERIC_GET_ALL_WHERE_ORDERED_LOG_MESSAGE), ex);
            }
            return(result);
        }
        private bool RecordExistsCheck(SQLiteCommand cmd, IExpenseTypeModel expenseTypeModel)
        {
            Int32 countOfRecsFound        = 0;
            bool  RecordExistsCheckPassed = true;

            DataAccessResult dataAccessResult = new DataAccessResult();

            cmd.Prepare();
            cmd.CommandText = "Select count(*) from ExpenseType where ExpenseTypeName=@ExpenseTypeName";
            cmd.Parameters.AddWithValue("@ExpenseTypeName", expenseTypeModel.ExpenseTypeName);

            try
            {
                countOfRecsFound = Convert.ToInt32(cmd.ExecuteScalar());
            }
            catch (SQLiteException e)
            {
                string msg = e.Message;
                throw;
            }

            if (countOfRecsFound > 0)
            {
                dataAccessResult.Status = "Error";
                RecordExistsCheckPassed = false;
                throw new DataAccessException(dataAccessResult);
            }
            return(RecordExistsCheckPassed);
        }
Exemplo n.º 7
0
        public async Task <DataAccessResult <List <string> > > GetUsersAsync()
        {
            int             userCount  = 0;
            QueryDefinition countQuery = new QueryDefinition("SELECT COUNT(c) AS ItemCount FROM c WHERE c.pk = \"Credential\"");

            await foreach (Models.CountHeader header in container.GetItemQueryIterator <Models.CountHeader>(countQuery, requestOptions: new QueryRequestOptions()
            {
                PartitionKey = new PartitionKey("Credential")
            }))
            {
                userCount = header.ItemCount;
            }
            if (userCount == 0)
            {
                return(DataAccessResult <List <string> > .Ok(new List <string>()));
            }
            var             users      = new List <string>(userCount);
            QueryDefinition usersQuery = new QueryDefinition("SELECT c.Resource.StudentId FROM c WHERE c.pk = \"Credential\"");

            await foreach (Models.StudentIdHeader header in container.GetItemQueryIterator <Models.StudentIdHeader>(usersQuery, requestOptions: new QueryRequestOptions()
            {
                PartitionKey = new PartitionKey("Credential")
            }))
            {
                users.Add(header.StudentId);
            }
            return(DataAccessResult <List <string> > .Ok(users));
        }
Exemplo n.º 8
0
        public async Task <DataAccessResult> RemovePushChannelAsync(string username, PushPlatform platform, IEnumerable <string> channelIdentifiers)
        {
            DataAccessResult <NotificationChannelCollection> fetchResult = await GetPushChannelsAsync(username, platform);

            NotificationChannelCollection collection;

            if (fetchResult.Success)
            {
                collection = fetchResult.Resource;
            }
            else
            {
                return(new DataAccessResult(false, fetchResult.StatusCode));
            }

            int removedCount = 0;

            foreach (string id in channelIdentifiers)
            {
                removedCount += collection.Channels.RemoveAll(x => x.ChannelIdentifier.Equals(id, StringComparison.Ordinal));
            }
            if (removedCount == 0)
            {
                return(new DataAccessResult(false, 404));
            }
            return(await SetResourceAsync(collection));
        }
Exemplo n.º 9
0
        public async Task <DataAccessResult> AddPushChannelAsync(string username, PushPlatform platform, string channelIdentifier)
        {
            DataAccessResult <NotificationChannelCollection> fetchResult = await GetPushChannelsAsync(username, platform);

            NotificationChannelCollection collection;

            if (fetchResult.Success)
            {
                collection = fetchResult.Resource;
            }
            else if (fetchResult.StatusCode == 404)
            {
                collection = new NotificationChannelCollection(username, platform);
            }
            else
            {
                return(new DataAccessResult(false, fetchResult.StatusCode));
            }
            if (collection.Channels.Exists(x => x.ChannelIdentifier.Equals(channelIdentifier, StringComparison.Ordinal)))
            {
                return(DataAccessResult.Ok);
            }

            collection.Channels.Add(new NotificationChannelItem(channelIdentifier));
            if (collection.Channels.Count > maxChannelCountPerPlatform)
            {
                collection.Channels.RemoveAt(0);
            }
            return(await SetResourceAsync(collection));
        }
Exemplo n.º 10
0
        public async Task SendNotificationAsync(string username, Func <WindowsPushNotification> notificationFunc, ILogger log)
        {
            Task <string?> tokenTask = GetTokenAsync(log);
            DataAccessResult <NotificationChannelCollection> channelResult = await dataService.GetPushChannelsAsync(username, Platform);

            if (channelResult.StatusCode == 404)
            {
                return;
            }
            else if (!channelResult.Success)
            {
                log.LogError("Failed to fetch WNS channels from databse. Username: {username}", username);
            }
            string?token = await tokenTask;

            if (token == null)
            {
                return;
            }

            List <string> channelsToRemove = new List <string>();

            for (int i = 0; i < channelResult.Resource.Channels.Count; i++)
            {
                string channel = channelResult.Resource.Channels[i].ChannelIdentifier;
                if (!new Uri(channel).Host.EndsWith(validChannelHost, StringComparison.Ordinal))
                {
                    log.LogWarning("Invalid channel found. Channel URI: {channelUri}", channel);
                    channelsToRemove.Add(channel);
                    continue;
                }

                WindowsPushNotification notification = notificationFunc();
                if (notification.Type == WindowsNotificationType.Raw)
                {
                    throw new NotSupportedException($"Notification type {notification.Type} is not currently supported.");
                }
                HttpRequestMessage  request  = CreateRequest(token, channel, notification);
                HttpResponseMessage response = await httpClient.SendAsync(request);

                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    token = await RenewTokenAsync(log);

                    if (token == null)
                    {
                        return;
                    }
                    i--;
                }
                else if (response.StatusCode == System.Net.HttpStatusCode.NotFound || response.StatusCode == System.Net.HttpStatusCode.Gone)
                {
                    channelsToRemove.Add(channel);
                }
                else if (!response.IsSuccessStatusCode)
                {
                    log.LogWarning("Failed to send notification to WNS server. Username: {username}", username);
                }
            }
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "UserInit/{id}")] HttpRequest req,
            string id,
            ILogger log)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return(new BadRequestResult());
            }
            DataAccessResult <UserInitializeStatus> result = await dataService.GetUserInitializeStatusAsync(id);

            if (result.Success)
            {
                if (result.Resource.Completed)
                {
                    return(new OkObjectResult(new BackendResult <UserInitializeStatus>(result.Resource)));
                }
                else
                {
                    return(new AcceptedResult($"{serviceBaseAddress}/UserInit/{id}", new BackendResult <UserInitializeStatus>(true, result.Resource, locService.GetString("UserInitPrepare"))));
                }
            }
            else
            {
                return(new NotFoundResult());
            }
        }
        public IEnumerable <MonthCategoryCost> GetTotalCostPerCategoryAndMonth(int year, int month, int UserId)
        {
            List <MonthCategoryCost> list             = new List <MonthCategoryCost>();
            DataAccessResult         dataAccessResult = new DataAccessResult();

            string sql = "SELECT Expense.ExpenseTypeId, " +
                         "ExpenseType.ExpenseTypeName, " +
                         "SUM(Cost) as TotalCost " +
                         "from Expense INNER JOIN ExpenseType " +
                         "ON Expense.ExpenseTypeId = ExpenseType.ExpenseTypeId " +
                         "WHERE UserId = @UserId AND strftime('%Y', Expense.Date) = @Year AND strftime('%m', Expense.Date) = @Month " +
                         "GROUP BY Expense.ExpenseTypeId";

            using (SQLiteConnection connection = new SQLiteConnection(_connectionString))
            {
                try
                {
                    connection.Open();

                    using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
                    {
                        cmd.CommandText = sql;
                        cmd.Prepare();
                        cmd.Parameters.Add(new SQLiteParameter("@UserId", UserId));
                        cmd.Parameters.Add(new SQLiteParameter("@Year", year.ToString()));
                        cmd.Parameters.Add(new SQLiteParameter("@Month", month.ToString("00")));

                        using (SQLiteDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                MonthCategoryCost item = new MonthCategoryCost();
                                item.ExpenseTypeId   = Int32.Parse(reader["ExpenseTypeId"].ToString());
                                item.ExpenseTypeName = reader["ExpenseTypeName"].ToString();
                                item.TotalCost       = Double.Parse(reader["TotalCost"].ToString());
                                list.Add(item);
                            }
                        }
                    }
                }
                catch (SQLiteException e)
                {
                    dataAccessResult.setValues(
                        status: "Error",
                        operationSucceeded: false,
                        exceptionMessage: e.Message,
                        customMessage: "Greška kod dohvata zapisa o trošku za zadani mjesec i kategoriju [Expense->GetTotalCostPerCategoryAndMonth]",
                        helpLink: e.HelpLink,
                        errorCode: e.ErrorCode,
                        stackTrace: e.StackTrace);
                    throw new DataAccessException(e.Message, e.InnerException, dataAccessResult);
                }
            }
            return(list);
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = "notifyChannel/windows")] HttpRequest req,
            [UserIdentity] string?username,
            ILogger log)
        {
            if (username == null)
            {
                return(new UnauthorizedResult());
            }
            NotificationChannelItem channel;

            try
            {
                channel = await JsonSerializer.DeserializeAsync <NotificationChannelItem>(req.Body);
            }
            catch (JsonException)
            {
                return(new BadRequestResult());
            }
            if (!Uri.TryCreate(channel.ChannelIdentifier, UriKind.Absolute, out Uri? uri) || !uri.Host.EndsWith(validChannelHost, StringComparison.Ordinal))
            {
                return(new BadRequestResult());
            }

            DataAccessResult <StudentCredential> userFetchResult = await userDataService.GetCredentialAsync(username);

            if (userFetchResult.StatusCode == 404)
            {
                return(new UnauthorizedResult());
            }
            else if (!userFetchResult.Success)
            {
                log.LogError("Cannot fetch user information from database. Status: {statusCode}", userFetchResult.StatusCode);
                return(new ObjectResult(new BackendResult <object>(false, new object(), null))
                {
                    StatusCode = 503
                });
            }

            DataAccessResult result = await pushDataService.AddPushChannelAsync(username, PushPlatform.Wns, channel.ChannelIdentifier);

            if (result.Success)
            {
                return(new OkObjectResult(new BackendResult <object>(new object())));
            }
            else
            {
                log.LogError("Cannot write notification channel to database. Status: {statusCode}", result.StatusCode);
                return(new ObjectResult(new BackendResult <object>(false, new object(), null))
                {
                    StatusCode = 503
                });
            }
        }
Exemplo n.º 14
0
        public async Task <IActionResult> RunGet(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "Calendar/{username}/{id}")] HttpRequest req,
            string?username,
            string?id,
            ILogger log)
        {
            if (username == null || id == null)
            {
                return(new BadRequestResult());
            }
            Task <DataAccessResult <Schedule> >     scheduleFetchTask = dataService.GetScheduleAsync(username);
            Task <DataAccessResult <ExamSchedule> > examsFetchTask    = dataService.GetExamsAsync(username);
            DataAccessResult <StudentInfo>          userFetchResult   = await dataService.GetStudentInfoAsync(username);

            if (!userFetchResult.Success)
            {
                if (userFetchResult.StatusCode == 404)
                {
                    return(new OkObjectResult(calService.GetEmptyCalendar()));
                }
                else
                {
                    log.LogWarning("Failed to fetch user info from database. Status {statusCode}", userFetchResult.StatusCode);
                    return(new StatusCodeResult(503));
                }
            }
            if (!id.Equals(userFetchResult.Resource.CalendarSubscriptionId))
            {
                return(new OkObjectResult(calService.GetEmptyCalendar()));
            }

            DataAccessResult <Schedule> scheduleFetchResult = await scheduleFetchTask;

            if (!scheduleFetchResult.Success)
            {
                log.LogError("Failed to fetch schedule from database. Status {statusCode}", scheduleFetchResult.StatusCode);
                return(new StatusCodeResult(503));
            }
            DataAccessResult <ExamSchedule> examsFetchResult = await examsFetchTask;
            ExamSchedule?exams;

            if (examsFetchResult.Success)
            {
                exams = examsFetchResult.Resource;
            }
            else
            {
                exams = null;
                log.LogError("Failed to fetch exams from database. Status {statusCode}", examsFetchResult.StatusCode);
            }
            return(new OkObjectResult(calService.GetCalendar(scheduleFetchResult.Resource, exams, 15)));
        }
Exemplo n.º 15
0
        private async Task <DataAccessResult <T> > GetResourceAsync <T>(string id, string partitionKey) where T : ICosmosResource
        {
            try
            {
                ItemResponse <CosmosResource <T> > result = await container.ReadItemAsync <CosmosResource <T> >(id, new PartitionKey(partitionKey));

                return(DataAccessResult <T> .Ok(result.Value.Resource));
            }
            catch (CosmosException ex)
            {
                return(new DataAccessResult <T>(false, default(T), ex.Status));
            }
        }
Exemplo n.º 16
0
        public DataAccessResult ModifySickness(Sickness sickness, int[] habitList, int[] adviceList, int[] areaList)
        {
            var result = new DataAccessResult();

            var filterHabitList = from x in DbContext.Habits where habitList.Any(y => y == x.Id) select x;

            // Clear exsiting habits
            sickness.Habits = new List <Habit>();
            // Add new habits
            filterHabitList.ToList().ForEach(x => sickness.Habits.Add(x));

            var filterAdviceList = from x in DbContext.Advice where adviceList.Any(y => y == x.Id) select x;

            sickness.Advice = new List <Advice>();
            filterAdviceList.ToList().ForEach(x => sickness.Advice.Add(x));

            var filterAreaList = from x in DbContext.Areas where areaList.Any(y => y == x.Id) select x;

            sickness.Areas = new List <Area>();
            filterAreaList.ToList().ForEach(x => sickness.Areas.Add(x));

            try
            {
                DbContext.Set <Sickness>().Attach(sickness);
                DbContext.Entry(sickness).State = EntityState.Modified;
                if (DbContext.SaveChanges() > 0)
                {
                    result.ResultCode = ResultCodeOption.Ok;
                    result.Message    = DataAccessResult.SuccessDefaultString;
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                LogHelper.Log.Error($"{GetType().Name} exception.", dbEx);
                result.ResultCode = ResultCodeOption.ValidationFailure;
                result.Message    = dbEx.InnerException?.InnerException?.Message;
            }
            catch (DbUpdateException dbEx)
            {
                LogHelper.Log.Error($"{GetType().Name} exception.", dbEx);
                result.ResultCode = ResultCodeOption.Duplicate;
                result.Message    = dbEx.InnerException?.InnerException?.Message;
            }
            catch (Exception dbEx)
            {
                LogHelper.Log.Error($"{GetType().Name} exception.", dbEx);
                result.Message = dbEx.GetType().ToString();
            }

            return(result);
        }
        public IEnumerable <IExpenseModel> GetAllByUserIdAndExpenseType(int UserId, IExpenseTypeModel expenseTypeModel)
        {
            List <ExpenseModel> list             = new List <ExpenseModel>();
            DataAccessResult    dataAccessResult = new DataAccessResult();

            string sql = "SELECT * FROM Expense WHERE Expense.UserId = @UserId AND Expense.ExpenseTypeId = @ExpenseTypeId";

            using (SQLiteConnection connection = new SQLiteConnection(_connectionString))
            {
                try
                {
                    connection.Open();

                    using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
                    {
                        cmd.CommandText = sql;
                        cmd.Prepare();
                        cmd.Parameters.Add(new SQLiteParameter("@ExpenseTypeId", expenseTypeModel.ExpenseTypeId));
                        cmd.Parameters.Add(new SQLiteParameter("@UserId", UserId));

                        using (SQLiteDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                ExpenseModel expenseModel = new ExpenseModel();
                                expenseModel.ExpenseId     = Int32.Parse(reader["ExpenseId"].ToString());
                                expenseModel.ExpenseTypeId = Int32.Parse(reader["ExpenseTypeId"].ToString());
                                expenseModel.Date          = reader["Date"].ToString();
                                expenseModel.Cost          = Double.Parse(reader["Cost"].ToString());
                                list.Add(expenseModel);
                            }
                        }
                    }
                }
                catch (SQLiteException e)
                {
                    dataAccessResult.setValues(
                        status: "Error",
                        operationSucceeded: false,
                        exceptionMessage: e.Message,
                        customMessage: "Greška kod dohvata zapisa o trošku za zadanu kategoriju troška [Expense->getAllByExpenseType]",
                        helpLink: e.HelpLink,
                        errorCode: e.ErrorCode,
                        stackTrace: e.StackTrace);

                    throw new DataAccessException(e.Message, e.InnerException, dataAccessResult);
                }
            }
            return(list);
        }
Exemplo n.º 18
0
        public void Create(IUserModel userModel)
        {
            DataAccessResult dataAccessResult = new DataAccessResult();

            string sql = "INSERT INTO User (FirstName, LastName, CarModel) VALUES (@FirstName, @LastName, @CarModel)";

            using (SQLiteConnection connection = new SQLiteConnection(_connectionString))
            {
                try
                {
                    connection.Open();

                    using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
                    {
                        try
                        {
                            RecordExistsCheck(cmd, userModel);
                        }
                        catch (DataAccessException ex)
                        {
                            ex.DataAccessResult.CustomMessage    = "Korisnik već postoji u bazi podataka";
                            ex.DataAccessResult.ExceptionMessage = string.Copy(ex.Message);
                            ex.DataAccessResult.StackTrace       = string.Copy(ex.StackTrace);
                            throw ex;
                        }

                        cmd.CommandText = sql;
                        cmd.Prepare();
                        cmd.Parameters.AddWithValue("@FirstName", userModel.FirstName);
                        cmd.Parameters.AddWithValue("@LastName", userModel.LastName);
                        cmd.Parameters.AddWithValue("@CarModel", userModel.CarModel);
                        cmd.ExecuteNonQuery();
                    }
                }
                catch (SQLiteException e)
                {
                    dataAccessResult.setValues(
                        status: "Error",
                        operationSucceeded: false,
                        exceptionMessage: e.Message,
                        customMessage: "Greška kod kreiranja novog korisnika [User->Create]",
                        helpLink: e.HelpLink,
                        errorCode: e.ErrorCode,
                        stackTrace: e.StackTrace);

                    throw new DataAccessException(e.Message, e.InnerException, dataAccessResult);
                }
            }
            return;
        }
        public void Update(IExpenseTypeModel expenseTypeModel)
        {
            DataAccessResult dataAccessResult = new DataAccessResult();

            string sql = "UPDATE ExpenseType SET ExpenseTypeName = @ExpenseTypeName WHERE ExpenseType.ExpenseTypeId = @ExpenseTypeId;";

            using (SQLiteConnection connection = new SQLiteConnection(_connectionString))
            {
                try
                {
                    connection.Open();

                    using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
                    {
                        try
                        {
                            RecordExistsCheck(cmd, expenseTypeModel);
                        }
                        catch (DataAccessException ex)
                        {
                            ex.DataAccessResult.CustomMessage    = "Kategorija troška već postoji u bazi podataka";
                            ex.DataAccessResult.ExceptionMessage = string.Copy(ex.Message);
                            ex.DataAccessResult.StackTrace       = string.Copy(ex.StackTrace);
                            throw ex;
                        }

                        cmd.CommandText = sql;
                        cmd.Prepare();
                        cmd.Parameters.Add(new SQLiteParameter("@ExpenseTypeId", expenseTypeModel.ExpenseTypeId));
                        cmd.Parameters.Add(new SQLiteParameter("@ExpenseTypeName", expenseTypeModel.ExpenseTypeName));
                        cmd.ExecuteNonQuery();
                    }
                }
                catch (SQLiteException e)
                {
                    dataAccessResult.setValues(
                        status: "Error",
                        operationSucceeded: false,
                        exceptionMessage: e.Message,
                        customMessage: "Greška kod ažuriranja zapisa kategorije troška [ExpenseType->Update]",
                        helpLink: e.HelpLink,
                        errorCode: e.ErrorCode,
                        stackTrace: e.StackTrace);

                    throw new DataAccessException(e.Message, e.InnerException, dataAccessResult);
                }
            }
            return;
        }
Exemplo n.º 20
0
            private void _parse()
            {
                _dataResultType = m_io.ReadU1();
                switch (DataResultType)
                {
                case 0: {
                    _dataResultValue = new DlmsData(m_io);
                    break;
                }

                case 1: {
                    _dataResultValue = new DataAccessResult(m_io, this, m_root);
                    break;
                }
                }
            }
Exemplo n.º 21
0
        public async Task <IActionResult> RunGet(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "preferences")] HttpRequest req,
            [UserIdentity] string?username,
            ILogger log)
        {
            if (username == null)
            {
                return(new UnauthorizedResult());
            }

            DataAccessResult <UserPreferences> result = await dataService.GetUserPreferences(username);

            if (result.Success)
            {
                return(new OkObjectResult(new BackendResult <UserPreferences>(result.Resource)));
            }
            else if (result.StatusCode == 404)
            {
                DataAccessResult <StudentCredential> fetchUserResult = await dataService.GetCredentialAsync(username);

                if (fetchUserResult.Success)
                {
                    UserPreferences  preferences             = new UserPreferences(username);
                    DataAccessResult createPreferencesResult = await dataService.SetUserPreferences(preferences);

                    if (!createPreferencesResult.Success)
                    {
                        log.LogWarning("Failed to create preference record in database. Username: {username}, Status {statusCode}", username, createPreferencesResult.StatusCode);
                    }
                    return(new OkObjectResult(new BackendResult <UserPreferences>(preferences)));
                }
                else if (fetchUserResult.StatusCode == 404)
                {
                    return(new UnauthorizedResult());
                }
                else
                {
                    log.LogError("Failed to fetch user credentials from database. Username: {username}, Status {statusCode}", username, result.StatusCode);
                    return(GetFailedResult(false));
                }
            }
            else
            {
                log.LogError("Failed to fetch user preferences from database. Username: {username}, Status {statusCode}", username, result.StatusCode);
                return(GetFailedResult(false));
            }
        }
Exemplo n.º 22
0
            private void _parse()
            {
                _lastBlock    = m_io.ReadU1();
                _blockNumber  = m_io.ReadU4be();
                _resultChoice = m_io.ReadU1();
                switch (ResultChoice)
                {
                case 0: {
                    _result = new DlmsData.OctetString(m_io);
                    break;
                }

                case 1: {
                    _result = new DataAccessResult(m_io, this, m_root);
                    break;
                }
                }
            }
Exemplo n.º 23
0
        private async Task <string?> GetTokenAsync(ILogger log)
        {
            DataAccessResult <PushAccessToken> result = await dataService.GetPushAccessTokenAsync(Platform);

            if (result.Success)
            {
                return(result.Resource.Token);
            }
            else if (result.StatusCode == 404)
            {
                return(await RenewTokenAsync(log));
            }
            else
            {
                log.LogWarning("Unable to fetch WNS token from database. Status code: {statusCode}", result.StatusCode);
                return(null);
            }
        }
Exemplo n.º 24
0
        public virtual DataAccessResult <TEntity> Get(TPK byId)
        {
            var result = new DataAccessResult <TEntity>();

            try
            {
                result.Data         = GetEntity(byId);
                result.IsSuccessful = true;
            }
            catch (Exception ex)
            {
                result.IsSuccessful = false;
                result.Error        = ErrorValues.GENERIC_FATAL_BACKEND_ERROR;
                Logger.Error(GetFormattedGenericLogMessage(GENERIC_GET_LOG_MESSAGE), ex);
            }

            return(result);
        }
Exemplo n.º 25
0
        public async Task <DataAccessResult <StudentCredential> > GetCredentialAsync(string username)
        {
            DataAccessResult <StudentCredential> fetchResult = await GetResourceAsync <StudentCredential>($"Credential-{username}", "Credential");

            if (fetchResult.Success)
            {
                try
                {
                    encryptionService.DecryptCredential(fetchResult.Resource);
                }
                catch (System.Security.Cryptography.CryptographicException)
                {
                    // Key changed after last encryption. Equivalent to credential loss.
                    return(new DataAccessResult <StudentCredential>(false, null, 404));
                }
            }
            return(fetchResult);
        }
        public IExpenseTypeModel GetById(int Id)
        {
            DataAccessResult dataAccessResult = new DataAccessResult();
            ExpenseTypeModel expenseModel     = new ExpenseTypeModel();
            string           sql = "SELECT * FROM ExpenseType WHERE ExpenseType.ExpenseTypeId = @ExpenseTypeId";

            using (SQLiteConnection connection = new SQLiteConnection(_connectionString))
            {
                try
                {
                    connection.Open();

                    using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
                    {
                        cmd.CommandText = sql;
                        cmd.Prepare();
                        cmd.Parameters.Add(new SQLiteParameter("@ExpenseTypeId", Id));

                        using (SQLiteDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                expenseModel.ExpenseTypeId   = Int32.Parse(reader["ExpenseTypeId"].ToString());
                                expenseModel.ExpenseTypeName = reader["ExpenseTypeName"].ToString();
                            }
                        }
                    }
                }
                catch (SQLiteException e)
                {
                    dataAccessResult.setValues(
                        status: "Error",
                        operationSucceeded: false,
                        exceptionMessage: e.Message,
                        customMessage: "Greška kod dohvata zapisa o trošku [ExpenseType->GetById]",
                        helpLink: e.HelpLink,
                        errorCode: e.ErrorCode,
                        stackTrace: e.StackTrace);

                    throw new DataAccessException(e.Message, e.InnerException, dataAccessResult);
                }
            }
            return(expenseModel);
        }
        public List <int> GetDistinctYears(int UserId)
        {
            List <int>       list             = new List <int>();
            DataAccessResult dataAccessResult = new DataAccessResult();

            string sql = "SELECT DISTINCT(strftime('%Y', Date)) as Year from Expense WHERE UserId = @UserId";

            using (SQLiteConnection connection = new SQLiteConnection(_connectionString))
            {
                try
                {
                    connection.Open();

                    using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
                    {
                        cmd.CommandText = sql;
                        cmd.Prepare();
                        cmd.Parameters.Add(new SQLiteParameter("@UserId", UserId));

                        using (SQLiteDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                list.Add(Int32.Parse(reader["Year"].ToString()));
                            }
                        }
                    }
                }
                catch (SQLiteException e)
                {
                    dataAccessResult.setValues(
                        status: "Error",
                        operationSucceeded: false,
                        exceptionMessage: e.Message,
                        customMessage: "Greška kod dohvata liste godina potrošnje [Expense->GetDistinctYears]",
                        helpLink: e.HelpLink,
                        errorCode: e.ErrorCode,
                        stackTrace: e.StackTrace);
                    throw new DataAccessException(e.Message, e.InnerException, dataAccessResult);
                }
            }
            return(list);
        }
Exemplo n.º 28
0
        public async Task <List <string>?> GetUsersAsync(ILogger log)
        {
            try
            {
                DataAccessResult <List <string> > userFetchResult = await dataService.GetUsersAsync();

                return(userFetchResult.Resource);
            }
            catch (Azure.Cosmos.CosmosException ex)
            {
                log.LogError(ex, "Cannot fetch user credentials. Status {statusCode}", ex.Status);
                return(null);
            }
            catch (Exception ex)
            {
                log.LogError(ex, "Cannot fetch user credentials.");
                return(null);
            }
        }
Exemplo n.º 29
0
        protected DataAccessResult <T> ExecuteAdataAccess <T>(Func <DataAccessResult <T>, T> func, T defaultValue = default(T))
        {
            var response = new DataAccessResult <T>();
            var result   = defaultValue;

            try
            {
                result         = func(response);
                response.Value = result;
            }
            catch (Exception ex)
            {
                response.Error = ex;
                response.Value = defaultValue;
                SkExceptionHandler.HandleDataAccessException(ex);
            }

            return(response);
        }
        public IEnumerable <IExpenseTypeModel> GetAll()
        {
            DataAccessResult        dataAccessResult = new DataAccessResult();
            List <ExpenseTypeModel> list             = new List <ExpenseTypeModel>();
            string sql = "SELECT * FROM ExpenseType";

            using (SQLiteConnection connection = new SQLiteConnection(_connectionString))
            {
                try
                {
                    connection.Open();

                    using (SQLiteCommand cmd = new SQLiteCommand(sql, connection))
                    {
                        using (SQLiteDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                ExpenseTypeModel expenseTypeModel = new ExpenseTypeModel();
                                expenseTypeModel.ExpenseTypeId   = Int32.Parse(reader["ExpenseTypeId"].ToString());
                                expenseTypeModel.ExpenseTypeName = reader["ExpenseTypeName"].ToString();

                                list.Add(expenseTypeModel);
                            }
                        }
                    }
                }
                catch (SQLiteException e)
                {
                    dataAccessResult.setValues(
                        status: "Error",
                        operationSucceeded: false,
                        exceptionMessage: e.Message,
                        customMessage: "Greška kod dohvata svih zapisa kategorije troška [ExpenseType->GetAll]",
                        helpLink: e.HelpLink,
                        errorCode: e.ErrorCode,
                        stackTrace: e.StackTrace);

                    throw new DataAccessException(e.Message, e.InnerException, dataAccessResult);
                }
            }
            return(list);
        }
        /// <summary>
        /// Saves a file attachment for an application.
        /// </summary>
        /// <param name="applicationId">The application id.</param>
        /// <param name="controlName">The name of the file upload control.</param>
        /// <param name="fileIdentifier">The file identifier.</param>
        /// <param name="data">The file to save as a byte array.</param>
        /// <returns>A <see cref="DataAccessResult"/>.</returns>
        protected override DataAccessResult DoSaveAttachment(string applicationId, string controlName, string fileIdentifier, byte[] data)
        {
            var attachmentCollection = this.database.GetCollection(iApplyDb.ApplicationAttachments._COLLECTION_NAME);

            BsonValue bsonApplicationId = new BsonString(applicationId);
            BsonValue bsonControlName = new BsonString(controlName);
            BsonValue bsonFileIdentifier = new BsonString(fileIdentifier);

            var query = Query.And(
                Query.EQ(iApplyDb.ApplicationAttachments.APPLICATION_ID, bsonApplicationId),
                Query.EQ(iApplyDb.ApplicationAttachments.CONTROL_NAME, bsonControlName));

            BsonDocument document = attachmentCollection.FindOne(query) ?? new BsonDocument
                                                                           {
                                                                               { iApplyDb.ApplicationAttachments.APPLICATION_ID, bsonApplicationId },
                                                                               { iApplyDb.ApplicationAttachments.CONTROL_NAME, bsonControlName },
                                                                               { iApplyDb.ApplicationAttachments.FILES, new BsonArray() }
                                                                           };

            BsonArray array = document.GetValue(iApplyDb.ApplicationAttachments.FILES).AsBsonArray;
            BsonValue fileDocument = array.FirstOrDefault(d => ((BsonDocument)d).GetValue(iApplyDb.ApplicationAttachments.Files.FILE_IDENTIFIER).AsString == fileIdentifier);
            if (fileDocument == null)
            {
                fileDocument = new BsonDocument();
                fileDocument.AsBsonDocument.Add(iApplyDb.ApplicationAttachments.Files.FILE_IDENTIFIER, bsonFileIdentifier);
                array.Add(fileDocument);
            }

            fileDocument.AsBsonDocument[iApplyDb.ApplicationAttachments.Files.FILE] = new BsonBinaryData(data);
            attachmentCollection.Save(document);

            DataAccessResult result = new DataAccessResult
                                      {
                                          ApplicationId = applicationId,
                                          Id = document[iApplyDb.ApplicationAttachments._ID].AsObjectId.ToString()
                                      };

            return result;
        }
        /// <summary>
        /// Saves a payment response, associated to an application.
        /// </summary>
        /// <param name="applicationId">The application id.</param>
        /// <param name="response">The response from the payment provider.</param>
        /// <returns>A <see cref="DataAccessResult"/>.</returns>
        protected override DataAccessResult DoSavePaymentResponse(string applicationId, TransactionResponse response)
        {
            var applicationCollection = this.database.GetCollection("applicationPayments");

            BsonValue bsonApplicationId = new BsonString(applicationId);
            BsonDocument bsonResponse = this.TransactionResponseToBsonDocument(response);

            IMongoQuery query = Query.EQ("applicationId", bsonApplicationId);
            BsonDocument document = applicationCollection.FindOne(query) ?? new BsonDocument
                                                                            {
                                                                                { "applicationId", bsonApplicationId },
                                                                                { "payments", new BsonArray() }
                                                                            };

            BsonArray array = document.GetValue("payments").AsBsonArray;
            array.Add(bsonResponse);
            applicationCollection.Save(document);

            DataAccessResult result = new DataAccessResult
                                      {
                                          ApplicationId = applicationId,
                                          Id = document["_id"].AsObjectId.ToString()
                                      };
            return result;
        }