Beispiel #1
0
        public AdvancedResult <string> Register(string account, string pwd)
        {
            AdvancedResult <string> result = new AdvancedResult <string>();

            try
            {
                AdvancedResult <bool> dr = CheckAccout(account);
                if (dr.Data)
                {
                    result.Error = AppError.ERROR_PERSON_FOUND;
                    return(result);
                }

                AdUser user = new AdUser();
                user.UserAccount = account;
                user.Pwd         = pwd;
                int i = UserAccessor.Instance.Insert(user);

                if (i > 0)
                {
                    result.Error = AppError.ERROR_SUCCESS;
                    result.Data  = SecurityHelper.GetToken(i.ToString());
                }
            }
            catch (Exception e)
            {
                result.Error     = AppError.ERROR_FAILED;
                result.ExMessage = e.ToString();
            }
            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public AdvancedResult <AdUser> GetUserInfo(string token)
        {
            AdvancedResult <AdUser> result = new AdvancedResult <AdUser>();

            try
            {
                if (!CacheManagerFactory.GetMemoryManager().Contains(token))
                {
                    result.Error = AppError.ERROR_PERSON_NOT_LOGIN;
                }
                else
                {
                    int userid = Convert.ToInt32(CacheManagerFactory.GetMemoryManager().Get(token));
                    if (userid > 0)
                    {
                        AdUser user = UserAccessor.Instance.Get(userid, string.Empty, string.Empty, StateType.Ignore);
                        result.Error = AppError.ERROR_SUCCESS;
                        result.Data  = user;
                    }
                    else
                    {
                        result.Error = AppError.ERROR_FAILED;
                    }
                }
            }
            catch (Exception e)
            {
                result.Error     = AppError.ERROR_FAILED;
                result.ExMessage = e.ToString();
            }
            return(result);
        }
Beispiel #3
0
        /// <summary>
        /// 修改指定的数据
        /// <param name="e">修改后的数据实体对象</param>
        /// <para>数据对应的主键必须在实例中设置</para>
        /// </summary>
        public void Update(AdUser e)
        {
            MySqlConnection oc = ConnectManager.Create();
            MySqlCommand    _cmdUpdateAdUser = cmdUpdateAdUser.Clone() as MySqlCommand;

            _cmdUpdateAdUser.Connection = oc;

            try
            {
                if (oc.State == ConnectionState.Closed)
                {
                    oc.Open();
                }

                _cmdUpdateAdUser.Parameters["@AdUserId"].Value     = e.AdUserId;
                _cmdUpdateAdUser.Parameters["@UserAccount"].Value  = e.UserAccount;
                _cmdUpdateAdUser.Parameters["@Pwd"].Value          = e.Pwd;
                _cmdUpdateAdUser.Parameters["@BabyBirthday"].Value = e.BabyBirthday;
                _cmdUpdateAdUser.Parameters["@Sex"].Value          = e.Sex;
                _cmdUpdateAdUser.Parameters["@Qq"].Value           = e.Qq;
                _cmdUpdateAdUser.Parameters["@Mobile"].Value       = e.Mobile;
                _cmdUpdateAdUser.Parameters["@State"].Value        = e.State;

                _cmdUpdateAdUser.ExecuteNonQuery();
            }
            finally
            {
                oc.Close();
                oc.Dispose();
                oc = null;
                _cmdUpdateAdUser.Dispose();
                _cmdUpdateAdUser = null;
                GC.Collect();
            }
        }
Beispiel #4
0
        public RespResult UpdateBabyAge(int bbage, string token)
        {
            RespResult result = new RespResult();

            try
            {
                if (!CacheManagerFactory.GetMemoryManager().Contains(token))
                {
                    result.Error = AppError.ERROR_PERSON_NOT_LOGIN;
                }
                else
                {
                    int userid = Convert.ToInt32(CacheManagerFactory.GetMemoryManager().Get(token));
                    if (userid > 0)
                    {
                        AdUser user = UserAccessor.Instance.Get(userid, string.Empty, string.Empty, StateType.Ignore);
                        user.BabyBirthday = DateTime.Now.AddYears(0 - bbage);
                        UserAccessor.Instance.Update(user);
                        result.Error = AppError.ERROR_SUCCESS;
                    }
                    else
                    {
                        result.Error = AppError.ERROR_FAILED;
                    }
                }
            }
            catch (Exception e)
            {
                result.Error     = AppError.ERROR_FAILED;
                result.ExMessage = e.ToString();
            }
            return(result);
        }
Beispiel #5
0
        public override async void Execute(TelegramBotClient botClient, System.Object message)
        {
            CallbackQuery _message = message as CallbackQuery;
            DataBase      db       = Singleton.GetInstance().Context;
            await Task.Run(() => DeleteMessage(botClient, _message));

            try
            {
                if (IsBan.Ban(botClient, message))
                {
                    User user = db.GetUser(_message.From.Id);
                    if (IsNullDataBase.IsNull(botClient, _message, user))
                    {
                        return;
                    }
                    AdUser adUser = db.GetAdUser(user.ID);
                    adUser.EditingPostTemplateId = -1;
                    db.Save();
                    InlineKeyboardMarkup answer = InlineButton.GetAdvertising(user);
                    await botClient.EditMessageTextAsync(_message.From.Id, _message.Message.MessageId,
                                                         "📞Ваша реклама📞", Telegram.Bot.Types.Enums.ParseMode.Html,
                                                         replyMarkup : answer);
                }
            }
            catch (System.Exception ex)
            {
                Log.Logging(ex);
            }
        }
Beispiel #6
0
        public List <AdUser> GetDomainUsers()
        {
            List <AdUser> users = new List <AdUser>();

            using (var context = new PrincipalContext(ContextType.Domain, "yimihaodi.net", "CN=Users,DC=yimihaodi,DC=net"))
            {
                using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
                {
                    var list = searcher.FindAll();

                    foreach (var result in list)
                    {
                        DirectoryEntry de     = result.GetUnderlyingObject() as DirectoryEntry;
                        AdUser         adUser = new AdUser {
                            Username = result.SamAccountName, IsEnabled = true
                        };
                        UserPrincipal userPrincipal = result as UserPrincipal;
                        if (userPrincipal != null)
                        {
                            adUser.IsEnabled = userPrincipal.Enabled.HasValue ? userPrincipal.Enabled.Value : true;
                        }
                        users.Add(adUser);
                    }

                    //Console.WriteLine($"count: {count}");
                }
            }

            return(users);
        }
Beispiel #7
0
        /// <summary>
        ///     RenderTable displays the list of users registered on the Application
        /// </summary>
        ///
        private void RenderTable()
        {
            // CRITICAL : Change this connection string to the one where users are actually stored (Needs to be changed : Source)
            string connectionStringPatrimoine = ConfigurationManager.ConnectionStrings["Patrimoine"].ConnectionString;

            // Connect to the Database.
            using (SqlConnection sqlConn = new SqlConnection(connectionStringPatrimoine))
            {
                string cmdString = "SELECT DISTINCT id, AdresseMail, telephone, NomAffiche FROM [dbo].[AD_CCIT] WHERE CompanyID = @val1";
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection  = sqlConn;
                    cmd.CommandText = cmdString;
                    cmd.Parameters.AddWithValue("@val1", "CCINCA");

                    sqlConn.Open();

                    var           dr    = cmd.ExecuteReader();
                    List <AdUser> datas = new List <AdUser>();

                    while (dr.Read())
                    {
                        AdUser adUser = new AdUser
                        {
                            Id          = dr["id"].ToString(),
                            AdresseMail = dr["AdresseMail"].ToString(),
                            Telephone   = dr["telephone"].ToString(),
                            NomAffiche  = dr["NomAffiche"].ToString()
                        };
                        datas.Add(adUser);
                    }
                    JsonData = JsonConvert.SerializeObject(datas);
                }
            }
        }
Beispiel #8
0
        internal async void SendMessage(TelegramBotClient botClient, Message _message)
        {
            DataBase db   = Singleton.GetInstance().Context;
            User     user = db.GetUser(_message.From.Id); if (IsNullDataBase.IsNull(botClient, _message, user))
            {
                return;                                                                                                         // - заменить на другую таблицу
            }
            AdUser       adUser       = db.GetAdUser(user.ID);
            PostTemplate postTemplate = db.GetTempalte(adUser.User.ID, adUser.EditingPostTemplateId);

            try
            {
                AdController.SetContent(botClient, postTemplate, _message, adUser.Order);
                botClient.DeleteMessage(_message.From.Id, _message.MessageId, "78 - AddPhoto ChainAnaliz");
                botClient.DeleteMessage(_message.From.Id, _message.MessageId - 1, "79 - AddPhoto ChainAnaliz");
                botClient.SendText(_message.From.Id, "Управление шаблоном\n1. Заполните контент\n2. Введите время постинга.\n3. Выберете чат(ы)\n4. Отправьте на проверку администрации.", user, replyMarkup: InlineButton.ContentKeyboard(postTemplate, true));
                user.Chain = (System.Int32)SetChain.MessageUserInBot;
                db.Save();
            }
            catch (System.Exception ex)
            {
                Log.Logging(ex);
            }
            db.Save();
        }
    public ActiveDirectoryHandlerResults ModifyUser(string identity, AdUser user)
    {
        string            planName = config.Plans.User.Modify;
        StartPlanEnvelope pe       = GetPlanEnvelope(identity, user);

        return(CallPlan(planName, pe));
    }
        public static async Task <User> AddUser(this AppDbContext db, AdUser adUser)
        {
            User user = null;

            if (await adUser.Validate(db))
            {
                user = new User
                {
                    Email      = adUser.UserPrincipalName,
                    FirstName  = adUser.GivenName,
                    Guid       = adUser.Guid.Value,
                    IsDeleted  = false,
                    IsAdmin    = false,
                    LastName   = adUser.Surname,
                    Sidepanel  = "thin",
                    SocketName = $@"{adUser.GetDomainPrefix()}\{adUser.SamAccountName}",
                    Theme      = "light-blue",
                    UserName   = adUser.SamAccountName.UrlEncode()
                };

                await user.GenerateUniqueUsername(db);

                await db.Users.AddAsync(user);

                await db.SaveChangesAsync();
            }

            return(user);
        }
    public ActiveDirectoryHandlerResults ModifyUser(string identity, AdUser user, string domain = null)
    {
        string            planName = config.Plans.User.Modify;
        StartPlanEnvelope pe       = GetPlanEnvelope(BuildIdentity(domain, identity), user);

        return(CallPlan(planName, pe));
    }
Beispiel #12
0
        public JsonResult AjaxLogin()
        {
            string username    = Request["username"];
            string password    = Request["password"];
            string getUserInfo = Request["userinfo"];
            AdUser user        = null;
            AdvancedResult <string> response = Login(username, password, ref user);

            if (string.IsNullOrEmpty(getUserInfo))
            {
                return(this.Json(response));
            }
            else
            {
                AdvancedResult <UserModel> userResponse = new AdvancedResult <UserModel>();
                if (response.Error != AppError.ERROR_SUCCESS)
                {
                    return(this.Json(response));
                }
                else
                {
                    userResponse.Error        = response.Error;
                    userResponse.ErrorMessage = response.ErrorMessage;
                    userResponse.ExMessage    = response.ExMessage;
                    ViewModelBindOption bindoption = new ViewModelBindOption();
                    userResponse.Data = new UserModel().Bind(user, bindoption);
                }
                return(this.Json(userResponse));
            }
        }
Beispiel #13
0
        public AdvancedResult <string> Login(string account, string pwd)
        {
            AdvancedResult <string> result = new AdvancedResult <string>();

            try
            {
                AdUser user = null;
                user = UserAccessor.Instance.Get(0, account.Trim(), pwd.Trim(), StateType.Active);
                if (user != null)
                {
                    result.Error = AppError.ERROR_SUCCESS;
                    result.Data  = SecurityHelper.GetToken(user.AdUserId.ToString());
                }
                else
                {
                    result.Error = AppError.ERROR_LOGIN_FAILED;
                }
            }
            catch (Exception e)
            {
                result.Error     = AppError.ERROR_FAILED;
                result.ExMessage = e.ToString();
            }
            return(result);
        }
Beispiel #14
0
        /// <summary>
        /// 添加数据
        /// <param name="es">数据实体对象数组</param>
        /// <returns></returns>
        /// </summary>
        public int Insert(AdUser e)
        {
            MySqlConnection oc = ConnectManager.Create();
            MySqlCommand    _cmdInsertAdUser = cmdInsertAdUser.Clone() as MySqlCommand;
            int             returnValue      = 0;

            _cmdInsertAdUser.Connection = oc;
            try
            {
                if (oc.State == ConnectionState.Closed)
                {
                    oc.Open();
                }
                _cmdInsertAdUser.Parameters["@UserAccount"].Value  = e.UserAccount;
                _cmdInsertAdUser.Parameters["@Pwd"].Value          = e.Pwd;
                _cmdInsertAdUser.Parameters["@BabyBirthday"].Value = e.BabyBirthday;

                _cmdInsertAdUser.Parameters["@Sex"].Value    = e.Sex;
                _cmdInsertAdUser.Parameters["@Qq"].Value     = e.Qq;
                _cmdInsertAdUser.Parameters["@Mobile"].Value = e.Mobile;

                _cmdInsertAdUser.ExecuteNonQuery();
                returnValue = Convert.ToInt32(_cmdInsertAdUser.LastInsertedId);
                return(returnValue);
            }
            finally
            {
                oc.Close();
                oc.Dispose();
                oc = null;
                _cmdInsertAdUser.Dispose();
                _cmdInsertAdUser = null;
            }
        }
    public override object GetParametersInstance()
    {
        ActiveDirectoryHandlerParameters parms = new ActiveDirectoryHandlerParameters();

        parms.Users = new List <AdUser>();
        AdUser user = new AdUser();

        user.Identity = "cn=mfox,ou=FamousActors,dc=sandbox,dc=local";
        parms.Users.Add(user);

        parms.Groups = new List <AdGroup>();
        AdGroup group = new AdGroup();

        group.Identity = "cn=BackToTheFuture,ou=Movies,dc=sandbox,dc=local";
        parms.Groups.Add(group);

        parms.OrganizationalUnits = new List <AdOrganizationalUnit>();
        AdOrganizationalUnit ou = new AdOrganizationalUnit();

        ou.Identity = "ou=Movies,dc=sandbox,dc=local";
        parms.OrganizationalUnits.Add(ou);

        parms.SearchRequests = new List <AdSearchRequest>();
        AdSearchRequest search = new AdSearchRequest();

        search.SearchBase       = "ou=Synapse,dc=sandbox,dc=local";
        search.Filter           = "(objectClass=User)";
        search.ReturnAttributes = new List <string>();
        search.ReturnAttributes.Add("Name");
        search.ReturnAttributes.Add("objectGUID");
        parms.SearchRequests.Add(search);


        return(parms);
    }
    private void ProcessDelete(AdObject obj, bool returnObject = false)
    {
        ActiveDirectoryObjectResult result = new ActiveDirectoryObjectResult()
        {
            Type     = obj.Type,
            Identity = obj.Identity
        };

        ActiveDirectoryStatus status = new ActiveDirectoryStatus()
        {
            Action  = config.Action,
            Status  = AdStatusType.Success,
            Message = "Success",
        };

        try
        {
            roleManager.CanPerformActionOrException(requestUser, ActionType.Delete, obj.Identity);
            switch (obj.Type)
            {
            case AdObjectType.User:
                AdUser user = (AdUser)obj;
                DirectoryServices.DeleteUser(user.Identity);
                result.Statuses.Add(status);
                break;

            case AdObjectType.Group:
                AdGroup group = (AdGroup)obj;
                DirectoryServices.DeleteGroup(group.Identity, isDryRun);
                result.Statuses.Add(status);
                break;

            case AdObjectType.OrganizationalUnit:
                AdOrganizationalUnit ou = (AdOrganizationalUnit)obj;
                DirectoryServices.DeleteOrganizationUnit(ou.Identity);
                result.Statuses.Add(status);
                break;

            default:
                throw new AdException("Action [" + config.Action + "] Not Implemented For Type [" + obj.Type + "]", AdStatusType.NotSupported);
            }

            String message = $"{obj.Type} [{obj.Identity}] Deleted.";
            OnLogMessage("ProcessDelete", message);
        }
        catch (AdException ex)
        {
            ProcessActiveDirectoryException(result, ex, status.Action);
        }
        catch (Exception e)
        {
            OnLogMessage("ProcessDelete", e.Message);
            OnLogMessage("ProcessDelete", e.StackTrace);
            AdException le = new AdException(e);
            ProcessActiveDirectoryException(result, le, status.Action);
        }

        results.Add(result);
    }
        public void AdUserGetAdAccountGroupsTest()
        {
            Console.WriteLine("Initializing [FacebookAds.Object.AdUser]");
            AdUser user = new AdUser(id);

            Console.WriteLine("Calling [FacebookAds.Object.AdUser].GetAdAccountGroups()");
            Console.WriteLine("Result: {0}", user.GetAdAccountGroups());
        }
Beispiel #18
0
        public static async Task <IEnumerable <int> > GetListIdsAsync(AdUser curUser, DateTime planDate)
        {
            TaskTrackerContext db = new TaskTrackerContext();

            var list = await db.TaskPlans.Where(x => x.Enabled && DbFunctions.TruncateTime(x.PlanDate) == DbFunctions.TruncateTime(planDate)).Select(x => x.TaskPlanId).ToListAsync();

            return(list);
        }
        private async void BotClient_OnUpdate(System.Object sender, Telegram.Bot.Args.UpdateEventArgs e)
        {
            DataBase db = Singleton.GetInstance().Context;

            if (e.Update.PreCheckoutQuery != null)
            {
                await BotClient.AnswerPreCheckoutQueryAsync(e.Update.PreCheckoutQuery.Id);

                if (e.Update.PreCheckoutQuery.InvoicePayload == "Pay is correct")
                {
                    User user = db.GetUser(e.Update.PreCheckoutQuery.From.Id);
                    user.BanDate = System.DateTime.Now;
                    db.Save();
                    IsUnBan.ThisUnBan(BotClient, user);
                    await Task.Run(() => SetIncomeChannel(e.Update.PreCheckoutQuery.From.Id, e.Update.PreCheckoutQuery.TotalAmount / 100));
                }
                else if (e.Update.PreCheckoutQuery.InvoicePayload == "Balance is correct")
                {
                    AdUser adUser = db.GetAdUser(e.Update.PreCheckoutQuery.From.Id);
                    adUser.Balance += e.Update.PreCheckoutQuery.TotalAmount / 100;
                    db.Save();
                    await Task.Run(() => SetIncomeChannel(e.Update.PreCheckoutQuery.From.Id, e.Update.PreCheckoutQuery.TotalAmount / 100));
                }
                else if (e.Update.PreCheckoutQuery.InvoicePayload == "PostTemplate is correct")
                {
                    AdUser       adUser       = db.GetAdUser(e.Update.PreCheckoutQuery.From.Id);
                    PostTemplate postTemplate = db.GetTempalte(adUser.User.ID, adUser.EditingPostTemplateId);
                    postTemplate.IsPaid = true;
                    System.Object ob = await AdController.AssemblyTemplate(BotClient, postTemplate);

                    if (ob is Message)
                    {
                        Message       mes  = (Message)ob;
                        System.String text = mes.Text;
                        await BotClient.SendTextMessageAsync(CommandText.bufferChannelId, text);
                    }
                    else
                    {
                        List <InputMediaBase> inputMedias = (List <InputMediaBase>)ob;

                        await BotClient.SendMediaGroupAsync(CommandText.bufferChannelId, inputMedias);
                    }
                    IsDataTaken.IsCheck(BotClient, e.Update.PreCheckoutQuery.From.Id, postTemplate.PostTime.ToList());
                    db.Save();

                    await Task.Run(() => SetIncomeChannel(e.Update.PreCheckoutQuery.From.Id, e.Update.PreCheckoutQuery.TotalAmount / 100, postTemplate));
                }
                else if (e.Update.PreCheckoutQuery.InvoicePayload == "Pay Confirm User")
                {
                    User user = db.GetUser(e.Update.PreCheckoutQuery.From.Id);
                    user.PayConfirm = true;
                    user.PayDate    = System.DateTime.Today.AddMonths(1);
                    db.Save();

                    await Task.Run(() => SetIncomeChannel(e.Update.PreCheckoutQuery.From.Id, e.Update.PreCheckoutQuery.TotalAmount / 100));
                }
            }
        }
Beispiel #20
0
 /// <summary>
 /// Creates a new Database user from an Active Directory User (basic)
 /// </summary>
 /// <param name="user">Some user Information from Active Directory</param>
 /// <param name="isAdmin">The user is an administrator</param>
 public User(AdUser user, bool isAdmin = false)
 {
     Guid              = user.Guid;
     LastName          = user.LastName;
     WillBeThere       = false;
     FirstName         = user.FirstName;
     DrinkId           = 1;
     CoffeeOptionsJson = "[{\"Key\":\"SoyMilk\",\"Value\":{\"Key\":\"int\",\"Value\":\"0\"}},{\"Key\":\"ExtraShot\",\"Value\":{\"Key\":\"int\",\"Value\":\"0\"}},{\"Key\":\"Sugar\",\"Value\":{\"Key\":\"int\",\"Value\":\"0\"}},{\"Key\":\"Vanilla\",\"Value\":{\"Key\":\"int\",\"Value\":\"0\"}},{\"Key\":\"Hazelnut\",\"Value\":{\"Key\":\"int\",\"Value\":\"0\"}},{\"Key\":\"Caramel\",\"Value\":{\"Key\":\"int\",\"Value\":\"0\"}},{\"Key\":\"No Sugar\",\"Value\":{\"Key\":\"bool\",\"Value\":\"false\"}},{\"Key\":\"Trim\",\"Value\":{\"Key\":\"bool\",\"Value\":\"false\"}},{\"Key\":\"Marshmallows\",\"Value\":{\"Key\":\"bool\",\"Value\":\"false\"}}]";
 }
        public void RiseProductPostedEvent(AdUser user, ProductModel product)
        {
            AsyncCallback ac = new AsyncCallback(ProductPostedCallBack);

            if (OnProductPostedEvent != null)
            {
                OnProductPostedEvent.BeginInvoke(user, product, ac, null);
            }
        }
        public static async Task <User> SyncUser(this AdUser adUser, AppDbContext db)
        {
            var user = await db.Users
                       .FirstOrDefaultAsync(x => x.Guid == adUser.Guid);

            user = user == null ?
                   await db.AddUser(adUser) :
                   await db.UpdateUser(adUser);

            return(user);
        }
Beispiel #23
0
        //发布宝贝帖子
        public AdvancedResult <int> publishBBPost(string title, string qq, string mobile, string bbinfo, bool iswash, double price, int age, ItemType bbType, ItemSort bbSort, SexType sex, string token)
        {
            AdvancedResult <int> result = new AdvancedResult <int>();

            try
            {
                if (!CacheManagerFactory.GetMemoryManager().Contains(token))
                {
                    result.Error = AppError.ERROR_PERSON_NOT_LOGIN;
                }
                else
                {
                    int userid = Convert.ToInt32(CacheManagerFactory.GetMemoryManager().Get(token));

                    if (!string.IsNullOrEmpty(qq) || !string.IsNullOrEmpty(mobile))
                    {
                        AdUser user = UserAccessor.Instance.Get(userid, string.Empty, string.Empty, StateType.Active);
                        if (!string.IsNullOrEmpty(qq))
                        {
                            user.Qq = qq;
                        }
                        if (!string.IsNullOrEmpty(mobile))
                        {
                            user.Mobile = mobile;
                        }
                        UserAccessor.Instance.Update(user);
                    }

                    ProProduct pro = new ProProduct();
                    pro.Title  = title.Trim();
                    pro.BbInfo = bbinfo.Trim();

                    pro.Price      = price;
                    pro.MinAge     = (age - 1) < 0 ? 0 : (age - 1);
                    pro.MaxAge     = age + 1;
                    pro.ItemType   = bbType;
                    pro.Sex        = sex;
                    pro.ItemSort   = bbSort;
                    pro.CreateId   = userid;
                    pro.CreateTime = DateTime.Now;
                    pro.Level      = 1;
                    pro.IsWash     = iswash;

                    result.Data  = ProProductAccessor.Instance.Insert(pro);
                    result.Error = AppError.ERROR_SUCCESS;
                }
            }
            catch (Exception e)
            {
                result.Error     = AppError.ERROR_FAILED;
                result.ExMessage = e.ToString();
            }
            return(result);
        }
        public static async Task <bool> Validate(this AdUser user, AppDbContext db)
        {
            var check = await db.Users
                        .FirstOrDefaultAsync(x => x.Guid == user.Guid.Value);

            if (check != null)
            {
                throw new Exception("The provided user already has an account");
            }

            return(true);
        }
Beispiel #25
0
        public AdUserByEgnViewModel GetUserByEgn(long egn)
        {
            AdUser user = this.Context.AdAccounts.Where(u => u.Egn == egn).FirstOrDefault();

            if (user == null)
            {
                return(null);
            }

            AdUserByEgnViewModel uv = Mapper.Map <AdUser, AdUserByEgnViewModel>(user);

            return(uv);
        }
Beispiel #26
0
 public XMediusUser(AdUser adUser, List <FaxApiGroup> faxUserGroups, List <FaxApiUser> faxUsers, List <FaxApiNumber> faxNumbers, List <string> blackListedFaxNumbers)
 {
     if (adUser == null)
     {
         return;
     }
     AdUser = adUser;
     BlackListedFaxNumbers = blackListedFaxNumbers;
     SetFaxUser(faxUsers);
     SetFaxUserGroup(faxUserGroups);
     SetFaxNumber(faxNumbers);
     AnalyzeUserSyncActions();
 }
Beispiel #27
0
        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="user">修改用户名,性别,密码,地址,qq,手机</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public RespResult EditeUserInfo(AdUser user, string token)
        {
            RespResult result = new RespResult();

            try
            {
                if (!CacheManagerFactory.GetMemoryManager().Contains(token))
                {
                    result.Error = AppError.ERROR_PERSON_NOT_LOGIN;
                }
                else
                {
                    int userid = Convert.ToInt32(CacheManagerFactory.GetMemoryManager().Get(token));
                    if (userid > 0)
                    {
                        AdUser olduser = UserAccessor.Instance.Get(userid, string.Empty, string.Empty, StateType.Ignore);
                        if (olduser.UserAccount != user.UserAccount)
                        {
                            AdvancedResult <bool> dr = CheckAccout(user.UserAccount);
                            if (dr.Data)
                            {
                                result.Error = AppError.ERROR_PERSON_FOUND;
                                return(result);
                            }
                        }
                        olduser.UserAccount = user.UserAccount;
                        olduser.Sex         = user.Sex;
                        olduser.Pwd         = user.Pwd;
                        olduser.Province    = user.Province;
                        olduser.City        = user.City;
                        olduser.County      = user.County;
                        olduser.Street      = user.Street;
                        olduser.Mobile      = user.Mobile;
                        olduser.Qq          = user.Qq;

                        UserAccessor.Instance.Update(olduser);
                        result.Error = AppError.ERROR_SUCCESS;
                    }
                    else
                    {
                        result.Error = AppError.ERROR_FAILED;
                    }
                }
            }
            catch (Exception e)
            {
                result.Error     = AppError.ERROR_FAILED;
                result.ExMessage = e.ToString();
            }
            return(result);
        }
        private static async Task <User> UpdateUser(this AppDbContext db, AdUser adUser)
        {
            var user = await db.Users
                       .FirstOrDefaultAsync(x => x.Guid == adUser.Guid);

            user.Email      = adUser.UserPrincipalName;
            user.FirstName  = adUser.GivenName;
            user.LastName   = adUser.Surname;
            user.SocketName = $@"{adUser.GetDomainPrefix()}\{adUser.SamAccountName}";

            await db.SaveChangesAsync();

            return(user);
        }
Beispiel #29
0
        private static async Task <TokenUser> ValidateFormsUserInAD(string userName, string password)
        {
            ADService adService = new ADService();
            AdUser    formsUser = adService.AuthenticateUser(userName, password);

            if (formsUser == null)
            {
                throw new WebAuthException("Windows user not found in AD.");
            }

            return(new TokenUser {
                UserName = formsUser.Name
            });
        }
        public static PostTemplate CreateTemplate(AdUser user)
        {
            DataBase     db       = Singleton.GetInstance().Context;
            PostTemplate template = new PostTemplate
            {
                AdUser = user,
                Name   = "Шаблон"
            };

            db.AddTemplate(template);
            db.Save();

            return(template);
        }
Beispiel #31
0
        protected AdUser GetCurUser()
        {
            AdUser curUser = new AdUser();
            curUser.User =  base.RequestContext.Principal;

            string sid = null;
            var wi = (WindowsIdentity)RequestContext.Principal.Identity;
            if (wi.User != null)
            {
                var domain = new PrincipalContext(ContextType.Domain);
                curUser.Sid = wi.User.Value;
            }
            return curUser;
        }
Beispiel #32
0
        public void Send(string subject, string message, AdUser from, params AdUser[] to)
        {
            var smtpClient = new SmtpClient(config.SmtpServer);
            var credential = new NetworkCredential(config.UserName, config.Password, config.Domain);

            var msg = new MailMessage
            {
                Subject = subject,
                Body = message,
                From = new MailAddress(from.Email)
            };

            to.ToList().ForEach(x=>msg.To.Add(new MailAddress(x.Email)));

            smtpClient.Host = config.SmtpServer;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = credential;

            smtpClient.Send(msg);
        }
Beispiel #33
0
        private static AdUser MapUserFromAdResult(SearchResult result)
        {
            var user = new AdUser();

            //user.Id = (string)result.Properties["samaccountname"][0];
            user.FullName = string.Format("{0} {1}",
                result.Properties["extensionattribute14"][0],
                result.Properties["extensionattribute13"][0]);
            user.Department = (string)result.Properties["department"][0];

            user.JobPosition = (string)result.Properties["title"][0];

            user.Email = (string)result.Properties["mail"][0];
            user.Login = (string)result.Properties["samaccountname"][0];
            return user;
        }