コード例 #1
0
        private void MainWindow_Login_Btn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _authenticationHeader = new AuthenticationHeader();

                _authenticationHeader._login = MainWindow_Login_TBox.Text;
                _authenticationHeader._password = MainWindow_Password_PBox.Password;

                _authorisation.AuthenticationHeaderValue = _authenticationHeader;

                _loginUser = _authorisation.Login();

                if (_loginUser != null)
                {
                    new DailyWindow(_loginUser, _authorisation, _authenticationHeader).Show();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Niepoprawne dane! Spróbuj ponownie.");
                }

            }
            catch (Exception)
            {

                MessageBox.Show("Serwer nie odpowiada!");
            }
            
        }
コード例 #2
0
        private static void TestUser()
        {
            UserHelper helper = new UserHelper();
            var r1 = helper.CreateTable(new Repositories.CommandRequest() { TrueScalar_FalseIntByResult = false });
            var r2 = helper.Save(new Repositories.RepositoryRequest<UserKey, User>()
            {
                CreateEntities = new List<User>()
                {
                    new User(){ Guid = "1", Code="A", Name = "A", IsAdministrator=0},
                    new User(){ Guid = "2", Code="B", Name = "B", IsAdministrator=0},
                    new User(){ Guid = "3", Code="C", Name = "C", IsAdministrator=0},
                    new User(){ Guid = "4", Code="D", Name = "D", IsAdministrator=0},
                },
                UpdateEntities = new List<User>()
                {
                    new User(){ Guid = "1", Code="A", Name = "AA", IsAdministrator=0},
                    new User(){ Guid = "4", Code="D", Name = "DD", IsAdministrator=0},
                 },
                RemoveEntities = new List<UserKey>()
                {
                    new UserKey(){ Guid ="2" },
                    new UserKey(){ Guid ="3" },
                },

            });
            var r3 = helper.ChangeUserState(new Repositories.CommandRequest()
            {
                TrueScalar_FalseIntByResult = false,
                Params = new List<RequestParameter>()
                {
                    new RequestParameter(){ Name = "IsAdministrator", Value ="1", Type ="bit", },
                    new RequestParameter(){ Name = "Guid", Value ="1", Type ="string", }
               },
            });
            var r4 = helper.Get(new QueryBySingleRequest()
            {
                Params = new List<RequestParameter>()
                {
                    new RequestParameter(){ Name = "Guid", Value ="1", Type ="string", }
                },
            });
            var r5 = helper.GetCount(new QueryBySingleRequest()
            {
                ParamPlus = "1=1",
                ParamSort = new Dictionary<string, string>()
                {
                    {"[Code]","desc"},
                    {"[Name]","desc"},
                }
            });
            var r6 = helper.Gets(new QueryByMoreRequest()
            {
                ParamPlus = "1=1",
                ParamSort = new Dictionary<string, string>()
                {
                    {"[Code]","desc"},
                    {"[Name]","desc"},
                },
            });
        }
コード例 #3
0
        public GetUserDataHandlerTests()
        {
            context = A.Fake<WeeeContext>();
            weeeAuthorization = A.Fake<IWeeeAuthorization>();
            userContext = A.Fake<IUserContext>();

            userHelper = new UserHelper();
            helper = new DbContextHelper();
        }
コード例 #4
0
 public FetchTaskHelper(IAccountConnectionService connectionService
     , string git_api_issues
     , UserHelper userHelper
     , string ali_api_user
     , string ali_api_tasks
     , Castle.Facilities.NHibernateIntegration.ISessionManager sessionManager)
     : base(connectionService, git_api_issues)
 {
     this._userHelper = userHelper;
     this._sessionManager = sessionManager;
     this._ali_api_tasks = ali_api_tasks;
 }
コード例 #5
0
 public AssociateMemberAccountService(IAccountService accountService,
     IAccountHelper accountHelper,
     IAccountConnectionService accountConnectionService,
     UserHelper userHelper,
     ITeamService teamService,
     ITeamRepository teamRepository,
     ILoggerFactory factory)
 {
     this._accountService = accountService;
     this._accountHelper = accountHelper;
     this._userHelper = userHelper;
     this._accountConnectionService = accountConnectionService;
     this._teamService = teamService;
     this._teamRepository = teamRepository;
     this._logger = factory.Create(typeof(AssociateMemberAccountService));
 }
コード例 #6
0
        public DailyWindow(UserHelper me, DailyServer authorisation, AuthenticationHeader authenticationHeader)
        {
            InitializeComponent();
            _me = me;
            _authorisation = authorisation;
            _authenticationHeader = authenticationHeader;

            DailyW_Login_Label.Content = _me.Login;

            TargetAndCaloriesNeedHelper targetHelper = _authorisation.GetTargetInfoAndCaloriesNeedInfo(Me.UserId);

            string _myCaloriesNeedString = targetHelper.TargetCaloriesNeed + "kcal (B: " + targetHelper.TargetProteins + "g, W: " + targetHelper.TargetCarbohydrates + "g, T: " + targetHelper.TargetFat + "g)";
            
            string _myTargetString = targetHelper.TargetDate.ToShortDateString() + ", waga: " + targetHelper.TargetWeight + "kg, bf: " + targetHelper.TargetBodyFat + "%";
            
            targetHelper = _authorisation.GetActualProgress(Me.UserId);
            string _myActualProgressString;
            if (targetHelper != null)
            {
                _myActualProgressString = targetHelper.TargetDate.ToShortDateString() + ", waga: " + targetHelper.TargetWeight + "kg, bf: " + targetHelper.TargetBodyFat + "%";
            }
            else
            {
                _myActualProgressString = "brak informacji";
            }
            
            DailyW_CaloriesNeed_Label.Content = (_myCaloriesNeedString);
            DailyW_MyTarget_Label.Content = (_myTargetString);
            DailyW_ActualProgress_Label.Content = (_myActualProgressString);
            DailyW_DailyCalendar_Calendar.SelectedDate = DateTime.Today;

            LoadDailyPhotosToListView(); 

            LoadDailyTrainingToListView(); 

            LoadDailyMealToListView();

            LoadDailyMensurationToListView(); 

            DailyW_NewMensurationResult_TBox.IsEnabled = false;
            DailyW_AddNewMensurationInscription_Btn.IsEnabled = false;
            DailyWindow_BFChoseHelper_Btn.Visibility = System.Windows.Visibility.Hidden;
            DailyWindow_BFCalculateHelper_Btn.Visibility = System.Windows.Visibility.Hidden;
        }
コード例 #7
0
        public TeamController(ILoggerFactory factory
            , IAccountService accountService
            , IAccountConnectionService accountConnectionService
            , ITaskService taskService
            , ITaskFolderService taskFolderService
            , IFetchTaskHelper fetchTaskHelper
            , Teams.ITeamService teamService
            , Teams.ITaskService teamTaskService

            , UserHelper userHelper)
            : base(factory
            , accountService
            , accountConnectionService
            , taskService
            , taskFolderService
            , fetchTaskHelper
            , teamService
            , teamTaskService)
        {
            this._userHelper = userHelper;
        }
コード例 #8
0
        public MyProfileWindow(UserHelper me, DailyServer authorisation)
        {
            InitializeComponent();
            this._authorisation = authorisation;
            MyProfileW_Login_TBox.Text = me.Login;
            MyProfileW_Name_TBox.Text = me.Name;
            MyProfileW_Surname_TBox.Text = me.Surname;
            MyProfileW_BirthDay_Calendar.SelectedDate = me.BirthDay;
            if (me.Sex == "M")
            {
                MyProfileW_Sex_CBox.SelectedIndex = 0;
            }
            else if (me.Sex == "K")
            {
                MyProfileW_Sex_CBox.SelectedIndex = 1;
            }
            MyProfileW_AboutMe_RichTBox.Document.Blocks.Clear(); 
            MyProfileW_AboutMe_RichTBox.Document.Blocks.Add(new Paragraph(new Run(me.AboutMe))); 

            MyProfileW_EMail_TBox.Text = me.eMail;
        }
コード例 #9
0
        public override bool TakeAction()
        {
            var guildData = new ShareCacheStruct <GuildsCache>().FindKey(GetGuild.GuildID);

            if (guildData == null)
            {
                return(false);
            }

            var guildcfg = new ShareCacheStruct <Config_Society>().FindKey(guildData.Lv);

            if (guildcfg == null)
            {
                return(false);
            }


            if (guildData.FindAtevent().UserID != Current.UserId &&
                guildData.FindVice(Current.UserId) == null)
            {
                receipt = RequestGuildResult.NoAuthority;
                return(true);
            }

            var basis = UserHelper.FindUserBasis(_DestUid);
            var guild = UserHelper.FindUserGuild(_DestUid);

            if (basis == null)
            {
                return(false);
            }



            if (_isAgree)
            {
                if (guildData.MemberList.Count >= guildcfg.Number)
                {
                    receipt = RequestGuildResult.Full;
                }

                else if (!guild.GuildID.IsEmpty())
                {
                    receipt = RequestGuildResult.HadGuild;
                }
                else
                {
                    GuildCharacter member = new GuildCharacter()
                    {
                        UserID   = basis.UserID,
                        JobTitle = GuildJobTitle.Normal,
                        Liveness = 0
                    };

                    GuildLogData log = new GuildLogData()
                    {
                        UserId   = basis.UserID,
                        UserName = basis.NickName,
                        LogTime  = DateTime.Now,
                        Content  = string.Format("玩家 {0} 加入了公会。", basis.NickName),
                    };
                    guildData.NewLog(log);

                    // 通知公会成员有新成员加入
                    foreach (var v in guildData.MemberList)
                    {
                        PushMessageHelper.NewGuildMemberNotification(GameSession.Get(v.UserID), _DestUid);
                        PushMessageHelper.NewGuildLogNotification(GameSession.Get(v.UserID));
                    }

                    guildData.AddNewMember(member);
                    guild.GuildID  = guildData.GuildID;
                    guild.IsSignIn = false;

                    // 通知新成员公会信息
                    PushMessageHelper.JoinGuildNotification(GameSession.Get(_DestUid));

                    GlobalRemoteService.SendUserData(basis, guild.GuildID);

                    receipt = RequestGuildResult.Successfully;
                }
            }
            // 从邀请列表里清除
            guildData.RemoveRequest(_DestUid);

            foreach (var v in guildData.MemberList)
            {
                PushMessageHelper.GuildApplyRemoveNotification(GameSession.Get(v.UserID), _DestUid);
            }
            return(true);
        }
コード例 #10
0
    private void SaveCFF()
    {
        bool        exit        = false;
        string      description = string.Empty;
        int         _block      = 0;
        string      assessment  = string.Empty;
        string      _letter     = string.Empty;
        CultureInfo ci          = new CultureInfo("es-AR");
        string      separator   = ci.NumberFormat.NumberDecimalSeparator;

        string username = UserHelper.GetUserId(Request.LogonUserIdentity.Name);

        string[] _params = new string[] { };

        _params = Encryption.Decrypt(Request.Params["."]).Split('.');

        int groupId = Convert.ToInt16(_params[0]);
        int profile = Convert.ToInt16(_params[1]);

        if (profile > 1)
        {
            username = _params[2];
        }

        for (int i = 0; !exit; i++)
        {
            Control answer = (Control)this.Master.FindControl("CPH").FindControl("CFF").FindControl("ctl" + i.ToString("00"));
            exit = answer == null;
            if (!exit)
            {
                if (answer.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
                {
                    TextBox  myControl = (TextBox)answer;
                    string[] values    = myControl.SkinID.Split('_');
                    if (!myControl.ReadOnly)
                    {
                        // ********* 1 linea modificada del original
                        //SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SaveResultComment]", new object[] { values[0], 5, myControl.Text, values[1] });
                        SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SaveResultComment]", new object[] { values[0], 5, myControl.Text, values[1], "0" });
                    }
                    myControl.Dispose();
                }

                if (answer.GetType().ToString() == "System.Web.UI.WebControls.RadioButton")
                {
                    RadioButton myControl = (RadioButton)answer;
                    string[]    values    = myControl.SkinID.ToUpper().Split('_');
                    if (myControl.Checked)
                    {
                        // ************ 9 linea agregada al original
                        if (values.Length != 1)
                        {
                            _block = (Convert.ToInt16(values[1]) <= 5) ? 2 : 3;
                            SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "SaveResultCompetency", new object[] { values[0], _block, values[1], values[2], values[3], true });
                        }
                    }
                    myControl.Dispose();
                }
                answer.Dispose();
            }
        }
        SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "SaveOverallResult", new object[] { username, groupId });
    }
コード例 #11
0
        public JsonResult ChangePassword(ChangePasswordModel model)
        {
            var user = UserHelper.GetCurrentUser();

            if (user == null)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "The user is not existed."
                }));
            }

            // 验证密码是否为空
            if (model.OldPassword == null || model.OldPassword.Trim() == "")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Old password is not allowed to be empty."
                }));
            }

            if (model.NewPassword == null || model.NewPassword.Trim() == "")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "New password is not allowed to be empty."
                }));
            }

            if (model.ConfirmPassword == null || model.ConfirmPassword.Trim() == "")
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Confirm password is not allowed to be empty."
                }));
            }

            if (model.NewPassword != model.ConfirmPassword)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "New password and confirm password is not the same."
                }));
            }

            // 验证旧密码
            var oldPassword = MD5Helper.Encrypt(model.OldPassword + user.Salt);

            if (oldPassword != user.Password)
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Old password is not correct."
                }));
            }

            // 修改密码
            var salt     = DateTime.Now.ToString("yyyyMMddHHmmss");
            var password = MD5Helper.Encrypt(model.NewPassword + salt);

            var filter = Builders <BsonDocument> .Filter.Eq("ID", ObjectId.Parse(user.ID));

            var update1 = Builders <BsonDocument> .Update.Set("Password", password);

            var update2 = Builders <BsonDocument> .Update.Set("Salt", salt);

            var update = Builders <BsonDocument> .Update.Combine(update1, update2);

            var mongo = new MongoHelper();

            mongo.UpdateOne(Constant.UserCollectionName, filter, update);

            return(Json(new
            {
                Code = 200,
                Msg = "Password changed successfully!"
            }));
        }
コード例 #12
0
ファイル: SendNotification.cs プロジェクト: rajeshwarn/YAFNET
        /// <summary>
        /// Sends notification about new PM in user's inbox.
        /// </summary>
        /// <param name="toUserId">
        /// User supposed to receive notification about new PM.
        /// </param>
        /// <param name="subject">
        /// Subject of PM user is notified about.
        /// </param>
        public void ToPrivateMessageRecipient(int toUserId, [NotNull] string subject)
        {
            try
            {
                // user's PM notification setting
                var privateMessageNotificationEnabled = false;

                // user's email
                var toEMail = string.Empty;

                var toUser = this.GetRepository <User>().GetById(toUserId);

                if (toUser != null)
                {
                    privateMessageNotificationEnabled = toUser.PMNotification;
                    toEMail = toUser.Email;
                }

                if (!privateMessageNotificationEnabled)
                {
                    return;
                }

                // get the PM ID
                var userPMessageId = this.GetRepository <UserPMessage>().GetSingle(p => p.UserID == toUserId).ID;

                var languageFile = UserHelper.GetUserLanguageFile(toUserId);

                var displayName = BoardContext.Current.User.DisplayOrUserName();

                // send this user a PM notification e-mail
                var notificationTemplate = new TemplateEmail("PMNOTIFICATION")
                {
                    TemplateLanguageFile = languageFile,
                    TemplateParams       =
                    {
                        ["{fromuser}"] = displayName,
                        ["{link}"]     =
                            $"{this.Get<LinkBuilder>().GetLink(ForumPages.PrivateMessage, true, "pm={0}", userPMessageId)}\r\n\r\n",
                        ["{subject}"]  = subject,
                        ["{username}"] = toUser.DisplayOrUserName()
                    }
                };

                // create notification email subject
                var emailSubject = string.Format(
                    this.Get <ILocalization>().GetText("COMMON", "PM_NOTIFICATION_SUBJECT", languageFile),
                    displayName,
                    this.BoardSettings.Name,
                    subject);

                // send email
                notificationTemplate.SendEmail(new MailAddress(toEMail), emailSubject);
            }
            catch (Exception x)
            {
                // report exception to the forum's event log
                this.Get <ILogger>().Error(x, $"Send PM Notification Error for UserID {BoardContext.Current.PageUserID}");

                // tell user about failure
                BoardContext.Current.AddLoadMessage(
                    this.Get <ILocalization>().GetTextFormatted("Failed", x.Message),
                    MessageTypes.danger);
            }
        }
コード例 #13
0
ファイル: SendNotification.cs プロジェクト: rajeshwarn/YAFNET
        /// <summary>
        /// Sends Notifications to Moderators that Message Needs Approval
        /// </summary>
        /// <param name="forumId">The forum id.</param>
        /// <param name="newMessageId">The new message id.</param>
        /// <param name="isSpamMessage">if set to <c>true</c> [is spam message].</param>
        public void ToModeratorsThatMessageNeedsApproval(int forumId, int newMessageId, bool isSpamMessage)
        {
            var moderatorsFiltered = this.Get <DataBroker>().GetModerators().Where(f => f.ForumID.Equals(forumId));
            var moderatorUserNames = new List <string>();

            moderatorsFiltered.ForEach(
                moderator =>
            {
                if (moderator.IsGroup)
                {
                    moderatorUserNames.AddRange(this.Get <IAspNetRolesHelper>().GetUsersInRole(moderator.Name).Select(u => u.UserName));
                }
                else
                {
                    moderatorUserNames.Add(moderator.Name);
                }
            });

            var themeCss =
                $"{this.Get<BoardSettings>().BaseUrlMask}{this.Get<ITheme>().BuildThemePath("bootstrap-forum.min.css")}";

            var forumLink = this.Get <LinkBuilder>().ForumUrl;

            var adminLink = this.Get <LinkBuilder>().GetLink(ForumPages.Moderate_UnapprovedPosts, true, "f={0}", forumId);

            var currentContext = HttpContext.Current;

            // send each message...
            moderatorUserNames.Distinct().AsParallel().ForAll(
                userName =>
            {
                HttpContext.Current = currentContext;

                try
                {
                    // add each member of the group
                    var membershipUser = this.Get <IAspNetUsersHelper>().GetUserByName(userName);
                    var userId         =
                        this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(membershipUser.Id);

                    var languageFile = UserHelper.GetUserLanguageFile(userId);

                    var subject = string.Format(
                        this.Get <ILocalization>().GetText(
                            "COMMON",
                            isSpamMessage
                                        ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL"
                                        : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL",
                            languageFile),
                        this.BoardSettings.Name);

                    var notifyModerators =
                        new TemplateEmail(
                            isSpamMessage
                                        ? "NOTIFICATION_ON_MODERATOR_SPAMMESSAGE_APPROVAL"
                                        : "NOTIFICATION_ON_MODERATOR_MESSAGE_APPROVAL")
                    {
                        TemplateLanguageFile = languageFile,
                        TemplateParams       =
                        {
                            ["{user}"]      = userName,
                            ["{adminlink}"] = adminLink,
                            ["{themecss}"]  = themeCss,
                            ["{forumlink}"] = forumLink
                        }
                    };

                    notifyModerators.SendEmail(
                        new MailAddress(membershipUser.Email, membershipUser.UserName),
                        subject);
                }
                finally
                {
                    HttpContext.Current = null;
                }
            });
        }
コード例 #14
0
 public void GetCurrentUser_ThrowsError_NullCtx()
 {
     Assert.Throws <ArgumentException>(() => UserHelper.GetCurrentUser(null));
 }
コード例 #15
0
 public bool Put(string userName, [FromBody] User user) => UserHelper.ResetPassword(userName, user.Password);
コード例 #16
0
 /// <summary>
 /// 刪除方法
 /// </summary>
 protected override bool Delete(IEnumerable <User> users) => UserHelper.Delete(users.Select(item => item.Id ?? ""));
コード例 #17
0
 /// <summary>
 /// 保存方法
 /// </summary>
 protected override bool Save(User user) => UserHelper.Save(user);
コード例 #18
0
        public JsonResult Save(SceneSaveModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            if (model.Name.StartsWith("_"))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to start with _."
                }));
            }

            // 查询场景信息
            var mongo  = new MongoHelper();
            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var doc = mongo.FindOne(Constant.SceneCollectionName, filter);

            var now = DateTime.Now;

            string collectionName;
            var    version = -1;

            if (doc == null) // 新建场景
            {
                collectionName = "Scene" + now.ToString("yyyyMMddHHmmss");
                version        = 0;
            }
            else // 编辑场景
            {
                collectionName = doc["CollectionName"].ToString();
                version        = doc.Contains("Version") ? int.Parse(doc["Version"].ToString()) : 0;
                version++;
            }

            // 保存或更新场景综合信息
            if (doc == null)
            {
                var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

                doc = new BsonDocument
                {
                    ["ID"]             = objectId,
                    ["Name"]           = model.Name,
                    ["TotalPinYin"]    = string.Join("", pinyin.TotalPinYin),
                    ["FirstPinYin"]    = string.Join("", pinyin.FirstPinYin),
                    ["CollectionName"] = collectionName,
                    ["Version"]        = version,
                    ["CreateTime"]     = BsonDateTime.Create(now),
                    ["UpdateTime"]     = BsonDateTime.Create(now),
                    ["IsPublic"]       = false,
                };

                if (ConfigHelper.EnableAuthority)
                {
                    var user = UserHelper.GetCurrentUser();

                    if (user != null)
                    {
                        doc["UserID"] = user.ID;
                    }
                }

                mongo.InsertOne(Constant.SceneCollectionName, doc);
            }
            else
            {
                var update1 = Builders <BsonDocument> .Update.Set("Version", version);

                var update2 = Builders <BsonDocument> .Update.Set("UpdateTime", BsonDateTime.Create(now));

                var update = Builders <BsonDocument> .Update.Combine(update1, update2);

                mongo.UpdateOne(Constant.SceneCollectionName, filter, update);

                // 将当前场景移入历史表
                var old = mongo.FindAll(collectionName).ToList();

                foreach (var i in old)
                {
                    i[Constant.VersionField] = version - 1;
                }

                if (old.Count > 0)
                {
                    // 移除_id,避免移入历史表时重复
                    for (var i = 0; i < old.Count; i++)
                    {
                        old[i].Remove("_id");
                    }

                    mongo.InsertMany($"{collectionName}{Constant.HistorySuffix}", old);
                }
            }

            // 保存新的场景信息
            var list = JsonHelper.ToObject <JArray>(model.Data);

            var docs = new List <BsonDocument>();

            foreach (var i in list)
            {
                docs.Add(BsonDocument.Parse(i.ToString()));
            }

            mongo.DeleteAll(collectionName);
            mongo.InsertMany(collectionName, docs);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!",
                ID = objectId
            }));
        }
コード例 #19
0
        public JsonResult List()
        {
            var mongo = new MongoHelper();

            // 获取所有类别
            var categories = mongo.FindAll(Constant.CategoryCollectionName).ToList();

            var docs = new List <BsonDocument>();

            if (ConfigHelper.EnableAuthority)
            {
                var user = UserHelper.GetCurrentUser();

                if (user != null)
                {
                    var filter1 = Builders <BsonDocument> .Filter.Eq("UserID", user.ID);

                    var filter11 = Builders <BsonDocument> .Filter.Eq("IsPublic", true);

                    filter1 = Builders <BsonDocument> .Filter.Or(filter1, filter11);

                    if (user.Name == "Administrator")
                    {
                        var filter2 = Builders <BsonDocument> .Filter.Exists("UserID");

                        var filter3 = Builders <BsonDocument> .Filter.Not(filter2);

                        filter1 = Builders <BsonDocument> .Filter.Or(filter1, filter3);
                    }
                    docs = mongo.FindMany(Constant.SceneCollectionName, filter1).ToList();
                }
                else // 不登录可以查看所有公开场景
                {
                    var filter1 = Builders <BsonDocument> .Filter.Eq("IsPublic", true);

                    docs = mongo.FindMany(Constant.SceneCollectionName, filter1).ToList();
                }
            }
            else
            {
                docs = mongo.FindAll(Constant.SceneCollectionName).ToList();
            }

            var list = new List <SceneModel>();

            foreach (var i in docs)
            {
                var categoryID   = "";
                var categoryName = "";

                if (i.Contains("Category") && !i["Category"].IsBsonNull && !string.IsNullOrEmpty(i["Category"].ToString()))
                {
                    var doc = categories.Where(n => n["_id"].ToString() == i["Category"].ToString()).FirstOrDefault();
                    if (doc != null)
                    {
                        categoryID   = doc["_id"].ToString();
                        categoryName = doc["Name"].ToString();
                    }
                }

                var info = new SceneModel
                {
                    ID             = i["ID"].AsObjectId.ToString(),
                    Name           = i["Name"].AsString,
                    CategoryID     = categoryID,
                    CategoryName   = categoryName,
                    TotalPinYin    = i["TotalPinYin"].ToString(),
                    FirstPinYin    = i["FirstPinYin"].ToString(),
                    CollectionName = i["CollectionName"].AsString,
                    Version        = i["Version"].AsInt32,
                    CreateTime     = i["CreateTime"].ToUniversalTime(),
                    UpdateTime     = i["UpdateTime"].ToUniversalTime(),
                    Thumbnail      = i.Contains("Thumbnail") && !i["Thumbnail"].IsBsonNull ? i["Thumbnail"].ToString() : null,
                    IsPublic       = i.Contains("IsPublic") ? i["IsPublic"].ToBoolean() : false,
                };
                list.Add(info);
            }

            list = list.OrderByDescending(o => o.UpdateTime).ToList();

            return(Json(new
            {
                Code = 200,
                Msg = "Get Successfully!",
                Data = list
            }));
        }
コード例 #20
0
        public JsonResult Edit(SceneEditModel model)
        {
            var objectId = ObjectId.GenerateNewId();

            if (!string.IsNullOrEmpty(model.ID) && !ObjectId.TryParse(model.ID, out objectId))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "ID is not allowed."
                }));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to be empty."
                }));
            }

            if (model.Name.StartsWith("_"))
            {
                return(Json(new
                {
                    Code = 300,
                    Msg = "Name is not allowed to start with _."
                }));
            }

            var mongo = new MongoHelper();

            // 开启权限时,判断是否是自己的场景
            if (ConfigHelper.EnableAuthority)
            {
                var user = UserHelper.GetCurrentUser();

                var filter11 = Builders <BsonDocument> .Filter.Eq("ID", objectId);

                var doc = mongo.FindOne(Constant.SceneCollectionName, filter11);

                if (doc == null)
                {
                    return(Json(new
                    {
                        Code = 300,
                        Msg = "The scene is not existed."
                    }));
                }

                // 保存其他人的场景
                if (doc.Contains("UserID") && doc["UserID"].ToString() != user.ID)
                {
                    return(Json(new
                    {
                        Code = 300,
                        Msg = "Permission denied."
                    }));
                }

                // 非管理员组保存不带UserID的场景
                if (!doc.Contains("UserID") && user.RoleName != "Administrator")
                {
                    return(Json(new
                    {
                        Code = 300,
                        Msg = "Permission denied."
                    }));
                }
            }

            var pinyin = PinYinHelper.GetTotalPinYin(model.Name);

            var filter = Builders <BsonDocument> .Filter.Eq("ID", objectId);

            var update1 = Builders <BsonDocument> .Update.Set("Name", model.Name);

            var update2 = Builders <BsonDocument> .Update.Set("TotalPinYin", pinyin.TotalPinYin);

            var update3 = Builders <BsonDocument> .Update.Set("FirstPinYin", pinyin.FirstPinYin);

            var update4 = Builders <BsonDocument> .Update.Set("Thumbnail", model.Image);

            UpdateDefinition <BsonDocument> update5;

            if (string.IsNullOrEmpty(model.Category))
            {
                update5 = Builders <BsonDocument> .Update.Unset("Category");
            }
            else
            {
                update5 = Builders <BsonDocument> .Update.Set("Category", model.Category);
            }

            var update6 = Builders <BsonDocument> .Update.Set("IsPublic", model.IsPublic);

            var update = Builders <BsonDocument> .Update.Combine(update1, update2, update3, update4, update5, update6);

            mongo.UpdateOne(Constant.SceneCollectionName, filter, update);

            return(Json(new
            {
                Code = 200,
                Msg = "Saved successfully!"
            }));
        }
コード例 #21
0
 public WordsUploaderController(IRepositoryFactory repositoryFactory)
 {
     _repositoryFactory = repositoryFactory;
     _userHelper        = new UserHelper(_repositoryFactory);
 }
コード例 #22
0
ファイル: Task3Library.cs プロジェクト: AlexanderChechet/ADAM
 public string GetUserValue(string username)
 {
     string result = null;
     var userHelper = new UserHelper(app);
     var userId = userHelper.GetId(new SearchExpression(username));
     if (userId.HasValue)
     {
         using (var context = new ImpersonateContext(app, userId.Value))
         {
             var setting = (TextSetting)app.GetSetting("AlexanderChechetSetting");
             result = setting.Value;
         }
     }
     return result;
 }
コード例 #23
0
        public AccountController(ILoggerFactory factory
            , IContextService context
            , IAccountHelper accountHelper
            , IAccountService accountService
            , IAccountConnectionService accountConnectionService

            , ITeamService teamService

            , string sysConfig_versionFlag

            , string googleOAuth2Url
            , string googleOAuth2TokenUrl
            , string googleOAuth2UserUrl
            , string googleScope
            , string googleClientId
            , string googleClientSecret
            , string googleClientId_mobi
            , string googleClientSecret_mobi

            , string gitOAuthUrl
            , string gitOAuthTokenUrl
            , string gitOAuthUserUrl
            , string gitClientId
            , string gitClientSecret
            , string gitScope

            , string arkOAuth2Url
            , string arkOAuth2UserUrl
            , string arkOAuth2Enable

            , UserHelper userHelper)
            : base(factory
            , context
            , accountHelper
            , accountService
            , accountConnectionService

            , teamService

            , sysConfig_versionFlag

            , googleOAuth2Url
            , googleOAuth2TokenUrl
            , googleOAuth2UserUrl
            , googleScope
            , googleClientId
            , googleClientSecret
            , googleClientId_mobi
            , googleClientSecret_mobi

            , gitOAuthUrl
            , gitOAuthTokenUrl
            , gitOAuthUserUrl
            , gitClientId
            , gitClientSecret
            , gitScope)
        {
            this._arkOAuth2Url = arkOAuth2Url;
            this._arkOAuth2UserUrl = arkOAuth2UserUrl;
            this._arkOAuth2Enable = Convert.ToBoolean(arkOAuth2Enable);

            this._userHelper = userHelper;
        }
コード例 #24
0
        private static ODataReadOnlyControllerBase <T, TKey, FakeDbContext> CreateControllerWithData <T, TKey>(IQueryable <T> data, Func <TKey, Expression <Func <T, bool> > > primaryKeyPredicate) where T : class
        {
            var dbContext  = DatabaseMocker.GetMockedDbContext <FakeDbContext, T>(data);
            var controller = new ODataReadOnlyControllerBase <T, TKey, FakeDbContext>(new NLogLogger(), UserHelper.CreateTestCurrentUser(), dbContext.Object, primaryKeyPredicate);

            return(controller);
        }
コード例 #25
0
 public void CacheCurrnetUser(Employee user)
 {
     UserHelper.SetCurrentUser(ConvertCurrentUser(user));
 }
コード例 #26
0
        public void ControllerHasNoDataTest()
        {
            //Given:
            var data       = new List <TestBasicGuid>().AsQueryable();
            var dbContext  = DatabaseMocker.GetMockedDbContext <FakeDbContext, TestBasicGuid>(data);
            var controller = new ODataReadOnlyControllerBase <TestBasicGuid, Guid, FakeDbContext>(new NLogLogger(), UserHelper.CreateTestCurrentUser(), dbContext.Object, key => x => x.ID == key);

            //When:
            var result = controller.Get().ToList();

            //Then:
            Assert.IsEmpty(result, "An empty list was expected.");
        }
コード例 #27
0
        void LoadExistingDocument(int documentId)
        {
            var document = DocumentsDataProvider.Instance.GetDocument(documentId, ModuleId);

            if (document != null)
            {
                txtName.Text                        = document.Title;
                txtDescription.Text                 = document.Description;
                chkForceDownload.Checked            = document.ForceDownload;
                datetimeStartDate.SelectedDate      = document.StartDate;
                datetimeEndDate.SelectedDate        = document.EndDate;
                textLinkAttributes.Text             = document.LinkAttributes;
                pickerCreatedDate.SelectedDate      = document.CreatedDate;
                pickerLastModifiedDate.SelectedDate = document.ModifiedDate;
                txtSortIndex.Text                   = document.SortOrderIndex.ToString();

                if (!string.IsNullOrEmpty(document.Url))
                {
                    ctlUrl.Url = document.Url;
                }

                // test to see if the document has been removed/deleted
                if (CheckFileExists(document.Url))
                {
                    CheckFileSecurity(document.Url);
                }

                var ownerUserName = UserHelper.GetUserDisplayName(PortalId, document.OwnedByUserId);
                if (string.IsNullOrEmpty(ownerUserName))
                {
                    lblOwner.Text = Localization.GetString("None_Specified");
                }
                else
                {
                    lblOwner.Text = ownerUserName;
                }

                if (txtCategory.Visible)
                {
                    txtCategory.Text = document.Category;
                }
                else
                {
                    // look for the category by name
                    var found = lstCategory.Items.FindByText(document.Category);
                    if (found != null)
                    {
                        lstCategory.SelectedValue = found.Value;
                    }
                    else
                    {
                        // legacy support, do a fall-back
                        found = lstCategory.Items.FindByValue(document.Category);
                        if (found != null)
                        {
                            lstCategory.SelectedValue = found.Value;
                        }
                    }
                }

                // FIXME: Audit data not preserved between postbacks
                ctlAudit.CreatedByUser      = UserHelper.GetUserDisplayName(PortalId, document.CreatedByUserId);
                ctlAudit.CreatedDate        = document.CreatedDate.ToString();
                ctlAudit.LastModifiedByUser = UserHelper.GetUserDisplayName(PortalId, document.ModifiedByUserId);
                ctlAudit.LastModifiedDate   = document.ModifiedDate.ToString();

                ctlUrlTracking.URL      = document.Url;
                ctlUrlTracking.ModuleID = ModuleId;
            }
            else
            {
                AddLog("Security violation: Attempt to access document not related to the module.", EventLogController.EventLogType.ADMIN_ALERT);
                Response.Redirect(Globals.NavigateURL(), true);
            }

            cmdUpdate.Text    = LocalizeString("UpdateDocument.Text");
            cmdUpdate.ToolTip = LocalizeString("UpdateDocument.ToolTip");
        }
コード例 #28
0
 public List <DispatchDetails> GetOrderDispatches(int orderId)
 {
     if (UserHelper.IsAuthorize(new List <int> {
         (int)UserType.SuperAdmin, (int)UserType.Admin, (int)UserType.Client
     }))
     {
         try
         {
             List <DispatchDetails>  result = new List <DispatchDetails>();
             List <Orders_Positions> listOfOrdersPositions = _context.Orders_Positions.Where(o => o.Order_id == orderId && o.Deleted_At == null).ToList();
             Delivery delivery = _context.Deliveries.FirstOrDefault(d => d.Order_Id == orderId && d.Deleted_At == null);
             List <Deliveries_Dispatches> listOfDeliveryDispatches = _context.Deliveries_Dispatches.Where(d => d.Delivery_Id == delivery.Id && d.Deleted_At == null).ToList();
             foreach (var deliveryDispatch in listOfDeliveryDispatches)
             {
                 Dispatch         dispatch         = _context.Dispatches.FirstOrDefault(d => d.Id == deliveryDispatch.Dispatch_Id && d.Deleted_At == null);
                 DispatchDetails  dispatchDetails  = new DispatchDetails();
                 CarrierDispatch  carrierDispatch  = new CarrierDispatch();
                 ReceiverDispatch receiverDispatch = new ReceiverDispatch();
                 List <OrderPositionsDispatchInfo> listOfOrderPositionsDispatchInfo = new List <OrderPositionsDispatchInfo>();
                 List <Dispatches_Positions>       listOfDispatchPositions          = new List <Dispatches_Positions>();
                 foreach (var item in listOfOrdersPositions)
                 {
                     var dispatchPosition = _context.Dispatches_Positions.FirstOrDefault(d => d.Order_Position_Id == item.Id && d.Dispatch_Id == dispatch.Id && d.Deleted_At == null);
                     if (dispatchPosition != null)
                     {
                         var     dispatchesPositionsForOrderPosition = _context.Dispatches_Positions.Where(d => d.Order_Position_Id == item.Id && EntityFunctions.DiffSeconds(d.Created_At, dispatchPosition.Created_At) < 0 && d.Deleted_At == null).OrderBy(d => d.Created_At).ToList();
                         int?    dispatchedAmount = dispatchesPositionsForOrderPosition.Sum(d => d.Amount);
                         decimal?dispatchedWeight = dispatchesPositionsForOrderPosition.Sum(d => d.Weight_Gross);
                         OrderPositionsDispatchInfo orderPositionsDispatchInfo = new OrderPositionsDispatchInfo();
                         orderPositionsDispatchInfo.Id                     = item.Id;
                         orderPositionsDispatchInfo.Name                   = item.Name;
                         orderPositionsDispatchInfo.Amount                 = item.Amount;
                         orderPositionsDispatchInfo.Amount_Received        = item.Amount_Received;
                         orderPositionsDispatchInfo.Amount_Before_Dispatch = item.Amount_Received - dispatchedAmount;
                         orderPositionsDispatchInfo.Amount_Dispatch        = dispatchPosition.Amount;
                         orderPositionsDispatchInfo.Amount_After_Dispatch  = orderPositionsDispatchInfo.Amount_Before_Dispatch - orderPositionsDispatchInfo.Amount_Dispatch;
                         orderPositionsDispatchInfo.Weight_Gross           = item.Weight_Gross;
                         orderPositionsDispatchInfo.Weight_Gross_Received  = item.Weight_Gross_Received;
                         orderPositionsDispatchInfo.Weight_Before_Dispatch = item.Weight_Gross_Received - dispatchedWeight;
                         orderPositionsDispatchInfo.Weight_Dispatch        = dispatchPosition.Weight_Gross;
                         orderPositionsDispatchInfo.Weight_After_Dispatch  = orderPositionsDispatchInfo.Weight_Before_Dispatch - orderPositionsDispatchInfo.Weight_Dispatch;
                         listOfOrderPositionsDispatchInfo.Add(orderPositionsDispatchInfo);
                     }
                 }
                 carrierDispatch.Carrier_Name           = dispatch.Carrier_Name;
                 carrierDispatch.Carrier_Email          = dispatch.Carrier_Email;
                 carrierDispatch.Carrier_Address        = dispatch.Carrier_Address;
                 carrierDispatch.Carrier_PrefixVat_Id   = dispatch.Carrier_PrefixVat_Id;
                 carrierDispatch.Carrier_VAT_Id         = dispatch.Carrier_VAT_Id;
                 carrierDispatch.Carrier_PhoneNumber    = dispatch.Carrier_PhoneNumber;
                 receiverDispatch.Receiver_Name         = dispatch.Receiver_Name;
                 receiverDispatch.Receiver_Email        = dispatch.Receiver_Email;
                 receiverDispatch.Receiver_Address      = dispatch.Receiver_Address;
                 receiverDispatch.Receiver_PrefixVat_Id = dispatch.Receiver_PrefixVat_Id;
                 receiverDispatch.Receiver_VAT_Id       = dispatch.Receiver_VAT_Id;
                 receiverDispatch.Receiver_PhoneNumber  = dispatch.Receiver_PhoneNumber;
                 dispatchDetails.Id = dispatch.Id;
                 dispatchDetails.Dispatch_Number      = dispatch.Dispatch_Number;
                 dispatchDetails.Creation_Date        = dispatch.Creation_Date == null ? string.Empty : ((DateTime)(dispatch.Creation_Date)).ToString("dd-MM-yyyy");
                 dispatchDetails.Car_Id               = dispatch.Car_Id;
                 dispatchDetails.Carrier              = carrierDispatch;
                 dispatchDetails.Receiver             = receiverDispatch;
                 dispatchDetails.ListOfOrderPositions = listOfOrderPositionsDispatchInfo;
                 result.Add(dispatchDetails);
             }
             return(result);
         }
         catch (Exception ex)
         {
             throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
         }
     }
     else
     {
         throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User don't have acces to this method"));
     }
 }
コード例 #29
0
ファイル: SendNotification.cs プロジェクト: rajeshwarn/YAFNET
        /// <summary>
        /// Sends Notifications to Moderators that a Message was Reported
        /// </summary>
        /// <param name="pageForumID">
        /// The page Forum ID.
        /// </param>
        /// <param name="reportedMessageId">
        /// The reported message id.
        /// </param>
        /// <param name="reporter">
        /// The reporter.
        /// </param>
        /// <param name="reportText">
        /// The report Text.
        /// </param>
        public void ToModeratorsThatMessageWasReported(
            int pageForumID,
            int reportedMessageId,
            int reporter,
            string reportText)
        {
            try
            {
                var moderatorsFiltered =
                    this.Get <DataBroker>().GetModerators().Where(f => f.ForumID.Equals(pageForumID));
                var moderatorUserNames = new List <string>();

                moderatorsFiltered.ForEach(
                    moderator =>
                {
                    if (moderator.IsGroup)
                    {
                        moderatorUserNames.AddRange(
                            this.Get <IAspNetRolesHelper>().GetUsersInRole(moderator.Name).Select(u => u.UserName));
                    }
                    else
                    {
                        moderatorUserNames.Add(moderator.Name);
                    }
                });

                var currentContext = HttpContext.Current;

                // send each message...
                moderatorUserNames.Distinct().AsParallel().ForAll(
                    userName =>
                {
                    HttpContext.Current = currentContext;

                    try
                    {
                        // add each member of the group
                        var membershipUser = this.Get <IAspNetUsersHelper>().GetUserByName(userName);
                        var userId         =
                            this.Get <IAspNetUsersHelper>().GetUserIDFromProviderUserKey(membershipUser.Id);

                        var languageFile = UserHelper.GetUserLanguageFile(userId);

                        var subject = string.Format(
                            this.Get <ILocalization>().GetText(
                                "COMMON",
                                "NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE",
                                languageFile),
                            this.BoardSettings.Name);

                        var notifyModerators = new TemplateEmail("NOTIFICATION_ON_MODERATOR_REPORTED_MESSAGE")
                        {
                            // get the user localization...
                            TemplateLanguageFile = languageFile,
                            TemplateParams       =
                            {
                                ["{user}"]     = userName,
                                ["{reason}"]   = reportText,
                                ["{reporter}"] =
                                    this.Get <IUserDisplayName>()
                                    .GetNameById(reporter),
                                ["{adminlink}"] = this.Get <LinkBuilder>().GetLink(
                                    ForumPages.Moderate_ReportedPosts,
                                    true,
                                    "f={0}",
                                    pageForumID)
                            }
                        };

                        notifyModerators.SendEmail(
                            new MailAddress(membershipUser.Email, membershipUser.UserName),
                            subject);
                    }
                    finally
                    {
                        HttpContext.Current = null;
                    }
                });
            }
            catch (Exception x)
            {
                // report exception to the forum's event log
                this.Get <ILogger>().Error(
                    x,
                    $"Send Message Report Notification Error for UserID {BoardContext.Current.PageUserID}");
            }
        }
コード例 #30
0
        public RequestResult EditDispatch([FromBody] EditDispatch editDispatch, bool isCMR)
        {
            if (UserHelper.IsAuthorize(new List <int> {
                (int)UserType.SuperAdmin
            }))
            {
                Dispatch      dispatchToEdit = _context.Dispatches.FirstOrDefault(o => o.Id == editDispatch.Id && o.Deleted_At == null);
                DateTime      dateOfEdit     = DateTime.Now;
                RequestResult result         = new RequestResult();
                try
                {
                    int            CMRId       = Convert.ToInt32(dispatchToEdit.CMR_Id);
                    CMR_Dispatches CMRDispatch = _context.CMR_Dispatches.FirstOrDefault(c => c.Id == CMRId);
                    if (isCMR)
                    {
                        if (CMRDispatch != null)
                        {
                            CMRDispatch.Edited_At           = dateOfEdit;
                            CMRDispatch.Destination         = editDispatch.CMRDispatch.Destination;
                            CMRDispatch.Sender_Address      = editDispatch.CMRDispatch.Sender_Address;
                            CMRDispatch.Sender_Email        = editDispatch.CMRDispatch.Sender_Email;
                            CMRDispatch.Sender_Name         = editDispatch.CMRDispatch.Sender_Name;
                            CMRDispatch.Sender_PrefixVat_Id = editDispatch.CMRDispatch.Sender_PrefixVat_Id;
                            CMRDispatch.Sender_VAT_Id       = editDispatch.CMRDispatch.Sender_VAT_Id.RemoveWhiteSpaces();
                            _context.SaveChanges();
                        }
                        else
                        {
                            CMRDispatch                     = new CMR_Dispatches();
                            CMRDispatch.Created_At          = dateOfEdit;
                            CMRDispatch.Destination         = editDispatch.CMRDispatch.Destination;
                            CMRDispatch.Dispatch_Id         = 0;
                            CMRDispatch.Sender_Address      = editDispatch.CMRDispatch.Sender_Address;
                            CMRDispatch.Sender_Email        = editDispatch.CMRDispatch.Sender_Email;
                            CMRDispatch.Sender_Name         = editDispatch.CMRDispatch.Sender_Name;
                            CMRDispatch.Sender_PrefixVat_Id = editDispatch.CMRDispatch.Sender_PrefixVat_Id;
                            CMRDispatch.Sender_VAT_Id       = editDispatch.CMRDispatch.Sender_VAT_Id.RemoveWhiteSpaces();
                            _context.CMR_Dispatches.Add(CMRDispatch);
                            _context.SaveChanges();
                        }
                    }
                    else
                    {
                        if (CMRDispatch != null)
                        {
                            CMRDispatch.Deleted_At = dateOfEdit;
                            _context.SaveChanges();
                        }
                    }

                    if (dispatchToEdit != null)
                    {
                        dispatchToEdit.Carrier_Address      = editDispatch.Carrier.Carrier_Address;
                        dispatchToEdit.Carrier_Email        = editDispatch.Carrier.Carrier_Email;
                        dispatchToEdit.Carrier_Name         = editDispatch.Carrier.Carrier_Name;
                        dispatchToEdit.Carrier_PrefixVat_Id = editDispatch.Carrier.Carrier_PrefixVat_Id;
                        dispatchToEdit.Carrier_VAT_Id       = editDispatch.Carrier.Carrier_VAT_Id.RemoveWhiteSpaces();
                        dispatchToEdit.Carrier_PhoneNumber  = editDispatch.Carrier.Carrier_PhoneNumber.RemoveWhiteSpaces();
                        dispatchToEdit.Car_Id                = editDispatch.Car_Id.RemoveWhiteSpaces();
                        dispatchToEdit.Creation_Date         = editDispatch.Creation_Date;
                        dispatchToEdit.Dispatch_Number       = editDispatch.Dispatch_Number;
                        dispatchToEdit.Receiver_Address      = editDispatch.Receiver.Receiver_Address;
                        dispatchToEdit.Receiver_Email        = editDispatch.Receiver.Receiver_Email;
                        dispatchToEdit.Receiver_Name         = editDispatch.Receiver.Receiver_Name;
                        dispatchToEdit.Receiver_PrefixVat_Id = editDispatch.Receiver.Receiver_PrefixVat_Id;
                        dispatchToEdit.Receiver_VAT_Id       = editDispatch.Receiver.Receiver_VAT_Id.RemoveWhiteSpaces();
                        dispatchToEdit.Receiver_PhoneNumber  = editDispatch.Receiver.Receiver_PhoneNumber.RemoveWhiteSpaces();
                        dispatchToEdit.Edited_At             = dateOfEdit;
                        dispatchToEdit.If_CMR                = isCMR;
                        dispatchToEdit.Duty_Doc_Id           = editDispatch.Duty_Doc_Id;
                        dispatchToEdit.CMR_Id                = CMRDispatch == null ? null : CMRDispatch.Id.ToString();

                        _context.SaveChanges();
                        var dispatchPositionsFromDB = _context.Dispatches_Positions.Where(d => d.Dispatch_Id == editDispatch.Id && d.Deleted_At == null).ToList();

                        //Editing and adding orderPositions
                        foreach (var dispatchPosition in editDispatch.DispatchPositions)
                        {
                            Dispatches_Positions dispatchPositionForParameter = _context.Dispatches_Positions
                                                                                .FirstOrDefault(d => d.Order_Position_Id == dispatchPosition.Id && d.Dispatch_Id == editDispatch.Id && d.Deleted_At == null);

                            //foreach (var dispatchPositionFromDB in dispatchPositionsFromDB)
                            //{
                            //if (dispatchPosition.Id == dispatchPositionFromDB.Order_Position_Id)
                            //{
                            //Dispatches_Positions dispatchPositionForParameter = _context.Dispatches_Positions.FirstOrDefault(d => d.Order_Position_Id == dispatchPosition.Id && d.Dispatch_Id == editDispatch.Id && d.Deleted_At == null);
                            if (dispatchPositionForParameter != null)
                            {
                                Orders_Positions orderPosition = _context.Orders_Positions.FirstOrDefault(o => o.Id == dispatchPositionForParameter.Order_Position_Id && o.Deleted_At == null);
                                dispatchPositionForParameter.Amount       = dispatchPosition.Amount;
                                dispatchPositionForParameter.Edited_At    = dateOfEdit;
                                dispatchPositionForParameter.Weight_Gross = Math.Round((decimal)(dispatchPosition.Amount * orderPosition.Unit_Weight), 2);
                                _context.SaveChanges();
                                Delivery delivery = _context.Deliveries.FirstOrDefault(d => d.Order_Id == orderPosition.Order_id && d.Deleted_At == null);
                                List <Orders_Positions> listOfOrdersPositionsForOrderPosition = _context.Orders_Positions.Where(o => o.Order_id == orderPosition.Order_id && o.Deleted_At == null).ToList();
                                bool isBalanced = true;
                                foreach (var orderPositionForOrder in listOfOrdersPositionsForOrderPosition)
                                {
                                    List <Dispatches_Positions> dispatchPositions = _context.Dispatches_Positions.Where(d => d.Order_Position_Id == orderPositionForOrder.Id && d.Deleted_At == null).ToList();
                                    if (orderPositionForOrder.Amount_Received != dispatchPositions.Sum(d => d.Amount))
                                    {
                                        isBalanced = false;
                                    }
                                }
                                if (isBalanced)
                                {
                                    delivery.If_Delivery_Dispatch_Balanced = true;
                                }
                                _context.SaveChanges();
                            }
                            else
                            {
                                Orders_Positions orderPosition = _context.Orders_Positions.FirstOrDefault(o => o.Id == dispatchPosition.Id && o.Deleted_At == null);

                                if (orderPosition == null)
                                {
                                    throw new Exception(string.Format("Order position (id = {0}) not exist in database", dispatchPosition.Id));
                                }

                                Dispatches_Positions dispatchPostionToAdd = new Dispatches_Positions();
                                dispatchPostionToAdd.Amount            = dispatchPosition.Amount;
                                dispatchPostionToAdd.Created_At        = dateOfEdit;
                                dispatchPostionToAdd.Dispatch_Id       = editDispatch.Id;
                                dispatchPostionToAdd.Order_Position_Id = dispatchPosition.Id;
                                dispatchPostionToAdd.Weight_Gross      = Math.Round((decimal)(dispatchPosition.Amount * orderPosition.Unit_Weight), 2);
                                _context.Dispatches_Positions.Add(dispatchPostionToAdd);
                                _context.SaveChanges();


                                Delivery delivery = _context.Deliveries.FirstOrDefault(d => d.Order_Id == orderPosition.Order_id && d.Deleted_At == null);

                                if (delivery == null)
                                {
                                    throw new Exception(string.Format("Delivery not exist in database for order (id = {0})", orderPosition.Order_id));
                                }

                                if (_context.Deliveries_Dispatches.FirstOrDefault(d => d.Delivery_Id == delivery.Id && d.Dispatch_Id == dispatchPostionToAdd.Id && d.Deleted_At == null) == null)
                                {
                                    Deliveries_Dispatches deliveryDispatch = new Deliveries_Dispatches();
                                    deliveryDispatch.Created_At  = dateOfEdit;
                                    deliveryDispatch.Dispatch_Id = (int)dispatchPostionToAdd.Dispatch_Id;
                                    deliveryDispatch.Delivery_Id = delivery.Id;
                                    _context.Deliveries_Dispatches.Add(deliveryDispatch);
                                    _context.SaveChanges();
                                }

                                List <Orders_Positions> listOfOrdersPositionsForOrderPosition = _context.Orders_Positions.Where(o => o.Order_id == orderPosition.Order_id && o.Deleted_At == null).ToList();
                                bool isBalanced = true;
                                foreach (var orderPositionForOrder in listOfOrdersPositionsForOrderPosition)
                                {
                                    List <Dispatches_Positions> dispatchPositions = _context.Dispatches_Positions.Where(d => d.Order_Position_Id == orderPositionForOrder.Id && d.Deleted_At == null).ToList();
                                    if (orderPositionForOrder.Amount_Received != dispatchPositions.Sum(d => d.Amount))
                                    {
                                        isBalanced = false;
                                    }
                                }
                                if (isBalanced)
                                {
                                    delivery.If_Delivery_Dispatch_Balanced = true;
                                }
                            }


                            //}
                            //if (dispatchPosition.Id == null)//jak dispatchPositionId jest nullem to tworze nowy na podstawie OrderId
                            //{
                            //    if (dispatchPosition.OrderId != null)
                            //    {

                            //    }

                            //}

                            //}
                        }
                        _context.SaveChanges();

                        //Deleting orderPosition
                        List <int> listOfIdsToDelete = _dispatchManager.GetIdstoRemove(editDispatch.DispatchPositions, dispatchPositionsFromDB);
                        foreach (var id in listOfIdsToDelete)
                        {
                            var dispatchPositionToDelete = _context.Dispatches_Positions.FirstOrDefault(d => d.Order_Position_Id == id && d.Dispatch_Id == editDispatch.Id && d.Deleted_At == null);
                            dispatchPositionToDelete.Deleted_At = dateOfEdit;
                            //Dispatches_Positions dispatchPositionForParameter = _context.Dispatches_Positions.FirstOrDefault(d => d.Id == id && d.Deleted_At == null);
                            Orders_Positions orderPosition = _context.Orders_Positions.FirstOrDefault(o => o.Id == dispatchPositionToDelete.Order_Position_Id && o.Deleted_At == null);
                            Delivery         delivery      = _context.Deliveries.FirstOrDefault(d => d.Order_Id == orderPosition.Order_id && d.Deleted_At == null);
                            delivery.If_Delivery_Dispatch_Balanced = false;
                            _context.SaveChanges();


                            //sprawdzam czy jakiś orderPOsition z delivery dla tego dispatchPositions należy do tego dispatcha
                            bool       isDeliveryDispatch           = false;
                            List <int> orderPositionsForDeliveryIds = _context.Orders_Positions.Where(o => o.Order_id == delivery.Order_Id && o.Deleted_At == null).Select(o => o.Id).ToList();
                            List <int> listOfdispatchPositionsIds   = _context.Dispatches_Positions.Where(d => d.Dispatch_Id == editDispatch.Id && d.Deleted_At == null).Select(d => d.Id).ToList();
                            foreach (var item in orderPositionsForDeliveryIds)
                            {
                                if (listOfdispatchPositionsIds.Contains(item))
                                {
                                    isDeliveryDispatch = true;
                                }
                            }

                            if (!isDeliveryDispatch)
                            {
                                Deliveries_Dispatches deliveryDispatch = _context.Deliveries_Dispatches.FirstOrDefault(d => d.Delivery_Id == delivery.Id && d.Dispatch_Id == editDispatch.Id && d.Deleted_At == null);
                                deliveryDispatch.Deleted_At = dateOfEdit;
                                _context.SaveChanges();
                            }
                        }

                        _context.SaveChanges();
                        dispatchToEdit.Number_Of_Positions = _context.Dispatches_Positions.Where(d => d.Dispatch_Id == editDispatch.Id && d.Deleted_At == null).Count();
                        _context.SaveChanges();
                    }
                    else
                    {
                        result.Status  = false;
                        result.Message = "Dispatch not found";
                    }
                    result.Status  = true;
                    result.Message = "Order has been edited";
                }
                catch (Exception ex)
                {
                    result.Status  = false;
                    result.Message = ex.ToString();
                }
                return(result);
            }
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User don't have acces to this method"));
            }
        }
コード例 #31
0
        public RequestResult CreateDispatch([FromBody] CreateDispatch newDispatch, bool isCMR)
        {
            if (UserHelper.IsAuthorize(new List <int> {
                (int)UserType.SuperAdmin, (int)UserType.Admin
            }))
            {
                RequestResult result = new RequestResult();
                try
                {
                    if (_context.Orders.OrderByDescending(o => o.Created_At).FirstOrDefault() == null || _context.Orders.OrderByDescending(o => o.Created_At).FirstOrDefault().Created_At.Value.Month != DateTime.Now.Month)
                    {
                        var counter = _context.Counters.FirstOrDefault(c => c.Name == "DispatchCounter");
                        counter.Count = 1;
                        _context.SaveChanges();
                    }
                    DateTime       dateOfCreate  = DateTime.Now;
                    Dispatch       dispatchToAdd = new Dispatch();
                    CMR_Dispatches cmrDispatch   = new CMR_Dispatches();
                    dispatchToAdd.Carrier_Address      = newDispatch.Carrier.Carrier_Address;
                    dispatchToAdd.Carrier_Email        = newDispatch.Carrier.Carrier_Email;
                    dispatchToAdd.Carrier_Name         = newDispatch.Carrier.Carrier_Name;
                    dispatchToAdd.Carrier_PrefixVat_Id = newDispatch.Carrier.Carrier_PrefixVat_Id;
                    dispatchToAdd.Carrier_VAT_Id       = newDispatch.Carrier.Carrier_VAT_Id.RemoveWhiteSpaces();
                    dispatchToAdd.Carrier_PhoneNumber  = newDispatch.Carrier.Carrier_PhoneNumber.RemoveWhiteSpaces();
                    dispatchToAdd.Car_Id                = newDispatch.Car_Id.RemoveWhiteSpaces();
                    dispatchToAdd.Creation_Date         = dateOfCreate;
                    dispatchToAdd.Dispatch_Number       = _context.Counters.FirstOrDefault(c => c.Name == "DispatchCounter").Count.ToString() + "/" + ((DateTime)dispatchToAdd.Creation_Date).Month.ToString() + "/" + ((DateTime)dispatchToAdd.Creation_Date).Year.ToString();
                    dispatchToAdd.Receiver_Address      = newDispatch.Receiver.Receiver_Address;
                    dispatchToAdd.Receiver_Email        = newDispatch.Receiver.Receiver_Email;
                    dispatchToAdd.Receiver_Name         = newDispatch.Receiver.Receiver_Name;
                    dispatchToAdd.Receiver_PrefixVat_Id = newDispatch.Receiver.Receiver_PrefixVat_Id;
                    dispatchToAdd.Receiver_VAT_Id       = newDispatch.Receiver.Receiver_VAT_Id.RemoveWhiteSpaces();
                    dispatchToAdd.Receiver_PhoneNumber  = newDispatch.Receiver.Receiver_PhoneNumber.RemoveWhiteSpaces();
                    dispatchToAdd.Created_At            = dateOfCreate;
                    if (isCMR)
                    {
                        cmrDispatch.Created_At          = dateOfCreate;
                        cmrDispatch.Destination         = newDispatch.CMRDispatch.Destination;
                        cmrDispatch.Dispatch_Id         = 0;
                        cmrDispatch.Sender_Address      = newDispatch.CMRDispatch.Sender_Address;
                        cmrDispatch.Sender_Email        = newDispatch.CMRDispatch.Sender_Email;
                        cmrDispatch.Sender_Name         = newDispatch.CMRDispatch.Sender_Name;
                        cmrDispatch.Sender_PrefixVat_Id = newDispatch.CMRDispatch.Sender_PrefixVat_Id;
                        cmrDispatch.Sender_VAT_Id       = newDispatch.CMRDispatch.Sender_VAT_Id.RemoveWhiteSpaces();
                        cmrDispatch.Dispatch_Id         = dispatchToAdd.Id;
                        cmrDispatch.Commodity_Type      = newDispatch.CMRDispatch.Commodity_Type;
                        _context.CMR_Dispatches.Add(cmrDispatch);
                        _context.SaveChanges();
                        dispatchToAdd.CMR_Id = cmrDispatch.Id == null ? null : cmrDispatch.Id.ToString();
                        _context.SaveChanges();
                    }
                    else
                    {
                        dispatchToAdd.CMR_Id = null;
                    }

                    dispatchToAdd.Number_Of_Positions = newDispatch.DispatchPositions.Count;
                    dispatchToAdd.If_PDF_And_Sent     = false;
                    dispatchToAdd.If_CMR_And_Sent     = false;
                    dispatchToAdd.If_CMR      = isCMR;
                    dispatchToAdd.Duty_Doc_Id = newDispatch.Duty_Doc_Id;
                    dispatchToAdd.Creator_Id  = UserHelper.GetCurrentUserId();
                    _context.Dispatches.Add(dispatchToAdd);
                    _context.SaveChanges();
                    foreach (var item in newDispatch.DispatchPositions)
                    {
                        Orders_Positions     orderPosition   = _context.Orders_Positions.FirstOrDefault(o => o.Id == item.Id && o.Deleted_At == null);
                        Dispatches_Positions dispatchPostion = new Dispatches_Positions();
                        dispatchPostion.Amount            = item.Amount;
                        dispatchPostion.Created_At        = dateOfCreate;
                        dispatchPostion.Dispatch_Id       = dispatchToAdd.Id;
                        dispatchPostion.Order_Position_Id = item.Id;
                        dispatchPostion.Weight_Gross      = Math.Round((decimal)(item.Amount * orderPosition.Unit_Weight), 2);
                        _context.Dispatches_Positions.Add(dispatchPostion);
                        _context.SaveChanges();


                        Delivery delivery = _context.Deliveries.FirstOrDefault(d => d.Order_Id == orderPosition.Order_id && d.Deleted_At == null);
                        if (_context.Deliveries_Dispatches.FirstOrDefault(d => d.Delivery_Id == delivery.Id && d.Dispatch_Id == dispatchToAdd.Id && d.Deleted_At == null) == null)
                        {
                            Deliveries_Dispatches deliveryDispatch = new Deliveries_Dispatches();
                            deliveryDispatch.Created_At  = dateOfCreate;
                            deliveryDispatch.Dispatch_Id = (int)dispatchPostion.Dispatch_Id;
                            deliveryDispatch.Delivery_Id = delivery.Id;
                            _context.Deliveries_Dispatches.Add(deliveryDispatch);
                            _context.SaveChanges();
                        }

                        List <Orders_Positions> listOfOrdersPositionsForOrderPosition = _context.Orders_Positions.Where(o => o.Order_id == orderPosition.Order_id && o.Deleted_At == null).ToList();
                        bool isBalanced = true;
                        foreach (var orderPositionForOrder in listOfOrdersPositionsForOrderPosition)
                        {
                            List <Dispatches_Positions> dispatchPositions = _context.Dispatches_Positions.Where(d => d.Order_Position_Id == orderPositionForOrder.Id && d.Deleted_At == null).ToList();
                            if (orderPositionForOrder.Amount_Received != dispatchPositions.Sum(d => d.Amount))
                            {
                                isBalanced = false;
                            }
                        }
                        if (isBalanced)
                        {
                            delivery.If_Delivery_Dispatch_Balanced = true;
                        }
                    }
                    var orderCounter = _context.Counters.FirstOrDefault(c => c.Name == "DispatchCounter");
                    orderCounter.Count++;
                    _context.SaveChanges();
                    result.Status  = true;
                    result.Message = "Order has been edited";
                }
                catch (Exception ex)
                {
                    result.Status  = false;
                    result.Message = ex.ToString();
                }
                return(result);
            }
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User don't have acces to this method"));
            }
        }
コード例 #32
0
ファイル: Action1305.cs プロジェクト: zxx0367/Scut-samples
        public override bool TakeAction()
        {
            UserHelper.GetUserLightOpen(ContextUser.UserID);
            short opType     = 0;
            int   huntingID2 = 0;

            if (huntingID < 1005)
            {
                huntingID2 = MathUtils.Addition(huntingID, 1, int.MaxValue);
            }
            else
            {
                huntingID2 = 1001; //huntingID;
            }
            UserHelper.ChechDailyRestrain(ContextUser.UserID);

            if (!CrystalHelper.CheckAllowCrystall(ContextUser))
            {
                ErrorCode = 1000;
                ErrorInfo = LanguageManager.GetLang().St1305_FateBackpackFull;
                return(false);
            }
            else
            {
                if (!CrystalHelper.CheckAllowCrystall(ContextUser))
                {
                    ErrorCode = errorNum;
                    ErrorInfo = LanguageManager.GetLang().St1305_FateBackpackFull;
                    return(false);
                }
            }

            ProbabilityInfo probabilityInfo = null;

            if (ops == 1)
            {
                #region
                opType = 1;
                UserDailyRestrain userRestrain = new GameDataCacheSet <UserDailyRestrain>().FindKey(ContextUser.UserID);
                probabilityInfo = new ConfigCacheSet <ProbabilityInfo>().FindKey(huntingID); //当前猎命人物的概率
                if (probabilityInfo == null)
                {
                    return(false);
                }
                ProbabilityInfo probability1 = new ConfigCacheSet <ProbabilityInfo>().FindKey(huntingID2);
                if (userRestrain != null && userRestrain.Funtion2 >= VipHelper.GetVipUseNum(ContextUser.VipLv, RestrainType.MianFeiLieMing) && DateTime.Now.Date == userRestrain.RefreshDate.Date)
                {
                    if (probabilityInfo.Price > ContextUser.GameCoin)
                    {
                        ErrorCode = errorNum;
                        ErrorInfo = LanguageManager.GetLang().St_GameCoinNotEnough;
                        return(false);
                    }
                }
                //暑期第三弹
                if (huntingID2 == 1001 && !NoviceHelper.IsGianCrystalPack(ContextUser))
                {
                    ErrorCode = errorNum;
                    ErrorInfo = LanguageManager.GetLang().St1305_BeiBaoBackpackFull;
                    return(false);
                }
                var lightCacheSet = new GameDataCacheSet <UserLight>();
                if (huntingID != 1001)
                {
                    UserLight userLight1 = lightCacheSet.FindKey(ContextUser.UserID, huntingID);
                    if (userLight1.IsLight == 2)
                    {
                        ErrorCode = LanguageManager.GetLang().ErrorCode;
                        return(false);
                    }

                    if (userLight1.IsLight == 1)
                    {
                        userLight1.IsLight = 2;
                        //userLight1.Update();
                    }
                }
                UserLight userLight = new GameDataCacheSet <UserLight>().FindKey(ContextUser.UserID, huntingID2);
                if (RandomUtils.IsHit(probability1.Light))
                {
                    ErrorCode = ErrorCode;
                    ErrorInfo = probability1.HuntingName;

                    if (userLight != null)
                    {
                        userLight.IsLight = 1;
                        //userLight.Update();
                    }
                    else
                    {
                        userLight = new UserLight()
                        {
                            UserID    = ContextUser.UserID,
                            HuntingID = huntingID2,
                            IsLight   = 1
                        };
                        lightCacheSet.Add(userLight);
                    }
                }

                if (userRestrain != null)
                {
                    if (userRestrain.Funtion2 >= VipHelper.GetVipUseNum(ContextUser.VipLv, RestrainType.MianFeiLieMing) && DateTime.Now.Date == userRestrain.RefreshDate.Date)
                    {
                        ContextUser.GameCoin = MathUtils.Subtraction(ContextUser.GameCoin, probabilityInfo.Price, 0);
                        //ContextUser.Update();
                    }
                    else
                    {
                        userRestrain.Funtion2 = MathUtils.Addition(userRestrain.Funtion2, 1, int.MaxValue);
                        //userRestrain.Update();
                    }
                }
                else
                {
                    ContextUser.GameCoin = MathUtils.Subtraction(ContextUser.GameCoin, probabilityInfo.Price, 0);
                    //ContextUser.Update();
                }

                lightArray = new GameDataCacheSet <UserLight>().FindAll(ContextUser.UserID);
                #endregion
            }
            else if (ops == 2)
            {
                #region
                opType = 2;
                if (ContextUser.VipLv < 5)
                {
                    ErrorCode = LanguageManager.GetLang().ErrorCode;
                    ErrorInfo = LanguageManager.GetLang().St_VipNotEnough;
                    return(false);
                }

                probabilityInfo = new ConfigCacheSet <ProbabilityInfo>().FindKey(huntingID); //当前猎命人物的概率
                if (probabilityInfo == null)
                {
                    return(false);
                }

                if (ContextUser.GoldNum < probabilityInfo.Price)
                {
                    ErrorCode = LanguageManager.GetLang().ErrorCode;
                    ErrorInfo = LanguageManager.GetLang().St_GoldNotEnough;
                    return(false);
                }
                UserLight uLightInfo = new GameDataCacheSet <UserLight>().FindKey(ContextUser.UserID, probabilityInfo.GoldHunting);
                if (uLightInfo != null && uLightInfo.IsLight == 1)
                {
                    ErrorCode = LanguageManager.GetLang().ErrorCode;
                    ErrorInfo = LanguageManager.GetLang().St1305_HuntingIDLight;
                    return(false);
                }
                else if (uLightInfo != null && (uLightInfo.IsLight == 2 || uLightInfo.IsLight == 0))
                {
                    uLightInfo.IsLight = 1;
                }
                else
                {
                    uLightInfo = new UserLight()
                    {
                        UserID    = ContextUser.UserID,
                        HuntingID = probabilityInfo.GoldHunting,
                        IsLight   = 1
                    };
                    new GameDataCacheSet <UserLight>().Add(uLightInfo);
                }

                ContextUser.UseGold = MathUtils.Addition(ContextUser.UseGold, probabilityInfo.Price, int.MaxValue);
                lightArray          = new GameDataCacheSet <UserLight>().FindAll(ContextUser.UserID);
                #endregion
            }

            //每种品质的概率
            double[]           probabilityArray2 = { (double)probabilityInfo.Gray, (double)probabilityInfo.Green, (double)probabilityInfo.Blue, (double)probabilityInfo.Purple, (double)probabilityInfo.Yellow, (double)probabilityInfo.Red };
            int                index2            = RandomUtils.GetHitIndex(probabilityArray2);
            CrystalQualityType qualityType       = (CrystalQualityType)Enum.Parse(typeof(CrystalQualityType), (index2 + 1).ToString());
            List <CrystalInfo> crystalArray2     = new ConfigCacheSet <CrystalInfo>().FindAll(u => u.CrystalQuality == qualityType && u.DemandLv <= ContextUser.UserLv);
            if (crystalArray2.Count > 0)
            {
                int randomNum = RandomUtils.GetRandom(0, crystalArray2.Count);
                crystal = new ConfigCacheSet <CrystalInfo>().FindKey(crystalArray2[randomNum].CrystalID);
                if (crystal != null && crystal.CrystalQuality == CrystalQualityType.Gray)
                {
                    //wuzf修改 8-15 灰色放在临时背包不存DB
                    CrystalHelper.AppendGrayCrystal(ContextUser, crystal.CrystalID);
                }
                else if (crystal != null)
                {
                    var package = UserCrystalPackage.Get(Uid);

                    UserCrystalInfo userCrystal = new UserCrystalInfo()
                    {
                        UserCrystalID = Guid.NewGuid().ToString(),
                        CrystalID     = crystal.CrystalID,
                        CrystalLv     = 1,
                        CurrExprience = 0,
                        GeneralID     = 0,
                        IsSale        = 1,
                        CreateDate    = DateTime.Now
                    };
                    package.SaveCrystal(userCrystal);
                    UserLogHelper.AppenCtystalLog(ContextUser.UserID, opType, crystal.CrystalID, probabilityInfo.Price, probabilityInfo.Price, null, 1, 0);
                    //高品质聊天通知);
                    if (crystal.CrystalQuality >= CrystalQualityType.Yellow)
                    {
                        var    cacheChat = new TjxChatService();
                        string content   = string.Format(LanguageManager.GetLang().St1305_HighQualityNotice,
                                                         ContextUser.NickName,
                                                         CrystalHelper.GetQualityName(crystal.CrystalQuality),
                                                         crystal.CrystalName
                                                         );
                        cacheChat.SystemSend(ChatType.World, content);
                    }
                }
            }

            //日常任务-猎命
            TaskHelper.TriggerDailyTask(Uid, 4009);
            return(true);
        }
コード例 #33
0
    // ******************* 3 linea modificada del original
    private void SetStatus(int current_profile)
    {
        // **************** 2 linea modificada del original
        //string username = UserHelper.GetUserId(Request.LogonUserIdentity.Name);
        //SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { null, Convert.ToInt16(_params[0]), username, _status });


        string username = UserHelper.GetUserId(Request.LogonUserIdentity.Name);
        //SqlDataReader myReader = SQLHelper.ExecuteReader( Cache["ApplicationDatabase"].ToString( ) , "GetEvaluatedPeople" , new object[] { _params[2] } );
        //myReader.Read( );


        bool        exit        = false;
        string      description = string.Empty;
        string      assessment  = string.Empty;
        string      _letter     = string.Empty;
        CultureInfo ci          = new CultureInfo("es-AR");
        string      separator   = ci.NumberFormat.NumberDecimalSeparator;


        _params = Encryption.Decrypt(Request.Params["."]).Split('.');

        int groupId = Convert.ToInt16(_params[0]);
        int profile = Convert.ToInt16(_params[1]);


        if (current_profile == 1) // Si el que firma es el evaluador envia la evaluacion al concurrente....
        {
            //SQLHelper.ExecuteNonQuery( Cache["ApplicationDatabase"].ToString( ) , "[SetAssessmentsSatus]" , new object[] { null , Convert.ToInt16( _params[0] ) , username , 3 } );

            if (profile > 1)
            {
                username = _params[2];
            }

            for (int i = 0; !exit; i++)
            {
                Control answer = (Control)this.Master.FindControl("CPH").FindControl("CFF").FindControl("ctl" + i.ToString("00"));
                exit = answer == null;
                if (!exit)
                {
                    if (answer.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
                    {
                        TextBox myControl = (TextBox)answer;

                        string[] values = ((TextBox)answer).SkinID.Split('_');

                        if (!myControl.ReadOnly)
                        {
                            Control radio = (Control)this.Master.FindControl("CPH").FindControl("CFF").FindControl("ctl" + (i - 1).ToString("00"));

                            //if( ( (RadioButton)radio ).Checked )

                            if (profile == 1) // Si envia el evaluador...
                            {
                                SqlDataReader ReaderDR = SQLHelper.ExecuteReader(Cache["ApplicationDatabase"].ToString(), "EvaluatedHasConcurrent", new object[] { Convert.ToInt32(((TextBox)answer).SkinID.Split('_')[0].ToString()) });
                                ReaderDR.Read();

                                if (ReaderDR.HasRows) // si el concurrente no es nulo va al concurrente y el envia un email...
                                {
                                    SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 3 });
                                }
                                else // si no tiene concurrente se fija si tiene doble reporte
                                {
                                    ReaderDR = SQLHelper.ExecuteReader(Cache["ApplicationDatabase"].ToString(), "EvaluatedHasDoubleReport", new object[] { Convert.ToInt32(((TextBox)answer).SkinID.Split('_')[0].ToString()) });
                                    ReaderDR.Read();

                                    if (ReaderDR.HasRows) // si tiene doble reporte va al Doble Reporte y el envia un email...
                                    {
                                        SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 6 });
                                    }
                                    else // si no tiene doble reporte va a RRHH y le envia un email...
                                    {
                                        SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 9 });
                                    }
                                }
                            }
                        }
                        myControl.Dispose();
                    }
                }
            }
        }
        else
        {
            //bool exit = false;
            //string description = string.Empty;
            //string assessment = string.Empty;
            //string _letter = string.Empty;
            //CultureInfo ci = new CultureInfo( "es-AR" );
            //string separator = ci.NumberFormat.NumberDecimalSeparator;


            //_params = Encryption.Decrypt( Request.Params["."] ).Split( '.' );

            //int groupId = Convert.ToInt16( _params[0] );
            //int profile = Convert.ToInt16( _params[1] );
            if (profile > 1)
            {
                username = _params[2];
            }

            t2c.Value = "0";

            for (int i = 0; !exit; i++)
            {
                Control answer = (Control)this.Master.FindControl("CPH").FindControl("CFF").FindControl("ctl" + i.ToString("00"));
                exit = answer == null;
                if (!exit)
                {
                    if (answer.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
                    {
                        TextBox myControl = (TextBox)answer;

                        string[] values = ((TextBox)answer).SkinID.Split('_');

                        if (!myControl.ReadOnly)
                        {
                            Control radio = (Control)this.Master.FindControl("CPH").FindControl("CFF").FindControl("ctl" + (i - 1).ToString("00"));

                            if (((RadioButton)radio).Checked)
                            {
                                if (((System.Web.UI.WebControls.CheckBox)(((RadioButton)radio))).Text == "Aprobar")
                                {
                                    if (!(((((TextBox)answer).Text.Trim().Replace("/[&/\\#'\", +$~%.:() *?<>{ }]/ g", "") == "") || (((TextBox)answer).Text.Trim().Replace("/[&/\\#'\", +$~%.:() *?<>{ }]/ g", "").Length < 3) || (((TextBox)answer).Text.Trim().IndexOf("En caso de") > -1))))
                                    {
                                        if (profile == 2) // Si firma el concurrente...
                                        {
                                            SqlDataReader ReaderDR = SQLHelper.ExecuteReader(Cache["ApplicationDatabase"].ToString(), "EvaluatedHasDoubleReport", new object[] { Convert.ToInt32(((TextBox)answer).SkinID.Split('_')[0].ToString()) });
                                            ReaderDR.Read();

                                            if (ReaderDR.HasRows) // si tiene doble reporte va al Doble Reporte y el envia un email...
                                            {
                                                SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 6 });
                                            }
                                            else // si no tiene doble reporte va a RRHH y le envia un email...
                                            {
                                                SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 9 });
                                            }
                                        }
                                        if (profile == 3) // Si firma el Doble Reporte va a RRHH y le envia un email...
                                        {
                                            SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 9 });
                                        }
                                        if (profile == 5) // Si firma RRHH termina la evaluación y le envía un email al evaluador....
                                        {
                                            SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 10 });
                                        }
                                    }
                                }
                                else if (((System.Web.UI.WebControls.CheckBox)(((RadioButton)radio))).Text == "Rechazar")
                                // si se rechaza una evaluacion hay que ver quien la rechaza.................
                                {
                                    if (!(((((TextBox)answer).Text.Trim().Replace("/[&/\\#'\", +$~%.:() *?<>{ }]/ g", "") == "") || (((TextBox)answer).Text.Trim().Replace("/[&/\\#'\", +$~%.:() *?<>{ }]/ g", "").Length < 3) || (((TextBox)answer).Text.Trim().IndexOf("En caso de") > -1))))
                                    {
                                        switch (profile)
                                        {
                                        case 2:
                                            SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 5 });
                                            break;

                                        case 3:
                                            SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 8 });
                                            break;

                                        case 5:
                                            SQLHelper.ExecuteNonQuery(Cache["ApplicationDatabase"].ToString(), "[SetAssessmentsSatus]", new object[] { ((TextBox)answer).SkinID.Split('_')[0], Convert.ToInt16(_params[0]), _params[2], 11 });
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        myControl.Dispose();
                    }
                }
            }
        }
    }
コード例 #34
0
ファイル: DispatchController.cs プロジェクト: Resgrid/Core
        public async Task <ActionResult <List <PersonnelForCallResult> > > GetPersonnelForCallGrid()
        {
            var result = new List <PersonnelForCallResult>();

            var users = await _departmentsService.GetAllUsersForDepartmentAsync(DepartmentId);            //.GetAllUsersForDepartmentUnlimitedMinusDisabled(DepartmentId);

            var personnelNames = await _departmentsService.GetAllPersonnelNamesForDepartmentAsync(DepartmentId);

            var lastUserActionlogs = await _actionLogsService.GetLastActionLogsForDepartmentAsync(DepartmentId);

            var userStates = await _userStateService.GetLatestStatesForDepartmentAsync(DepartmentId);

            var personnelSortOrder = await _departmentSettingsService.GetDepartmentPersonnelSortOrderAsync(DepartmentId);

            var personnelStatusSortOrder = await _departmentSettingsService.GetDepartmentPersonnelListStatusSortOrderAsync(DepartmentId);

            foreach (var user in users)
            {
                PersonnelForCallResult person = new PersonnelForCallResult();
                person.UserId = user.UserId;
                person.Name   = await UserHelper.GetFullNameForUser(personnelNames, user.UserName, user.UserId);

                var group = await _departmentGroupsService.GetGroupForUserAsync(user.UserId, DepartmentId);

                if (group != null)
                {
                    person.Group = group.Name;
                }

                var roles = await _personnelRolesService.GetRolesForUserAsync(user.UserId, DepartmentId);

                person.Roles = new List <string>();
                foreach (var role in roles)
                {
                    person.Roles.Add(role.Name);
                }

                var currentStaffing = userStates.FirstOrDefault(x => x.UserId == user.UserId);
                if (currentStaffing != null)
                {
                    var staffing = await CustomStatesHelper.GetCustomPersonnelStaffing(DepartmentId, currentStaffing);

                    if (staffing != null)
                    {
                        person.Staffing      = staffing.ButtonText;
                        person.StaffingColor = staffing.ButtonClassToColor();
                    }
                }
                else
                {
                    person.Staffing      = "Available";
                    person.StaffingColor = "#000";
                }

                var currentStatus = lastUserActionlogs.FirstOrDefault(x => x.UserId == user.UserId);
                if (currentStatus != null)
                {
                    var status = await CustomStatesHelper.GetCustomPersonnelStatus(DepartmentId, currentStatus);

                    if (status != null)
                    {
                        person.Status      = status.ButtonText;
                        person.StatusColor = status.ButtonClassToColor();
                    }
                }
                else
                {
                    person.Status      = "Standing By";
                    person.StatusColor = "#000";
                }

                person.Eta = "N/A";

                if (currentStatus != null)
                {
                    if (personnelStatusSortOrder != null && personnelStatusSortOrder.Any())
                    {
                        var statusSorting = personnelStatusSortOrder.FirstOrDefault(x => x.StatusId == currentStatus.ActionTypeId);
                        if (statusSorting != null)
                        {
                            person.Weight = statusSorting.Weight;
                        }
                        else
                        {
                            person.Weight = 9000;
                        }
                    }
                    else
                    {
                        person.Weight = 9000;
                    }
                }
                else
                {
                    person.Weight = 9000;
                }

                result.Add(person);
            }

            switch (personnelSortOrder)
            {
            case PersonnelSortOrders.Default:
                result = result.OrderBy(x => x.Weight).ToList();
                break;

            case PersonnelSortOrders.FirstName:
                result = result.OrderBy(x => x.Weight).ThenBy(x => x.FirstName).ToList();
                break;

            case PersonnelSortOrders.LastName:
                result = result.OrderBy(x => x.Weight).ThenBy(x => x.LastName).ToList();
                break;

            case PersonnelSortOrders.Group:
                result = result.OrderBy(x => x.Weight).ThenBy(x => x.GroupId).ToList();
                break;

            default:
                result = result.OrderBy(x => x.Weight).ToList();
                break;
            }

            return(Ok(result));
        }
コード例 #35
0
 public UpdateUserHandlerTests()
 {
     userHelper = new UserHelper();
     helper = new DbContextHelper();
 }
コード例 #36
0
        public override void BuildPacket()
        {
            PushIntoStack(ObjectExtend.ToNotNullString(ContextUser.NickName));
            PushIntoStack(sportsName.ToNotNullString());
            PushIntoStack(ContextUser.ObtainNum);
            PushIntoStack(rankID);
            PushIntoStack(victoryNum);
            PushIntoStack(sportsReward == null ? 0 : sportsReward.RewardGoin);
            PushIntoStack(sportsReward == null ? 0 : sportsReward.RewardObtian);
            PushIntoStack(receiveDate);
            PushIntoStack(sportNum);
            PushIntoStack(codeTime);
            PushIntoStack(_userRankArray.Count);
            var userGeneralCacheSet = new PersonalCacheStruct <UserGeneral>();

            foreach (UserRank user in _userRankArray)
            {
                DataStruct dsItem = new DataStruct();
                dsItem.PushIntoStack(user.UserID.ToNotNullString());
                dsItem.PushIntoStack(user.NickName.ToNotNullString());
                dsItem.PushIntoStack(user.HeadID.ToNotNullString());
                dsItem.PushIntoStack(user.RankId);
                dsItem.PushIntoStack(user.UserLv);

                var embattleList = EmbattleHelper.CurrEmbattle(user.UserID, true);
                dsItem.PushIntoStack(embattleList.Count);
                foreach (var item in embattleList)
                {
                    var        userGenearl = userGeneralCacheSet.FindKey(item.UserID, item.GeneralID);
                    DataStruct dsItem1     = new DataStruct();
                    dsItem1.PushIntoStack(item.GeneralID);
                    dsItem1.PushIntoStack(userGenearl == null ? string.Empty : userGenearl.GeneralName.ToNotNullString());
                    dsItem1.PushIntoStack(userGenearl == null ? string.Empty : userGenearl.HeadID.ToNotNullString());
                    dsItem1.PushIntoStack(userGenearl == null ? 0 : userGenearl.GeneralQuality.ToInt());
                    dsItem1.PushIntoStack(userGenearl == null ? 0 : userGenearl.GeneralLv.ToInt());
                    dsItem.PushIntoStack(dsItem1);
                }

                SportsRewardInfo sportsInfo = new ShareCacheStruct <SportsRewardInfo>().FindKey(user.RankId);
                var embatList = EmbattleHelper.CurrEmbattle(user.UserID, false);
                dsItem.PushIntoStack(embatList.Count);
                dsItem.PushIntoStack(embattleList.Count);
                dsItem.PushIntoStack(sportsInfo == null ? 0 : sportsInfo.RewardObtian);
                PushIntoStack(dsItem);
            }

            int index = 0;

            PushIntoStack(_userCombatArray.Count);
            foreach (var usercombat in _userCombatArray)
            {
                short  iswin      = usercombat.IsWin ? (short)1 : (short)2;
                string userName   = string.Empty;
                string toUserName = string.Empty;
                if (usercombat.IsSelf)
                {
                    userName   = LanguageManager.GetLang().St5101_JingJiChangMingCheng;
                    toUserName = usercombat.ToUserName;
                }
                else
                {
                    userName   = usercombat.ToUserName;
                    toUserName = LanguageManager.GetLang().St5101_JingJiChangMingCheng;
                }
                DataStruct dsItem = new DataStruct();
                dsItem.PushIntoStack(MathUtils.ToNotNullString(usercombat.CombatDate.ToString("t")));
                dsItem.PushIntoStack(userName.ToNotNullString());
                dsItem.PushIntoStack(toUserName.ToNotNullString());
                dsItem.PushIntoStack(iswin);
                dsItem.PushIntoStack(usercombat.RankStatus.ToInt());
                dsItem.PushIntoStack(usercombat.TopID);
                dsItem.PushIntoStack(index.ToNotNullString());
                PushIntoStack(dsItem);

                index++;
            }


            string spoName = string.Empty;

            PushIntoStack(userRankArray.Count);
            foreach (UserRank rank in userRankArray)
            {
                spoName = UserHelper.SportTitleName(rank.ObtainNum);
                DataStruct dsItem = new DataStruct();
                dsItem.PushIntoStack(rank.RankId);
                dsItem.PushIntoStack(rank.UserID.ToNotNullString());
                dsItem.PushIntoStack(rank.NickName.ToNotNullString());
                dsItem.PushIntoStack(rank.UserLv);
                dsItem.PushIntoStack(rank.TotalCombatNum > 0 ? rank.TotalCombatNum : UserHelper.GetTotalCombatNum(rank.UserID));
                dsItem.PushIntoStack(spoName);
                dsItem.PushIntoStack(rank.VictoryNum);

                var embattleList = EmbattleHelper.CurrEmbattle(rank.UserID, true);
                dsItem.PushIntoStack(embattleList.Count);
                foreach (var item in embattleList)
                {
                    var        userGenearl = userGeneralCacheSet.FindKey(item.UserID, item.GeneralID);
                    DataStruct dsItem1     = new DataStruct();
                    dsItem1.PushIntoStack(item.GeneralID);
                    dsItem1.PushIntoStack(userGenearl == null ? string.Empty : userGenearl.GeneralName.ToNotNullString());
                    dsItem1.PushIntoStack(userGenearl == null ? string.Empty : userGenearl.HeadID.ToNotNullString());
                    dsItem1.PushIntoStack(userGenearl == null ? 0 : userGenearl.GeneralQuality.ToInt());
                    dsItem1.PushIntoStack(userGenearl == null ? 0 : userGenearl.GeneralLv.ToInt());
                    dsItem.PushIntoStack(dsItem1);
                }

                SportsRewardInfo sportsInfo = new ShareCacheStruct <SportsRewardInfo>().FindKey(rank.RankId);
                var embatList = EmbattleHelper.CurrEmbattle(rank.UserID, false);
                dsItem.PushIntoStack(embatList.Count);
                dsItem.PushIntoStack(embattleList.Count);
                dsItem.PushIntoStack(sportsInfo == null ? 0 : sportsInfo.RewardObtian);
                PushIntoStack(dsItem);
            }

            PushIntoStack(sportsIntegral);
        }
コード例 #37
0
ファイル: Task3Library.cs プロジェクト: AlexanderChechet/ADAM
        public void EditUserValue(string newValue, string username)
        {
            var setting = new TextSetting(app);

            var userHelper = new UserHelper(app);
            var userId = userHelper.GetId(new SearchExpression(username));
            if (userId.HasValue)
            {
                setting.LoadUserValue("AlexanderChechetSetting", userId.Value);
                setting.Value = newValue;
                setting.Save();
            }
        }
コード例 #38
0
 public bool Get(string userName)
 {
     return(UserHelper.RetrieveUserByUserName(userName) == null && !UserHelper.RetrieveNewUsers().Any(u => u.UserName == userName));
 }
コード例 #39
0
        public DispatchDetailsDispatchInfo GetDispatchDetails(int dispatchId)
        {
            if (UserHelper.IsAuthorize(new List <int> {
                (int)UserType.SuperAdmin, (int)UserType.Admin, (int)UserType.Client
            }))
            {
                DispatchDetailsDispatchInfo result = new DispatchDetailsDispatchInfo();
                List <DispatchOrderList>    listOfDispatchOrders = new List <DispatchOrderList>();

                CarrierDispatch  carrier     = new CarrierDispatch();
                ReceiverDispatch receiver    = new ReceiverDispatch();
                CMRDispatch      cmrToResult = new CMRDispatch();

                try
                {
                    Dispatch dispatchFromDB = _context.Dispatches.FirstOrDefault(d => d.Id == dispatchId && d.Deleted_At == null);
                    if (dispatchFromDB != null)
                    {
                        List <int> listOfDeliveryIdsForDispatch = _dispatchManager.GetListOfDeliveriesIdsForDispatch(dispatchFromDB);
                        foreach (var deliveryId in listOfDeliveryIdsForDispatch)
                        {
                            DispatchOrderList dispatchOrderList = new DispatchOrderList();
                            Delivery          delivery          = _context.Deliveries.FirstOrDefault(d => d.Id == deliveryId && d.Deleted_At == null);
                            //if (delivery != null)
                            //{
                            Order order = _context.Orders.FirstOrDefault(o => o.Id == delivery.Order_Id && o.Deleted_At == null);
                            //}

                            Dispatch dispatch = _context.Dispatches.FirstOrDefault(d => d.Id == dispatchId && d.Deleted_At == null);
                            if (dispatch.CMR_Id != null)
                            {
                                int            cmrId       = Convert.ToInt32(dispatch.CMR_Id);
                                CMR_Dispatches cmrDispatch = _context.CMR_Dispatches.FirstOrDefault(c => c.Id == cmrId && c.Deleted_At == null);
                                cmrToResult.Commodity_Type      = cmrDispatch.Commodity_Type;
                                cmrToResult.Destination         = cmrDispatch.Destination;
                                cmrToResult.Sender_Address      = cmrDispatch.Sender_Address;
                                cmrToResult.Sender_Email        = cmrDispatch.Sender_Email;
                                cmrToResult.Sender_Name         = cmrDispatch.Sender_Name;
                                cmrToResult.Sender_PrefixVat_Id = cmrDispatch.Sender_PrefixVat_Id;
                                cmrToResult.Sender_VAT_Id       = cmrDispatch.Sender_VAT_Id;
                            }

                            List <DispatchPositionsDispatchInfo> listOfDispatchPositions = new List <DispatchPositionsDispatchInfo>();

                            List <Orders_Positions> listOfOrdersPositions = _context.Orders_Positions.Where(o => o.Order_id == order.Id && o.Deleted_At == null).ToList();
                            foreach (var orderPosition in listOfOrdersPositions)
                            {
                                List <Dispatches_Positions> dispatchPositionsFromDB = _context.Dispatches_Positions.Where(d => d.Dispatch_Id == dispatchId && d.Order_Position_Id == orderPosition.Id && d.Deleted_At == null).ToList();
                                foreach (var dispatchPositionFromDB in dispatchPositionsFromDB)
                                {
                                    DispatchPositionsDispatchInfo dispatchPosition = new DispatchPositionsDispatchInfo();
                                    dispatchPosition.Id           = (int)dispatchPositionFromDB.Order_Position_Id;
                                    dispatchPosition.Amount       = dispatchPositionFromDB.Amount;
                                    dispatchPosition.Weight_Gross = dispatchPositionFromDB.Weight_Gross;
                                    dispatchPosition.Name         = _context.Orders_Positions.FirstOrDefault(o => o.Id == dispatchPositionFromDB.Order_Position_Id && o.Deleted_At == null).Name;
                                    listOfDispatchPositions.Add(dispatchPosition);
                                }
                            }
                            dispatchOrderList.Delivery_Id             = delivery.Id;
                            dispatchOrderList.Delivery_Number         = delivery.Delivery_Number;
                            dispatchOrderList.Order_Number            = order.Order_Number;
                            dispatchOrderList.ContainerId             = order.Container_Id;
                            dispatchOrderList.ListOfDispatchPositions = listOfDispatchPositions;
                            listOfDispatchOrders.Add(dispatchOrderList);
                        }

                        carrier.Carrier_Address        = dispatchFromDB.Carrier_Address;
                        carrier.Carrier_Email          = dispatchFromDB.Carrier_Email;
                        carrier.Carrier_PrefixVat_Id   = dispatchFromDB.Carrier_PrefixVat_Id;
                        carrier.Carrier_VAT_Id         = dispatchFromDB.Carrier_VAT_Id;
                        carrier.Carrier_Name           = dispatchFromDB.Carrier_Name;
                        carrier.Carrier_PhoneNumber    = dispatchFromDB.Carrier_PhoneNumber;
                        receiver.Receiver_Address      = dispatchFromDB.Receiver_Address;
                        receiver.Receiver_Email        = dispatchFromDB.Receiver_Email;
                        receiver.Receiver_Name         = dispatchFromDB.Receiver_Name;
                        receiver.Receiver_PrefixVat_Id = dispatchFromDB.Receiver_PrefixVat_Id;
                        receiver.Receiver_VAT_Id       = dispatchFromDB.Receiver_VAT_Id;
                        receiver.Receiver_PhoneNumber  = dispatchFromDB.Receiver_PhoneNumber;
                        result.Dispatch_Number         = dispatchFromDB.Dispatch_Number;
                        result.Carrier = carrier;
                        result.Id      = dispatchFromDB.Id;
                        result.ListOfDispatchOrders = listOfDispatchOrders;
                        result.Receiver             = receiver;
                        result.isCMR         = dispatchFromDB.If_CMR;
                        result.CmrDispatch   = cmrToResult;
                        result.Duty_Doc_Id   = dispatchFromDB.Duty_Doc_Id;
                        result.Car_Id        = dispatchFromDB.Car_Id;
                        result.Creation_Date = dispatchFromDB.Creation_Date == null ? string.Empty : dispatchFromDB.Creation_Date.Value.ToString("dd-MM-yyyy");
                    }
                    return(result);
                }
                catch (Exception ex)
                {
                    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message));
                }
            }
            else
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User don't have acces to this method"));
            }
        }
コード例 #40
0
        protected override void ChangeRankNo(UserRank item)
        {
            var basis = UserHelper.FindUserBasis(item.UserID);

            basis.ComboRankID = item.RankId;
        }
コード例 #41
0
        public override bool TakeAction()
        {
            UserStatus status = ContextUser.UserStatus;

            if (status == UserStatus.FengJin)
            {
                return(false);
            }
            UserGeneral        general = UserGeneral.GetMainGeneral(ContextUser.UserID);
            Ranking <UserRank> ranking = RankingFactory.Get <UserRank>(CombatRanking.RankingKey);
            UserRank           rankInfo;

            if (ranking.TryGetRankNo(m => m.UserID == ContextUser.UserID, out rankID))
            {
                rankInfo = ranking.Find(s => s.UserID == ContextUser.UserID);
                //ContextUser.RankID = rankID;
            }
            else
            {
                rankInfo = new UserRank()
                {
                    UserID         = ContextUser.UserID,
                    HeadID         = general.HeadID,
                    GameCoin       = ContextUser.GameCoin,
                    NickName       = ContextUser.NickName,
                    ObtainNum      = ContextUser.ObtainNum,
                    UserLv         = ContextUser.UserLv,
                    RankId         = int.MaxValue,
                    RankDate       = DateTime.Now,
                    SportsIntegral = 0
                };
                ranking.TryAppend(rankInfo);
            }

            sportsName = UserHelper.SportTitleName(ContextUser.ObtainNum);

            sportNum       = GetChallGeNum(ContextUser.UserID);
            sportsIntegral = ContextUser.SportsIntegral.ToInt();
            sportsReward   = new ShareCacheStruct <SportsRewardInfo>().FindKey(rankInfo.RankId);
            receiveDate    = (int)(RankingHelper.GetNextReceiveDate() - DateTime.Now).TotalSeconds;

            CombatRanking combatrank = (CombatRanking)ranking;

            _userRankArray = combatrank.GetRanking(ContextUser);
            _userRankArray.Add(rankInfo);
            _userRankArray.QuickSort((x, y) =>
            {
                if (x == null && y == null)
                {
                    return(0);
                }
                if (x != null && y == null)
                {
                    return(1);
                }
                if (x == null)
                {
                    return(-1);
                }
                return(x.RankId.CompareTo(y.RankId));
            });

            _userCombatArray = ContextUser.GetSportsCombat();
            _userCombatArray.QuickSort((x, y) =>
            {
                if (x == null && y == null)
                {
                    return(0);
                }
                if (x != null && y == null)
                {
                    return(1);
                }
                if (x == null)
                {
                    return(-1);
                }
                return(y.CombatDate.CompareTo(x.CombatDate));
            });

            if (rankInfo != null && rankID > 0)
            {
                victoryNum = rankInfo.VictoryNum;
            }

            //NoviceHelper.SportVictoryNum(ContextUser, 2001, victoryNum); //竞技场奖励
            if (victoryNum >= 7)
            {
                ActivitiesAward.HolidayFestival(ContextUser.UserID);
            }
            rankID = ContextUser.RankID;



            int count     = 10;
            int pagecount = 0;

            userRankArray = ranking.GetRange(1, count, out pagecount);
            return(true);
        }
コード例 #42
0
 public void StartApplicationWithConsoleInput()
 {
     UserHelper userHelper = new UserHelper();
     ThreadStarter threadStarter = new ThreadStarter();
     threadStarter.ProccessThreadPoolMethod(userHelper.GetThreadCount(), userHelper.GetArrayOfThreadIncrement());
 }