コード例 #1
0
ファイル: DbUtilTest.cs プロジェクト: randomjs/thunder
        public void Clear()
        {
            var dbUtil = new DbUtil().Bind();
            dbUtil.CreateSchema();

            var session = SessionManager.SessionFactory.GetCurrentSession();

            using (var transaction = session.BeginTransaction())
            {
                session.Save(new Tire { Id = 1, Name = "Pirelli" });
                session.Save(new Tire { Id = 2, Name = "Goodyear" });

                session.Save(new Gol { Color = "Black", Door = 4, Name = "Gol 1.0 Flex", Tire = new Tire { Id = 1 } });
                session.Save(new Gol { Color = "White", Door = 4, Name = "Gol 1.6 Flex", Tire = new Tire { Id = 1 } });
                session.Save(new Uno { Color = "Red", Door = 2, Name = "Uno 1.0", Tire = new Tire { Id = 2 } });

                transaction.Commit();
            }

            dbUtil.Clear(typeof(Tire))
                .Clear(typeof(Gol))
                .Clear(typeof(Uno))
                .Clear(typeof(Car))
                .Unbind();
        }
コード例 #2
0
 public List<MessageEntity> Create()
 {
     // DBに接続してメッセージマスタを取得して変数にセット
     using (DbUtil db = new DbUtil())
     {
         return Select(db);
     }
 }
コード例 #3
0
 public SoshikiEntity Create(string soshikiCd)
 {
     // DBに接続して組織マスタを取得して変数にセット
     using (DbUtil db = new DbUtil())
     {
         return Select(db, soshikiCd);
     }
 }
コード例 #4
0
ファイル: ShainServer.cs プロジェクト: higeneko2015/WcfSample
 public ShainEntity Create(string shainCd)
 {
     // DBに接続して社員マスタを取得して変数にセット
     using (DbUtil db = new DbUtil())
     {
         return Select(db, shainCd);
     }
 }
コード例 #5
0
ファイル: CodeServer.cs プロジェクト: higeneko2015/WcfSample
 public List<CodeEntity> Create()
 {
     // DBに接続してコードマスタを取得して変数にセット
     using (DbUtil db = new DbUtil())
     {
         return Select(db);
     }
 }
コード例 #6
0
        /// <summary>
        /// システム全体で共有する情報を取得
        /// </summary>
        /// <returns></returns>
        public InitSystemEntity Init()
        {
            // 戻り値
            InitSystemEntity ReturnValue = new InitSystemEntity();

            // DBに接続
            using (DbUtil Db = new DbUtil())
            {
                // コードマスタ取得
                ReturnValue.CodeList = new CodeServer().Create(Db);
                // メッセージマスタ取得
                ReturnValue.MsgList = new MessagingServer().Create(Db);
            }

            // サーバー側のContextを初期設定
            ContextModel.CodeList = ReturnValue.CodeList;
            ContextModel.MsgList = ReturnValue.MsgList;

            // クライアント用に取得値を戻す
            return ReturnValue;
        }
コード例 #7
0
        // ReSharper disable once FunctionComplexityOverflow
        public ActionResult RegisterLink(string id, bool?showfamily, string source)
        {
            var li = new LinkInfo(registerlinkSTR, landingSTR, id);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                if (!li.pid.HasValue)
                {
                    throw new Exception("missing peopleid");
                }

                if (!li.oid.HasValue)
                {
                    throw new Exception("missing orgid");
                }

                var linktype = li.a.Length > 3 ? li.a[3].Split(':') : "".Split(':');
                int?gsid     = null;
                if (linktype[0].Equal("supportlink"))
                {
                    gsid = linktype.Length > 1 ? linktype[1].ToInt() : 0;
                }

                var q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == li.oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == li.oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();

                if (q.org == null && CurrentDatabase.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();
                }

                if (q.org == null)
                {
                    throw new Exception("org missing, bad link");
                }

                if (q.om == null && !gsid.HasValue && q.org.Limit <= q.org.RegLimitCount(CurrentDatabase))
                {
                    throw new Exception("sorry, maximum limit has been reached");
                }

                if (q.om == null && (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive))
                {
                    throw new Exception("sorry, registration has been closed");
                }

                DbUtil.LogActivity($"{registerlinkSTR}{landingSTR}", li.oid, li.pid);

                var url = string.IsNullOrWhiteSpace(source)
                    ? $"/OnlineReg/{li.oid}?registertag={id}"
                    : $"/OnlineReg/{li.oid}?registertag={id}&source={source}";
                if (gsid.HasValue)
                {
                    url += "&gsid=" + gsid;
                }

                if (showfamily == true)
                {
                    url += "&showfamily=true";
                }

                if (linktype[0].Equal("supportlink") && q.org.TripFundingPagesEnable && q.org.TripFundingPagesPublic)
                {
                    url = $"/OnlineReg/{li.oid}/Giving/?gsid={gsid}";
                }

                return(Redirect(url));
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{registerlinkSTR}{landingSTR}Error: {ex.Message}", li.oid, li.pid);
                return(Message(ex.Message));
            }
        }
コード例 #8
0
        public ActionResult VoteLinkSg(string id, string message, bool?confirm, FormCollection formCollection)
        {
            var li = new LinkInfo(votelinkSTR, confirmSTR, id);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                var smallgroup = li.a[4];

                if (!li.oid.HasValue)
                {
                    throw new Exception("orgid missing");
                }

                if (!li.pid.HasValue)
                {
                    throw new Exception("peopleid missing");
                }

                var q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == li.oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == li.oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();

                if (q.org == null && CurrentDatabase.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.Organizations.SingleOrDefault(oo => oo.OrganizationId == oid)
                                   let om = CurrentDatabase.OrganizationMembers.SingleOrDefault(oo => oo.OrganizationId == oid && oo.PeopleId == li.pid)
                                            select new { p = pp, org, om }).Single();
                }

                if (q.org == null)
                {
                    throw new Exception("org missing, bad link");
                }
                if ((q.org.RegistrationTypeId ?? RegistrationTypeCode.None) == RegistrationTypeCode.None)
                {
                    throw new Exception("votelink is no longer active");
                }

                if (q.om == null && q.org.Limit <= q.org.RegLimitCount(CurrentDatabase))
                {
                    throw new Exception("sorry, maximum limit has been reached");
                }

                if (q.om == null &&
                    (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive))
                {
                    throw new Exception("sorry, registration has been closed");
                }

                var setting = CurrentDatabase.CreateRegistrationSettings(li.oid.Value);
                if (IsSmallGroupFilled(setting, li.oid.Value, smallgroup))
                {
                    throw new Exception("sorry, maximum limit has been reached for " + smallgroup);
                }

                var omb = OrganizationMember.Load(CurrentDatabase, li.pid.Value, li.oid.Value) ??
                          OrganizationMember.InsertOrgMembers(CurrentDatabase,
                                                              li.oid.Value, li.pid.Value, MemberTypeCode.Member, Util.Now, null, false);

                if (q.org.AddToSmallGroupScript.HasValue())
                {
                    var script = CurrentDatabase.Content(q.org.AddToSmallGroupScript);
                    if (script != null && script.Body.HasValue())
                    {
                        try
                        {
                            var pe = new PythonModel(Util.Host, "RegisterEvent", script.Body);
                            pe.instance.AddToSmallGroup(smallgroup, omb);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                omb.AddToGroup(CurrentDatabase, smallgroup);
                li.ot.Used = true;
                CurrentDatabase.SubmitChanges();

                DbUtil.LogActivity($"{votelinkSTR}{confirmSTR}: {smallgroup}", li.oid, li.pid);

                if (confirm == true)
                {
                    var subject = Util.PickFirst(setting.Subject, "no subject");
                    var msg     = Util.PickFirst(setting.Body, "no message");
                    msg = APIOrganization.MessageReplacements(CurrentDatabase, q.p, q.org.DivisionName, q.org.OrganizationId, q.org.OrganizationName, q.org.Location, msg);
                    msg = msg.Replace("{details}", smallgroup);
                    var NotifyIds = CurrentDatabase.StaffPeopleForOrg(q.org.OrganizationId);

                    try
                    {
                        CurrentDatabase.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation
                    }
                    catch (Exception ex)
                    {
                        CurrentDatabase.Email(q.p.FromEmail, NotifyIds,
                                              q.org.OrganizationName,
                                              "There was a problem sending confirmation from org: " + ex.Message);
                    }
                    CurrentDatabase.Email(q.p.FromEmail, NotifyIds,
                                          q.org.OrganizationName,
                                          $"{q.p.Name} has registered for {q.org.OrganizationName}<br>{smallgroup}<br>(from votelink)");
                }
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{votelinkSTR}{confirmSTR}Error: {ex.Message}", li.oid, li.pid);
                return(Message(ex.Message));
            }

            return(Message(message));
        }
コード例 #9
0
        /// <summary>
        /// 获取用户数据表
        /// </summary>
        /// <param name="systemCode"></param>
        /// <param name="roleId"></param>
        /// <param name="companyId"></param>
        /// <param name="userId"></param>
        /// <param name="searchKey"></param>
        /// <param name="recordCount"></param>
        /// <param name="pageNo"></param>
        /// <param name="pageSize"></param>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        public DataTable GetUserDataTable(string systemCode, string roleId, string companyId, string userId, string searchKey, out int recordCount, int pageNo, int pageSize, string orderBy)
        {
            var result = new DataTable(BaseUserEntity.CurrentTableName);

            var tableName = BaseUserRoleEntity.CurrentTableName;

            if (!string.IsNullOrWhiteSpace(systemCode))
            {
                tableName = systemCode + "UserRole";
            }

            var commandText = @"SELECT BaseUser.Id
                                    , BaseUser.Code
                                    , BaseUser.UserName
                                    , BaseUser.CompanyName
                                    , BaseUser.DepartmentName
                                    , BaseUser.RealName 
                                    , BaseUser.Description 
                                    , UserRole.Enabled
                                    , UserRole.CreateTime
                                    , UserRole.CreateBy
                                    , UserRole.UpdateTime
                                    , UserRole.UpdateBy
 FROM BaseUser,
                          (SELECT UserId, Enabled, CreateTime, CreateBy, UpdateTime, UpdateBy
 FROM BaseUserRole
                            WHERE RoleId = " + DbHelper.GetParameter(BaseUserRoleEntity.FieldRoleId) + @" AND " + BaseUserEntity.FieldDeleted + @" = 0) UserRole 
                         WHERE BaseUser.Id = UserRole.UserId 
                               AND BaseUser." + BaseUserEntity.FieldDeleted + " = 0 ";

            if (!string.IsNullOrEmpty(searchKey))
            {
                // 2016-02-25 吉日嘎拉 增加搜索功能、方便管理
                if (searchKey.IndexOf("%") < 0)
                {
                    searchKey = string.Format("%{0}%", searchKey);
                }
                commandText += " AND (" + BaseUserEntity.FieldCode + " LIKE '%" + searchKey + "%'"
                               + " OR " + BaseUserEntity.FieldUserName + " LIKE '%" + searchKey + "%'"
                               + " OR " + BaseUserEntity.FieldDepartmentName + " LIKE '%" + searchKey + "%'"
                               + " OR " + BaseUserEntity.FieldRealName + " LIKE '%" + searchKey + "%')";
            }
            // ORDER BY UserRole.CreateTime DESC ";
            commandText = commandText.Replace("BaseUserRole", tableName);
            var dbParameters = new List <IDbDataParameter>
            {
                DbHelper.MakeParameter(BaseUserRoleEntity.FieldRoleId, roleId)
            };

            if (!string.IsNullOrEmpty(companyId))
            {
                commandText += " AND " + BaseUserEntity.CurrentTableName + "." + BaseUserEntity.FieldCompanyId + " = " + DbHelper.GetParameter(BaseUserEntity.FieldCompanyId);
                dbParameters.Add(DbHelper.MakeParameter(BaseUserEntity.FieldCompanyId, companyId));
            }
            if (!string.IsNullOrEmpty(userId))
            {
                commandText += " AND " + BaseUserEntity.CurrentTableName + "." + BaseUserEntity.FieldId + " = " + DbHelper.GetParameter(BaseUserEntity.FieldId);
                dbParameters.Add(DbHelper.MakeParameter(BaseUserEntity.FieldId, userId));
            }
            commandText = "(" + commandText + ") T ";
            // 2015-12-05 吉日嘎拉 增加参数化功能
            result = DbUtil.GetDataTableByPage(DbHelper, out recordCount, commandText, "*", pageNo, pageSize, null, dbParameters.ToArray(), orderBy);

            return(result);
        }
コード例 #10
0
ファイル: MeetingController.cs プロジェクト: lightyeare/bvcms
        public ActionResult Attendance(int?id, bool?currentMembers)
        {
            if (!id.HasValue)
            {
                return(RedirectShowError("no id"));
            }

            var m = new MeetingModel(id.Value, CurrentDatabase)
            {
                currmembers = currentMembers ?? false
            };

            m.showall = true;
            if (m.meeting == null)
            {
                return(RedirectShowError("no meeting"));
            }

            if (Util2.OrgLeadersOnly &&
                !CurrentDatabase.OrganizationMembers.Any(om =>
                                                         om.OrganizationId == m.meeting.OrganizationId &&
                                                         om.PeopleId == Util.UserPeopleId &&
                                                         om.MemberType.AttendanceTypeId == AttendTypeCode.Leader))
            {
                return(RedirectShowError("You must be a leader of this organization to have access to this page"));
            }

            DbUtil.LogActivity($"Attendance for Meeting for {m.meeting.OrganizationId}({m.meeting.MeetingDate:d})");
            List <Reports.Models.RollsheetModel.AttendInfo> Guests  = new List <Reports.Models.RollsheetModel.AttendInfo>();
            List <Reports.Models.RollsheetModel.AttendInfo> Members = new List <Reports.Models.RollsheetModel.AttendInfo>();
            int MembersPresent = 0;
            int GuestsPresent  = 0;
            var attends        = m.Attends(true, "iPadAttendanceHighlight");

            foreach (var attend in attends)
            {
                if (!attend.CurrMember)
                {
                    attend.MemberType = "Guest";
                    Guests.Add(attend);
                    if (attend.Attended)
                    {
                        GuestsPresent++;
                    }
                }
                else
                {
                    if (!attend.CurrMemberType.HasValue())
                    {
                        attend.CurrMemberType = "Member";
                    }
                    Members.Add(attend);
                    if (attend.Attended)
                    {
                        MembersPresent++;
                    }
                }
            }
            ViewBag.Guests         = Guests;
            ViewBag.Members        = Members;
            ViewBag.GuestsPresent  = GuestsPresent;
            ViewBag.MembersPresent = MembersPresent;
            return(View(m));
        }
コード例 #11
0
ファイル: CodeServer.cs プロジェクト: higeneko2015/WcfSample
 public List<CodeEntity> Create(DbUtil db)
 {
     return Select(db);
 }
コード例 #12
0
        public static void CheckBatchSettlements(CMSDataContext db, IGateway gateway, DateTime start, DateTime end)
        {
            var response = gateway.GetBatchDetails(start, end);

            // get distinct batches
            var allBatchReferences = (from batchTran in response.BatchTransactions
                                      select batchTran.BatchReference).Distinct();

            // first filter out batches that we have already been updated or inserted.
            // now find unmatched batch references
            var unmatchedBatchReferences = allBatchReferences.Where(br => !db.CheckedBatches.Any(tt => tt.BatchRef == br)).ToList();

            // given unmatched batch references, get the matched batch transactions again
            var unMatchedBatchTransactions =
                response.BatchTransactions.Where(x => unmatchedBatchReferences.Contains(x.BatchReference)).ToList();


            var batchTypes = unMatchedBatchTransactions.Select(x => x.BatchType).Distinct();

            foreach (var batchType in batchTypes)
            {
                // key it by transaction reference and payment type.
                var unMatchedKeyedByReference = unMatchedBatchTransactions.Where(x => x.BatchType == batchType).ToDictionary(x => x.Reference, x => x);

                // next let's get all the approved matching transactions from our transaction table by transaction id (reference).
                var approvedMatchingTransactions = from transaction in db.Transactions
                                                   where unMatchedKeyedByReference.Keys.Contains(transaction.TransactionId)
                                                   where (transaction.PaymentType == null || transaction.PaymentType == (batchType == BatchType.Ach ? PaymentType.Ach : PaymentType.CreditCard))
                                                   where transaction.Approved == true
                                                   select transaction;

                // next key the matching approved transactions that came from our transaction table by the transaction id (reference).
                var distinctTransactionIds = approvedMatchingTransactions.Select(x => x.TransactionId).Distinct();

                // finally let's get a list of all transactions that need to be inserted, which we don't already have.
                var transactionsToInsert = from transaction in unMatchedKeyedByReference
                                           where !distinctTransactionIds.Contains(transaction.Key)
                                           select transaction.Value;

                var notbefore = DateTime.Parse("6/1/12"); // the date when Sage payments began in BVCMS (?)

                // spin through each transaction and insert them to the transaction table.
                foreach (var transactionToInsert in transactionsToInsert)
                {
                    // get the original transaction.
                    var originalTransaction = db.Transactions.SingleOrDefault(t => t.TransactionId == transactionToInsert.Reference && transactionToInsert.TransactionDate >= notbefore && t.PaymentType == (batchType == BatchType.Ach ? PaymentType.Ach : PaymentType.CreditCard));

                    if (originalTransaction == null)
                    {
                        DbUtil.LogActivity(
                            string.Format("OriginalTransactionNotFoundWithReference {0} and Batch {1}",
                                          transactionToInsert.Reference, transactionToInsert.BatchReference));
                    }

                    // get the first and last name.
                    string first, last;
                    Util.NameSplit(transactionToInsert.Name, out first, out last);

                    // get the settlement date, however we are not exactly sure why we add four hours to the settlement date.
                    // we think it is to handle all timezones and push to the next day??
                    var settlementDate = AdjustSettlementDateForAllTimeZones(transactionToInsert.SettledDate);

                    // insert the transaction record.
                    db.Transactions.InsertOnSubmit(new Transaction
                    {
                        Name          = transactionToInsert.Name,
                        First         = first,
                        Last          = last,
                        TransactionId = transactionToInsert.Reference,
                        Amt           = transactionToInsert.TransactionType == TransactionType.Credit ||
                                        transactionToInsert.TransactionType == TransactionType.Refund
                            ? -transactionToInsert.Amount
                            : transactionToInsert.Amount,
                        Approved           = transactionToInsert.Approved,
                        Message            = transactionToInsert.Message,
                        TransactionDate    = transactionToInsert.TransactionDate,
                        TransactionGateway = gateway.GatewayType,
                        Settled            = settlementDate,
                        Batch       = settlementDate, // this date now will be the same as the settlement date.
                        Batchref    = transactionToInsert.BatchReference,
                        Batchtyp    = transactionToInsert.BatchType == BatchType.Ach ? "eft" : "bankcard",
                        OriginalId  = originalTransaction != null ? (originalTransaction.OriginalId ?? originalTransaction.Id) : (int?)null,
                        Fromsage    = true,
                        Description = originalTransaction != null ? originalTransaction.Description : $"no description from {gateway.GatewayType}, id={transactionToInsert.TransactionId}",
                        PaymentType = transactionToInsert.BatchType == BatchType.Ach ? PaymentType.Ach : PaymentType.CreditCard,
                        LastFourCC  = transactionToInsert.BatchType == BatchType.CreditCard ? transactionToInsert.LastDigits : null,
                        LastFourACH = transactionToInsert.BatchType == BatchType.Ach ? transactionToInsert.LastDigits : null
                    });
                }

                // next update Existing transactions with new batch data if there are any.
                foreach (var existingTransaction in approvedMatchingTransactions)
                {
                    if (!unMatchedKeyedByReference.ContainsKey(existingTransaction.TransactionId))
                    {
                        continue;
                    }

                    // first get the matching batch transaction.
                    var batchTransaction = unMatchedKeyedByReference[existingTransaction.TransactionId];

                    // get the adjusted settlement date
                    var settlementDate = AdjustSettlementDateForAllTimeZones(batchTransaction.SettledDate);

                    existingTransaction.Batch       = settlementDate; // this date now will be the same as the settlement date.
                    existingTransaction.Batchref    = batchTransaction.BatchReference;
                    existingTransaction.Batchtyp    = batchTransaction.BatchType == BatchType.Ach ? "eft" : "bankcard";
                    existingTransaction.Settled     = settlementDate;
                    existingTransaction.PaymentType = batchTransaction.BatchType == BatchType.Ach ? PaymentType.Ach : PaymentType.CreditCard;
                    existingTransaction.LastFourCC  = batchTransaction.BatchType == BatchType.CreditCard ? batchTransaction.LastDigits : null;
                    existingTransaction.LastFourACH = batchTransaction.BatchType == BatchType.Ach ? batchTransaction.LastDigits : null;
                }
            }


            // finally we need to mark these batches as completed if there are any.
            foreach (var batch in unMatchedBatchTransactions.DistinctBy(x => x.BatchReference))
            {
                var checkedBatch = db.CheckedBatches.SingleOrDefault(bb => bb.BatchRef == batch.BatchReference);
                if (checkedBatch == null)
                {
                    db.CheckedBatches.InsertOnSubmit(
                        new CheckedBatch
                    {
                        BatchRef = batch.BatchReference,
                        CheckedX = DateTime.Now
                    });
                }
                else
                {
                    checkedBatch.CheckedX = DateTime.Now;
                }
            }

            db.SubmitChanges();
        }
コード例 #13
0
ファイル: VolSubModel.cs プロジェクト: chrisgundersen/bvcms
        public void SendEmails()
        {
            var tag = Db.FetchOrCreateTag(Util.SessionId, Util.UserPeopleId, Db.NextTagId);

            Db.ExecuteCommand("delete TagPerson where Id = {0}", tag.Id);
            Db.TagAll(pids, tag);
            var dt = new DateTime(ticks);

            foreach (var id in pids)
            {
                var vr = new SubRequest
                {
                    AttendId     = attend.AttendId,
                    RequestorId  = person.PeopleId,
                    Requested    = dt,
                    SubstituteId = id,
                };
                attend.SubRequests.Add(vr);
            }

            var qb = Db.ScratchPadCondition();

            qb.Reset(Db);
            qb.AddNewClause(QueryType.HasMyTag, CompareType.Equal, "{0},temp".Fmt(tag.Id));
            attend.Commitment = CmsData.Codes.AttendCommitmentCode.FindSub;
            qb.Save(DbUtil.Db);

            var rurl       = DbUtil.Db.ServerLink("/OnlineReg/VolSubReport/{0}/{1}/{2}".Fmt(attend.AttendId, person.PeopleId, dt.Ticks));
            var reportlink = @"<a href=""{0}"">Substitute Status Report</a>".Fmt(rurl);
            var list       = Db.PeopleFromPidString(org.NotifyIds).ToList();

            //list.Insert(0, person);
            Db.Email(person.FromEmail, list,
                     "Volunteer Substitute Commitment for " + org.OrganizationName,
                     @"
<p>{0} has requested a substitute on {1:MMM d} at {1:h:mm tt}.</p>
<blockquote>
{2}
</blockquote>".Fmt(person.Name, attend.MeetingDate, reportlink));

            // Email subs
            var m = new MassEmailer(qb.Id);

            m.Subject = subject;
            m.Body    = message;

            DbUtil.LogActivity("Emailing Vol Subs");
            m.FromName    = person.Name;
            m.FromAddress = person.FromEmail;

            var    eqid = m.CreateQueue(transactional: true);
            string host = Util.Host;
            // save these from HttpContext to set again inside thread local storage
            var useremail         = Util.UserEmail;
            var isinroleemailtest = HttpContext.Current.User.IsInRole("EmailTest");

            TaskAlias.Factory.StartNew(() =>
            {
                Thread.CurrentThread.Priority = ThreadPriority.BelowNormal;
                try
                {
                    var db  = new CMSDataContext(Util.GetConnectionString(host));
                    db.Host = host;
                    // set these again inside thread local storage
                    Util.UserEmail         = useremail;
                    Util.IsInRoleEmailTest = isinroleemailtest;
                    db.SendPeopleEmail(eqid);
                }
                catch (Exception ex)
                {
                    var ex2           = new Exception("Emailing error for queueid " + eqid, ex);
                    ErrorLog errorLog = ErrorLog.GetDefault(null);
                    errorLog.Log(new Error(ex2));

                    var db  = new CMSDataContext(Util.GetConnectionString(host));
                    db.Host = host;
                    // set these again inside thread local storage
                    Util.UserEmail         = useremail;
                    Util.IsInRoleEmailTest = isinroleemailtest;
                    var equeue             = db.EmailQueues.Single(ee => ee.Id == eqid);
                    equeue.Error           = ex.Message.Truncate(200);
                    db.SubmitChanges();
                }
            });
        }
コード例 #14
0
 public SoshikiEntity Create(DbUtil db, string soshikiCd)
 {
     return Select(db, soshikiCd);
 }
コード例 #15
0
        /// <summary>
        /// 要素のタグ付き値を取得し、taggedValues プロパティにセットする
        /// </summary>
        /// <param name="elem">対象の要素オブジェクト</param>
        private void readTaggedValuesByElement(ElementVO elem)
        {
            string strSQL;

            strSQL = "select PropertyID, ea_guid, Property, Notes, Value " +
                     " from t_objectproperties " +
                     " where object_id = " + elem.elementId +
                     " order by ea_guid, Property, Value, Notes ";

            // SQLを実行する
            OleDbCommand dbCom = new OleDbCommand();

            dbCom.CommandText = strSQL;
            dbCom.Connection  = objConn;

            OleDbDataReader      reader     = dbCom.ExecuteReader();
            List <TaggedValueVO> retTagVals = new List <TaggedValueVO>();

            // 結果を表示します。
            while (reader.Read())
            {
                TaggedValueVO tag = new TaggedValueVO();
                // tag.propertyId = reader.GetValue(0);
                tag.guid     = DbUtil.readStringField(reader, 1);
                tag.name     = StringUtil.excludeSpecialChar("t_objectproperties", "name", tag.guid, DbUtil.readStringField(reader, 2));
                tag.notes    = DbUtil.readStringField(reader, 3);
                tag.tagValue = StringUtil.excludeSpecialChar("t_objectproperties", "value", tag.guid, DbUtil.readStringField(reader, 4));

                retTagVals.Add(tag);
            }
            reader.Close();

            elem.taggedValues = retTagVals;
        }
コード例 #16
0
ファイル: QueryModel.cs プロジェクト: sengithub/SenSourcecode
 public QueryModel(Guid?id)
     : this()
 {
     QueryId = id;
     DbUtil.LogActivity("Running Query ({0})".Fmt(id));
 }
コード例 #17
0
        /// <summary>
        /// パッケージ配下の要素を読み込み、パッケージオブジェクトのelementsにセットする
        /// </summary>
        /// <param name="package">対象パッケージオブジェクト</param>
        private void readElements(PackageVO package)
        {
            //	WScript.Echo "Start ExportElements"
            Console.WriteLine("readElements(): packageID =" + package.packageId);

            string strSQL, strFields, strWhere;

            // 読み込む項目リスト
            strFields =
                "Object_ID, ea_guid, Alias, Author, CreatedDate, ModifiedDate, " +
                "Name, Note, NType, Package_ID, ParentID, Stereotype, PDATA5, " +
                "TPos, Object_Type, Version, Visibility, GenType,  GenFile ";

            // WHERE文: DBに対しては主に パッケージID で検索(キー=IDで結合する必要があるため)
            strWhere = " where  Package_ID = " + package.packageId + " " +
                       " AND Object_Type IN ('GUIElement', 'Screen', 'Class', 'Interface', 'Enumeration', 'Note', 'Artifact', 'UseCase') ";

            // SQL文 を作成
            strSQL = "select " + strFields +
                     " from t_object  " +
                     strWhere +
                     " ORDER BY  ea_guid ";

            OleDbCommand dbCom = new OleDbCommand();

            // SQLを実行する
            dbCom.CommandText = strSQL;
            dbCom.Connection  = objConn;

            OleDbDataReader  reader      = dbCom.ExecuteReader();
            List <ElementVO> retElements = new List <ElementVO>();

            // 結果を表示します。
            while (reader.Read())
            {
                ElementVO elem = new ElementVO();

                elem.elementId  = DbUtil.readIntField(reader, 0);
                elem.guid       = DbUtil.readStringField(reader, 1);
                elem.alias      = StringUtil.excludeSpecialChar("t_object", "alias", elem.guid, DbUtil.readStringField(reader, 2));
                elem.author     = DbUtil.readStringField(reader, 3);
                elem.created    = (DateTime)reader.GetValue(4);
                elem.modified   = (DateTime)reader.GetValue(5);
                elem.name       = StringUtil.excludeSpecialChar("t_object", "name", elem.guid, DbUtil.readStringField(reader, 6));
                elem.notes      = DbUtil.readStringField(reader, 7);
                elem.objectType = DbUtil.readIntField(reader, 8).ToString();
                //elem.packageId = reader.GetValue(9);
                elem.parentID   = DbUtil.readIntField(reader, 10);
                elem.stereoType = DbUtil.readStringField(reader, 11);
                elem.tag        = DbUtil.readStringField(reader, 12);
                elem.treePos    = DbUtil.readIntField(reader, 13);
                elem.eaType     = DbUtil.readStringField(reader, 14);
                elem.version    = DbUtil.readStringField(reader, 15);
                elem.visibility = DbUtil.readStringField(reader, 16);

                elem.genType = DbUtil.readStringField(reader, 17);
                elem.genFile = DbUtil.readStringField(reader, 18);

                // elem.Diagrams = null;
                // elem.Elements = null;

                // 要素の接続情報出力フラグ=Trueの時のみデータ取得処理呼び出し
                // If EXP_ELEMENT_CONNECTOR_FLG = True Then
                //  Set elem.Connectors = getEA_ConnectorsByElement(objConn, elem.ElementID)
                // Else
                //  Set elem.Connectors = Nothing
                // End If

                if (g_AllAttributesInElementMap.ContainsKey(elem.elementId) == true)
                {
                    elem.attributes = g_AllAttributesInElementMap[elem.elementId];
                }
                else
                {
                    elem.attributes = new List <AttributeVO>();
                }

                if (g_AllMethodsInElementMap.ContainsKey(elem.elementId) == true)
                {
                    elem.methods = g_AllMethodsInElementMap[elem.elementId];
                }
                else
                {
                    elem.methods = new List <MethodVO>();
                }

                readTaggedValuesByElement(elem);

                // 返却用の要素のリストに追加
                retElements.Add(elem);
            }
            reader.Close();

            package.elements = retElements;
        }
コード例 #18
0
        /// <summary>
        /// 親の存在するサブパッケージ配下のパッケージ、要素の読み込み
        /// </summary>
        /// <param name="parent"></param>
        private void readSubPackage(PackageVO parent, bool isNeccesseryReadElemDiag)
        {
            Console.WriteLine("readSubPackage(): " + parent.name + "packageID =" + parent.packageId);

            string strSQL;

            strSQL =
                "SELECT  pac.PACKAGE_ID " +
                "       ,pac.NAME " +
                "       ,obj.Alias " +
                "       ,obj.Stereotype " +
                "       ,pac.ea_guid " +
                "       ,pac.PARENT_ID " +
                "       ,pac.TPOS " +
                "       ,pac.IsControlled " +
                " FROM t_package pac left outer join t_object obj on pac.ea_guid = obj.ea_guid " +
                " WHERE pac.PARENT_ID = " + parent.packageId + " " +
                " ORDER BY pac.TPOS, pac.NAME  ";

            OleDbCommand dbCom = new OleDbCommand();

            // SQLを実行する
            dbCom.CommandText = strSQL;
            dbCom.Connection  = objConn;


            List <PackageVO> retPackages = new List <PackageVO>();

            using (OleDbDataReader reader = dbCom.ExecuteReader())
            {
                // 結果を表示します。
                while (reader.Read())
                {
                    PackageVO pack = new PackageVO();

                    pack.packageId    = DbUtil.readIntField(reader, 0);
                    pack.guid         = DbUtil.readStringField(reader, 4);
                    pack.name         = StringUtil.excludeSpecialChar("t_package", "name", pack.guid, DbUtil.readStringField(reader, 1));
                    pack.alias        = StringUtil.excludeSpecialChar("t_object", "alias", pack.guid, DbUtil.readStringField(reader, 2));
                    pack.stereoType   = DbUtil.readStringField(reader, 3);
                    pack.treePos      = DbUtil.readIntField(reader, 6);
                    pack.isControlled = DbUtil.readBoolField(reader, 7);
                    pack.pathName     = parent.pathName + "/" + pack.name;

                    // このパッケージに isControlled が立っていたら、
                    // 以降の要素とダイアグラムを読み込むフラグを立てる
                    if (pack.isControlled)
                    {
                        isNeccesseryReadElemDiag = true;
                    }

                    if (isNeccesseryReadElemDiag)
                    {
                        // このパッケージ配下の要素読み込み
                        readElements(pack);

                        // このパッケージ配下のダイアグラム読み込み
                        readDiagrams(pack);
                    }
                    // このパッケージ配下の子パッケージ読み込み
                    readSubPackage(pack, isNeccesseryReadElemDiag);

                    retPackages.Add(pack);

                    // 全パッケージマップのキャッシュに、Key=IDとして追加
                    AllPackageMap.Add(pack.packageId, pack);
                }
            }

            parent.childPackageList = retPackages;
        }
コード例 #19
0
ファイル: CodeServer.cs プロジェクト: higeneko2015/WcfSample
 private List<CodeEntity> Select(DbUtil db)
 {
     return db.DbSelect<CodeEntity>(strSql);
 }
コード例 #20
0
        /// <summary>
        /// Update location
        /// </summary>
        private void UpdateLocation(IDbConnection conn, IDbTransaction tx, Place loc)
        {
            IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx);

            try
            {
                cmd.CommandText = "upd_plc";

                // parameters
                cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_in", DbType.Decimal, loc.Id));
                cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_addr_set_id_in", DbType.Decimal, loc.Address == null ? DBNull.Value : (Object)DbUtil.CreateAddressSet(conn, tx, loc.Address)));
                cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_typ_cd_id_in", DbType.Decimal, loc.LocationType == null ? DBNull.Value : (Object)DbUtil.CreateCodedValue(conn, tx, loc.LocationType)));

                // Execute
                cmd.ExecuteNonQuery();
            }
            finally
            {
                cmd.Dispose();
            }
        }
コード例 #21
0
ファイル: TireTest.cs プロジェクト: randomjs/thunder
 public void Setup()
 {
     _util = new DbUtil().Bind();
     Tire.Create(new Tire {Name = "Tire 1"});
     Tire.All(Order.Asc("Name"));
 }
コード例 #22
0
 public void Log(string action)
 {
     DbUtil.LogActivity("OnlineReg ManageGiving " + action, orgid, pid);
 }
コード例 #23
0
        public ActionResult CreditVoid(int id, string type, decimal?amt, TransactionsModel m)
        {
            var t = DbUtil.Db.Transactions.SingleOrDefault(tt => tt.Id == id);

            if (t == null)
            {
                return(Content("notran"));
            }

            var qq = from tt in DbUtil.Db.Transactions
                     where tt.OriginalId == id || tt.Id == id
                     orderby tt.Id descending
                     select tt;
            var t0 = qq.First();
            var gw = DbUtil.Db.Gateway(t.Testing ?? false);
            TransactionResponse resp = null;
            var re = t.TransactionId;

            if (re.Contains("(testing"))
            {
                re = re.Substring(0, re.IndexOf("(testing)"));
            }
            if (type == "Void")
            {
                resp = gw.VoidCreditCardTransaction(re);
                if (!resp.Approved)
                {
                    resp = gw.VoidCheckTransaction(re);
                }

                t.Voided = resp.Approved;
                amt      = t.Amt;
            }
            else
            {
                if (t.PaymentType == PaymentType.Ach)
                {
                    resp = gw.RefundCheck(re, amt ?? 0);
                }
                else if (t.PaymentType == PaymentType.CreditCard)
                {
                    resp = gw.RefundCreditCard(re, amt ?? 0, t.LastFourCC);
                }

                t.Credited = resp.Approved;
            }

            if (!resp.Approved)
            {
                return(Content("error: " + resp.Message));
            }

            var transaction = new Transaction
            {
                TransactionId      = resp.TransactionId + (t.Testing == true ? "(testing)" : ""),
                First              = t.First,
                MiddleInitial      = t.MiddleInitial,
                Last               = t.Last,
                Suffix             = t.Suffix,
                Amt                = -amt,
                Amtdue             = t0.Amtdue + amt,
                Approved           = true,
                AuthCode           = t.AuthCode,
                Message            = t.Message,
                Donate             = -t.Donate,
                Regfees            = -t.Regfees,
                TransactionDate    = DateTime.Now,
                TransactionGateway = t.TransactionGateway,
                Testing            = t.Testing,
                Description        = t.Description,
                OrgId              = t.OrgId,
                OriginalId         = t.OriginalId,
                Participants       = t.Participants,
                Financeonly        = t.Financeonly,
                PaymentType        = t.PaymentType,
                LastFourCC         = t.LastFourCC,
                LastFourACH        = t.LastFourACH
            };

            DbUtil.Db.Transactions.InsertOnSubmit(transaction);
            DbUtil.Db.SubmitChanges();
            DbUtil.Db.SendEmail(Util.TryGetMailAddress(DbUtil.Db.StaffEmailForOrg(transaction.OrgId ?? 0)),
                                "Void/Credit Transaction Type: " + type,
                                $@"<table>
<tr><td>Name</td><td>{Transaction.FullName(t)}</td></tr>
<tr><td>Email</td><td>{t.Emails}</td></tr>
<tr><td>Address</td><td>{t.Address}</td></tr>
<tr><td>Phone</td><td>{t.Phone}</td></tr>
<tr><th colspan=""2"">Transaction Info</th></tr>
<tr><td>Description</td><td>{t.Description}</td></tr>
<tr><td>Amount</td><td>{-amt:N2}</td></tr>
<tr><td>Date</td><td>{t.TransactionDate.FormatDateTm()}</td></tr>
<tr><td>TranIds</td><td>Org: {t.Id} {t.TransactionId}, Curr: {transaction.Id} {transaction.TransactionId}</td></tr>
<tr><td>User</td><td>{Util.UserFullName}</td></tr>
</table>", Util.EmailAddressListFromString(DbUtil.Db.StaffEmailForOrg(transaction.OrgId ?? 0)));
            DbUtil.LogActivity("CreditVoid for " + t.TransactionId);

            return(View("List", m));
        }
コード例 #24
0
ファイル: ShainServer.cs プロジェクト: higeneko2015/WcfSample
 private ShainEntity Select(DbUtil db, string shainCd)
 {
     return db.DbSelect<ShainEntity>(strSql, new { SHAIN_CD = shainCd }).FirstOrDefault();
 }
コード例 #25
0
 public Setting(string cat, string key, object value)
 {
     Category = cat;
     Key      = key;
     Value    = DbUtil.Serialize(value);
 }
コード例 #26
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Create the response.
            var    method        = request.Method;
            string requestString = request.ToString();

            string[] segments = new string[request.RequestUri.Segments.Length];

            WindowsIdentity identity = HttpContext.Current.Request.LogonUserIdentity;
            // Med Windows Authentication får man ut Windows-namnet i identity.Name.

            string path = request.RequestUri.LocalPath;

            /*
             * for (int i=0, j=0;i< request.RequestUri.Segments.Length; i++)
             * {
             *  string s = request.RequestUri.Segments[i];
             *  if (s != "/")
             *  {
             *      segments[j++] = s.Replace("/", "");
             *  }
             * }
             */


            // Finns diverse varningar om att man kan skapa deadlocks om man gör fel med asynkrona trådar.
            // Jag är för grön på detta för att veta vad jag gör.
            string requestText = request.Content.ReadAsStringAsync().Result;

            DbUtil  dbUtil = new DbUtil();
            DataSet ds     = dbUtil.GetDataSet(
                configuration,
                request,
                identity.Name
                );

            string responsebody = "";
            int    statusCode   = 200;

            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                responsebody = (string)(dr["ResponseBody"] != DBNull.Value ? dr["ResponseBody"] : "");
                statusCode   = (int)(dr["statusCode"] != DBNull.Value ? dr["statusCode"] : 404);
            }

            var response = new HttpResponseMessage((HttpStatusCode)statusCode)
            {
                Content = new StringContent(responsebody)
            };

            // Svara med headers.

            if (ds.Tables.Count > 1 && ds.Tables[1].Rows.Count > 0)
            {
                DataRow row = ds.Tables[1].Rows[0];
                foreach (DataColumn dc in ds.Tables[1].Columns)
                {
                    response.Headers.Add(
                        dc.ColumnName,
                        (string)(row[dc.ColumnName])
                        );
                }
            }

            if (isDebug)
            {
                response.Headers.Add("X-HandledBy", name);
            }

            // Note: TaskCompletionSource creates a task that does not contain a delegate.
            var tsc = new TaskCompletionSource <HttpResponseMessage>();

            tsc.SetResult(response);   // Also sets the task state to "RanToCompletion"
            return(tsc.Task);
        }
コード例 #27
0
        /// <summary>
        /// De-persist the specified change summary
        /// </summary>
        public System.ComponentModel.IComponent DePersist(System.Data.IDbConnection conn, decimal identifier, System.ComponentModel.IContainer container, SVC.Core.ComponentModel.HealthServiceRecordSiteRoleType?role, bool loadFast)
        {
            // TODO: Ensure that when a parent with context conduction exists, to grab contextual data (authors, etc...) from the parent
            ChangeSummary retVal = new ChangeSummary();

            // Configuration service
            ISystemConfigurationService configService = ApplicationContext.ConfigurationService; //ApplicationContext.Current.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService;

            // Get the health service event
            IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, null);

            try
            {
                cmd.CommandText = "get_hsr_crnt_vrsn";
                cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_id_in", DbType.Decimal, identifier));

                decimal tsId          = default(decimal),
                        cdId          = default(decimal),
                        rplcVersionId = default(decimal);

                // Read data
                IDataReader reader = cmd.ExecuteReader();
                try
                {
                    if (!reader.Read())
                    {
                        return(null);
                    }

                    retVal.Id = Convert.ToDecimal(reader["hsr_id"]);
                    retVal.VersionIdentifier   = Convert.ToDecimal(reader["hsr_vrsn_id"]);
                    retVal.AlternateIdentifier = new VersionedDomainIdentifier()
                    {
                        Domain     = configService.OidRegistrar.GetOid(ClientRegistryOids.EVENT_OID).Oid,
                        Identifier = retVal.Id.ToString(),
                        Version    = retVal.VersionIdentifier.ToString()
                    };
                    retVal.LanguageCode = reader["lang_cs"].ToString();
                    retVal.Timestamp    = DateTime.Parse(Convert.ToString(reader["aut_utc"]));
                    retVal.Status       = (StatusType)Convert.ToDecimal(reader["status_cs_id"]);
                    tsId          = reader["efft_ts_set_id"] == DBNull.Value ? default(decimal) : Convert.ToDecimal(reader["efft_ts_set_id"]);
                    cdId          = Convert.ToDecimal(reader["evt_typ_cd_id"]);
                    rplcVersionId = reader["rplc_vrsn_id"] == DBNull.Value ? default(decimal) : Convert.ToDecimal(reader["rplc_vrsn_id"]);
                }
                finally
                {
                    reader.Close();
                }

                // Read codes and times
                retVal.ChangeType = DbUtil.GetCodedValue(conn, null, cdId);
                if (tsId != default(decimal))
                {
                    retVal.EffectiveTime = DbUtil.GetEffectiveTimestampSet(conn, null, tsId);
                }

                if (container != null)
                {
                    container.Add(retVal);
                }

                if (role.HasValue && (role.Value & HealthServiceRecordSiteRoleType.ReplacementOf) == HealthServiceRecordSiteRoleType.ReplacementOf)
                {
                    ;
                }
                else
                {
                    DbUtil.DePersistComponents(conn, retVal, this, loadFast);
                }
            }
            finally
            {
                cmd.Dispose();
            }

            return(retVal);
        }
コード例 #28
0
        internal void PostContribution()
        {
            if (!(AmountGeneral > 0) && !(AmountGoer > 0))
            {
                return;
            }

            var org       = DbUtil.Db.LoadOrganizationById(OrgId);
            var notifyIds = DbUtil.Db.NotifyIds(org.GiftNotifyIds);
            var person    = DbUtil.Db.LoadPersonById(PeopleId ?? 0);
            var setting   = DbUtil.Db.CreateRegistrationSettings(OrgId ?? 0);
            var fund      = setting.DonationFundId;

            if (AmountGoer > 0)
            {
                var goerid = Goer.Value.ToInt();
                DbUtil.Db.GoerSenderAmounts.InsertOnSubmit(
                    new GoerSenderAmount
                {
                    Amount      = AmountGoer,
                    GoerId      = goerid,
                    Created     = DateTime.Now,
                    OrgId       = org.OrganizationId,
                    SupporterId = PeopleId ?? 0,
                });
                var c = person.PostUnattendedContribution(DbUtil.Db,
                                                          AmountGoer ?? 0, fund,
                                                          $"SupportMissionTrip: org={OrgId}; goer={Goer.Value}", typecode: BundleTypeCode.MissionTrip);
                c.CheckNo = (CheckNo ?? "").Trim().Truncate(20);
                if (PeopleId == goerid)
                {
                    var om = DbUtil.Db.OrganizationMembers.Single(
                        mm => mm.PeopleId == goerid && mm.OrganizationId == OrgId);
                    var descriptionForPayment = OnlineRegModel.GetDescriptionForPayment(OrgId);
                    om.AddTransaction(DbUtil.Db, "Payment", AmountGoer ?? 0, "Payment", pmtDescription: descriptionForPayment);
                }
                // send notices
                var goer = DbUtil.Db.LoadPersonById(goerid);
                ToGoerName = "to " + goer.Name;
                DbUtil.Db.Email(notifyIds[0].FromEmail, goer, org.OrganizationName + "-donation",
                                $"{AmountGoer:C} donation received from {person.Name}");
                DbUtil.LogActivity("OrgMem SupportMissionTrip goer=" + goerid, OrgId, PeopleId);
            }
            if (AmountGeneral > 0)
            {
                DbUtil.Db.GoerSenderAmounts.InsertOnSubmit(
                    new GoerSenderAmount
                {
                    Amount      = AmountGeneral,
                    Created     = DateTime.Now,
                    OrgId       = org.OrganizationId,
                    SupporterId = PeopleId ?? 0
                });
                var c = person.PostUnattendedContribution(DbUtil.Db,
                                                          AmountGeneral ?? 0, fund,
                                                          $"SupportMissionTrip: org={OrgId}", typecode: BundleTypeCode.MissionTrip);
                if (CheckNo.HasValue())
                {
                    c.CheckNo = (CheckNo ?? "").Trim().Truncate(20);
                }
                DbUtil.LogActivity("OrgMem SupportMissionTrip", OrgId, PeopleId);
            }
            DbUtil.Db.SubmitChanges();
        }
コード例 #29
0
        /// <summary>
        /// Create an HSR record
        /// </summary>
        private VersionedDomainIdentifier CreateHSRRecord(IDbConnection conn, IDbTransaction tx, ChangeSummary hsr)
        {
            IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx);

            cmd.CommandText = "crt_hsr";

            // Get the terminology service
            ISystemConfigurationService iscs = ApplicationContext.ConfigurationService; //ApplicationContext.Current.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService;

            // Parameters
            // classifier = 0x400 = Change Summary
            cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "hsr_cls_in", DbType.Decimal, RegistrationEventType.ComponentEvent | RegistrationEventType.Revise));
            // event type code
            cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "evt_typ_cd_id_in", DbType.Decimal, DbUtil.CreateCodedValue(conn, tx, hsr.ChangeType)));
            // refuted indicator
            cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "refuted_ind_in", DbType.Boolean, false));

            decimal?efftTimeId = null;

            if (hsr.EffectiveTime != null)
            {
                efftTimeId = DbUtil.CreateTimeset(conn, tx, hsr.EffectiveTime);
            }

            cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "efft_ts_set_id_in", DbType.Decimal, efftTimeId == null ? (object)DBNull.Value : efftTimeId.Value));
            // status code
            cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "status_cs_in", DbType.Decimal, hsr.Status == null ? (object)DBNull.Value : (int)hsr.Status));
            // authored time
            cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "aut_utc_in", DbType.DateTime, hsr.Timestamp == default(DateTime) ? (object)DBNull.Value : hsr.Timestamp));
            // language code
            cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "lang_cs_in", DbType.String, hsr.LanguageCode));

            // Execute the command
            IDataReader resultRdr = cmd.ExecuteReader();

            try
            {
                // Create the return value
                VersionedDomainIdentifier id = new VersionedDomainIdentifier();
                if (!resultRdr.Read())
                {
                    return(null);
                }

                id.Version    = Convert.ToString(resultRdr["VRSN_ID"]);
                id.Identifier = Convert.ToString(resultRdr["ID"]);
                id.Domain     = iscs.OidRegistrar.GetOid(ClientRegistryOids.EVENT_OID).Oid;

                return(id);
            }
            finally
            {
                resultRdr.Close();
            }
        }
コード例 #30
0
ファイル: MeetingController.cs プロジェクト: lightyeare/bvcms
 private ActionResult NotAllowed(string error, string name)
 {
     DbUtil.LogActivity($"Trying to view Meeting for Org ({name})");
     return(Content($"<h3 style='color:red'>{error}</h3>\n<a href='{"javascript: history.go(-1)"}'>{"Go Back"}</a>"));
 }
コード例 #31
0
        public Result Add(CMSDataContext db)
        {
            if (!Util.ValidEmail(Email))
            {
                throw new Exception("Need a valid email address");
            }

            if (Amount <= 0)
            {
                throw new Exception("Amount must be > 0");
            }

            Person person = null;
            var    list   = db.FindPerson(First, Last, null, Email, Phone.GetDigits()).ToList();
            var    count  = list.Count;

            if (count > 0)
            {
                person = db.LoadPersonById(list[0].PeopleId ?? 0);
            }

            var result = new Result();

            if (count > 1)
            {
                result.MultipleMatches = true;
            }

            if (person == null)
            {
                result.NewPerson = true;
                var f = new Family
                {
                    AddressLineOne = Address,
                    ZipCode        = Zip,
                    HomePhone      = Phone.GetDigits().Truncate(20),
                };
                var amsresult = AddressVerify.LookupAddress(Address, null, null, null, Zip);
                if (amsresult.found != false && !amsresult.error.HasValue() && amsresult.Line1 != "error")
                {
                    f.CityName  = amsresult.City;
                    f.StateCode = amsresult.State;
                    f.ZipCode   = amsresult.Zip.GetDigits().Truncate(10);
                }
                db.SubmitChanges();

                var position = 10;
                person = Person.Add(db, true, f, position, null, First.Trim(), null, Last.Trim(), "", 0, 0, OriginCode.Contribution, null);
                person.EmailAddress      = Email.Trim();
                person.SendEmailAddress1 = true;

                if (count == 0)
                {
                    person.Comments = "Added during api postcontribution because record was not found";
                }
            }

            var c = person.PostUnattendedContribution(db, Amount, Fundid, Notes);

            c.ContributionDate = Date ?? DateTime.Now;
            c.MetaInfo         = Source;
            db.SubmitChanges();
            result.PeopleId       = person.PeopleId;
            result.ContributionId = c.ContributionId;
            result.Source         = Source;
            DbUtil.LogActivity($"ApiPostContribution {result}", person.PeopleId);
            return(result);
        }
コード例 #32
0
        public ActionResult RsvpLinkSg(string id, string message, bool?confirm, FormCollection formCollection, bool regrets = false)
        {
            var li = new LinkInfo(rsvplinkSTR, landingSTR, id, false);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                if (!li.pid.HasValue)
                {
                    throw new Exception("missing peopleid");
                }

                var meetingid  = li.a[0].ToInt();
                var emailid    = li.a[2].ToInt();
                var smallgroup = li.a[3];
                if (meetingid == 0 && li.a[0].EndsWith(".next"))
                {
                    var orgid    = li.a[0].Split('.')[0].ToInt();
                    var nextmeet = (from mm in CurrentDatabase.Meetings
                                    where mm.OrganizationId == orgid
                                    where mm.MeetingDate > DateTime.Now
                                    orderby mm.MeetingDate
                                    select mm).FirstOrDefault();
                    if (nextmeet == null)
                    {
                        return(Message("no meeting"));
                    }

                    meetingid = nextmeet.MeetingId;
                }
                var q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let meeting = CurrentDatabase.Meetings.SingleOrDefault(mm => mm.MeetingId == meetingid)
                                       let org = meeting.Organization
                                                 select new { p = pp, org, meeting }).Single();

                if (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive)
                {
                    throw new Exception("sorry, registration has been closed");
                }

                if (q.org.RegistrationTypeId == RegistrationTypeCode.None)
                {
                    throw new Exception("rsvp is no longer available");
                }

                if (q.org.Limit <= q.meeting.Attends.Count(aa => aa.Commitment == 1))
                {
                    throw new Exception("sorry, maximum limit has been reached");
                }

                var omb = OrganizationMember.Load(CurrentDatabase, li.pid.Value, q.meeting.OrganizationId) ??
                          OrganizationMember.InsertOrgMembers(CurrentDatabase,
                                                              q.meeting.OrganizationId, li.pid.Value, MemberTypeCode.Member, DateTime.Now, null, false);
                if (smallgroup.HasValue())
                {
                    omb.AddToGroup(CurrentDatabase, smallgroup);
                }

                li.ot.Used = true;
                CurrentDatabase.SubmitChanges();
                Attend.MarkRegistered(CurrentDatabase, li.pid.Value, meetingid, regrets ? AttendCommitmentCode.Regrets : AttendCommitmentCode.Attending);
                DbUtil.LogActivity($"{rsvplinkSTR}{confirmSTR}: {regrets}", q.org.OrganizationId, li.pid);
                var setting = CurrentDatabase.CreateRegistrationSettings(q.meeting.OrganizationId);

                if (confirm == true)
                {
                    var subject = Util.PickFirst(setting.Subject, "no subject");
                    var msg     = Util.PickFirst(setting.Body, "no message");
                    msg = APIOrganization.MessageReplacements(CurrentDatabase, q.p, q.org.DivisionName, q.org.OrganizationId, q.org.OrganizationName, q.org.Location, msg);
                    msg = msg.Replace("{details}", q.meeting.MeetingDate.ToString2("f"));
                    var NotifyIds = CurrentDatabase.StaffPeopleForOrg(q.org.OrganizationId);

                    CurrentDatabase.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation
                    CurrentDatabase.Email(q.p.FromEmail, NotifyIds,
                                          q.org.OrganizationName,
                                          $"{q.p.Name} has registered for {q.org.OrganizationName}<br>{q.meeting.MeetingDate.ToString2("f")}");
                }
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{rsvplinkSTR}{confirmSTR}Error: {regrets}", peopleid: li.pid);
                return(Message(ex.Message));
            }
            return(Message(message));
        }
コード例 #33
0
ファイル: EmailController.cs プロジェクト: ilkerhalil/bvcms
        public ActionResult Index(Guid id, int?templateID, bool?parents, string body, string subj, bool?ishtml, bool?ccparents, bool?nodups, int?orgid, int?personid, bool?recover, bool?onlyProspects, bool?membersAndProspects)
        {
            if (Util.SessionTimedOut())
            {
                return(Redirect("/Errors/SessionTimeout.htm"));
            }
            if (!body.HasValue())
            {
                body = TempData["body"] as string;
            }

            if (!subj.HasValue() && templateID != 0)
            {
                if (templateID == null)
                {
                    return(View("SelectTemplate", new EmailTemplatesModel
                    {
                        WantParents = parents ?? false,
                        QueryId = id,
                    }));
                }

                DbUtil.LogActivity("Emailing people");

                var m = new MassEmailer(id, parents, ccparents, nodups);

                m.Host = Util.Host;

                if (body.HasValue())
                {
                    templateID = SaveDraft(null, null, 0, null, body);
                }

                ViewBag.templateID = templateID;
                m.OrgId            = orgid;
                m.guid             = id;
                if (recover == true)
                {
                    m.recovery = true;
                }
                return(View("Compose", m));
            }

            // using no templates

            DbUtil.LogActivity("Emailing people");

            var me = new MassEmailer(id, parents, ccparents, nodups);

            me.Host          = Util.Host;
            me.OnlyProspects = onlyProspects.GetValueOrDefault();

            // Unless UX-AllowMyDataUserEmails is true, CmsController.OnActionExecuting() will filter them
            if (!User.IsInRole("Access"))
            {
                if (templateID != 0 || (!personid.HasValue && !orgid.HasValue))
                {
                    return(Redirect($"/Person2/{Util.UserPeopleId}"));
                }
            }

            if (personid.HasValue)
            {
                me.AdditionalRecipients = new List <int> {
                    personid.Value
                };

                var person = DbUtil.Db.LoadPersonById(personid.Value);
                ViewBag.ToName = person?.Name;
            }
            else if (orgid.HasValue)
            {
                var org = DbUtil.Db.LoadOrganizationById(orgid.Value);
                GetRecipientsFromOrg(me, orgid.Value, onlyProspects, membersAndProspects);
                me.Count       = me.Recipients.Count();
                ViewBag.ToName = org?.OrganizationName;
            }

            if (body.HasValue())
            {
                me.Body = Server.UrlDecode(body);
            }

            if (subj.HasValue())
            {
                me.Subject = Server.UrlDecode(subj);
            }

            ViewData["oldemailer"] = "/EmailPeople.aspx?id=" + id
                                     + "&subj=" + subj + "&body=" + body + "&ishtml=" + ishtml
                                     + (parents == true ? "&parents=true" : "");

            if (parents == true)
            {
                ViewData["parentsof"] = "with ParentsOf option";
            }

            return(View("Index", me));
        }
コード例 #34
0
        public ActionResult SendLink(string id, FormCollection formCollection)
        {
            var li = new LinkInfo(sendlinkSTR, landingSTR, id);

            if (li.error.HasValue())
            {
                return(Message(li.error));
            }

            try
            {
                if (!li.pid.HasValue)
                {
                    throw new Exception("missing peopleid");
                }

                if (!li.oid.HasValue)
                {
                    throw new Exception("missing orgid");
                }

                var queueid  = li.a[2].ToInt();
                var linktype = li.a[3]; // for supportlink, this will also have the goerid
                var q        = (from pp in CurrentDatabase.People
                                where pp.PeopleId == li.pid
                                let org = CurrentDatabase.LoadOrganizationById(li.oid)
                                          select new { p = pp, org }).Single();

                if (q.org == null && CurrentDatabase.Host == "trialdb")
                {
                    var oid = li.oid + Util.TrialDbOffset;
                    q = (from pp in CurrentDatabase.People
                         where pp.PeopleId == li.pid
                         let org = CurrentDatabase.LoadOrganizationById(oid)
                                   select new { p = pp, org }).Single();
                }

                if (q.org.RegistrationClosed == true || q.org.OrganizationStatusId == OrgStatusCode.Inactive)
                {
                    throw new Exception("sorry, registration has been closed");
                }

                if (q.org.RegistrationTypeId == RegistrationTypeCode.None)
                {
                    throw new Exception("sorry, registration is no longer available");
                }

                DbUtil.LogActivity($"{sendlinkSTR}{confirmSTR}", li.oid, li.pid);

                var    expires = DateTime.Now.AddMinutes(CurrentDatabase.Setting("SendlinkExpireMinutes", "30").ToInt());
                string action  = (linktype.Contains("supportlink") ? "support" : "register for");
                string minutes = CurrentDatabase.Setting("SendLinkExpireMinutes", "30");
                var    c       = DbUtil.Content("SendLinkMessage");
                if (c == null)
                {
                    c = new Content
                    {
                        Name  = "SendLinkMessage",
                        Title = "Your Link for {org}",
                        Body  = @"
<p>Here is your temporary <a href='{url}'>LINK</a> to {action} {org}.</p>

<p>This link will expire at {time} ({minutes} minutes).
You may request another link by clicking the link in the original email you received.</p>

<p>Note: If you did not request this link, please ignore this email,
or contact the church if you need help.</p>
"
                    };
                    CurrentDatabase.Contents.InsertOnSubmit(c);
                    CurrentDatabase.SubmitChanges();
                }
                var url = EmailReplacements.RegisterLinkUrl(CurrentDatabase,
                                                            li.oid.Value, li.pid.Value, queueid, linktype, expires);
                var subject = c.Title.Replace("{org}", q.org.OrganizationName);
                var msg     = c.Body.Replace("{org}", q.org.OrganizationName)
                              .Replace("{time}", expires.ToString("f"))
                              .Replace("{url}", url)
                              .Replace("{action}", action)
                              .Replace("{minutes}", minutes)
                              .Replace("%7Burl%7D", url);

                var NotifyIds = CurrentDatabase.StaffPeopleForOrg(q.org.OrganizationId);
                CurrentDatabase.Email(NotifyIds[0].FromEmail, q.p, subject, msg); // send confirmation

                return(Message($"Thank you, {q.p.PreferredName}, we just sent an email to {Util.ObscureEmail(q.p.EmailAddress)} with your link..."));
            }
            catch (Exception ex)
            {
                DbUtil.LogActivity($"{sendlinkSTR}{confirmSTR}Error: {ex.Message}", li.oid, li.pid);
                return(Message(ex.Message));
            }
        }
コード例 #35
0
ファイル: EmailController.cs プロジェクト: ilkerhalil/bvcms
        public ActionResult QueueEmails(MassEmailer m)
        {
            m.Body = GetBody(m.Body);
            if (UsesGrammarly(m))
            {
                return(Json(new { error = GrammarlyNotAllowed }));
            }
            if (TooLarge(m))
            {
                return(Json(new { error = TooLargeError }));
            }
            if (!m.Subject.HasValue() || !m.Body.HasValue())
            {
                return(Json(new { id = 0, error = "Both subject and body need some text." }));
            }
            if (!User.IsInRole("Admin") && m.Body.Contains("{createaccount}", ignoreCase: true))
            {
                return(Json(new { id = 0, error = "Only Admin can use {createaccount}." }));
            }

            if (Util.SessionTimedOut())
            {
                Session["massemailer"] = m;
                return(Content("timeout"));
            }

            DbUtil.LogActivity("Emailing people");

            if (m.EmailFroms().Count(ef => ef.Value == m.FromAddress) == 0)
            {
                return(Json(new { id = 0, error = "No email address to send from." }));
            }

            m.FromName = m.EmailFroms().First(ef => ef.Value == m.FromAddress).Text;

            int id;

            try
            {
                var eq = m.CreateQueue();
                if (eq == null)
                {
                    throw new Exception("No Emails to send (tag does not exist)");
                }
                id = eq.Id;

                // If there are additional recipients, add them to the queue
                if (m.AdditionalRecipients != null)
                {
                    foreach (var pid in m.AdditionalRecipients)
                    {
                        // Protect against duplicate PeopleIDs ending up in the queue
                        var q3 = from eqt in DbUtil.Db.EmailQueueTos
                                 where eqt.Id == eq.Id
                                 where eqt.PeopleId == pid
                                 select eqt;
                        if (q3.Any())
                        {
                            continue;
                        }
                        eq.EmailQueueTos.Add(new EmailQueueTo
                        {
                            PeopleId = pid,
                            OrgId    = eq.SendFromOrgId,
                            Guid     = Guid.NewGuid(),
                        });
                    }
                    DbUtil.Db.SubmitChanges();
                }

                if (m.RecipientIds != null)
                {
                    foreach (var pid in m.RecipientIds)
                    {
                        // Protect against duplicate PeopleIDs ending up in the queue
                        var q3 = from eqt in DbUtil.Db.EmailQueueTos
                                 where eqt.Id == eq.Id
                                 where eqt.PeopleId == pid
                                 select eqt;
                        if (q3.Any())
                        {
                            continue;
                        }
                        eq.EmailQueueTos.Add(new EmailQueueTo
                        {
                            PeopleId = pid,
                            OrgId    = eq.SendFromOrgId,
                            Guid     = Guid.NewGuid(),
                        });
                    }
                    DbUtil.Db.SubmitChanges();
                }

                if (eq.SendWhen.HasValue)
                {
                    return(Json(new { id = 0, content = "Emails queued to be sent." }));
                }
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(ex);
                return(Json(new { id = 0, error = ex.Message }));
            }

            var host      = Util.Host;
            var currorgid = DbUtil.Db.CurrentSessionOrgId;
            // save these from HttpContext to set again inside thread local storage
            var userEmail         = Util.UserEmail;
            var isInRoleEmailTest = User.IsInRole("EmailTest");
            var isMyDataUser      = User.IsInRole("Access") == false;

            try
            {
                ValidateEmailReplacementCodes(DbUtil.Db, m.Body, new MailAddress(m.FromAddress));
            }
            catch (Exception ex)
            {
                return(Json(new { error = ex.Message }));
            }

            var onlyProspects = m.OnlyProspects;

            HostingEnvironment.QueueBackgroundWorkItem(ct =>
            {
                try
                {
                    var db  = DbUtil.Create(host);
                    var cul = db.Setting("Culture", "en-US");
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo(cul);
                    Thread.CurrentThread.CurrentCulture   = CultureInfo.CreateSpecificCulture(cul);
                    // set these again inside thread local storage
                    db.SetCurrentOrgId(currorgid);
                    Util.UserEmail         = userEmail;
                    Util.IsInRoleEmailTest = isInRoleEmailTest;
                    Util.IsMyDataUser      = isMyDataUser;
                    db.SendPeopleEmail(id, onlyProspects);
                }
                catch (Exception ex)
                {
                    var ex2 = new Exception($"Emailing error for queueid {id} on {host}\n{ex.Message}", ex);
                    var cb  = new SqlConnectionStringBuilder(Util.ConnectionString)
                    {
                        InitialCatalog = "ELMAH"
                    };
                    var errorLog = new SqlErrorLog(cb.ConnectionString)
                    {
                        ApplicationName = "BVCMS"
                    };
                    errorLog.Log(new Error(ex2));

                    var db       = DbUtil.Create(host);
                    var equeue   = db.EmailQueues.Single(ee => ee.Id == id);
                    equeue.Error = ex.Message.Truncate(200);
                    db.SubmitChanges();
                }
            });
            return(Json(new { id = id }));
        }
コード例 #36
0
 internal Exception LinkException(string msg)
 {
     DbUtil.LogActivity($"{link}{@from}Error: {msg}", oid, pid);
     return(new Exception(msg));
 }
コード例 #37
0
 private SoshikiEntity Select(DbUtil db, string soshikiCd)
 {
     return db.DbSelect<SoshikiEntity>(strSql, new { SOSHIKI_CD = soshikiCd }).FirstOrDefault();
 }
コード例 #38
0
        /// <summary>
        /// Get location data from the database
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="tx"></param>
        /// <param name="domainIdentifier"></param>
        /// <returns></returns>
        private Place GetLocation(System.Data.IDbConnection conn, System.Data.IDbTransaction tx, DomainIdentifier domainIdentifier)
        {
            // Get configuration service
            ISystemConfigurationService config = ApplicationContext.ConfigurationService; //ApplicationContext.Current.GetService(typeof(ISystemConfigurationService)) as ISystemConfigurationService;

            // Create database command
            IDbCommand cmd = DbUtil.CreateCommandStoredProc(conn, tx);

            try
            {
                // Fetch the client data using shrid
                if (String.IsNullOrEmpty(domainIdentifier.Domain) || domainIdentifier.Domain.Equals(config.OidRegistrar.GetOid(ClientRegistryOids.LOCATION_CRID).Oid))
                {
                    cmd.CommandText = "get_plc";
                    cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_in", DbType.Decimal, Convert.ToDecimal(domainIdentifier.Identifier)));
                }
                else // get using alt id
                {
                    cmd.CommandText = "get_plc_extern";
                    cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_domain_in", DbType.StringFixedLength, domainIdentifier.Domain));
                    cmd.Parameters.Add(DbUtil.CreateParameterIn(cmd, "plc_id_in", DbType.StringFixedLength, (object)domainIdentifier.Identifier ?? DBNull.Value));
                }

                // Execute the reader
                IDataReader reader = cmd.ExecuteReader();

                // read data
                if (!reader.Read())
                {
                    return(null);
                }

                // Parse data
                Place   retVal = new Place();
                decimal?codeTypeId = null, addrSetId = null;
                try
                {
                    retVal.Id = Convert.ToDecimal(reader["plc_id"]);

                    // Define set identifiers
                    retVal.Name  = reader["plc_name"] == DBNull.Value ? null : Convert.ToString(reader["plc_name"]);
                    retVal.Class = reader["plc_cls_cs"] == DBNull.Value ? null : Convert.ToString(reader["plc_cls_cs"]);
                    addrSetId    = reader["plc_addr_set_id"] == DBNull.Value ? null : (decimal?)Convert.ToDecimal(reader["plc_addr_set_id"]);
                    codeTypeId   = reader["plc_typ_cd_id"] == DBNull.Value ? null : (decimal?)Convert.ToDecimal(reader["plc_typ_cd_id"]);
                }
                finally
                {
                    // Close the reader
                    reader.Close();
                }

                // Get addr set
                if (addrSetId.HasValue)
                {
                    retVal.Address = DbUtil.GetAddress(conn, tx, addrSetId, false);
                }
                // Get type code
                if (codeTypeId.HasValue)
                {
                    retVal.LocationType = DbUtil.GetCodedValue(conn, tx, codeTypeId);
                }

                // Read alternate identifiers
                retVal.AlternateIdentifiers.AddRange(GetAlternateIdentifiers(conn, tx, retVal.Id));

                // Return type

                return(retVal);
            }
            finally
            {
                cmd.Dispose();
            }
        }
コード例 #39
0
        public void FriendActionRequest(ChatSession session, FriendActionReqMessage message)
        {
            var plr = session.Player;

            if (message.AccountId == plr.Account.Id)
            {
                return;
            }

            using (var authdb = AuthDatabase.Open())
                using (var db = GameDatabase.Open())
                {
                    var target = DbUtil.Find <AccountDto>(authdb, statement => statement
                                                          .Where($"{nameof(AccountDto.Id):C} = @Id")
                                                          .WithParameters(new { Id = message.AccountId })).FirstOrDefault();

                    var targetPlayerAccount = DbUtil.Find <PlayerDto>(db, statement => statement
                                                                      .Where($"{nameof(PlayerDto.Id):C} = @Id")
                                                                      .WithParameters(new { Id = message.AccountId })).FirstOrDefault();

                    if (target == null || targetPlayerAccount == null)
                    {
                        plr.SendAsync(new FriendActionAckMessage
                        {
                            Friend = new FriendDto(),
                            Result = FriendResult.UserNotExist,
                            Unk    = 0
                        });
                        return;
                    }

                    var targetPlayer = GameServer.Instance.PlayerManager.Get(message.AccountId);
                    session.Player.FriendManager.GetValue(message.AccountId, out var friend);

                    switch (message.Action)
                    {
                    case FriendAction.Add:
                        if (friend != null)
                        {
                            plr.SendAsync(new ServerResultAckMessage(ServerResult.DBError));
                            return;
                        }

                        var settingMananger = new PlayerSettingManager(null, targetPlayerAccount);
                        switch (settingMananger.GetSetting("AllowFriendRequest"))
                        {
                        case CommunitySetting.Allow:
                            friend = plr.FriendManager.AddOrUpdate(message.AccountId, targetPlayer,
                                                                   FriendState.Requesting, FriendState.RequestDialog);

                            session.SendAsync(new FriendActionAckMessage
                            {
                                Friend = friend.GetFriend(),
                                Result = FriendResult.Ok,
                                Unk    = 0
                            });

                            if (targetPlayer != null)
                            {
                                targetPlayer.ChatSession?.SendAsync(new FriendActionAckMessage
                                {
                                    Friend = friend.GetPlayer(),
                                    Result = FriendResult.Ok,
                                    Unk    = 0
                                });
                            }

                            break;

                        case CommunitySetting.Deny:
                            session.SendAsync(new FriendActionAckMessage
                            {
                                Friend = new FriendDto(),
                                Result = FriendResult.UserNotExist,
                                Unk    = 0
                            });
                            break;
                        }

                        break;

                    case FriendAction.Decline:
                    case FriendAction.Remove:
                        if (friend == null)
                        {
                            plr.SendAsync(new ServerResultAckMessage(ServerResult.DBError));
                            return;
                        }

                        friend.PlayerState = FriendState.NotInList;
                        friend.FriendState = FriendState.NotInList;
                        plr.FriendManager.Remove(message.AccountId, targetPlayer);

                        session.SendAsync(new FriendActionAckMessage
                        {
                            Friend = friend.GetFriend(),
                            Result = FriendResult.Ok,
                            Unk    = 0
                        });
                        session.SendAsync(
                            new FriendListAckMessage(plr.FriendManager.Select(d => d.GetFriend())
                                                     .Where(x => x.State != 0).ToArray()));

                        if (targetPlayer != null)
                        {
                            targetPlayer.ChatSession?.SendAsync(new FriendActionAckMessage
                            {
                                Friend = friend.GetPlayer(),
                                Result = FriendResult.Ok,
                                Unk    = 0
                            });
                            targetPlayer.ChatSession?.SendAsync(
                                new FriendListAckMessage(targetPlayer.FriendManager.Select(d => d.GetFriend())
                                                         .Where(x => x.State != 0).ToArray()));
                        }

                        break;

                    case FriendAction.Update:
                        if (friend == null)
                        {
                            plr.SendAsync(new ServerResultAckMessage(ServerResult.DBError));
                            return;
                        }

                        friend = plr.FriendManager.AddOrUpdate(message.AccountId, targetPlayer,
                                                               FriendState.InList, FriendState.InList);

                        session.SendAsync(new FriendActionAckMessage
                        {
                            Friend = friend.GetFriend(),
                            Result = FriendResult.Ok,
                            Unk    = 0
                        });

                        if (targetPlayer != null)
                        {
                            targetPlayer.ChatSession?.SendAsync(new FriendActionAckMessage
                            {
                                Friend = friend.GetPlayer(),
                                Result = FriendResult.Ok,
                                Unk    = 0
                            });
                        }

                        break;

                    default:
                        Console.WriteLine("UNKNOWN FriendAction:" + message.Action);
                        break;
                    }

                    targetPlayer?.SendAsync(new ChatPlayerInfoAckMessage(plr.Map <Player, PlayerInfoDto>()));
                    plr.SendAsync(new ChatPlayerInfoAckMessage(targetPlayerAccount.Map <PlayerDto, PlayerInfoDto>()));
                }
        }
コード例 #40
0
ファイル: BaseService.cs プロジェクト: higeneko2015/WcfSample
 /// <summary>
 /// コンストラクタ
 /// </summary>
 public BaseService()
 {
     _db = new DbUtil();
 }
コード例 #41
0
        /// <summary>
        /// 执行sql 带参数
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <param name="commandText">语句</param>
        /// <param name="dbParameters">参数</param>
        /// <param name="commandType">语句类型</param>
        /// <returns></returns>
        public int ExecuteNonQuery(BaseUserInfo userInfo, string commandText, List <KeyValuePair <string, object> > dbParameters, string commandType = "Text")
        {
            InsertDebugInfo(userInfo, commandText);

            var result = 0;
            // 判断是否已经登录的用户?
            var userManager = new BaseUserManager(userInfo);

            // 判断是否已经登录的用户?
            if (userManager.UserIsLogon(userInfo))
            {
                result = DbHelper.ExecuteNonQuery(commandText, DbHelper.MakeParameters(dbParameters), DbUtil.GetCommandType(commandType));
            }
            return(result);
        }
コード例 #42
0
ファイル: ShainServer.cs プロジェクト: higeneko2015/WcfSample
 public ShainEntity Create(DbUtil db, string shainCd)
 {
     return Select(db, shainCd);
 }
コード例 #43
0
        /// <summary>
        /// 执行Sql 返回DataTable
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        /// <param name="commandText">语句</param>
        /// <param name="dbParameters">参数</param>
        /// <param name="commandType">语句类型</param>
        /// <returns></returns>
        public DataTable Fill(BaseUserInfo userInfo, string commandText, List <KeyValuePair <string, object> > dbParameters, string commandType = "Text")
        {
            InsertDebugInfo(userInfo, commandText);

            DataTable result = null;
            // 判断是否已经登录的用户?
            var userManager = new BaseUserManager(userInfo);

            // 判断是否已经登录的用户?
            if (userManager.UserIsLogon(userInfo))
            {
                result = DbHelper.Fill(commandText, DbHelper.MakeParameters(dbParameters), DbUtil.GetCommandType(commandType));
            }
            return(result);
        }
コード例 #44
0
ファイル: SearchAddModel.cs プロジェクト: SolidCharity/bvcms
        private ReturnResult AddOrgMembers(int id, int origin, int membertypeid = MemberTypeCode.Member, bool pending = false)
        {
            string message = null;

            if (id > 0)
            {
                var org = DbUtil.Db.LoadOrganizationById(id);
                if (pending == false && PendingList.Count == 1 && org.AllowAttendOverlap != true)
                {
                    var om = DbUtil.Db.OrganizationMembers.FirstOrDefault(mm =>
                                                                          mm.OrganizationId != id &&
                                                                          mm.MemberTypeId != 230 && // inactive
                                                                          mm.MemberTypeId != 500 && // inservice
                                                                          mm.Organization.AllowAttendOverlap != true &&
                                                                          mm.PeopleId == PendingList[0].PeopleId &&
                                                                          mm.Organization.OrgSchedules.Any(ss =>
                                                                                                           DbUtil.Db.OrgSchedules.Any(os =>
                                                                                                                                      os.OrganizationId == id &&
                                                                                                                                      os.ScheduleId == ss.ScheduleId)));
                    if (om != null)
                    {
                        message = ViewExtensions2.Markdown($@"
**Already a member of {om.OrganizationId} (orgid) with same schedule**

You can do one of these things:

* Drop the person from the other org first
* Use the 'move' feature to transfer them to the new org
* Use Allow Attendance Overlap, if appropriate
* See <a href=""https://docs.touchpointsoftware.com/Organizations/AlreadyAMember.html"" 
  title=""Already a Member"" target=""_blank"">this help article</a>
").ToString();
                        message = $@"<div style=""text-align: left"">{message}</div>";
                        return(new ReturnResult {
                            close = true, how = "CloseAddDialog", error = message, from = AddContext
                        });
                    }
                }
                foreach (var p in PendingList)
                {
                    AddPerson(p, PendingList, origin, EntryPointId);
                    var om = OrganizationMember.InsertOrgMembers(DbUtil.Db,
                                                                 id, p.PeopleId.Value, membertypeid, Util.Now, null, pending);
                    if (membertypeid == MemberTypeCode.InActive && org.IsMissionTrip == true)
                    {
                        om.AddToGroup(DbUtil.Db, "Sender");
                    }

                    if (om.CreatedDate.HasValue)
                    {
                        if ((DateTime.Now - om.CreatedDate.Value).TotalSeconds < 5)
                        {
                            var type = pending
                                ? "Pending"
                                : membertypeid == MemberTypeCode.InActive
                                    ? "Inactive"
                                    : membertypeid == MemberTypeCode.Prospect
                                        ? "Prospect"
                                        : "Member";
                            DbUtil.LogActivity($"Org{type} Add", om.OrganizationId, om.PeopleId);
                        }
                    }
                }
                DbUtil.Db.SubmitChanges();
                DbUtil.Db.UpdateMainFellowship(id);
            }
            return(new ReturnResult {
                close = true, how = "rebindgrids", error = message, from = AddContext
            });
        }
コード例 #45
0
 public List<MessageEntity> Create(DbUtil db)
 {
     return Select(db);
 }