public async Task <IEnumerable <RolePermission> > Gets(string condition = "")
        {
            var param = new DynamicParameters();

            param.Add("@ConditionStr", condition, System.Data.DbType.String, System.Data.ParameterDirection.Input, int.MaxValue);
            return(await DalHelper.SPExecuteQuery <RolePermission>(SP_GETS_WITHCONDITION, param, dbTransaction : DbTransaction, connection : DbConnection));
        }
        public ActionResult Reports()
        {
            var dalHelper = new DalHelper();

            var courseResult = dalHelper.GetProfessorCoursesByUser(HttpContext.User.Identity.Name);

            if (courseResult.HasError)
            {
                throw new InvalidOperationException(courseResult.Message);
            }

            if (courseResult.Value == null || !courseResult.Value.Any())
            {
                return(View(new ReportsViewModel()));
            }

            var studentReportsResult = dalHelper.GetStudentReportByCourse(courseResult.Value.FirstOrDefault().Id);

            if (studentReportsResult.HasError)
            {
                throw new InvalidOperationException(studentReportsResult.Message);
            }

            var reportModel = new ReportsViewModel
            {
                AvailableCourses = courseResult.Value,
                StudentsReports  = studentReportsResult.Value
            };

            return(View(reportModel));
        }
        public async Task <RolePermission> Get(int id)
        {
            var param = new DynamicParameters();

            param.Add("@Id", id, System.Data.DbType.Int64, System.Data.ParameterDirection.Input);
            return((await DalHelper.SPExecuteQuery <RolePermission>(SP_GET, param, dbTransaction: DbTransaction, connection: DbConnection)).FirstOrDefault());
        }
        public void Save(IEnumerable <MessageTrafficTypeMapping> messageTrafficTypeMappingBatch, int?persistentStoreCopyId = null)
        {
            if (messageTrafficTypeMappingBatch == null)
            {
                throw new ArgumentNullException("messageTrafficTypeMappingBatch");
            }
            IHashBucket hashBucket = this.DataProvider as IHashBucket;

            if (hashBucket == null)
            {
                throw new NotSupportedException(string.Format("Save(MessageTrafficTypeMapping) is not supported for DataProvider: {0}", this.DataProvider.GetType()));
            }
            foreach (MessageTrafficTypeMapping messageTrafficTypeMapping in messageTrafficTypeMappingBatch)
            {
                messageTrafficTypeMapping[CommonReportingSchema.DomainHashKeyProp]  = new byte[0];
                messageTrafficTypeMapping[CommonReportingSchema.DataSourceProperty] = (messageTrafficTypeMapping.DataSource ?? "EXO");
            }
            Dictionary <object, List <MessageTrafficTypeMapping> > dictionary = DalHelper.SplitByPhysicalInstance <MessageTrafficTypeMapping>(hashBucket, CommonReportingSchema.OrganizationalUnitRootProperty, messageTrafficTypeMappingBatch, DalHelper.HashBucketProp);

            foreach (object obj in dictionary.Keys)
            {
                MessageTrafficTypeMappings messageTrafficTypeMappings = new MessageTrafficTypeMappings(dictionary[obj]);
                messageTrafficTypeMappings[DalHelper.PhysicalInstanceKeyProp] = obj;
                if (persistentStoreCopyId != null)
                {
                    messageTrafficTypeMappings[DalHelper.FssCopyIdProp] = persistentStoreCopyId;
                }
                this.DataProvider.Save(messageTrafficTypeMappings);
            }
        }
        public void Save(MessageTraceBatch messageTraceBatch)
        {
            if (messageTraceBatch == null)
            {
                throw new ArgumentNullException("messageTraceBatch");
            }
            IHashBucket hashBucket = this.DataProvider as IHashBucket;

            if (hashBucket != null)
            {
                Dictionary <object, List <MessageTrace> > dictionary = DalHelper.SplitByPhysicalInstance <MessageTrace>(hashBucket, MessageTraceSchema.OrganizationalUnitRootProperty, messageTraceBatch.ToList <MessageTrace>(), CommonMessageTraceSchema.HashBucketProperty);
                foreach (object obj in dictionary.Keys)
                {
                    dictionary[obj].Sort();
                    IEnumerable <List <MessageTrace> > optimizedBathesForSave = this.GetOptimizedBathesForSave(dictionary[obj]);
                    foreach (List <MessageTrace> messageList in optimizedBathesForSave)
                    {
                        MessageTraceForSaveDataSet instance = MessageTraceForSaveDataSet.CreateDataSet(obj, null, messageList, messageTraceBatch.PersistentStoreCopyId);
                        this.DataProvider.Save(instance);
                    }
                }
                return;
            }
            if (messageTraceBatch.OrganizationalUnitRoot == null)
            {
                throw new ArgumentException("MessageTraceBatch.OrganizationalUnitRoot should have valid TenantId");
            }
            foreach (MessageTrace messageTrace in messageTraceBatch)
            {
                messageTrace[CommonMessageTraceSchema.HashBucketProperty] = 1;
            }
            MessageTraceForSaveDataSet instance2 = MessageTraceForSaveDataSet.CreateDataSet(null, messageTraceBatch.OrganizationalUnitRoot, messageTraceBatch, null);

            this.DataProvider.Save(instance2);
        }
        internal IEnumerable <TenantInboundConnector> FindTenantInboundConnectorsForTenantIds(IEnumerable <Guid> tenantIds)
        {
            if (tenantIds == null)
            {
                throw new ArgumentNullException("tenantIds");
            }
            IEnumerable <Guid> enumerable = from tenantId in tenantIds.Distinct <Guid>()
                                            where tenantId != Guid.Empty
                                            select tenantId;

            if (enumerable.Count <Guid>() == 0)
            {
                throw new ArgumentException(HygieneDataStrings.ErrorEmptyList, "tenantIds");
            }
            Dictionary <object, List <Guid> > dictionary = DalHelper.SplitByPhysicalInstance <Guid>((IHashBucket)this.WebStoreDataProvider, enumerable, (Guid i) => i.ToString());
            List <TenantInboundConnector>     list       = new List <TenantInboundConnector>();

            foreach (object obj in dictionary.Keys)
            {
                list.AddRange(this.webStoreDataProvider.Find <TenantInboundConnector>(QueryFilter.AndTogether(new QueryFilter[]
                {
                    new ComparisonFilter(ComparisonOperator.Equal, DalHelper.TenantIds, new MultiValuedProperty <Guid>(dictionary[obj])),
                    new ComparisonFilter(ComparisonOperator.Equal, DalHelper.PhysicalInstanceKeyProp, obj)
                }), null, false, null).Cast <TenantInboundConnector>());
            }
            return(list);
        }
        internal void Save(IEnumerable <AggPolicyTrafficData> aggPolicyTrafficDataBatch, int?persistentStoreCopyId = null)
        {
            if (aggPolicyTrafficDataBatch == null)
            {
                throw new ArgumentNullException("aggPolicyTrafficDataBatch");
            }
            IHashBucket hashBucket = this.DataProvider as IHashBucket;

            if (hashBucket == null)
            {
                throw new NotSupportedException(string.Format("Save(AggPolicyTrafficData) is not supported for DataProvider: {0}", this.DataProvider.GetType()));
            }
            foreach (AggPolicyTrafficData aggPolicyTrafficData in aggPolicyTrafficDataBatch)
            {
                aggPolicyTrafficData[CommonReportingSchema.DomainHashKeyProp]  = new byte[0];
                aggPolicyTrafficData[CommonReportingSchema.DataSourceProperty] = (aggPolicyTrafficData.DataSource ?? "EXO");
            }
            Dictionary <object, List <AggPolicyTrafficData> > dictionary = DalHelper.SplitByPhysicalInstance <AggPolicyTrafficData>(hashBucket, CommonReportingSchema.OrganizationalUnitRootProperty, aggPolicyTrafficDataBatch, DalHelper.HashBucketProp);

            foreach (object obj in dictionary.Keys)
            {
                AggPolicyTrafficDatas aggPolicyTrafficDatas = new AggPolicyTrafficDatas(dictionary[obj]);
                aggPolicyTrafficDatas[DalHelper.PhysicalInstanceKeyProp] = obj;
                if (persistentStoreCopyId != null)
                {
                    aggPolicyTrafficDatas[DalHelper.FssCopyIdProp] = persistentStoreCopyId;
                }
                this.DataProvider.Save(aggPolicyTrafficDatas);
            }
        }
Beispiel #8
0
        private void btnatualiza_Click(object sender, EventArgs e)
        {
            try
            {
                //dgvOrdem.Rows.Add(dr["EntradaId"].ToString(), dr["Ordem"].ToString(), descricao, dr["Categoria"].ToString(), dr["Quantidade"].ToString(), dr["DataEntrada"].ToString(), dr["Preco"].ToString(), dr["Desconto"].ToString(), dr["Total"].ToString());
                if (dgvOrdem.Rows.Count > 0)
                {
                    foreach (DataGridViewRow dt in dgvOrdem.Rows)
                    {
                        int    entradaid  = Convert.ToInt32(dt.Cells["EntradaId"].Value.ToString());
                        double quantidade = Convert.ToDouble(dt.Cells["quantidade"].Value.ToString());
                        double desc       = Convert.ToDouble(txtDescontoSobreTotal.Text);
                        double preco      = Convert.ToDouble(dt.Cells["Preco"].Value.ToString());
                        string desconto   = "";
                        double total      = 0;
                        desconto = ((preco * desc) / 100).ToString("N2");
                        total    = quantidade * (preco - Convert.ToDouble(desconto));

                        DalHelper.ExecutaQuery($"UPDATE Entradas SET Desconto = '{desconto.ToString()}', Total = '{total.ToString()}', DescontoTotal = '{txtDescontoSobreTotal.Text.ToString()}' WHERE EntradaId = {entradaid};");
                    }
                }

                CarregaOrdem();
            }
            catch (Exception ex)
            {
                frmErro frm = new frmErro("Ocorreu um erro ao atualizar: " + ex.Message);
            }
        }
Beispiel #9
0
 public SchoolService()
 {
     //Remova os comentários da linha a seguir se usar componentes designados
     //InitializeComponent();
     DalHelper.CriarBancoSQLite();
     DalHelper.CriarTabelaSQlite();
 }
        public ActionResult Disputes()
        {
            var dalHelper    = new DalHelper();
            var courseResult = dalHelper.GetProfessorCoursesByUser(HttpContext.User.Identity.Name);

            if (courseResult.HasError)
            {
                throw new InvalidOperationException(courseResult.Message);
            }

            if (courseResult.Value == null || !courseResult.Value.Any())
            {
                return(View(new DisputesViewModel()));
            }

            var disputeResult = dalHelper.GetDisputesByCourseId(courseResult.Value.FirstOrDefault().Id);

            if (disputeResult.HasError)
            {
                throw new InvalidOperationException(disputeResult.Message);
            }

            var disputes = disputeResult.Value;
            var model    = new DisputesViewModel
            {
                AvailableCourses  = courseResult.Value,
                AvailableDisputes = disputes
            };

            return(View(model));
        }
Beispiel #11
0
        public string GetStudents()
        {
            JavaScriptSerializer dataContract   = new JavaScriptSerializer();
            string serializedDataInStringFormat = dataContract.Serialize(DalHelper.GetStudents());

            return(serializedDataInStringFormat);
        }
        public async Task <IEnumerable <RolePermission> > Gets(int roleId)
        {
            var param = new DynamicParameters();

            param.Add("@RoleId", roleId, System.Data.DbType.Int32, System.Data.ParameterDirection.Input);
            return(await DalHelper.SPExecuteQuery <RolePermission>(SP_GETS_WITHROLE, param, dbTransaction : DbTransaction, connection : DbConnection));
        }
Beispiel #13
0
 private void btnMvDown_Click(object sender, EventArgs e)
 {
     current = view.CurrentRow.Index;
     if (current < view.RowCount)
     {
         //view.Rows[0].Selected = true;
         //view.CurrentCell = view[1, 0];
         //atual
         int    id      = Convert.ToInt32(view.Rows[current].Cells[0].Value);
         string Comando = Convert.ToString(view.Rows[current].Cells[1].Value);
         int    X       = Convert.ToInt32(view.Rows[current].Cells[2].Value);
         int    Y       = Convert.ToInt32(view.Rows[current].Cells[3].Value);
         string Option  = Convert.ToString(view.Rows[current].Cells[4].Value);
         //anterior
         int    idproximo = Convert.ToInt32(view.Rows[current + 1].Cells[0].Value);
         string Cproximo  = Convert.ToString(view.Rows[current + 1].Cells[1].Value);
         int    Xproximo  = Convert.ToInt32(view.Rows[current + 1].Cells[2].Value);
         int    Yproximo  = Convert.ToInt32(view.Rows[current + 1].Cells[3].Value);
         string Oproximo  = Convert.ToString(view.Rows[current + 1].Cells[4].Value);
         //
         DalHelper.Update(id, Cproximo, Xproximo, Yproximo, Oproximo);
         DalHelper.Update(idproximo, Comando, X, Y, Option);
         update();
         //view.Rows[idproximo].Selected = true;
         //view.CurrentCell = view[1, idproximo];
     }
 }
        private IEnumerable <TransportRuleCollection> FindTransportRuleCollections(QueryFilter filter, ObjectId rootId, bool deepSearch, SortBy sortBy, int pageSize = 2147483647)
        {
            object obj;
            Guid   objectGuid;
            IEnumerable <TransportRuleCollection> enumerable;

            if (DalHelper.TryFindPropertyValueByName(filter, ADObjectSchema.Name.Name, out obj) && obj is string && FfoConfigurationSession.builtInTransportRuleContainers.TryGetValue((string)obj, out objectGuid))
            {
                TransportRuleCollection transportRuleCollection = new TransportRuleCollection
                {
                    Name = (string)obj
                };
                FfoDirectorySession.FixDistinguishedName(transportRuleCollection, base.TenantId.DistinguishedName, base.TenantId.ObjectGuid, objectGuid, null);
                enumerable = new TransportRuleCollection[]
                {
                    transportRuleCollection
                };
            }
            else
            {
                enumerable = base.FindAndHandleException <TransportRuleCollection>(filter, rootId, deepSearch, sortBy, pageSize);
                foreach (TransportRuleCollection transportRuleCollection2 in enumerable)
                {
                    FfoDirectorySession.FixDistinguishedName(transportRuleCollection2, base.TenantId.DistinguishedName, base.TenantId.ObjectGuid, ((ADObjectId)transportRuleCollection2.Identity).ObjectGuid, null);
                }
            }
            return(enumerable);
        }
Beispiel #15
0
        protected QueryFilter AddTenantIdFilter(QueryFilter filter)
        {
            if (this.TenantId == null)
            {
                return(filter);
            }
            ADObjectId extractedId             = null;
            bool       orgFilterAlreadyPresent = false;

            if (filter != null)
            {
                DalHelper.ForEachProperty(filter, delegate(PropertyDefinition propertyDefinition, object value)
                {
                    if (propertyDefinition == ExchangeConfigurationUnitSchema.ExternalDirectoryOrganizationId && value != null)
                    {
                        extractedId = new ADObjectId(DalHelper.GetTenantDistinguishedName(value.ToString()), Guid.Parse(value.ToString()));
                        return;
                    }
                    if (propertyDefinition == ADObjectSchema.OrganizationalUnitRoot && value != null)
                    {
                        orgFilterAlreadyPresent = true;
                    }
                });
            }
            if (!orgFilterAlreadyPresent)
            {
                QueryFilter queryFilter = new ComparisonFilter(ComparisonOperator.Equal, ADObjectSchema.OrganizationalUnitRoot, extractedId ?? this.TenantId);
                filter = ((filter == null) ? queryFilter : QueryFilter.AndTogether(new QueryFilter[]
                {
                    filter,
                    queryFilter
                }));
            }
            return(filter);
        }
        public static UnifiedPolicySettingStatus ToStatusStorage(UnifiedPolicyStatus status)
        {
            UnifiedPolicySettingStatus unifiedPolicySettingStatus = new UnifiedPolicySettingStatus();

            unifiedPolicySettingStatus[ADObjectSchema.OrganizationalUnitRoot] = new ADObjectId(status.TenantId);
            unifiedPolicySettingStatus.SetId((ADObjectId)DalHelper.ConvertFromStoreObject(status.ObjectId, typeof(ADObjectId)));
            unifiedPolicySettingStatus.SettingType           = UnifiedPolicyStorageFactory.ConvertToSettingType(status.ObjectType);
            unifiedPolicySettingStatus.ParentObjectId        = status.ParentObjectId;
            unifiedPolicySettingStatus.Container             = status.Workload.ToString();
            unifiedPolicySettingStatus.ObjectVersion         = status.Version.InternalStorage;
            unifiedPolicySettingStatus.ErrorCode             = (int)status.ErrorCode;
            unifiedPolicySettingStatus.ErrorMessage          = status.ErrorMessage;
            unifiedPolicySettingStatus.WhenProcessedUTC      = status.WhenProcessedUTC;
            unifiedPolicySettingStatus.AdditionalDiagnostics = status.AdditionalDiagnostics;
            switch (status.Mode)
            {
            case Mode.PendingDeletion:
                unifiedPolicySettingStatus.ObjectStatus = StatusMode.PendingDeletion;
                break;

            case Mode.Deleted:
                unifiedPolicySettingStatus.ObjectStatus = StatusMode.Deleted;
                break;

            default:
                unifiedPolicySettingStatus.ObjectStatus = StatusMode.Active;
                break;
            }
            return(unifiedPolicySettingStatus);
        }
Beispiel #17
0
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            // Register controller
            container.RegisterType <AirportsController>();
            container.RegisterType <HomeController>();
            container.RegisterType <CitiesController>();
            container.RegisterType <FlightsController>();
            container.RegisterType <HomeController>();
            container.RegisterType <LoginController>();
            container.RegisterType <ReportController>();

            // Register interface
            container.RegisterType <IUnit <Airport>, AirportTracker>();
            container.RegisterType <IUnit <City>, CityTracker>();
            container.RegisterType <IUnit <Flight>, FlightTracker>();
            container.RegisterType <IUnit <Plane>, PlaneTracker>();
            container.RegisterType <IUnit <Location>, LocationTracker>();
            container.RegisterType <IUnit <User>, UserTracker>();
            container.RegisterType <IUnit <HistoryLine>, HistoryUnit>();
            container.RegisterType <ITimeZoneApi, GoogleTimeZoneApi>();
            container.RegisterType <IInitialiser, TuiInitialiser>();

            TimeZoneHelper.Api = container.Resolve <ITimeZoneApi>();
            DalHelper.Set(container.Resolve <IInitialiser>());

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        }
        public PartialViewResult GetCourseDetails(int courseId)
        {
            var dalHelper              = new DalHelper();
            var courseDetails          = dalHelper.GetCourseDetails(courseId);
            var courseDetailsViewModel = new CoursesDetailsViewModel
            {
                CourseTitle   = courseDetails.Course.CourseName,
                StartTime     = courseDetails.Course.CourseStartTime.ToString(),
                EndTime       = courseDetails.Course.CourseEndTime.ToString(),
                BeforeCheckIn = courseDetails.Course.CheckInStartTime,
                AfterCheckIn  = courseDetails.Course.CheckInEndTime
            };

            var students = new List <Student>();

            courseDetails.TotalUsers.ForEach(c => students.Add(new Student
            {
                Id       = c.Id,
                Name     = $"{c.FirstName} {c.LastName}",
                Selected = false
            }));

            foreach (var user in courseDetails.CourseUsers)
            {
                var firstOrDefault = students.FirstOrDefault(c => c.Id == user.Id);
                if (firstOrDefault != null)
                {
                    firstOrDefault.Selected = true;
                }
            }

            courseDetailsViewModel.Students = students;

            return(PartialView("CourseDetails", courseDetailsViewModel));
        }
Beispiel #19
0
        private static MessageTraceEntityBase[] MapResultsTable <T>(DataTable table) where T : MessageTraceEntityBase, new()
        {
            List <MessageTraceEntityBase> list = new List <MessageTraceEntityBase>();

            if (list != null && table != null && table.Rows.Count > 0)
            {
                MessageTraceDataSet.< > c__DisplayClass3 <T> CS$ < > 8__locals1 = new MessageTraceDataSet.< > c__DisplayClass3 <T>();
                CS$ < > 8__locals1.columnSchema = table.Columns;
                foreach (object obj in table.Rows)
                {
                    DataRow dataRow = (DataRow)obj;
                    MessageTraceEntityBase           entity = Activator.CreateInstance <T>();
                    IEnumerable <PropertyDefinition> propertyDefinitions = (IEnumerable <PropertyDefinition>)entity.GetAllProperties();
                    using (IEnumerator enumerator2 = CS$ < > 8__locals1.columnSchema.GetEnumerator())
                    {
                        while (enumerator2.MoveNext())
                        {
                            DataColumn column = (DataColumn)enumerator2.Current;
                            try
                            {
                                PropertyDefinition propertyDefinition2 = propertyDefinitions.First((PropertyDefinition propertyDefinition) => string.Compare(propertyDefinition.Name, column.ColumnName, StringComparison.OrdinalIgnoreCase) == 0);
                                if (propertyDefinition2 != null)
                                {
                                    entity[propertyDefinition2] = DalHelper.ConvertFromStoreObject(dataRow[column], propertyDefinition2.Type);
                                }
                            }
                            catch (InvalidOperationException)
                            {
                            }
                        }
                    }
                    PropertyBase propertyBase = entity as PropertyBase;
                    if (propertyBase != null && propertyBase.PropertyName == MessageTraceCollapsedProperty.PropertyDefinition.Name)
                    {
                        byte[] data = Convert.FromBase64String(propertyBase.PropertyValueBlob.Value);
                        list.AddRange(MessageTraceCollapsedProperty.Expand <PropertyBase>(data, propertyBase.Namespace, delegate
                        {
                            PropertyBase propertyBase2 = Activator.CreateInstance <T>() as PropertyBase;
                            using (IEnumerator enumerator3 = CS$ < > 8__locals1.columnSchema.GetEnumerator())
                            {
                                while (enumerator3.MoveNext())
                                {
                                    MessageTraceDataSet.< > c__DisplayClass3 <T> CS$ < > 8__locals4 = CS$ < > 8__locals1;
                                    DataColumn column = (DataColumn)enumerator3.Current;
                                    try
                                    {
                                        PropertyDefinition propertyDefinition3 = propertyDefinitions.First((PropertyDefinition propertyDefinition) => string.Compare(propertyDefinition.Name, column.ColumnName, StringComparison.OrdinalIgnoreCase) == 0);
                                        if (propertyDefinition3 != null && propertyDefinition3 != PropertyBase.PropertyValueBlobProperty)
                                        {
                                            propertyBase2[propertyDefinition3] = entity[propertyDefinition3];
                                        }
                                    }
                                    catch (InvalidOperationException)
                                    {
                                    }
                                }
                            }
                            propertyBase2.PropertyId = Guid.NewGuid();
                            return(propertyBase2);
                        }));
Beispiel #20
0
        private void btnMvUp_Click(object sender, EventArgs e)
        {
            int current = view.CurrentRow.Index;

            if (current > 0)
            {
                //view.Rows[0].Selected = true;
                //view.CurrentCell = view[1, 0];
                //atual
                int    id      = Convert.ToInt32(view.Rows[current].Cells[0].Value);
                string Comando = Convert.ToString(view.Rows[current].Cells[1].Value);
                int    X       = Convert.ToInt32(view.Rows[current].Cells[2].Value);
                int    Y       = Convert.ToInt32(view.Rows[current].Cells[3].Value);
                string Option  = Convert.ToString(view.Rows[current].Cells[4].Value);
                //anterior
                int    idanterior = Convert.ToInt32(view.Rows[current - 1].Cells[0].Value);
                string Canterior  = Convert.ToString(view.Rows[current - 1].Cells[1].Value);
                int    Xanterior  = Convert.ToInt32(view.Rows[current - 1].Cells[2].Value);
                int    Yanterior  = Convert.ToInt32(view.Rows[current - 1].Cells[3].Value);
                string Oanterior  = Convert.ToString(view.Rows[current - 1].Cells[4].Value);
                //
                DalHelper.Update(idanterior, Comando, X, Y, Option);
                DalHelper.Update(id, Canterior, Xanterior, Yanterior, Oanterior);
                update();
                //view.Rows[idanterior].Selected = true;
                //view.CurrentCell = view[1, idanterior];
            }
        }
Beispiel #21
0
        public void Delete(StudentEntity entity)
        {
            // Guard against invalid arguments.
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (entity.Id <= 0)
            {
                throw new InvalidOperationException("Entity is invalid for Update, the Id must be greater than 0.");
            }

            var sqlHelper = new DalHelper(_connectionString);

            var parameters =
                new List <SqlParameter>
            {
                new SqlParameter("Id", entity.Id),
            };

            var procedureName = string.Format(
                DalHelper.DeleteStoredProcFormat,
                TableName);

            var rowsAffected = sqlHelper.ExecuteStoredProcedureNonQuery(
                procedureName,
                parameters);

            if (rowsAffected != 1)
            {
                throw new InvalidOperationException("Entity saving failed during Update.");
            }
        }
Beispiel #22
0
        public async Task Logout(UserSession userSession)
        {
            var param = new DynamicParameters();

            param.Add("@SessionId", userSession.SessionId, System.Data.DbType.Int32, System.Data.ParameterDirection.Input);
            await DalHelper.SPExecute(SP_LOGOUT, param, dbTransaction : DbTransaction, connection : DbConnection);
        }
Beispiel #23
0
        public async Task <UserSession> LoginAnotherUser(long sessionId, UserAccountViewModel user, AccessTokenModel token)
        {
            var param = new DynamicParameters();

            param.Add("@SessionId", sessionId, System.Data.DbType.Int32, System.Data.ParameterDirection.Input);
            param.Add("@UserId", user.Id, System.Data.DbType.Int32, System.Data.ParameterDirection.Input);
            param.Add("@AccessToken", token.AccessToken, System.Data.DbType.String, System.Data.ParameterDirection.Input);
            param.Add("@LoginDate", token.LoginDate, System.Data.DbType.DateTime, System.Data.ParameterDirection.Input);
            param.Add("@ExpiredDate", token.ExpiredDate, System.Data.DbType.DateTime, System.Data.ParameterDirection.Input);

            await DalHelper.SPExecute(SP_LOGIN_ANOTHER, param, dbTransaction : DbTransaction, connection : DbConnection);

            return(new UserSession()
            {
                LoginResult = 0,
                SessionId = sessionId,
                Username = user.Username,
                Email = user.Email,
                PhoneNumber = user.PhoneNumber,
                DisplayName = user.DisplayName,
                IsSuperAdmin = user.IsSuperAdmin,
                UserId = user.Id,
                RoleIds = user.Roles.Select(r => r.Id).ToList(),
                AccessToken = token.AccessToken
            });
        }
        public int Create(IndividualEntity entity)
        {
            // Guard against invalid arguments.
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (entity.Id > 0)
            {
                throw new InvalidOperationException("Entity is invalid for Create, the Id must be 0.");
            }

            var sqlHelper = new DalHelper(_connectionString);

            var parameters =
                new List <SqlParameter>
            {
                new SqlParameter("LastName", entity.LastName),
                new SqlParameter("FirstName", entity.FirstName),
                new SqlParameter("MiddleName", entity.MiddleName),
                new SqlParameter("Suffix", entity.Suffix),
                new SqlParameter("DateOfBirth", entity.DateOfBirth),
            };

            var procedureName = string.Format(
                DalHelper.CreateStoredProcFormat,
                TableName);

            try
            {
                var dataSet = sqlHelper.ExecuteStoredProcedure(
                    procedureName,
                    parameters);

                // Returns createdId if a record was created.
                var createdId = default(int);

                if (dataSet != null && dataSet.Tables.Count > 0)
                {
                    var table = dataSet.Tables[0];

                    foreach (DataRow row in table.Rows)
                    {
                        createdId = row.Field <int>("Id");

                        // Retrieve returns the first record.
                        break;
                    }
                }

                return(createdId);
            }
            catch (Exception exception)
            {
                // Throw an exception if the Id was not returned.
                throw new InvalidOperationException("Failed to create.", exception);
            }
        }
Beispiel #25
0
        public override async Task <int> HandleCommand(AddCommand request, CancellationToken cancellationToken)
        {
            if (request.Role == null || string.IsNullOrEmpty(request.Role.Name))
            {
                throw new BusinessException("Common.WrongInput");
            }

            var checkingRole = await roleQueries.GetByName(request.Role.Name);

            if (checkingRole != null)
            {
                throw new BusinessException("User.ExistedRole");
            }

            var roleId = -1;

            using (var conn = DalHelper.GetConnection())
            {
                conn.Open();
                using (var trans = conn.BeginTransaction())
                {
                    try
                    {
                        roleRepository.JoinTransaction(conn, trans);
                        rolePermissionRepository.JoinTransaction(conn, trans);

                        request.Role.IsExternalRole = false;
                        request.Role = CreateBuild(request.Role, request.LoginSession);
                        roleId       = await roleRepository.Add(request.Role);

                        foreach (var item in request.Role.RolePermissions)
                        {
                            item.RoleId = roleId;
                            await rolePermissionRepository.AddOrUpdate(item);
                        }
                    }
                    finally
                    {
                        if (roleId > 0)
                        {
                            trans.Commit();
                        }
                        else
                        {
                            try
                            {
                                trans.Rollback();
                            }
                            catch (Exception ex)
                            {
                                LogHelper.GetLogger().Error(ex);
                            }
                        }
                    }
                }
            }

            return(roleId);
        }
Beispiel #26
0
 public void Update(Aluno aluno)
 {
     if (aluno == null)
     {
         throw new ArgumentNullException("aluno");
     }
     DalHelper.UpdateAluno(aluno);
 }
Beispiel #27
0
 public void Insert(Aluno aluno)
 {
     if (aluno == null)
     {
         throw new ArgumentNullException("aluno");
     }
     DalHelper.InsertAluno(aluno);
 }
 public void Update(Produto produto)
 {
     if (produto == null)
     {
         throw new ArgumentNullException("produto");
     }
     DalHelper.UpdateProduto(produto);
 }
Beispiel #29
0
        public async Task <int> DeleteRole(int userId)
        {
            var param = new DynamicParameters();

            param.Add("@UserId", userId, System.Data.DbType.String, System.Data.ParameterDirection.Input);

            return(await DalHelper.SPExecute(SP_USERROLE_DELETE, param, dbTransaction : DbTransaction, connection : DbConnection));
        }
Beispiel #30
0
 private void btnRight_Click(object sender, EventArgs e)
 {
     DalHelper.Add(idatual, "Right", 0, 0, "");
     win32.SetForegroundWindow(otpHandle);
     SendKeys.SendWait("{Right}");
     idatual++;
     update();
 }
        public int Create(IndividualEntity entity)
        {
            // Guard against invalid arguments.
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (entity.Id > 0)
            {
                throw new InvalidOperationException("Entity is invalid for Create, the Id must be 0.");
            }

            var sqlHelper = new DalHelper(_connectionString);

            var parameters =
                new List<SqlParameter>
                    {
                        new SqlParameter("LastName", entity.LastName),
                        new SqlParameter("FirstName", entity.FirstName),
                        new SqlParameter("MiddleName", entity.MiddleName),
                        new SqlParameter("Suffix", entity.Suffix),
                        new SqlParameter("DateOfBirth", entity.DateOfBirth),
                    };

            try
            {
                var dataSet = sqlHelper.ExecuteStoredProcedure(
                    "dal_Individual_Create",
                    parameters);

                // Returns createdId if a record was created.
                var createdId = default(int);

                if (dataSet != null && dataSet.Tables.Count > 0)
                {
                    var table = dataSet.Tables[0];

                    foreach (DataRow row in table.Rows)
                    {
                        createdId = row.Field<int>("Id");

                        // Retrieve returns the first record.
                        break;
                    }
                }

                return createdId;
            }
            catch (Exception exception)
            {
                // Throw an exception if the Id was not returned.
                throw new InvalidOperationException("Failed to create.", exception);
            }
        }
        public IndividualEntity Retrieve(int id)
        {
            var sqlHelper = new DalHelper(_connectionString);

            var parameters =
                new List<SqlParameter>
                    {
                        new SqlParameter("Id", id),
                    };

            var dataSet = sqlHelper.ExecuteStoredProcedure(
                "dal_Individual_Retrieve",
                parameters);

            IndividualEntity entity = null;
            if (dataSet != null &&
                dataSet.Tables.Count > 0)
            {
                var table = dataSet.Tables[0];
                foreach (DataRow row in table.Rows)
                {
                    entity =
                        new IndividualEntity
                        {
                            Id = row.Field<int>("Id"),
                            LastName = row.Field<string>("LastName"),
                            FirstName = row.Field<string>("FirstName"),
                            MiddleName = row.Field<string>("MiddleName"),
                            Suffix = row.Field<string>("Suffix"),
                            DateOfBirth = row.Field<DateTime>("DateOfBirth"),
                        };

                    // Retrieve shouldn't return more than 1 row.
                    break;
                }
            }

            return entity;
        }
        public void Delete(IndividualEntity entity)
        {
            // Guard against invalid arguments.
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (entity.Id <= 0)
            {
                throw new InvalidOperationException("Entity is invalid for Update, the Id must be greater than 0.");
            }

            var sqlHelper = new DalHelper(_connectionString);

            var parameters =
                new List<SqlParameter>
                    {
                        new SqlParameter("Id", entity.Id),
                    };

            var rowsAffected = sqlHelper.ExecuteStoredProcedureNonQuery(
                "dal_Individual_Delete",
                parameters);

            if (rowsAffected != 1)
            {
                throw new InvalidOperationException("Entity saving failed during Update.");
            }
        }