Exemplo n.º 1
0
        public static void Execute()
        {
            // horrible hack

            Clear clear = new Clear();
            Create create = new Create();
            Delete delete = new Delete();
            Exit exit = new Exit();
            Ping ping = new Ping();
            SList slist = new SList();
            Start start = new Start();
            Help help = new Help();
            Alias alias = new Alias();
            View view = new View();

            // im sorry mom
            HelpDisplay.Add("   " + clear.Name + " - " + clear.Description);
            HelpDisplay.Add("   " + create.Name + " - " + create.Description);
            HelpDisplay.Add("   " + delete.Name + " - " + delete.Description);
            HelpDisplay.Add("   " + exit.Name + " - " + exit.Description);
            HelpDisplay.Add("   " + ping.Name + " - " + ping.Description);
            HelpDisplay.Add("   " + slist.Name + " - " + slist.Description);
            HelpDisplay.Add("   " + start.Name + " - " + start.Description);
            HelpDisplay.Add("   " + alias.Name + " - " + alias.Description);
            HelpDisplay.Add("   " + help.Name + " - " + help.Description);
            HelpDisplay.Add("   " + view.Name + " - " + view.Description);

            foreach (string command in HelpDisplay)
                Console.WriteLine(command);

            HelpDisplay.Clear(); // static list.
        }
Exemplo n.º 2
0
 protected override Expression VisitSelect(SelectExpression select)
 {
     var newAlias = new Alias();
     _map[select.Alias] = newAlias;
     select = (SelectExpression)base.VisitSelect(select);
     return new SelectExpression(newAlias, select.Fields, select.From, select.Where, select.OrderBy, select.GroupBy, select.IsDistinct, select.Skip, select.Take);
 }
        internal ReadOnlyCollection<MixinEntityExpression> GenerateMixins(Alias tableAlias, QueryBinder binder, Expression id)
        {
            if (this.Mixins == null)
                return null;

            return this.Mixins.Values.Select(m => (MixinEntityExpression)m.GetExpression(tableAlias, binder, id)).ToReadOnly();
        }
 public AggregateSubqueryExpression(Alias groupByAlias, Expression aggregateInGroupSelect, ScalarExpression aggregateAsSubquery)
     : base(MongoExpressionType.AggregateSubquery, aggregateAsSubquery.Type)
 {
     GroupByAlias = groupByAlias;
     AggregateInGroupSelect = aggregateInGroupSelect;
     AggregateAsSubquery = aggregateAsSubquery;
 }
Exemplo n.º 5
0
 public FieldExpression(Expression expression, Alias alias, string name)
     : base(MongoExpressionType.Field, expression.Type)
 {
     Alias = alias;
     Expression = expression;
     Name = name;
 }
Exemplo n.º 6
0
 public FieldExpression(Expression expression, Alias alias, string name, BsonMemberMap memberMap)
     : base(MongoExpressionType.Field, expression.Type)
 {
     Alias = alias;
     Expression = expression;
     Name = name;
     MemberMap = memberMap;
 }
Exemplo n.º 7
0
        int _idCounter; //id作成のための順次番号生成カウンタ

        #endregion Fields

        #region Constructors

        public MailSave(MailBox mailBox, Alias alias,MailQueue mailQueue, Logger logger, ReceivedHeader receivedHeader, List<string> domainList)
        {
            _mailBox = mailBox;
            _alias = alias;
            _mailQueue = mailQueue;
            _logger = logger;
            _receivedHeader = receivedHeader;
            _domainList = domainList;
            _localBox = new LocalBox(_logger);
        }
 protected virtual bool CompareAlias(Alias a, Alias b)        
 {
     if (_aliasScope != null)
     {
         Alias mapped;
         if (_aliasScope.TryGetValue(a, out mapped))
             return mapped == b;
     }
     return a == b;
 }
Exemplo n.º 9
0
 public Warn()
 {
     #if JTVBOT
     Privilege = PrivilegeLevel.Voiced;
     #else
     Privilege = PrivilegeLevel.None;
     #endif
     Alias alias = new Alias(this, "+w");
     alias.RequiresPrefix = false;
     alias.ForbidsPrefix = true;
 }
Exemplo n.º 10
0
        internal Expression GetIdExpression(Alias alias)
        {
            var field = Fields.TryGetC(Table.fiId.Name);

            if (field == null)
            {
                field = Fields.Values.FirstOrDefault(f => f .Field is IColumn && ((IColumn)f.Field).PrimaryKey);
                if (field == null)
                    return null;
            }

            return field.Field.GetExpression(alias, null, null);
        }
		public void NoLeadingUnderscores()
		{
			Alias alias = new Alias( "suffix" );
			Dialect.Dialect dialect = new Dialect.MsSql2000Dialect();
			
			Assert.IsFalse( 
				alias.ToAliasString( "__someIdentifier", dialect )
				.StartsWith( "_" ) );

			Assert.IsFalse( 
				alias.ToUnquotedAliasString( "__someIdentifier", dialect )
				.StartsWith( "_" ) );
		}
Exemplo n.º 12
0
    public void Foo(bool b)
    {
      Alias tmp = new Alias();

      tmp.x = -11;

      Alias alias = tmp;

      if(b)
      {
        alias.x = 10;
      }

      Contract.Assert(tmp.x == -11);
    }
Exemplo n.º 13
0
        public void IsUserによる登録ユーザの確認(String user, bool expected)
        {
            //setUp
            var sut = new Alias( _domainList, _mailBox);
            sut.Add("dmy","user1,user2",new Logger());
            sut.Add("user1", "user3,user4", new Logger());

            var rcptList = new List<MailAddress>();
            rcptList.Add(new MailAddress("*****@*****.**"));

            //exercise
            var actual = sut.IsUser(user);
            //verify
            Assert.That(actual, Is.EqualTo(expected));
        }
Exemplo n.º 14
0
        public SelectExpression(Alias alias, IEnumerable<FieldDeclaration> fields, Expression from, Expression where, IEnumerable<OrderExpression> orderBy, Expression groupBy, bool isDistinct, Expression skip, Expression take)
            : base(MongoExpressionType.Select, typeof(void), alias)
        {
            _fields = fields as ReadOnlyCollection<FieldDeclaration> ?? new List<FieldDeclaration>(fields).AsReadOnly();

            _orderBy = orderBy as ReadOnlyCollection<OrderExpression>;
            if (_orderBy == null && orderBy != null)
                _orderBy = new List<OrderExpression>(orderBy).AsReadOnly();

            _isDistinct = isDistinct;
            _from = from;
            _groupBy = groupBy;
            _take = take;
            _where = where;
            _skip = skip;
        }
Exemplo n.º 15
0
        static internal ProjectedColumns ProjectColumns(Expression projector, Alias newAlias, bool isGroupKey = false, bool selectTrivialColumns = false)
        {
            Expression newProj;
            var candidates = DbExpressionNominator.Nominate(projector, out newProj, isGroupKey: isGroupKey);

            ColumnProjector cp = new ColumnProjector
            {
                newAlias = newAlias,
                candidates = candidates,
                projectTrivialColumns = selectTrivialColumns
            };

            Expression e = cp.Visit(newProj);

            return new ProjectedColumns(e, cp.generator.Columns.ToReadOnly());
        }
Exemplo n.º 16
0
        public void Reflectionによる宛先の変換_USER()
        {
            //setUp
            var sut = new Alias(_domainList, _mailBox);
            sut.Add("user1", "$USER,user2", new Logger());

            var rcptList = new List<MailAddress>();
            rcptList.Add(new MailAddress("*****@*****.**"));

            //exercise
            var actual = sut.Reflection(rcptList, new Logger());
            //verify
            Assert.That(actual.Count, Is.EqualTo(2));
            Assert.That(actual[0].ToString(), Is.EqualTo("*****@*****.**"));
            Assert.That(actual[1].ToString(), Is.EqualTo("*****@*****.**"));
        }
        public static void NewMessage(CSSDataContext db, string subject, 
            string message, Alias sender, Login recipient, DateTime sendDate)
        {
            db.PersonalMessages.InsertOnSubmit(new PersonalMessage()
            {
                Subject         = subject,
                Message         = message,
                SenderAliasId   = sender.Id,
                LoginId         = recipient.Id,
                DateCreated     = DateTime.Now,
                DateExpires     = DateTime.Now.AddYears(1), //Leaving at one year until discussion
                DateToSend      = sendDate,
                DateViewed      = null
            });

            db.SubmitChanges();
        }
Exemplo n.º 18
0
        internal ReadOnlyCollection<FieldBinding> GenerateBindings(Alias tableAlias, QueryBinder binder, Expression id)
        {
            List<FieldBinding> result = new List<FieldBinding>();

           result.Add(new FieldBinding(Table.fiId, id));

            foreach (var ef in this.Fields.Values)
            {
                var fi = ef.FieldInfo;

                if (!ReflectionTools.FieldEquals(fi, fiId))
                    result.Add(new FieldBinding(fi, ef.Field.GetExpression(tableAlias, binder, id)));
            }


            return result.ToReadOnly();
        }
Exemplo n.º 19
0
        public EntityExpression(Type type, Expression externalId, Alias tableAlias, IEnumerable<FieldBinding> bindings, IEnumerable<MixinEntityExpression> mixins, bool avoidExpandOnRetrieving)
            : base(DbExpressionType.Entity, type)
        {
            if (type == null) 
                throw new ArgumentNullException("type");

            if (!type.IsIdentifiableEntity())
                throw new ArgumentException("type");
            
            if (externalId == null) 
                throw new ArgumentNullException("externalId");
            
            this.Table = Schema.Current.Table(type);
            this.ExternalId = externalId;

            this.TableAlias = tableAlias;
            this.Bindings = bindings.ToReadOnly();
            this.Mixins = mixins.ToReadOnly();

            this.AvoidExpandOnRetrieving = avoidExpandOnRetrieving;
        }
Exemplo n.º 20
0
 public Hotkeys(MainWindow parentwindow, ProgramSettings settings)
 {
     programSettings = settings;
     parent = parentwindow;
     InitializeComponent();
     rightClickGesture.MouseAction = MouseAction.RightClick;
     MouseBinding rightClickBinding = new MouseBinding();
     RoutedCommand rightClickCmd = new RoutedCommand();
     rightClickBinding.Gesture = rightClickGesture;
     rightClickBinding.Command = rightClickCmd;
     CommandBinding rightClickCmdBinding = new CommandBinding();
     rightClickCmdBinding.Command = rightClickCmd;
     rightClickCmdBinding.Executed += Button_RightClick;
     Uri uri = new Uri("pack://application:,,,/B_32x32.ico", UriKind.RelativeOrAbsolute);
     this.Icon = BitmapFrame.Create(uri);
     for (int i = 0; i < programSettings.NumHotKeys; i++)
     {
         Button btn = new Button();
         btn.Name = "btn" + i.ToString();
         btn.Click += Button_Click;
         btn.Width = 56;
         btn.InputBindings.Add(rightClickBinding);
         btn.CommandBindings.Add(rightClickCmdBinding);
         pnlButtons.Children.Add(btn);
         if (programSettings.HotkeyCommands.Count <= i)
         {
             Alias alias = new Alias();
             alias.Keyword = "(None)";
             btn.Content = "(none)";
             alias.Expansion = String.Empty;
             programSettings.HotkeyCommands.Add(alias);
         }
         else
         {
             btn.Content = programSettings.HotkeyCommands[i].Keyword;
         }
     }
 }
Exemplo n.º 21
0
 public Alias CreateAlias(SecureString secretPhrase, string alias, string uri, string fee, string deadline, ref string err)
 {
     Alias nxtAlias = new Alias();
     var client = new WebClient
     {
         Encoding = Encoding.UTF8
     };
     try
     {
         var rawData = client.DownloadString(_path + "/nxt?requestType=assignAlias&secretPhrase=" +
             HttpUtility.UrlEncode(ConvertToUnsecureString(secretPhrase)) + "&alias=" +
             HttpUtility.UrlEncode(alias) + "&uri=" +
             HttpUtility.UrlEncode(uri) + "&fee=" +
             HttpUtility.UrlEncode(fee) + "&deadline=" +
             HttpUtility.UrlEncode(deadline));
         nxtAlias = JsonConvert.DeserializeObject<Alias>(rawData);
     }
     catch (Exception e)
     {
         err = e.Message;
     }
     return nxtAlias;
 }
Exemplo n.º 22
0
        internal Expression GetProjectorExpression(Alias tableAlias, QueryBinder binder)
        {
            Expression id = GetIdExpression(tableAlias);

            if (IsView)
            {
                var bindings = this.Fields.Values.Select(ef=>new FieldBinding(ef.FieldInfo, ef.Field.GetExpression(tableAlias, binder, id))).ToReadOnly();

                var hasValue = id == null ? Expression.Constant(true): SmartEqualizer.NotEqualNullable(id, Expression.Constant(null, id.Type.Nullify()));

                return new EmbeddedEntityExpression(this.Type, hasValue, bindings, null);
            }
            else
            {
                var bindings = GenerateBindings(tableAlias, binder, id); 
                var mixins = GenerateMixins(tableAlias, binder, id);

                Schema.Current.AssertAllowed(Type, inUserInterface: false);

                var result = new EntityExpression(this.Type, (PrimaryKeyExpression)id, tableAlias, bindings, mixins, avoidExpandOnRetrieving: false);

                return result; 
            }
        }
Exemplo n.º 23
0
 /// <summary>Default constructor with nagivated alias.</summary>
 /// <param name="alias">Nagivated alias.</param>
 internal AliasNavigator(Alias alias)
     : base(alias)
 {
 }
Exemplo n.º 24
0
 public override int GetHashCode() =>
 unchecked (Alias.GetHashCode() *
            ColumnName.GetHashCode() *
            Table.GetHashCode());
Exemplo n.º 25
0
 public async Task <Alias> AddAliasAsync(Alias alias)
 {
     return(await PostJsonAsync <Alias>(Apiurl, alias));
 }
Exemplo n.º 26
0
 public SyncController(ISyncManager syncManager, ITenantManager tenantManager)
 {
     _syncManager = syncManager;
     _alias       = tenantManager.GetAlias();
 }
Exemplo n.º 27
0
        public ServerMailboxData CreateMailbox(string name, string localPart, int domainId, string userId)
        {
            ServerMailboxData mailboxData;

            using (var daoFactory = new DaoFactory())
            {
                var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);

                var serverDomain = serverDomainDao.GetDomain(domainId);

                var isSharedDomain = serverDomain.Tenant == Defines.SHARED_TENANT_ID;

                if (!IsAdmin && !isSharedDomain)
                {
                    throw new SecurityException("Need admin privileges.");
                }

                var tenantQuota = CoreContext.TenantManager.GetTenantQuota(Tenant);

                if (isSharedDomain &&
                    (tenantQuota.Trial ||
                     tenantQuota.Free))
                {
                    throw new SecurityException("Not available in unpaid version");
                }

                if (string.IsNullOrEmpty(localPart))
                {
                    throw new ArgumentException(@"Invalid local part.", "localPart");
                }

                if (domainId < 0)
                {
                    throw new ArgumentException(@"Invalid domain id.", "domainId");
                }

                if (name.Length > 255)
                {
                    throw new ArgumentException(@"Sender name exceed limitation of 64 characters.", "name");
                }

                Guid user;

                if (!Guid.TryParse(userId, out user))
                {
                    throw new ArgumentException(@"Invalid user id.", "userId");
                }

                if (isSharedDomain && !IsAdmin && user != SecurityContext.CurrentAccount.ID)
                {
                    throw new SecurityException(
                              "Creation of a shared mailbox is allowed only for the current account if user is not admin.");
                }

                var teamlabAccount = CoreContext.Authentication.GetAccountByID(user);

                if (teamlabAccount == null)
                {
                    throw new InvalidDataException("Unknown user.");
                }

                var userInfo = CoreContext.UserManager.GetUsers(user);

                if (userInfo.IsVisitor())
                {
                    throw new InvalidDataException("User is visitor.");
                }

                if (localPart.Length > 64)
                {
                    throw new ArgumentException(@"Local part of mailbox exceed limitation of 64 characters.",
                                                "localPart");
                }

                if (!Parser.IsEmailLocalPartValid(localPart))
                {
                    throw new ArgumentException("Incorrect local part of mailbox.");
                }

                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                if (serverAddressDao.IsAddressAlreadyRegistered(localPart, serverDomain.Name))
                {
                    throw new DuplicateNameException("You want to create a mailbox with already existing address.");
                }

                if (Defines.ServerDomainMailboxPerUserLimit > 0)
                {
                    var engineFactory = new EngineFactory(Tenant, userId);

                    var accounts = engineFactory.AccountEngine.GetAccountInfoList();

                    var countDomainMailboxes =
                        accounts.Count(a =>
                                       a.IsTeamlabMailbox &&
                                       Parser.ParseAddress(a.Email)
                                       .Domain.Equals(serverDomain.Name, StringComparison.InvariantCultureIgnoreCase));

                    if (countDomainMailboxes >= Defines.ServerDomainMailboxPerUserLimit)
                    {
                        throw new ArgumentOutOfRangeException(
                                  string.Format("Count of user's mailboxes must be less or equal {0}.",
                                                Defines.ServerDomainMailboxPerUserLimit));
                    }
                }

                var serverDao = daoFactory.CreateServerDao();

                var server = serverDao.Get(Tenant);

                var mailboxLocalPart = localPart.ToLowerInvariant();

                var login = string.Format("{0}@{1}", mailboxLocalPart, serverDomain.Name);

                var mailboxDao = daoFactory.CreateMailboxDao();

                var existMailbox = mailboxDao.GetMailBox(new СoncreteUserMailboxExp(new MailAddress(login), Tenant, userId));

                if (existMailbox != null)
                {
                    throw new DuplicateNameException("You want to create a mailbox that is already connected.");
                }

                var password = PasswordGenerator.GenerateNewPassword(12);

                var utcNow = DateTime.UtcNow;

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    var mailbox = new Mailbox
                    {
                        Id               = 0,
                        Tenant           = Tenant,
                        User             = userId,
                        Name             = name,
                        Address          = login,
                        OAuthToken       = null,
                        OAuthType        = (int)AuthorizationServiceType.None,
                        ServerId         = server.ImapSettingsId,
                        Password         = password,
                        SmtpServerId     = server.SmtpSettingsId,
                        SmtpPassword     = password,
                        SizeLast         = 0,
                        MsgCountLast     = 0,
                        BeginDate        = Defines.MinBeginDate,
                        Imap             = true,
                        Enabled          = true,
                        IsTeamlabMailbox = true,
                        IsRemoved        = false,
                        DateCreated      = utcNow
                    };

                    mailbox.Id = mailboxDao.SaveMailBox(mailbox);

                    var address = new ServerAddress
                    {
                        Id          = 0,
                        Tenant      = Tenant,
                        MailboxId   = mailbox.Id,
                        DomainId    = serverDomain.Id,
                        AddressName = localPart,
                        IsAlias     = false,
                        IsMailGroup = false,
                        DateCreated = utcNow
                    };

                    address.Id = serverAddressDao.Save(address);

                    var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                    var maildir = PostfixMaildirUtil.GenerateMaildirPath(serverDomain.Name, localPart, utcNow);

                    var serverMailbox = new Server.Core.Entities.Mailbox
                    {
                        Name      = name,
                        Password  = password,
                        Login     = login,
                        LocalPart = localPart,
                        Domain    = serverDomain.Name,
                        Active    = true,
                        Quota     = 0,
                        Maldir    = maildir,
                        Modified  = utcNow,
                        Created   = utcNow,
                    };

                    var serverAddress = new Alias
                    {
                        Name     = name,
                        Address  = login,
                        GoTo     = login,
                        Domain   = serverDomain.Name,
                        IsActive = true,
                        IsGroup  = false,
                        Modified = utcNow,
                        Created  = utcNow
                    };

                    engine.SaveMailbox(serverMailbox, serverAddress);

                    tx.Commit();

                    CacheEngine.Clear(userId);

                    mailboxData = ToMailboxData(mailbox, ToServerDomainAddressData(address, login),
                                                new List <ServerDomainAddressData>());
                }
            }

            return(mailboxData);
        }
Exemplo n.º 28
0
        public void RemoveMailbox(MailBoxData mailBox)
        {
            var engine = new EngineFactory(mailBox.TenantId);

            using (var daoFactory = new DaoFactory())
            {
                var serverAddressDao = daoFactory.CreateServerAddressDao(mailBox.TenantId);

                var serverMailboxAddresses = serverAddressDao.GetList(mailBox.MailBoxId);

                var serverMailboxAddress = serverMailboxAddresses.FirstOrDefault(a => !a.IsAlias && !a.IsMailGroup);

                if (serverMailboxAddress == null)
                {
                    throw new InvalidDataException("Mailbox address not found");
                }

                var serverDomainDao = daoFactory.CreateServerDomainDao(mailBox.TenantId);
                var serverDomain    = serverDomainDao.GetDomain(serverMailboxAddress.DomainId);

                if (serverDomain == null)
                {
                    throw new InvalidDataException("Domain not found");
                }

                var serverGroupDao = daoFactory.CreateServerGroupDao(mailBox.TenantId);

                var serverGroups = serverGroupDao.GetList();

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(mailBox.TenantId);

                var serverEngine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                var utcNow = DateTime.UtcNow;

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    foreach (var serverGroup in serverGroups)
                    {
                        var addresses = serverAddressDao.GetGroupAddresses(serverGroup.Id);

                        var index = addresses.FindIndex(a => a.Id == serverMailboxAddress.Id);

                        if (index < 0)
                        {
                            continue;
                        }

                        addresses.RemoveAt(index);

                        if (addresses.Count == 0)
                        {
                            serverGroupDao.Delete(serverGroup.Id);

                            serverAddressDao.DeleteAddressesFromMailGroup(serverGroup.Id);

                            serverEngine.RemoveAlias(serverGroup.Address);
                        }
                        else
                        {
                            serverAddressDao.DeleteAddressFromMailGroup(serverGroup.Id, serverMailboxAddress.Id);

                            var goTo = string.Join(",",
                                                   addresses.Select(m => string.Format("{0}@{1}", m.AddressName, serverDomain.Name)));

                            var serverAddress = new Alias
                            {
                                Name     = "",
                                Address  = serverGroup.Address,
                                GoTo     = goTo,
                                Domain   = serverDomain.Name,
                                IsActive = true,
                                IsGroup  = true,
                                Modified = utcNow,
                                Created  = serverGroup.DateCreated
                            };

                            serverEngine.SaveAlias(serverAddress);
                        }
                    }

                    serverAddressDao.Delete(serverMailboxAddresses.Select(a => a.Id).ToList());

                    foreach (var mailboxAddress in serverMailboxAddresses)
                    {
                        serverEngine.RemoveAlias(string.Format("{0}@{1}", mailboxAddress.AddressName, serverDomain.Name));
                    }

                    engine.MailboxEngine.RemoveMailBox(daoFactory, mailBox, false);

                    serverEngine.RemoveMailbox(string.Format("{0}@{1}", serverMailboxAddress.AddressName,
                                                             serverDomain.Name));

                    tx.Commit();
                }
            }
        }
Exemplo n.º 29
0
        static void Main(string[] args)
        {
            // Prologue
            IJsonClient json = Setup(args);
            IdentityWs  ws   = new IdentityWs(json);

            // Alias creation/linking
            ws.GetAliasAsync("*****@*****.**").Result.Should().BeNull("the alias has not been created yet");
            Alias  alias1    = ws.CreateAliasAsync("*****@*****.**", "password1").Result;
            Action linkWrong = () => ws.CreateLinkedAliasAsync("*****@*****.**", "*****@*****.**").Wait();

            linkWrong.Should().Throw <IdentityException>().Which.StatusCode.Should().Be(HttpStatusCode.NotFound, "the link target doesn't exist");
            Action linkDup = () => ws.CreateLinkedAliasAsync("*****@*****.**", "*****@*****.**").Wait();

            linkDup.Should().Throw <IdentityException>().Which.StatusCode.Should().Be(HttpStatusCode.Conflict, "the alias already exists");
            Action createDup = () => ws.CreateAliasAsync("*****@*****.**", "password2").Wait();

            createDup.Should().Throw <IdentityException>().Which.StatusCode.Should().Be(HttpStatusCode.Conflict, "the alias already exists");
            Alias  alias2      = ws.CreateLinkedAliasAsync("*****@*****.**", "*****@*****.**").Result;
            Action changeWrong = () => alias2.ChangePasswordAsync("wrong", "strong.password").Wait();

            changeWrong.Should().Throw <IdentityException>().Which.StatusCode.Should().Be(HttpStatusCode.Unauthorized, "the password is wrong");
            alias2.ChangePasswordAsync("password1", "strong.password").Wait();
            alias1.ChangePasswordAsync("strong.password", "stronger.password").Wait();

            // Password reset
            string resetTok      = alias2.GenerateResetTokenAsync().Result;
            string resetTokWrong = (resetTok[0] == '0' ? "1" : "0") + resetTok.Substring(1);
            Action resetWrong    = () => alias2.ChangePasswordViaResetTokenAsync(resetTokWrong, "impossible").Wait();

            resetWrong.Should().Throw <IdentityException>().Which.StatusCode.Should().Be(HttpStatusCode.Unauthorized, "the reset token is wrong");
            alias2.ChangePasswordViaResetTokenAsync(resetTok, "strongest.password").Wait();

            // Confirmation and email
            alias1.IsConfirmationTokenLoaded.Should().BeFalse("the token is automatically loaded only on alias get, not create");
            Action unfetched = () => _ = alias1.IsConfirmed;

            unfetched.Should().Throw <InvalidOperationException>("the confirmation token has not been loaded");
            alias1.FetchConfirmationTokenAsync().Wait();
            alias1.IsConfirmed.Should().BeFalse("the alias has not been confirmed yet");
            string confTok      = alias1.ConfirmationToken;
            string confTokWrong = (confTok[0] == '0' ? "1" : "0") + confTok.Substring(1);
            Action confWrong    = () => alias1.ConfirmAsync(confTokWrong).Wait();

            confWrong.Should().Throw <IdentityException>().Which.StatusCode.Should().Be(HttpStatusCode.Unauthorized, "the confirmation token is wrong");
            alias1.ConfirmAsync(confTok).Wait();
            alias1.IsConfirmed.Should().BeTrue("the alias was just confirmed");
            ws.GetAliasAsync("*****@*****.**").Result.IsConfirmed.Should().BeTrue("it's a copy of the confirmed alias");
            alias2.FetchConfirmationTokenAsync().Wait();
            alias2.IsConfirmed.Should().BeFalse("confirmation is at the alias level");
            alias2.EmailAsync("*****@*****.**", "Hello", "World!", "<html><body><strong>World!</strong></body></html>").Wait();

            // Client creation
            alias1.GetClientAsync("test1").Result.Should().BeNull("the client has not been created yet");
            Client client1   = alias1.CreateClientAsync("test1").Result;
            Action clientDup = () => alias2.CreateClientAsync("test1").Wait();

            clientDup.Should().Throw <IdentityException>().Which.StatusCode.Should().Be(HttpStatusCode.Conflict, "the client already exists for the being");
            Dictionary <string, string> data = new Dictionary <string, string>
            {
                ["flubble"] = "1",
                ["Bup"]     = "False"
            };
            Client client2 = alias2.CreateClientAsync("test2", data).Result;

            alias1.GetClientAsync("test2").Result.Data.Should().BeEquivalentTo(data, "it's a copy of the client just created with such data");

            // Login and alias deletion
            Action oldPassword = () => client1.LogInAsync("password1").Wait();

            oldPassword.Should().Throw <IdentityException>().Which.StatusCode.Should().Be(HttpStatusCode.Unauthorized, "the password was changed");
            client1.LogInAsync("strongest.password").Wait();
            alias1.DeleteAsync().Wait();
            Action tooEnthusiastic = () => alias2.DeleteAsync().Wait();

            tooEnthusiastic.Should().Throw <IdentityException>().Which.StatusCode.Should().Be(HttpStatusCode.Forbidden, "one alias must remain");
            client2.LogInAsync("strongest.password").Wait();
            Action tooLate = () => client1.LogInAsync("strongest.password").Wait();

            tooLate.Should().Throw <HttpRequestException>("the server will 404 because the alias has been deleted");

            // Client deletion
            client2.DeleteAsync().Wait();
            Alias  alias2Copy           = ws.GetAliasAsync("*****@*****.**").Result;
            Client client1ViaAlias2Copy = alias2Copy.GetClientAsync("test1").Result;

            client1ViaAlias2Copy.LogInAsync("strongest.password").Wait();
            client1ViaAlias2Copy.DeleteAsync().Wait();
            ws.GetAliasAsync("*****@*****.**").Result.Should().BeNull("everything should be deleted once the last service is deleted");

            // Epilogue
            (json as RecordingHttpJsonClient)?.Persist();
            Console.WriteLine("Test run succeeded");
        }
Exemplo n.º 30
0
 TypeDef TypeDeclaration()
 {
     if (currentToken.Tipo != TipoToken.TK_ID)
         throw new Exception("Se esperaba identificador.");
     else
     {//type id
         string tmp = currentToken.Lexema;
         currentToken = lex.NextToken();
         if (currentToken.Tipo != TipoToken.TK_ASSIGN)
             throw new Exception("Se esperaba asignacion.");
         else
         {//type id :=
             currentToken = lex.NextToken();
             if (currentToken.Tipo == TipoToken.TK_RECORD)
             {//type id := record
                 currentToken = lex.NextToken();
                 Structs ret = new Structs();
                 ret.nombre = tmp;
                 try
                 {
                     ret.campos = VariableDeclarationList();
                 }
                 catch (Exception ex) { throw ex; }
                 if (currentToken.Tipo != TipoToken.TK_END)
                     throw new Exception("Se esperaba end.");
                 else
                 {
                     currentToken = lex.NextToken();
                     Struct type = new Struct();
                     type.Campos = new T_Campos();
                     type.nombre = ret.nombre;
                     Declaracion temp = ret.campos;
                     while (temp != null)
                     {
                         type.Campos.Add(temp.Var.id, temp.Tip);
                         temp = temp.Sig;
                     }
                     try { InfSemantica.getInstance().tblTipos.Add(type.nombre, type); }
                     catch (Exception ex) { throw new Exception("Ya se ha definido un tipo con ese nombre."); }
                     return ret;
                 }
             }
             else
             {//type id := something
                 Alias ret = new Alias();
                 ret.type = new UserType();
                 ret.type.Nombre = tmp;
                 try
                 {
                     ret.type.Tip = ParseType();
                 }
                 catch (Exception ex) { throw ex; }
                 InfSemantica.getInstance().tblTipos.Add(ret.type.Nombre, ret.type);
                 return ret;
             }
         }
     }
 }
Exemplo n.º 31
0
 ColumnExpression ITablePrivate.GetPrimaryOrder(Alias alias)
 {
     return((ColumnExpression)RowIdExpression(alias).Value);
 }
Exemplo n.º 32
0
 internal ColumnExpression OrderExpression(Alias tableAlias)
 {
     return(new ColumnExpression(typeof(int), tableAlias, ((IColumn)this.Order !).Name));
 }
Exemplo n.º 33
0
        private void ProcessJoins(Table table)
        {
            if (!Tokenizer.HasMoreTokens)
            {
                return;
            }
            do
            {
                JoinType?joinType = GetJoinType();
                if (joinType == null)
                {
                    return;
                }

                ExpectToken(Constants.Join);

                Join join = null;
                if (Tokenizer.IsNextToken(Constants.OpenBracket))
                {
                    using (Tokenizer.ExpectBrackets())
                    {
                        join = new DerivedJoin {
                            Type = joinType.Value
                        };
                        Tokenizer.ExpectToken(Constants.Select);
                        var parser = new SelectStatementParser(Tokenizer);
                        ((DerivedJoin)join).SelectStatement = (SelectStatement)parser.Execute();
                    }
                }
                else
                {
                    join = new Join {
                        Type = joinType.Value
                    };
                    join.Name = GetTableName();
                }

                Debug.Assert(join != null);

                Alias alias = new Alias(null);
                if (Tokenizer.IsNextToken(Constants.As))
                {
                    alias.Type = AliasType.As;
                    Tokenizer.ReadNextToken();
                }
                if (alias.Type != AliasType.Implicit || !Tokenizer.IsNextToken(Constants.On))
                {
                    alias.Name = GetIdentifier();
                    join.Alias = alias;
                }

                ProcessTableHints(join);
                ExpectToken(Constants.On);
                Expression expr = ProcessExpression();

                if (!(expr is CriteriaExpression) && !(expr is NestedExpression && (expr as NestedExpression).Expression is CriteriaExpression))
                {
                    throw new SyntaxException("Expected Criteria Expression");
                }

                join.Condition = expr;

                table.Joins.Add(join);
            }while (Tokenizer.HasMoreTokens && !Tokenizer.IsNextToken(Constants.Order, Constants.Group));
        }
Exemplo n.º 34
0
        protected void ProcessFrom()
        {
            if (!Tokenizer.TokenEquals(Constants.From))
            {
                return;
            }

            do
            {
                Table table = null;

                if (Tokenizer.IsNextToken(Constants.OpenBracket))
                {
                    using (Tokenizer.ExpectBrackets())
                    {
                        DerivedTable derivedTable = new DerivedTable();
                        Tokenizer.ExpectToken(Constants.Select);
                        var parser = new SelectStatementParser(Tokenizer);
                        derivedTable.SelectStatement = (SelectStatement)parser.Execute();
                        table = derivedTable;
                    }
                }
                else
                {
                    table = new Table {
                        Name = GetTableName()
                    }
                };

                _statement.From.Add(table);

                // TODO: This needs to be changed to test Tokenizer.Token.Current.TokenType for TokenType.Keyword
                // if a new statement is initiated here, do not process the alias
                if (IsTerminatingFromExpression())
                {
                    return;
                }

                Alias alias = new Alias(null);
                if (Tokenizer.IsNextToken(Constants.As))
                {
                    alias.Type = AliasType.As;
                    Tokenizer.ReadNextToken();
                }
                if (!Tokenizer.IsNextToken(Constants.OpenBracket) && (alias.Type != AliasType.Implicit || !Tokenizer.IsNextToken(FromTerminatorSet)))
                {
                    if (Tokenizer.HasMoreTokens)
                    {
                        if (!Tokenizer.Current.IsTypeIn(
                                TokenType.AlphaNumeric, TokenType.AlphaNumeric, TokenType.BlockedText, TokenType.SingleQuote
                                )
                            )
                        {
                            throw new SyntaxException(String.Format("Incorrect syntax near '{0}'", CurrentToken));
                        }

                        alias.Name  = CurrentToken;
                        table.Alias = alias;
                        ReadNextToken();
                    }
                }
                ProcessTableHints(table);
                ProcessJoins(table);
            }while (Tokenizer.HasMoreTokens && Tokenizer.TokenEquals(Constants.Comma));
        }
Exemplo n.º 35
0
 public async Task <Alias> UpdateAliasAsync(Alias alias)
 {
     return(await PutJsonAsync <Alias>($"{Apiurl}/{alias.AliasId}", alias));
 }
Exemplo n.º 36
0
        internal PrimaryKeyExpression RowIdExpression(Alias tableAlias)
        {
            var primary = (IColumn)this.PrimaryKey;

            return(new PrimaryKeyExpression(new ColumnExpression(primary.Type.Nullify(), tableAlias, primary.Name)));
        }
Exemplo n.º 37
0
 internal PrimaryKeyExpression BackColumnExpression(Alias tableAlias)
 {
     return(new PrimaryKeyExpression(new ColumnExpression(BackReference.Type.Nullify(), tableAlias, BackReference.Name)));
 }
Exemplo n.º 38
0
 /// <summary>
 /// Optional. Sets the payer/grantor alias in order to bypass the Token email input UI.
 /// </summary>
 /// <param name="fromAlias">payer/grantor alias</param>
 /// <returns>builder</returns>
 public T SetFromAlias(Alias fromAlias)
 {
     requestOptions.From.Alias = fromAlias;
     return((T)this);
 }
Exemplo n.º 39
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Serves as the default hash function. </summary>
        ///
        /// <remarks>   Lucas Alves, 11/01/2016. </remarks>
        ///
        /// <returns>   A hash code for the current object. </returns>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public override int GetHashCode()
        {
            return(Alias.GetHashCode());
        }
Exemplo n.º 40
0
        internal static PlaceholderLocalSymbol CreatePlaceholderLocal(
            TypeNameDecoder<PEModuleSymbol, TypeSymbol> typeNameDecoder,
            MethodSymbol containingMethod,
            Alias alias)
        {
            var typeName = alias.Type;
            Debug.Assert(typeName.Length > 0);

            var type = typeNameDecoder.GetTypeSymbolForSerializedType(typeName);
            Debug.Assert((object)type != null);

            var id = alias.FullName;
            switch (alias.Kind)
            {
                case AliasKind.Exception:
                    return new ExceptionLocalSymbol(containingMethod, id, type, ExpressionCompilerConstants.GetExceptionMethodName);
                case AliasKind.StowedException:
                    return new ExceptionLocalSymbol(containingMethod, id, type, ExpressionCompilerConstants.GetStowedExceptionMethodName);
                case AliasKind.ReturnValue:
                    {
                        int index;
                        PseudoVariableUtilities.TryParseReturnValueIndex(id, out index);
                        Debug.Assert(index >= 0);
                        return new ReturnValueLocalSymbol(containingMethod, id, type, index);
                    }
                case AliasKind.ObjectId:
                    return new ObjectIdLocalSymbol(containingMethod, type, id, isWritable: false);
                case AliasKind.DeclaredLocal:
                    return new ObjectIdLocalSymbol(containingMethod, type, id, isWritable: true);
                default:
                    throw ExceptionUtilities.UnexpectedValue(alias.Kind);
            }
        }
Exemplo n.º 41
0
        public ServerDomainAddressData AddAlias(int mailboxId, string aliasName)
        {
            if (!IsAdmin)
            {
                throw new SecurityException("Need admin privileges.");
            }

            if (string.IsNullOrEmpty(aliasName))
            {
                throw new ArgumentException(@"Invalid alias name.", "aliasName");
            }

            if (mailboxId < 0)
            {
                throw new ArgumentException(@"Invalid mailbox id.", "mailboxId");
            }

            if (aliasName.Length > 64)
            {
                throw new ArgumentException(@"Local part of mailbox alias exceed limitation of 64 characters.", "aliasName");
            }

            if (!Parser.IsEmailLocalPartValid(aliasName))
            {
                throw new ArgumentException("Incorrect mailbox alias.");
            }

            var mailboxAliasName = aliasName.ToLowerInvariant();

            using (var daoFactory = new DaoFactory())
            {
                var mailboxDao = daoFactory.CreateMailboxDao();

                var mailbox = mailboxDao.GetMailBox(new ConcreteTenantMailboxExp(mailboxId, Tenant));

                if (mailbox == null)
                {
                    throw new ArgumentException("Mailbox not exists");
                }

                if (!mailbox.IsTeamlabMailbox)
                {
                    throw new ArgumentException("Invalid mailbox type");
                }

                if (mailbox.Tenant == Defines.SHARED_TENANT_ID)
                {
                    throw new InvalidOperationException("Adding mailbox alias is not allowed for shared domain.");
                }

                var mailAddress = new MailAddress(mailbox.Address);

                var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant);
                var serverDomain    = serverDomainDao.GetDomains().FirstOrDefault(d => d.Name == mailAddress.Host);

                if (serverDomain == null)
                {
                    throw new ArgumentException("Domain not exists");
                }

                var mailboxAddress = mailAddress.Address;

                var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant);

                if (serverAddressDao.IsAddressAlreadyRegistered(mailboxAliasName, serverDomain.Name))
                {
                    throw new DuplicateNameException("You want to create a mailbox with already existing address.");
                }

                var utcNow = DateTime.UtcNow;

                var address = new ServerAddress
                {
                    Id          = 0,
                    Tenant      = Tenant,
                    MailboxId   = mailbox.Id,
                    DomainId    = serverDomain.Id,
                    AddressName = mailboxAliasName,
                    IsAlias     = true,
                    IsMailGroup = false,
                    DateCreated = utcNow
                };

                var aliasEmail = string.Format("{0}@{1}", mailboxAliasName, serverDomain.Name);

                var serverDao = daoFactory.CreateServerDao();
                var server    = serverDao.Get(Tenant);

                var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString);

                using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted))
                {
                    address.Id = serverAddressDao.Save(address);

                    var serverAddress = new Alias
                    {
                        Name     = mailbox.Name,
                        Address  = aliasEmail,
                        GoTo     = mailboxAddress,
                        Domain   = serverDomain.Name,
                        IsActive = true,
                        IsGroup  = false,
                        Modified = utcNow,
                        Created  = utcNow
                    };

                    engine.SaveAlias(serverAddress);

                    tx.Commit();
                }

                CacheEngine.Clear(mailbox.User);

                return(new ServerDomainAddressData
                {
                    Id = address.Id,
                    DomainId = address.DomainId,
                    Email = aliasEmail
                });
            }
        }
Exemplo n.º 42
0
        /// <summary>
        /// Adds a Sim to the List
        /// </summary>
        /// <param name="objd"></param>
        /// <param name="ct"></param>
        /// <param name="step"></param>
        /// <returns>The Alias for that Sim</returns>
        /// <remarks>
        /// Alias.Tag has the following Structure:
        /// [0] : FileName of Character File (if NPC, this will be null)
        /// [1] : Thumbnail
        /// [2] : FamilyName
        /// [3] : Contains Age Data
        /// [4] : When NPC, this will get the Filename
        /// </remarks>
        protected Alias AddSim(SimPe.PackedFiles.Wrapper.ExtObjd objd, ref int ct, int step, bool npc)
        {
            //if (objd.Type!=Data.ObjectTypes.Person) return null;

            SimPe.Interfaces.Files.IPackageFile fl = objd.Package;
            //BinaryReader br = new BinaryReader(File.OpenRead(file));//new StreamReader(file)
            bool hasagedata = fl.FindFiles(0xAC598EAC).Length > 0;           //has Age Data

            object[] tags = new object[5];
            tags[0] = fl.FileName;
            tags[1] = null;
            tags[2] = Localization.Manager.GetString("Unknown");
            tags[3] = hasagedata;
            tags[4] = null;

            /*if (Helper.WindowsRegistry.HiddenMode)
             *      tags[5] = (!hasagedata) && (fl.FindFiles(0xAC506764).Length>0); //if this is true, the Sim has a Problem, and the package was probably split
             * else
             *      tags[5] = false;*/

            //set stuff for NPCs
            if (npc)
            {
                tags[4]  = tags[0];
                tags[0]  = "";
                tags[2] += " (NPC)";
            }

            Alias a = null;



            Interfaces.Files.IPackedFileDescriptor str_pfd = fl.FindFile(Data.MetaData.CTSS_FILE, 0, objd.FileDescriptor.Group, objd.CTSSInstance);

            if (str_pfd != null)
            {
                SimPe.PackedFiles.Wrapper.Str str = new SimPe.PackedFiles.Wrapper.Str();
                str.ProcessData(str_pfd, fl);
                SimPe.PackedFiles.Wrapper.StrItemList its = str.FallbackedLanguageItems(Helper.WindowsRegistry.LanguageCode);
                if (its.Length > 0)
                {
#if DEBUG
                    a = new Alias(objd.Guid, its[0].Title, "{name} {2} (0x{id})");
#else
                    a = new Alias(objd.Guid, its[0].Title, "{name} {2} (0x{id})");
#endif
                    if (its.Length > 2)
                    {
                        tags[2] = its[2].Title;
                    }
                }
            }


            if (a != null)
            {
                IPackedFileDescriptor[] piclist = fl.FindFiles(Data.MetaData.SIM_IMAGE_FILE);
                foreach (IPackedFileDescriptor pfd in piclist)
                {
                    if (pfd.Group != objd.FileDescriptor.Group)
                    {
                        continue;
                    }
                    if (pfd.Instance < 0x200)
                    {
                        SimPe.PackedFiles.Wrapper.Picture pic = new SimPe.PackedFiles.Wrapper.Picture();
                        pic.ProcessData(pfd, fl);

                        /*if (Helper.StartedGui==Executable.Classic)
                         *      WaitingScreen.UpdateImage(pic.Image);
                         * else
                         *      Wait.Image = pic.Image;								*/

                        tags[1] = pic.Image;
                        break;
                    }
                }

                a.Tag = tags;
                //if (Helper.StartedGui!=Executable.Classic)
                {
                    ct++;
                    if (ct % step == 1)
                    {
                        Wait.Message  = a.ToString();
                        Wait.Progress = ct;
                    }
                }

                //set stuff for NPCs
                if (npc)
                {
                    a.Tag[2] = a.Tag[2].ToString() + " (NPC)";
                }

                if (names == null)
                {
                    return(null);
                }
                if (!names.Contains(objd.Guid))
                {
                    names.Add(objd.Guid, a);
                }
            }

            return(a);
        }
Exemplo n.º 43
0
        public void Log(int siteId, LogLevel level, object @class, LogFunction function, Exception exception, string message, params object[] args)
        {
            Log log = new Log();

            if (siteId == -1)
            {
                log.SiteId = null;
                Alias alias = _tenantResolver.GetAlias();
                if (alias != null)
                {
                    log.SiteId = alias.SiteId;
                }
            }
            else
            {
                log.SiteId = siteId;
            }
            log.PageId   = null;
            log.ModuleId = null;
            log.UserId   = null;
            User user = _userPermissions.GetUser();

            if (user != null)
            {
                log.UserId = user.UserId;
            }
            log.Url = "";
            if (_accessor.HttpContext != null)
            {
                HttpRequest request = _accessor.HttpContext.Request;
                if (request != null)
                {
                    log.Url = $"{request.Scheme}://{request.Host}{request.Path}{request.QueryString}";
                }
            }

            Type type = Type.GetType(@class.ToString());

            if (type != null)
            {
                log.Category = type.AssemblyQualifiedName;
                log.Feature  = Utilities.GetTypeNameLastSegment(log.Category, 0);
            }
            else
            {
                log.Category = @class.ToString();
                log.Feature  = log.Category;
            }
            log.Function = Enum.GetName(typeof(LogFunction), function);
            log.Level    = Enum.GetName(typeof(LogLevel), level);
            if (exception != null)
            {
                log.Exception = exception.ToString();
            }
            log.Message         = message;
            log.MessageTemplate = "";
            try
            {
                log.Properties = JsonSerializer.Serialize(args);
            }
            catch // serialization error occurred
            {
                log.Properties = "";
            }
            Log(log);
        }
Exemplo n.º 44
0
 public UrlMappingController(IUrlMappingRepository urlMappings, ILogManager logger, ITenantManager tenantManager)
 {
     _urlMappings = urlMappings;
     _logger      = logger;
     _alias       = tenantManager.GetAlias();
 }
Exemplo n.º 45
0
        private void CheckVariable(string variableName, Alias alias, bool valid)
        {
            var source =
@"class C
{
    static void M()
    {
    }
}";
            string error;
            var testData = Evaluate(source, "C.M", variableName, out error, alias);
            if (valid)
            {
                var expectedNames = new[] { "<>x.<>m0()" };
                var actualNames = testData.Methods.Keys;
                AssertEx.SetEqual(expectedNames, actualNames);
            }
            else
            {
                Assert.Equal(error, string.Format("error CS0103: The name '{0}' does not exist in the current context", variableName));
            }
        }
Exemplo n.º 46
0
 /// <summary>
 /// Sets the alias of the payee/grantee.
 /// </summary>
 /// <param name="toAlias">to alias</param>
 /// <returns>builder</returns>
 public T SetToAlias(Alias toAlias)
 {
     requestPayload.To.Alias = toAlias;
     return((T)this);
 }
		public string[] GetCollectionPropertyColumnAliases(string propertyName, string suffix)
		{
			object aliases;
			if (!collectionPropertyColumnAliases.TryGetValue(propertyName, out aliases))
			{
				return null;
			}
			var rawAliases = (string[]) aliases;

			var result = new string[rawAliases.Length];
			for (int i = 0; i < rawAliases.Length; i++)
			{
				result[i] = new Alias(suffix).ToUnquotedAliasString(rawAliases[i], dialect);
			}
			return result;
		}
Exemplo n.º 48
0
        private ReadOnlyCollection<ColumnDeclaration> AnswerAndExpand(ReadOnlyCollection<ColumnDeclaration> columns, Alias currentAlias, Dictionary<ColumnExpression, Expression> askedColumns)
        {
            ColumnGenerator cg = new ColumnGenerator(columns);
         
            foreach (var col in askedColumns.Keys.ToArray())
            {
                if (col.Alias == currentAlias)
                {
                    Expression expr = columns.SingleEx(cd => (cd.Name ?? "-") == col.Name).Expression;

                    askedColumns[col] = expr.NodeType == (ExpressionType)DbExpressionType.SqlConstant? expr: col;
                }
                else
                {
                    Expression expr = CurrentScope[col];
                    ColumnExpression colExp = expr as ColumnExpression;
                    if (colExp != null)
                    {
                        ColumnDeclaration cd = cg.Columns.FirstOrDefault(c => c.Expression.Equals(colExp));
                        if (cd == null)
                        {
                            cd = cg.MapColumn(colExp);
                        }

                        askedColumns[col] = new ColumnExpression(col.Type, currentAlias, cd.Name);
                    }
                    else
                    {
                        askedColumns[col] = expr;
                    }
                }
            }


            if (columns.Count != cg.Columns.Count())
                return cg.Columns.ToReadOnly();

            return columns;
        }
Exemplo n.º 49
0
 private PlantUmlComponent GetComponentWithAlias(Alias alias, PlantUmlDiagram diagram)
 {
     return(diagram.ComponentsWithAlias.Where(c => alias.Equals(c.Alias)).Single());
 }
Exemplo n.º 50
0
 /// <summary>
 ///     Serves as a hash function for a particular type.
 /// </summary>
 /// <returns>
 ///     A hash code for the current <see cref="T:System.Object" />.
 /// </returns>
 public override int GetHashCode() => Alias.GetHashCode();
Exemplo n.º 51
0
            public static HashSet<ColumnExpression> Gatherer(Expression source, Alias externalAlias)
            {
                ExternalColumnGatherer ap = new ExternalColumnGatherer()
                {
                    externalAlias = externalAlias
                };

                ap.Visit(source);

                return ap.columns;
            }
Exemplo n.º 52
0
        public bool Save()
        {
            cms.businesslogic.web.DocumentType dt = cms.businesslogic.web.DocumentType.MakeNew(BusinessLogic.User.GetUser(_userID), Alias.Replace("'", "''"));
            dt.IconUrl = "folder.gif";

            // Create template?
            if (ParentID == 1)
            {
                cms.businesslogic.template.Template[] t = { cms.businesslogic.template.Template.MakeNew(_alias, BusinessLogic.User.GetUser(_userID)) };
                dt.allowedTemplates = t;
                dt.DefaultTemplate  = t[0].Id;
            }

            // Master Content Type?
            if (TypeID != 0)
            {
                dt.MasterContentType = TypeID;
            }

            m_returnUrl = "settings/EditNodeTypeNew.aspx?id=" + dt.Id.ToString();

            return(true);
        }
Exemplo n.º 53
0
 internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression?period, EntityContextInfo?entityContext)
 {
     return(new MListExpression(FieldType, (PrimaryKeyExpression)id, period, TableMList)); // keep back id empty for some seconds
 }
Exemplo n.º 54
0
    public string Search(int report, int dateGroup, string staffId, int status, string keyword, string listPlayerIdIncidents)
    {
        Keyword = keyword;

        string reportStatus = "";

        switch (status) // set status for writing the select query
        {
        case 2:
            reportStatus = "%Completion%";
            break;

        case 3:
            reportStatus = "%Manager%";
            break;

        case 4:
            reportStatus = "%Further%";
            break;

        case 5:
            reportStatus = "%Completed%";
            break;
        }

        DateTime date1 = DateTime.Now.Date, date2 = DateTime.Now.Date; // used to hold Date Group values

        switch (dateGroup)                                             // set the date being filtered
        {
        case 2:
            date2 = DateTime.Now.Date.AddDays(-1);      // reports from yesterday
            break;

        case 3:
            date2 = DateTime.Now.Date.AddDays(-7);      // reports from last seven days
            break;

        case 4:
            date2 = DateTime.Now.Date.AddDays(-14);      // reports from last 14 days
            break;

        case 5:
            date2 = DateTime.Now.Date.AddDays(-30);      // reports from last month
            break;

        case 6:
            date2 = DateTime.Now.Date.AddDays(-365);      // reports from last year
            break;

        case 7:
            date2 = DateTime.Parse(StartDate);
            date1 = DateTime.Parse(EndDate);
            break;
        }

        string reportType = "";

        switch (report) // set the report type being filtered (take note that any changes from the group will create an error - MRReportsDutyManager)
        {
        case 2:
            reportType = "MR Incident Report";
            break;

        case 3:
            reportType = "MR Duty Managers";
            break;

        case 4:
            reportType = "MR Supervisors";
            break;

        case 5:
            reportType = "MR Function Supervisor";
            break;

        case 6:
            reportType = "MR Reception Supervisor";
            break;

        case 7:
            reportType = "MR Reception";
            break;

        case 8:
            reportType = "CU Duty Managers";
            break;

        case 9:
            reportType = "CU Reception";
            break;

        case 10:
            reportType = "CU Incident Report";
            break;

        case 11:
            reportType = "MR Covid Marshall";
            break;

        case 12:
            reportType = "CU Covid Marshall";
            break;

        case 13:
            reportType = "MR Customer Relations Officer";
            break;

        case 14:
            reportType = "MR Caretaker";
            break;
        }

        // check if user has entered a keyword to be filtered
        bool hasKeyword = true;

        if (keyword.Equals("0") || keyword.Equals("")) // check whether the keyword filter is empty
        {
            hasKeyword = false;                        // keyword filter is empty
        }

        // check if staff has filter
        bool hasStaffFilter = true;

        if (ArchivedStaff)
        {
            if (string.IsNullOrEmpty(staffId))
            {
                staffId = "SELECT StaffId FROM Staff WHERE Active=0";
            }
        }
        else if (string.IsNullOrEmpty(staffId)) // if there is no staff filter selected, populate staff list
        {
            staffId        = "SELECT StaffId FROM Staff";
            hasStaffFilter = false;
        }

        // check if selected staff filter is the user logged in
        bool isAuthor = true;

        if (!staffId.Equals(UserCredentials.StaffId))
        {
            isAuthor = false;
        }

        string selectQuery = "",
               startQuery  = "SELECT [ReportId], [ReportName], [StaffId], [StaffName], [ShiftName], [ShiftDate], [ShiftDOW], [Report_Table], [Report_Version], [ReportStat], [AuditVersion], [RowNum]" +
                             " FROM [View_Reports] WHERE ",
               startQuery1 = "SELECT [ReportId], [ReportName], [StaffId], [StaffName], [ShiftName], [ShiftDate], [ShiftDOW], [Report_Table], [Report_Version], [ReportStat], [AuditVersion], ROW_NUMBER() OVER(ORDER BY ShiftDate DESC, ShiftId DESC) RowNum" +
                             " FROM [View_Reports] WHERE ",
               reportIdQuery = "", dateQuery = "", statusQuery = "", unreadQuery = "", reportQuery = "", authorQuery = "", cuQuery = "", mrQuery = "",
               endQuery = "ORDER BY ShiftDate DESC, ShiftId DESC, RowNum";

        if (report == 1) // no report type filter
        {
            string groupsUpdate = "";
            try
            {
                groupsUpdate = UserCredentials.GroupsQuery.Remove(UserCredentials.GroupsQuery.LastIndexOf("', 'MR Incident Report"));
            }
            catch { }
            try
            {
                groupsUpdate = UserCredentials.GroupsQuery.Remove(UserCredentials.GroupsQuery.LastIndexOf("', 'CU Incident Report"));
            }
            catch { }

            if (UnreadList && UserCredentials.GroupsQuery.Contains("Reception") && !UserCredentials.GroupsQuery.Contains("Supervisor") && !UserCredentials.GroupsQuery.Contains("Manager"))
            {
                reportQuery = "[ReportName] IN ('" + groupsUpdate + "') AND ";
            }
            else
            {
                if (UserCredentials.GroupsQuery.Contains("Reception") && !UserCredentials.GroupsQuery.Contains("Supervisor") && !UserCredentials.GroupsQuery.Contains("Manager"))
                {
                    reportQuery = "([ReportName] IN ('" + groupsUpdate + "') OR ([ReportName] IN ('" + UserCredentials.GroupsQuery + "') AND [StaffId] = '" + UserCredentials.StaffId + "')) AND ";
                }
                else
                {
                    reportQuery = "[ReportName] IN ('" + UserCredentials.GroupsQuery + "') AND ";
                }
            }
        }
        else // has report type filter
        {
            if (UserCredentials.GroupsQuery.Contains("Reception") && !UserCredentials.GroupsQuery.Contains("Supervisor") && !UserCredentials.GroupsQuery.Contains("Manager") && (reportType.Equals("MR Incident Report") || reportType.Equals("CU Incident Report")))
            {
                reportQuery = "([ReportName] = '" + reportType + "' AND [StaffId] = '" + UserCredentials.StaffId + "') AND ";
            }
            else
            {
                reportQuery = "[ReportName] = '" + reportType + "' AND ";
            }
        }

        if (string.IsNullOrWhiteSpace(ReportId))
        {
            reportIdQuery = " ";
        }
        else
        {
            reportIdQuery = "ReportId =" + ReportId + " AND ";
        }

        if (dateGroup != 1) // has date filter
        {
            dateQuery = "ShiftDate BETWEEN '" + date2.ToString("yyyy-MM-dd") + "' AND '" + date1.ToString("yyyy-MM-dd") + "' AND ";
        }
        else // no date filter
        {
            dateQuery = " ";
        }

        if (MROnly)
        {
            mrQuery = "[ReportName] LIKE '%MR%' AND ";
        }
        else
        {
            mrQuery = "";
        }

        if (CUOnly)
        {
            cuQuery = "[ReportName] LIKE '%CU%' AND ";
        }
        else
        {
            cuQuery = "";
        }

        if (status != 1) // has status filter
        {
            statusQuery = "[ReportStat] LIKE '" + reportStatus + "' AND ";
        }
        else // no status filter
        {
            statusQuery = " ";
        }

        if (!hasStaffFilter) // if staff filter is empty
        {
            authorQuery = "([ReportStat] = 'Report Completed' OR [ReportStat] = 'Further Action Required' OR [ReportStat] = 'Awaiting Manager Sign-off' OR ([ReportStat] = 'Awaiting Completion' AND [StaffId] = '" + UserCredentials.StaffId + "')) ";
        }
        else // has a staff filter
        {
            if (isAuthor)  // The user selected his ownself
            {
                authorQuery = "([ReportStat] = 'Report Completed' OR [ReportStat] = 'Further Action Required' OR [ReportStat] = 'Awaiting Manager Sign-off' OR ([ReportStat] = 'Awaiting Completion' AND [StaffId] = '" + UserCredentials.StaffId + "')) AND StaffId IN (" + staffId + ") ";
            }
            else //  // staff other than the user
            {
                authorQuery = "([ReportStat] = 'Report Completed' OR [ReportStat] = 'Further Action Required' OR [ReportStat] = 'Awaiting Manager Sign-off') AND StaffId IN (" + staffId + ") ";
            }
        }

        if (UnreadList && string.IsNullOrEmpty(ListPlayerIdIncidents)) // unread tickbox has been checked
        {
            unreadQuery = "AND ([ReadByList] NOT LIKE '%," + UserCredentials.StaffId + ",%' OR [ReadByList] IS NULL) AND ([ManagerSignId] NOT LIKE '%" + UserCredentials.StaffId + ",%' OR [ManagerSignId] IS NULL) ";
        }
        else // no unread list filter
        {
            unreadQuery = " ";
        }


        if (!hasKeyword && (WhatHappened.Equals("0") || string.IsNullOrEmpty(WhatHappened)) && (Location.Equals("0") || string.IsNullOrEmpty(Location)) &&
            (ActionTaken.Equals("0") || string.IsNullOrEmpty(ActionTaken)) && (MemberNo.Equals("0") || string.IsNullOrEmpty(MemberNo)) &&
            (FirstName.Equals("0") || string.IsNullOrEmpty(FirstName)) && (LastName.Equals("0") || string.IsNullOrEmpty(LastName)) &&
            (Alias.Equals("0") || string.IsNullOrEmpty(Alias)))    // if Keyword and advanced filters are empty
        {
            selectQuery = startQuery + reportQuery + reportIdQuery + dateQuery + mrQuery + cuQuery + statusQuery + authorQuery + unreadQuery + endQuery;
        }
        else // keyword filter and advanced filter has been entered
        {
            // run stored procedures
            SqlQuery sqlQuery = new SqlQuery();
            if (!string.IsNullOrEmpty(listPlayerIdIncidents)) // run all the list of incidents for the selected player id
            {
                sqlQuery.RetrieveData("Proc_ListPriorIncidents", "SearchKeyword");
            }
            else // no player id is selected, filter via keyword and report filters
            {
                // set appropriate stored procedure (either Proc_KeywordSearchAllReports - any report other than Incidents ; Proc_KeywordSearchIncidentReports - Incidents ONLY)
                if (reportType.Contains("Incident"))
                {
                    sqlQuery.RetrieveData("Proc_KeywordSearchIncidentReports", "SearchKeyword");
                }
                else
                {
                    sqlQuery.RetrieveData("Proc_KeywordSearchAllReports", "SearchKeyword");
                }
            }

            if (GlobalSearchId.Equals("")) // if no data retrieved, display an error message
            {
                return(selectQuery);
            }

            // take off the extra ', ' in Global Search Ids Variable
            int strLength = GlobalSearchId.Length;
            GlobalSearchId = GlobalSearchId.Remove(strLength - 2, 2);

            string keywordQuery = "AND [ReportId] IN (" + GlobalSearchId + ") ";
            GlobalSearchId        = ""; // to avoid this variable from getting appended
            ListPlayerIdIncidents = ""; // reset this variable to be reused again in searching incident reports related to player id selected

            selectQuery = startQuery1 + reportQuery + reportIdQuery + dateQuery + mrQuery + cuQuery + statusQuery + authorQuery + keywordQuery + unreadQuery + endQuery;
        }
        return(selectQuery);
    }
Exemplo n.º 55
0
 internal abstract Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression?period, EntityContextInfo?entityContext);
Exemplo n.º 56
0
        public String ParseInputToChoice(String input, IEnumerable <Alias> choices)
        {
            //aliases
            String suggestion = _db.GetAlias(_threadId, input);
            //punctuation
            //whitespace
            List <Alias> onlyAlphaNumChoices = new List <Alias>();

            foreach (var c in choices)
            {
                String newOriginal = new String(c.Original.Where(ch => char.IsLetterOrDigit(ch)).ToArray());
                Alias  a           = new Alias(newOriginal, c.MapsTo);
                if (newOriginal.Length >= 2)
                {
                    onlyAlphaNumChoices.Add(a);
                }
                else
                {
                    onlyAlphaNumChoices.Add(c);
                }
            }
            String alphaNumInput = new String(input.Where(ch => char.IsLetterOrDigit(ch)).ToArray());
            //repeated letters
            Regex r = new Regex("(.)(?<=\\1\\1)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);

            List <Alias> collapseRepeatsChoices = new List <Alias>();

            foreach (var c in onlyAlphaNumChoices)
            {
                String newOriginal = r.Replace(c.Original, String.Empty);
                Alias  a           = new Alias(newOriginal, c.MapsTo);
                if (newOriginal.Length >= 4)
                {
                    collapseRepeatsChoices.Add(a);
                }
                else
                {
                    collapseRepeatsChoices.Add(c);
                }
            }
            String collapseInput = r.Replace(alphaNumInput, String.Empty);

            if (collapseInput.Length < 4)
            {
                collapseInput = "";                                       // go back if too short
            }
            // off by one
            List <String> missingOneLetter = new List <string>();

            missingOneLetter.Add(collapseInput);
            if (collapseInput.Length > 3)
            {
                for (int i = 0; i < collapseInput.Length; i++)
                {
                    String missing = collapseInput.Remove(i) + collapseInput.Substring(i + 1);
                    missingOneLetter.Add(missing);
                }
            }
            // GOAT / WOAT / WOLF
            String noAids = collapseInput.Replace("GOAT", "", StringComparison.InvariantCultureIgnoreCase).
                            Replace("WOAT", "", StringComparison.InvariantCultureIgnoreCase).
                            Replace("WOLF", "", StringComparison.InvariantCultureIgnoreCase).
                            Replace("AIDS", "", StringComparison.InvariantCultureIgnoreCase).
                            Replace("THE", "", StringComparison.InvariantCultureIgnoreCase);

            if (noAids.Length <= 2)
            {
                noAids = "";
            }

            String rc = TryRules(input, choices);

            if (rc != null)
            {
                return(rc);
            }
            rc = TryRules(suggestion, choices);
            if (rc != null)
            {
                return(rc);
            }
            rc = TryRules(alphaNumInput, onlyAlphaNumChoices);
            if (rc != null)
            {
                return(rc);
            }
            rc = TryRules(collapseInput, collapseRepeatsChoices);
            if (rc != null)
            {
                return(rc);
            }
            rc = TryRules(missingOneLetter, collapseRepeatsChoices);
            if (rc != null)
            {
                return(rc);
            }
            rc = TryRules(noAids, collapseRepeatsChoices);
            if (rc != null)
            {
                return(rc);
            }

            return("");
        }
 /// <summary>Visit an alias.</summary>
 /// <param name="alias">Alias to be visited.</param>
 protected override void VisitAlias(Alias alias)
 {
     VisitComponent(alias.Component);
     _commandText.Append(" AS ");
     VisitComponent(alias.Name);
 }
Exemplo n.º 58
0
 internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression?period, EntityContextInfo?entityContext)
 {
     return(new PrimaryKeyExpression(new ColumnExpression(this.Type.Nullify(), tableAlias, this.Name).Nullify()));
 }
		public string[] GetSubclassPropertyColumnAliases(string propertyName, string suffix)
		{
			string[] rawAliases;

			if (!subclassPropertyAliases.TryGetValue(propertyName,out rawAliases))
				return null;

			string[] result = new string[rawAliases.Length];
			for (int i = 0; i < rawAliases.Length; i++)
				result[i] = new Alias(suffix).ToUnquotedAliasString(rawAliases[i], Factory.Dialect);

			return result;
		}
Exemplo n.º 60
0
 internal override Expression GetExpression(Alias tableAlias, QueryBinder binder, Expression id, IntervalExpression?period, EntityContextInfo?entityContext)
 {
     return(Expression.Convert(new ColumnExpression(this.Type, tableAlias, Name), FieldType));
 }