System.Guid.Parse(string)

Here are the examples of the csharp api System.Guid.Parse(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2207 Examples 7

19 View Source File : ExprPlainReader.cs
License : MIT License
Project Creator : 0x1000000

public bool TryGetGuid(IPlainItem node, string propertyName, out Guid value)
        {
            value = default;
            if (this.TryGetSubNode(node.Id, propertyName, null, out var prop) && prop.Value != null)
            {
                value = Guid.Parse(prop.Value);
                return true;
            }
            return false;
        }

19 View Source File : ScAllColumnTypes.cs
License : MIT License
Project Creator : 0x1000000

private static AllColumnTypesDto[] GetTestData(bool isPostgres)
        {
            byte[] GenerateTestArray(int shift, int size)
            {
                byte[] result = new byte[size];
                for(int i = 0; i< size; i++)
                {
                    unchecked
                    {
                        result[i] = (byte)(i + shift);
                    }
                }

                return result;
            }

            var result = new[]
            {
                new AllColumnTypesDto
                {
                    ColBoolean = true,
                    ColByte = isPostgres ? default : byte.MaxValue,
                    ColDateTime = new DateTime(2020, 10, 13),
                    ColDecimal = 2.123456m,
                    ColDouble = 2.123456,
                    ColGuid = Guid.Parse("e580d8df-78ed-4add-ac20-4c32bc8d94fc"),
                    ColInt16 = short.MaxValue,
                    ColInt32 = int.MaxValue,
                    ColInt64 = long.MaxValue,
                    ColStringMax = "abcdef",
                    ColStringUnicode = "\u0430\u0431\u0441\u0434\u0435\u0444",
                    ColString5 = "abcd",
                    ColByteArraySmall = GenerateTestArray(3, 255),
                    ColByteArrayBig = GenerateTestArray(29, 65535*2),

                    ColNullableBoolean = true,
                    ColNullableByte = isPostgres ? (byte?)null : byte.MaxValue,
                    ColNullableDateTime = new DateTime(2020, 10, 13),
                    ColNullableDecimal = 2.123456m,
                    ColNullableDouble = 2.123456,
                    ColNullableGuid = Guid.Parse("e580d8df-78ed-4add-ac20-4c32bc8d94fc"),
                    ColNullableInt16 = short.MaxValue,
                    ColNullableInt32 = int.MaxValue,
                    ColNullableInt64 = long.MaxValue,
                    ColNullableStringMax = "abcdef",
                    ColNullableStringUnicode = "\u0430\u0431\u0441\u0434\u0435\u0444",
                    ColNullableByteArraySmall = GenerateTestArray(17, 255),
                    ColNullableByteArrayBig = GenerateTestArray(17, 65535*2),

                    ColFixedSizeByteArray = new byte[]{255, 0},
                    ColFixedSizeString = "123",

                    ColNullableFixedSizeByteArray = new byte[]{0,255},
                    ColNullableFixedSizeString = "321",

                    ColXml = "<root><Item2 /></root>",
                    ColNullableXml = "<root><Item /></root>"

                },

                new AllColumnTypesDto
                {
                    ColBoolean = false,
                    ColByte = isPostgres ? default : byte.MinValue,
                    ColDateTime = new DateTime(2020, 10, 14),
                    ColDecimal = -2.123456m,
                    ColDouble = -2.123456,
                    ColGuid = Guid.Parse("0CFF587D-2A78-4891-83F6-5EE291221DFC"),
                    ColInt16 = short.MinValue,
                    ColInt32 = int.MinValue,
                    ColInt64 = long.MinValue,
                    ColStringMax = "",
                    ColStringUnicode = "",
                    ColString5 = "",
                    ColByteArraySmall = GenerateTestArray(7, 13),
                    ColByteArrayBig = GenerateTestArray(13, 17),
                    ColXml = "<root><Item3 /></root>",

                    ColNullableBoolean = null,
                    ColNullableByte = null,
                    ColNullableDateTime = null,
                    ColNullableDecimal = null,
                    ColNullableDouble = null,
                    ColNullableGuid = null,
                    ColNullableInt16 = null,
                    ColNullableInt32 = null,
                    ColNullableInt64 = null,
                    ColNullableStringMax = null,
                    ColNullableStringUnicode = null,
                    ColNullableByteArraySmall = null,
                    ColNullableByteArrayBig = null,


                    ColFixedSizeByteArray = new byte[]{128, 128},
                    ColFixedSizeString = "abc",

                    ColNullableFixedSizeByteArray = null,
                    ColNullableFixedSizeString = null,
                    ColNullableXml = null
                }
            };
            return result;
        }

19 View Source File : InPredicateTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public void InValuesTest()
        {
            var a = CustomColumnFactory.Int32("a");

            replacedert.AreEqual("[a] IN(1)", a.In(Literal(1)).ToSql());
            replacedert.AreEqual("[a] IN(1,2,3)", a.In(Literal(1), Literal(2), Literal(3)).ToSql());
            replacedert.AreEqual("[a] IN(1,2)", a.In(new []{ Literal(1), Literal(2) }).ToSql());

            replacedert.AreEqual("[a] IN(1)", a.In(1).ToSql());
            replacedert.AreEqual("[a] IN(1,2,3)", a.In(1,2,3).ToSql());
            replacedert.AreEqual("[a] IN(1,2)", a.In(new []{1, 2}).ToSql());

            replacedert.AreEqual("[a] IN('1')", a.In("1").ToSql());
            replacedert.AreEqual("[a] IN('1','2','3')", a.In("1","2","3").ToSql());
            replacedert.AreEqual("[a] IN('1','2')", a.In(new []{"1", "2"}).ToSql());

            var g1 = Guid.Parse("F46E2EC5-E08F-4CB9-8FD5-62DAC1A90C85");
            var g2 = Guid.Parse("FE716966-74D9-4449-83CE-16371698E8D0");
            var g3 = Guid.Parse("9614F808-E9EA-4BFE-8432-3711EB7E235C");

            replacedert.AreEqual("[a] IN('f46e2ec5-e08f-4cb9-8fd5-62dac1a90c85')", a.In(g1).ToSql());
            replacedert.AreEqual("[a] IN('f46e2ec5-e08f-4cb9-8fd5-62dac1a90c85','fe716966-74d9-4449-83ce-16371698e8d0','9614f808-e9ea-4bfe-8432-3711eb7e235c')", a.In(g1,g2,g3).ToSql());
            replacedert.AreEqual("[a] IN('f46e2ec5-e08f-4cb9-8fd5-62dac1a90c85','fe716966-74d9-4449-83ce-16371698e8d0')", a.In(new []{g1, g2}).ToSql());
        }

19 View Source File : TempTableBuilderTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public void BasicTest()
        {
            var data = new[]
            {
                new
                {
                    Bool = true,
                    Byte = byte.MaxValue,
                    Int16 = short.MaxValue,
                    Int32 = int.MaxValue,
                    Int64 = long.MaxValue,
                    Decimal = decimal.MaxValue,
                    Double = 123.456,
                    String = "ABCD",
                    DateTime = new DateTime(2099, 1, 1),
                    Guid = Guid.Parse("37197F28-AAED-480B-BA66-2C4D67A57E33")
                },
                new
                {
                    Bool = true,
                    Byte = byte.MinValue,
                    Int16 = short.MinValue,
                    Int32 = int.MinValue,
                    Int64 = long.MinValue,
                    Decimal = decimal.MinValue,
                    Double = -123.456,
                    String = "ABCDABCD",
                    DateTime = new DateTime(1900, 1, 1),
                    Guid = Guid.Parse("E8C3620B-B8CD-4574-A074-ACE09AA3DA8A")
                },
            };

            List<List<ExprValue>> dataList = new List<List<ExprValue>>(data.Length);

            foreach (var row in data)
            {
                var l = new List<ExprValue>();

                l.Add(SqQueryBuilder.Literal(row.Bool));
                l.Add(SqQueryBuilder.Literal(row.Byte));
                l.Add(SqQueryBuilder.Literal(row.Int16));
                l.Add(SqQueryBuilder.Literal(row.Int32));
                l.Add(SqQueryBuilder.Literal(row.Int64));
                l.Add(SqQueryBuilder.Literal(row.Decimal));
                l.Add(SqQueryBuilder.Literal(row.Double));
                l.Add(SqQueryBuilder.Literal(row.String));
                l.Add(SqQueryBuilder.Literal(row.DateTime));
                l.Add(SqQueryBuilder.Literal(row.Guid));

                dataList.Add(l);
            }

            var derivedTable = SqQueryBuilder.Values(dataList).AsColumns("Bool","Byte", "Int16", "Int32", "Int64", "Decimal", "Double", "String", "DateTime", "Guid");

            var q = TempTableData.FromDerivedTableValuesInsert(derivedTable, new []{ derivedTable.Columns[2], derivedTable.Columns[3] }, out var table, name: "TestTmpTable");

            var sql = q.ToMySql();
            replacedert.AreEqual(sql, "CREATE TEMPORARY TABLE `TestTmpTable`(`Bool` bit,`Byte` tinyint unsigned,`Int16` smallint,`Int32` int,`Int64` bigint,`Decimal` decimal(29,0),`Double` double,`String` varchar(8) character set utf8,`DateTime` datetime,`Guid` binary(16),CONSTRAINT PRIMARY KEY (`Int16`,`Int32`));INSERT INTO `TestTmpTable`(`Bool`,`Byte`,`Int16`,`Int32`,`Int64`,`Decimal`,`Double`,`String`,`DateTime`,`Guid`) VALUES (true,255,32767,2147483647,9223372036854775807,79228162514264337593543950335,123.456,'ABCD','2099-01-01',0x287F1937EDAA0B48BA662C4D67A57E33),(true,0,-32768,-2147483648,-9223372036854775808,-79228162514264337593543950335,-123.456,'ABCDABCD','1900-01-01',0x0B62C3E8CDB87445A074ACE09AA3DA8A)");

            sql = q.ToSql();
            replacedert.AreEqual(sql, "CREATE TABLE [#TestTmpTable]([Bool] bit,[Byte] tinyint,[Int16] smallint,[Int32] int,[Int64] bigint,[Decimal] decimal(29,0),[Double] float,[String] [nvarchar](8),[DateTime] datetime,[Guid] uniqueidentifier,CONSTRAINT [PK_TestTmpTable] PRIMARY KEY ([Int16],[Int32]));INSERT INTO [#TestTmpTable]([Bool],[Byte],[Int16],[Int32],[Int64],[Decimal],[Double],[String],[DateTime],[Guid]) VALUES (1,255,32767,2147483647,9223372036854775807,79228162514264337593543950335,123.456,'ABCD','2099-01-01','37197f28-aaed-480b-ba66-2c4d67a57e33'),(1,0,-32768,-2147483648,-9223372036854775808,-79228162514264337593543950335,-123.456,'ABCDABCD','1900-01-01','e8c3620b-b8cd-4574-a074-ace09aa3da8a')");
            
        }

19 View Source File : ScTransactions.cs
License : MIT License
Project Creator : 0x1000000

public async Task Exec(IScenarioContext context)
        {
            ISqDatabase database = this._newConnection ? context.CreteConnection() : context.Database;

            var guid = Guid.Parse("58AD8253-4F8F-4C84-B930-4F58A8F25912");
            var tCompany = AllTables.GereplacedCompany();
            var data = new[] { new CompanyInitData(id: 0, name: "TestCompany", externalId: guid) };

            var exprInsert = InsertDataInto(tCompany, data)
                .MapData(CompanyInitData.GetMapping)
                .AlsoInsert(m => m
                    .Set(m.Target.Modified, GetUtcDate())
                    .Set(m.Target.Created, GetUtcDate())
                    .Set(m.Target.Version, 1)
                ).Done();

            using (database.BeginTransactionOrUseExisting(out var newTransaction))
            {
                if (!newTransaction)
                {
                    throw new Exception("New transaction should be started");
                }

                using var t2 = database.BeginTransactionOrUseExisting(out newTransaction);

                await exprInsert.Exec(database);
                t2.Rollback();

                t2.Commit();

                if (newTransaction)
                {
                    throw new Exception("Already existing transaction should be reused");
                }
                if (!await CheckExistence())
                {
                    throw new Exception("Inside transaction the data should be visible");
                }
            }

            if (await CheckExistence())
            {
                throw new Exception("Transaction was not committed, so it should return nothing");
            }

            using (var t = database.BeginTransaction())
            {
                await exprInsert.Exec(database);
                t.Commit();
            }

            if (!await CheckExistence())
            {
                throw new Exception("Transaction was committed, so it should return something");
            }

            using (var t = database.BeginTransaction(IsolationLevel.Serializable))
            {
                await Delete(tCompany).Where(tCompany.ExternalId == guid).Exec(database);
                t.Commit();
            }

            if (await CheckExistence())
            {
                throw new Exception("The row is suppose to be deleted");
            }

            if (this._newConnection)
            {
                database.Dispose();
            }

            async Task<bool> CheckExistence()
            {
                var col = await Select(Literal(1).As("Col"))
                    .From(tCompany)
                    .Where(tCompany.ExternalId == guid)
                    .QueryList(database, r => r.GetInt32("Col"));

                return col.Count > 0;
            }
        }

19 View Source File : GuidTypeHandler.cs
License : MIT License
Project Creator : 17MKH

public override Guid Parse(object value)
    {
        return Guid.Parse(value.ToString());
    }

19 View Source File : JwtCredentialBuilder.cs
License : MIT License
Project Creator : 17MKH

public async Task<IResultModel> Build(List<Claim> claims)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Key));
        var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var jwtSecurityToken = new JwtSecurityToken(_options.Issuer, _options.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(_options.Expires), signingCredentials);
        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        _logger.LogDebug("生成AccessToken:{token}", token);

        var result = new JwtResultModel
        {
            AccountId = Guid.Parse(claims.First(m => m.Type == MkhClaimTypes.ACCOUNT_ID).Value),
            Platform = claims.First(m => m.Type == MkhClaimTypes.PLATFORM).Value.ToInt(),
            AccessToken = token,
            ExpiresIn = (_options.Expires < 0 ? 120 : _options.Expires) * 60,
            RefreshToken = Guid.NewGuid().ToString().Replace("-", "")
        };

        //存储令牌信息
        await _tokenStorageProvider.Save(result, claims);

        return ResultModel.Success(result);
    }

19 View Source File : ImClient.cs
License : MIT License
Project Creator : 2881099

public Guid[] GetChanClientList(string chan)
    {
        return _redis.HKeys($"{_redisPrefix}Chan{chan}").Select(a => Guid.Parse(a)).ToArray();
    }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 2881099

private void buttonItem29_Click(object sender, EventArgs e)
        {
            var node = advTree1.SelectedNode;
            if (node != null && node.Level == 1)
            {
                if (MessageBoxEx.Show("是否删除当前选中服务器", "删除提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    node.Nodes.Clear();
                    DataBaseInfo baseInfo = new DataBaseInfo();
                    baseInfo.Delete(Guid.Parse(node.Name));
                    advTree1.Nodes[0].Nodes.Remove(node);
                }
            }
            else
            {
                MessageBoxEx.Show("删除节点无效", "删除提示", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
            }
        }

19 View Source File : GuidFuzzerShould.cs
License : Apache License 2.0
Project Creator : 42skillz

[Test]
        public void Generate_random_but_deterministic_Guid()
        {
            var fuzzer = new Fuzzer(1898737139);
            var guid  = fuzzer.GenerateGuid();
            Check.That(guid).IsEqualTo(Guid.Parse("4b730026-135c-a175-888f-2fdda993e237"));

            guid = fuzzer.GenerateGuid();
            Check.That(guid).IsEqualTo(Guid.Parse("9a8471f9-0a1d-ccb7-f58a-e690f92ff5b2"));
        }

19 View Source File : UpdateTests.cs
License : Apache License 2.0
Project Creator : aadreja

[Fact]
        public void UpdateContactTest()
        {
            Vega.Config.CreatedUpdatedByColumnType = System.Data.DbType.Guid;

            Repository<Contact> repository = new Repository<Contact>(this.Fixture.Connection);

            Contact contact = new Contact()
            {
                Id = Guid.NewGuid(),
                Name = "Mehul V",
                MobileNo = "9924323876",
                CreatedBy = new Guid("00000000-0000-0000-0000-000000000001"),
                UpdatedBy = new Guid("00000000-0000-0000-0000-000000000001")
            };

            var objId = repository.Add(contact);

            contact = new Contact()
            {
                Id = Guid.Parse(objId.ToString()),
                Name = "Dashrath H",
                MobileNo = "1212121212",
                UpdatedBy = new Guid("00000000-0000-0000-0000-000000000002")
            };

            var result = repository.Update(contact);

            Vega.Config.CreatedUpdatedByColumnType = System.Data.DbType.Int32;

            replacedert.True(result);
        }

19 View Source File : FdbTuplePackers.cs
License : MIT License
Project Creator : abdullin

public static Guid DeserializeGuid(Slice slice)
		{
			if (slice.IsNullOrEmpty) return Guid.Empty;

			int type = slice[0];

			switch (type)
			{
				case FdbTupleTypes.Bytes:
					{
						return Guid.Parse(FdbTupleParser.ParseAscii(slice));
					}
				case FdbTupleTypes.Utf8:
					{
						return Guid.Parse(FdbTupleParser.ParseUnicode(slice));
					}
				case FdbTupleTypes.Uuid128:
					{
						return FdbTupleParser.ParseGuid(slice);
					}
					//REVIEW: should we allow converting a Uuid64 into a Guid? This looks more like a bug than an expected behavior...
			}

			throw new FormatException(String.Format("Cannot convert tuple segment of type 0x{0:X} into a System.Guid", type));
		}

19 View Source File : UserDataManager.cs
License : MIT License
Project Creator : Abdulrhman5

public virtual async Task<(Login, User)> AddUserIfNotExisted(Guid tokenId, string originUserId, string accessToken)
        {

            // if The user existed but the login does not exist
            var login = _loginRepo.Table.Include(login => login.User).SingleOrDefault(t => t.LoginId == tokenId);
            if (login is null)
            {
                // add the login 
                var loginInformation = await _loginInformationGetter.GetLoginInformation(tokenId.ToString());
                var userIdGuid = Guid.Parse(loginInformation.UserId);
                var theUser = _userRepo.Table.SingleOrDefault(u => u.UserId == userIdGuid);
                if (theUser is null)
                {
                    var userToBeAdded = new User
                    {
                        UserId = userIdGuid,
                        Status = UserStatus.Available,
                        UserName = loginInformation.Username,
                        Logins = new List<Login>
                        {
                            new Login
                            {
                                LoginId = Guid.Parse(loginInformation.TokenId),
                            }
                        }
                    };

                    _userRepo.Add(userToBeAdded);
                    await _userRepo.SaveChangesAsync();

                    return (userToBeAdded.Logins.FirstOrDefault(), userToBeAdded);
                }
                else
                {
                    var loginToBeAdded = new Login
                    {
                        LoginId = Guid.Parse(loginInformation.TokenId),
                        UserId = theUser.UserId,
                    };

                    _loginRepo.Add(loginToBeAdded);
                    await _loginRepo.SaveChangesAsync();
                    return (loginToBeAdded, theUser);
                }
            }
            else
            {
                return (login, login.User);
            }
        }

19 View Source File : UserDataManager.cs
License : MIT License
Project Creator : Abdulrhman5

public virtual async Task<(Login, User)> AddCurrentUserIfNeeded()
        {
            var credentials = GetCurrentUser();
            if (credentials is null)
            {
                return (null, null);
            }
            else
            {
                return await AddUserIfNotExisted(Guid.Parse(credentials.TokenId), credentials.UserId, credentials.AccessToken);
            }
        }

19 View Source File : Uuid128.cs
License : MIT License
Project Creator : abdullin

public static Uuid128 Parse([NotNull] string input)
		{
			return new Uuid128(Guid.Parse(input));
		}

19 View Source File : UserGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public IEnumerable<UserForAdministrationDto> GetUsers()
        {
            var x = from u in _usersRepo.Table
                    select new UserForAdministrationDto
                    {
                        Id= Guid.Parse(u.Id),
                        Email = u.Email,
                        Gender = u.Gender.ToString(),
                        IsEmailConfirmed = u.EmailConfirmed,
                        PhoneNumber = u.PhoneNumber,
                        RegisteredAt = u.CreatedAt,
                        Username = u.UserName,
                        AccessFeildCount = u.AccessFailedCount,
                    };
            return x;
        }

19 View Source File : UserGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async  Task<List<UserForAdministrationDto>> GetUsersAsync(PagingArguments args)
        {
            var x = from u in _usersRepo.Table
                    select new UserForAdministrationDto
                    {
                        Id = Guid.Parse(u.Id),
                        Email = u.Email,
                        Gender = u.Gender.ToString(),
                        IsEmailConfirmed = u.EmailConfirmed,
                        PhoneNumber = u.PhoneNumber,
                        RegisteredAt = u.CreatedAt,
                        Username = u.UserName,
                        AccessFeildCount = u.AccessFailedCount,
                        PictureUrl = _urlConstructor.ConstructOrDefault(u.Photos.OrderByDescending(pp => pp.AddedAtUtc).FirstOrDefault()),
                    };
            return await x.SkipTakeAsync(args);
        }

19 View Source File : UserGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<UserForAdministrationDto>> GetUsersAsync()
        {
            var x = from u in _usersRepo.Table
                    select new UserForAdministrationDto
                    {
                        Id = Guid.Parse(u.Id),
                        Email = u.Email,
                        Gender = u.Gender.ToString(),
                        IsEmailConfirmed = u.EmailConfirmed,
                        PhoneNumber = u.PhoneNumber,
                        RegisteredAt = u.CreatedAt,
                        Username = u.UserName,
                        AccessFeildCount = u.AccessFailedCount,
                        PictureUrl = _urlConstructor.ConstructOrDefault(u.Photos.OrderByDescending(pp => pp.AddedAtUtc).FirstOrDefault()),
                    };
            return await x.ToListAsync();
        }

19 View Source File : UserGetter.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<UserListDto> GetUsersWithStatsAsync()
        {
            var stats = (from u in _usersRepo.Table
                        group u by 1 into g
                        select new
                        {
                            Male = _usersRepo.Table.Where(u => u.Gender == Gender.Male).Count(),
                            Female = _usersRepo.Table.Where(u => u.Gender == Gender.Female).Count(),
                            Blocked = 0,
                            All = _usersRepo.Table.Count()
                        }).FirstOrDefault();

            var x = await (from u in _usersRepo.Table
                    select new UserForAdministrationDto
                    {
                        Id = Guid.Parse(u.Id),
                        Email = u.Email,
                        Gender = u.Gender.ToString(),
                        IsEmailConfirmed = u.EmailConfirmed,
                        PhoneNumber = u.PhoneNumber,
                        RegisteredAt = u.CreatedAt,
                        Username = u.UserName,
                        AccessFeildCount = u.AccessFailedCount,
                        PictureUrl = _urlConstructor.ConstructOrDefault(u.Photos.OrderByDescending(pp => pp.AddedAtUtc).FirstOrDefault()),
                    }).ToListAsync();

            var result = new UserListDto
            {
                AllUserCount = stats.All,
                BlockedUsersCount = stats.Blocked,
                FemaleUsersCount = stats.Female,
                MaleUsersCount = stats.Male,
                Users = x,
            };

            return result;
        }

19 View Source File : UserDataManager.cs
License : MIT License
Project Creator : Abdulrhman5

public virtual async Task<(Login, User)> AddCurrentUserIfNeeded()
        {
            var credentials = GetCuurentUser();
            if (credentials is null)
            {
                return (null, null);
            }
            else
            {
                return await AddUserIfNotExisted(Guid.Parse(credentials.TokenId), credentials.UserId, credentials.AccessToken);
            }
        }

19 View Source File : UserDataManager.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<User> AddUserIfNeeded(string userId)
        {
            var usersById = (from u in _userRepo.Table
                             where u.UserId.ToString() == userId
                             select u).FirstOrDefault();

            if (usersById is object)
            {
                return usersById;
            }

            var user = await _loginInformationGetter.GetUser(userId);
            var userToBeAdded = new User
            {
                UserId = Guid.Parse(userId),
                Status = UserStatus.Available,
                UserName = user.Username,
            };

            _userRepo.Add(userToBeAdded);
            await _userRepo.SaveChangesAsync();

            return userToBeAdded;
        }

19 View Source File : FdbConverters.cs
License : MIT License
Project Creator : abdullin

private static void RegisterDefaultConverters()
		{
			//TODO: there is too much generic type combinations! need to refactor this ...

			RegisterUnsafe<bool, Slice>((value) => Slice.FromByte(value ? (byte)1 : default(byte)));
			RegisterUnsafe<bool, byte[]>((value) => Slice.FromByte(value ? (byte)1 : default(byte)).GetBytes());
			RegisterUnsafe<bool, string>((value) => value ? "true" : "false");
			RegisterUnsafe<bool, sbyte>((value) => value ? (sbyte)1 : default(sbyte));
			RegisterUnsafe<bool, byte>((value) => value ? (byte)1 : default(byte));
			RegisterUnsafe<bool, short>((value) => value ? (short)1 : default(short));
			RegisterUnsafe<bool, ushort>((value) => value ? (ushort)1 : default(ushort));
			RegisterUnsafe<bool, int>((value) => value ? 1 : default(int));
			RegisterUnsafe<bool, uint>((value) => value ? 1U : default(uint));
			RegisterUnsafe<bool, long>((value) => value ? 1L : default(long));
			RegisterUnsafe<bool, ulong>((value) => value ? 1UL : default(ulong));
			RegisterUnsafe<bool, double>((value) => value ? 0.0d : 1.0d);
			RegisterUnsafe<bool, float>((value) => value ? 0.0f : 1.0f);

			RegisterUnsafe<int, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<int, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<int, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<int, bool>((value) => value != 0);
			RegisterUnsafe<int, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<int, byte>((value) => checked((byte)value));
			RegisterUnsafe<int, short>((value) => checked((short)value));
			RegisterUnsafe<int, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<int, uint>((value) => (uint)value);
			RegisterUnsafe<int, long>((value) => value);
			RegisterUnsafe<int, ulong>((value) => (ulong)value);
			RegisterUnsafe<int, double>((value) => value);
			RegisterUnsafe<int, float>((value) => checked((float)value));
			RegisterUnsafe<int, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<uint, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<uint, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<uint, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<uint, bool>((value) => value != 0);
			RegisterUnsafe<uint, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<uint, byte>((value) => checked((byte)value));
			RegisterUnsafe<uint, short>((value) => checked((short)value));
			RegisterUnsafe<uint, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<uint, int>((value) => (int)value);
			RegisterUnsafe<uint, long>((value) => value);
			RegisterUnsafe<uint, ulong>((value) => value);
			RegisterUnsafe<uint, double>((value) => value);
			RegisterUnsafe<uint, float>((value) => checked((float)value));

			RegisterUnsafe<long, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<long, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<long, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<long, bool>((value) => value != 0);
			RegisterUnsafe<long, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<long, byte>((value) => checked((byte)value));
			RegisterUnsafe<long, short>((value) => checked((short)value));
			RegisterUnsafe<long, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<long, int>((value) => checked((int)value));
			RegisterUnsafe<long, uint>((value) => (uint)value);
			RegisterUnsafe<long, ulong>((value) => (ulong)value);
			RegisterUnsafe<long, double>((value) => checked((double)value));
			RegisterUnsafe<long, float>((value) => checked((float)value));
			RegisterUnsafe<long, TimeSpan>((value) => TimeSpan.FromTicks(value));
			RegisterUnsafe<long, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<long, System.Net.IPAddress>((value) => new System.Net.IPAddress(value));

			RegisterUnsafe<ulong, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ulong, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ulong, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ulong, bool>((value) => value != 0);
			RegisterUnsafe<ulong, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ulong, byte>((value) => checked((byte)value));
			RegisterUnsafe<ulong, short>((value) => checked((short)value));
			RegisterUnsafe<ulong, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<ulong, int>((value) => checked((int)value));
			RegisterUnsafe<ulong, uint>((value) => checked((uint)value));
			RegisterUnsafe<ulong, long>((value) => checked((long)value));
			RegisterUnsafe<ulong, double>((value) => checked((double)value));
			RegisterUnsafe<ulong, float>((value) => checked((float)value));
			RegisterUnsafe<ulong, Uuid64>((value) => new Uuid64(value));
			RegisterUnsafe<ulong, TimeSpan>((value) => TimeSpan.FromTicks(checked((long)value)));

			RegisterUnsafe<short, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<short, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<short, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<short, bool>((value) => value != 0);
			RegisterUnsafe<short, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<short, byte>((value) => checked((byte)value));
			RegisterUnsafe<short, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<short, int>((value) => value);
			RegisterUnsafe<short, uint>((value) => checked((uint)value));
			RegisterUnsafe<short, long>((value) => value);
			RegisterUnsafe<short, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<short, double>((value) => value);
			RegisterUnsafe<short, float>((value) => value);
			RegisterUnsafe<short, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<ushort, Slice>((value) => Slice.FromUInt64(value));
			RegisterUnsafe<ushort, byte[]>((value) => Slice.FromUInt64(value).GetBytes());
			RegisterUnsafe<ushort, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<ushort, bool>((value) => value != 0);
			RegisterUnsafe<ushort, byte>((value) => checked((byte)value));
			RegisterUnsafe<ushort, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<ushort, short>((value) => checked((short)value));
			RegisterUnsafe<ushort, int>((value) => value);
			RegisterUnsafe<ushort, uint>((value) => value);
			RegisterUnsafe<ushort, long>((value) => value);
			RegisterUnsafe<ushort, ulong>((value) => value);
			RegisterUnsafe<ushort, double>((value) => value);
			RegisterUnsafe<ushort, float>((value) => value);

			RegisterUnsafe<byte, Slice>((value) => Slice.FromInt32(value));
			RegisterUnsafe<byte, byte[]>((value) => Slice.FromInt32(value).GetBytes());
			RegisterUnsafe<byte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<byte, bool>((value) => value != 0);
			RegisterUnsafe<byte, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<byte, short>((value) => value);
			RegisterUnsafe<byte, ushort>((value) => value);
			RegisterUnsafe<byte, int>((value) => value);
			RegisterUnsafe<byte, uint>((value) => value);
			RegisterUnsafe<byte, long>((value) => value);
			RegisterUnsafe<byte, ulong>((value) => value);
			RegisterUnsafe<byte, double>((value) => value);
			RegisterUnsafe<byte, float>((value) => value);
			RegisterUnsafe<byte, FdbTupleAlias>((value) => (FdbTupleAlias)value);

			RegisterUnsafe<sbyte, Slice>((value) => Slice.FromInt64(value));
			RegisterUnsafe<sbyte, byte[]>((value) => Slice.FromInt64(value).GetBytes());
			RegisterUnsafe<sbyte, string>((value) => value.ToString(CultureInfo.InvariantCulture)); //TODO: string table!
			RegisterUnsafe<sbyte, bool>((value) => value != 0);
			RegisterUnsafe<sbyte, byte>((value) => checked((byte)value));
			RegisterUnsafe<sbyte, short>((value) => value);
			RegisterUnsafe<sbyte, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<sbyte, int>((value) => value);
			RegisterUnsafe<sbyte, uint>((value) => checked((uint)value));
			RegisterUnsafe<sbyte, long>((value) => value);
			RegisterUnsafe<sbyte, ulong>((value) => checked((ulong)value));
			RegisterUnsafe<sbyte, double>((value) => value);
			RegisterUnsafe<sbyte, float>((value) => value);

			RegisterUnsafe<float, Slice>((value) => Slice.FromSingle(value));
			RegisterUnsafe<float, byte[]>((value) => Slice.FromSingle(value).GetBytes());
			RegisterUnsafe<float, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<float, bool>((value) => !(value == 0f || float.IsNaN(value)));
			RegisterUnsafe<float, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<float, byte>((value) => checked((byte)value));
			RegisterUnsafe<float, short>((value) => checked((short)value));
			RegisterUnsafe<float, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<float, int>((value) => checked((int)value));
			RegisterUnsafe<float, uint>((value) => (uint)value);
			RegisterUnsafe<float, long>((value) => checked((long)value));
			RegisterUnsafe<float, ulong>((value) => (ulong)value);
			RegisterUnsafe<float, double>((value) => value);

			RegisterUnsafe<double, Slice>((value) => Slice.FromDouble(value));
			RegisterUnsafe<double, byte[]>((value) => Slice.FromDouble(value).GetBytes());
			RegisterUnsafe<double, string>((value) => value.ToString("R", CultureInfo.InvariantCulture));
			RegisterUnsafe<double, bool>((value) => !(value == 0d || double.IsNaN(value)));
			RegisterUnsafe<double, sbyte>((value) => checked((sbyte)value));
			RegisterUnsafe<double, byte>((value) => checked((byte)value));
			RegisterUnsafe<double, short>((value) => checked((short)value));
			RegisterUnsafe<double, ushort>((value) => checked((ushort)value));
			RegisterUnsafe<double, int>((value) => checked((int)value));
			RegisterUnsafe<double, uint>((value) => (uint)value);
			RegisterUnsafe<double, long>((value) => checked((long)value));
			RegisterUnsafe<double, ulong>((value) => (ulong)value);
			RegisterUnsafe<double, float>((value) => checked((float)value));

			RegisterUnsafe<string, Slice>((value) => Slice.FromString(value));
			RegisterUnsafe<string, byte[]>((value) => Slice.FromString(value).GetBytes());
			RegisterUnsafe<string, bool>((value) => !string.IsNullOrEmpty(value));
			RegisterUnsafe<string, sbyte>((value) => string.IsNullOrEmpty(value) ? default(sbyte) : SByte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, byte>((value) => string.IsNullOrEmpty(value) ? default(byte) : Byte.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, short>((value) => string.IsNullOrEmpty(value) ? default(short) : Int16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ushort>((value) => string.IsNullOrEmpty(value) ? default(ushort) : UInt16.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, int>((value) => string.IsNullOrEmpty(value) ? default(int) : Int32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, uint>((value) => string.IsNullOrEmpty(value) ? default(uint) : UInt32.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, long>((value) => string.IsNullOrEmpty(value) ? default(long) : Int64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, ulong>((value) => string.IsNullOrEmpty(value) ? default(ulong) : UInt64.Parse(value, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, float>((value) => string.IsNullOrEmpty(value) ? default(float) : Single.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, double>((value) => string.IsNullOrEmpty(value) ? default(double) : Double.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture));
			RegisterUnsafe<string, Guid>((value) => string.IsNullOrEmpty(value) ? default(Guid) : Guid.Parse(value));
			RegisterUnsafe<string, Uuid128>((value) => string.IsNullOrEmpty(value) ? default(Uuid128) : Uuid128.Parse(value));
			RegisterUnsafe<string, Uuid64>((value) => string.IsNullOrEmpty(value) ? default(Uuid64) : Uuid64.Parse(value));
			RegisterUnsafe<string, System.Net.IPAddress>((value) => string.IsNullOrEmpty(value) ? default(System.Net.IPAddress) : System.Net.IPAddress.Parse(value));

			RegisterUnsafe<byte[], Slice>((value) => Slice.Create(value));
			RegisterUnsafe<byte[], string>((value) => value == null ? default(string) : value.Length == 0 ? String.Empty : System.Convert.ToBase64String(value));
			RegisterUnsafe<byte[], bool>((value) => value != null && value.Length > 0);
			RegisterUnsafe<byte[], sbyte>((value) => value == null ? default(sbyte) : Slice.Create(value).ToSByte());
			RegisterUnsafe<byte[], byte>((value) => value == null ? default(byte) : Slice.Create(value).ToByte());
			RegisterUnsafe<byte[], short>((value) => value == null ? default(short) : Slice.Create(value).ToInt16());
			RegisterUnsafe<byte[], ushort>((value) => value == null ? default(ushort) : Slice.Create(value).ToUInt16());
			RegisterUnsafe<byte[], int>((value) => value == null ? 0 : Slice.Create(value).ToInt32());
			RegisterUnsafe<byte[], uint>((value) => value == null ? 0U : Slice.Create(value).ToUInt32());
			RegisterUnsafe<byte[], long>((value) => value == null ? 0L : Slice.Create(value).ToInt64());
			RegisterUnsafe<byte[], ulong>((value) => value == null ? 0UL : Slice.Create(value).ToUInt64());
			RegisterUnsafe<byte[], Guid>((value) => value == null || value.Length == 0 ? default(Guid) : new Uuid128(value).ToGuid());
			RegisterUnsafe<byte[], Uuid128>((value) => value == null || value.Length == 0 ? default(Uuid128) : new Uuid128(value));
			RegisterUnsafe<byte[], Uuid64>((value) => value == null || value.Length == 0 ? default(Uuid64) : new Uuid64(value));
			RegisterUnsafe<byte[], TimeSpan>((value) => value == null ? TimeSpan.Zero : TimeSpan.FromTicks(Slice.Create(value).ToInt64()));
			RegisterUnsafe<byte[], System.Net.IPAddress>((value) => value == null || value.Length == 0 ? default(System.Net.IPAddress) : new System.Net.IPAddress(value));

			RegisterUnsafe<Guid, Slice>((value) => Slice.FromGuid(value));
			RegisterUnsafe<Guid, byte[]>((value) => Slice.FromGuid(value).GetBytes());
			RegisterUnsafe<Guid, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Guid, Uuid128>((value) => new Uuid128(value));
			RegisterUnsafe<Guid, bool>((value) => value != Guid.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(new Uuid128(value).ToByteArray()));

			RegisterUnsafe<Uuid128, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid128, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid128, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid128, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Uuid128, bool>((value) => value != Uuid128.Empty);
			RegisterUnsafe<Guid, System.Net.IPAddress>((value) => new System.Net.IPAddress(value.ToByteArray()));

			RegisterUnsafe<Uuid64, Slice>((value) => value.ToSlice());
			RegisterUnsafe<Uuid64, byte[]>((value) => value.ToByteArray());
			RegisterUnsafe<Uuid64, string>((value) => value.ToString("D", null));
			RegisterUnsafe<Uuid64, long>((value) => value.ToInt64());
			RegisterUnsafe<Uuid64, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Uuid64, bool>((value) => value.ToInt64() != 0L);

			RegisterUnsafe<TimeSpan, Slice>((value) => Slice.FromInt64(value.Ticks));
			RegisterUnsafe<TimeSpan, byte[]>((value) => Slice.FromInt64(value.Ticks).GetBytes());
			RegisterUnsafe<TimeSpan, long>((value) => value.Ticks);
			RegisterUnsafe<TimeSpan, ulong>((value) => checked((ulong)value.Ticks));
			RegisterUnsafe<TimeSpan, double>((value) => value.TotalSeconds);
			RegisterUnsafe<TimeSpan, bool>((value) => value == TimeSpan.Zero);

			RegisterUnsafe<System.Net.IPAddress, Slice>((value) => value != null ? Slice.Create(value.GetAddressBytes()) : Slice.Nil);
			RegisterUnsafe<System.Net.IPAddress, byte[]>((value) => value != null ? value.GetAddressBytes() : null);
			RegisterUnsafe<System.Net.IPAddress, string>((value) => value != null ? value.ToString() : null);

			RegisterUnsafe<FdbTupleAlias, byte>((value) => (byte)value);
			RegisterUnsafe<FdbTupleAlias, int>((value) => (int)value);
			RegisterUnsafe<FdbTupleAlias, Slice>((value) => Slice.FromByte((byte)value));

			//REVIEW: this should go in the Tuples layer !
			RegisterUnsafe<Slice, byte[]>((value) => value.GetBytes());
			RegisterUnsafe<Slice, string>((value) => value.ToUnicode());
			RegisterUnsafe<Slice, bool>((value) => value.ToBool());
			RegisterUnsafe<Slice, sbyte>((value) => value.ToSByte());
			RegisterUnsafe<Slice, byte>((value) => value.ToByte());
			RegisterUnsafe<Slice, short>((value) => value.ToInt16());
			RegisterUnsafe<Slice, ushort>((value) => value.ToUInt16());
			RegisterUnsafe<Slice, int>((value) => value.ToInt32());
			RegisterUnsafe<Slice, uint>((value) => value.ToUInt32());
			RegisterUnsafe<Slice, long>((value) => value.ToInt64());
			RegisterUnsafe<Slice, ulong>((value) => value.ToUInt64());
			RegisterUnsafe<Slice, Guid>((value) => value.ToGuid());
			RegisterUnsafe<Slice, Uuid128>((value) => value.ToUuid128());
			RegisterUnsafe<Slice, Uuid64>((value) => value.ToUuid64());
			RegisterUnsafe<Slice, TimeSpan>((value) => TimeSpan.FromTicks(value.ToInt64()));
			RegisterUnsafe<Slice, FdbTupleAlias>((value) => (FdbTupleAlias)value.ToByte());
			RegisterUnsafe<Slice, System.Net.IPAddress>((value) => !value.IsNullOrEmpty ? new System.Net.IPAddress(value.GetBytes()) : null);
		}

19 View Source File : CancelRegistrationCommandHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<CommandResult> Handle(CancelRegistrationCommand request, CancellationToken cancellationToken)
        {
            var registrationIdGuid = Guid.Parse(request.RegistrationId);

            var authResult = _ownershipAuth.IsAuthorized(or => or.ObjectRegistrationId == registrationIdGuid, or => or.RecipientLogin.User);
            if (!authResult)
            {
                return new ErrorMessage
                {
                    ErrorCode = "TRANSACTION.REGISTRATION.CANCEL.UNAUTHORIZED",
                    Message = "You are not authorized to cancel this registration",
                    StatusCode = System.Net.HttpStatusCode.Unauthorized
                }.ToCommand();
            }

            var registrations = from r in _registrationsRepo.Table
                                where r.ObjectRegistrationId == registrationIdGuid &&
                                r.ObjectReceiving == null &&
                                r.Status == ObjectRegistrationStatus.OK &&
                                r.ExpiresAtUtc > DateTime.UtcNow
                                select r;

            if (!registrations.Any())
            {
                return new ErrorMessage
                {
                    ErrorCode = "TRANSACTION.REGISTRATION.CANCEL.UNAVAILABLE",
                    Message = "You can not cancel this registration",
                    StatusCode = System.Net.HttpStatusCode.Unauthorized
                }.ToCommand();
            }


            var theRegistration = _registrationsRepo.Get(registrationIdGuid);
            theRegistration.Status = ObjectRegistrationStatus.Canceled;
            await _registrationsRepo.SaveChangesAsync();

            _eventBus.Publish(new TransactionCancelledIntegrationEvent
            {
                Id = Guid.NewGuid(),
                OccuredAt = DateTime.UtcNow,
                RegistrationId = theRegistration.ObjectRegistrationId,
                CancelledAtUtc = DateTime.UtcNow,
            });

            return default;
        }

19 View Source File : GenerateReturnTokenCommandHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<CommandResult<GenerateReturnTokenResultDto>> Handle(GenerateReturnTokenCommand request, CancellationToken cancellationToken)
        {
            var guidRegistrationId = Guid.Parse(request.RegistrationId);

            var registration = (from r in _registrationsRepo.Table
                                where r.ObjectRegistrationId == guidRegistrationId
                                select r)
                                .Include($"{nameof(ObjectRegistration.ObjectReceiving)}.{nameof(ObjectRegistration.ObjectReceiving.ObjectReturning)}, {nameof(ObjectRegistration.Object)}", _queryHelper)
                                .FirstOrDefault();

            if (registration is null || registration.Status == ObjectRegistrationStatus.Canceled)
            {
                return new ErrorMessage
                {
                    ErrorCode = "TRANSACTION.TOKEN.GENERATE.RETURN.INVALID.ID",
                    Message = "Please provide valid data",
                    StatusCode = System.Net.HttpStatusCode.BadRequest
                }.ToCommand<GenerateReturnTokenResultDto>();
            }

            if (!_authorizer.IsAuthorized(or => or.ObjectRegistrationId == guidRegistrationId, or => or.RecipientLogin.User))
            {
                new ErrorMessage
                {
                    ErrorCode = "TRANSACTION.TOKEN.GENERATE.RETURN.UNAUTHORIZED",
                    Message = "You are not authorized to execute this request",
                    StatusCode = System.Net.HttpStatusCode.Unauthorized
                }.ToCommand<GenerateReturnTokenResultDto>();
            }

            if (registration.ObjectReceiving is null)
            {
                return new ErrorMessage
                {
                    ErrorCode = "TRANSACTION.TOKEN.GENERATE.RETURN.NOT.RECEIVED",
                    Message = "The object has not been received yet",
                    StatusCode = System.Net.HttpStatusCode.BadRequest
                }.ToCommand<GenerateReturnTokenResultDto>();
            }

            if (registration.ObjectReceiving.ObjectReturning is object)
            {
                return new ErrorMessage
                {
                    ErrorCode = "TRANSACTION.TOKEN.GENERATE.RETURN.ALREADY.RETURNED",
                    Message = "The object has been returned",
                    StatusCode = System.Net.HttpStatusCode.BadRequest
                }.ToCommand<GenerateReturnTokenResultDto>();
            }
            var token = await _tokenManager.GenerateToken(registration.ObjectReceiving.ObjectReceivingId, TokenType.Returning);
            return new CommandResult<GenerateReturnTokenResultDto>(new GenerateReturnTokenResultDto
            {
                CreatedAtUtc = token.IssuedAtUtc,
                UseBeforeUtc = token.UseBeforeUtc,
                ReturnToken = token.Token
            });
        }

19 View Source File : RefreshRegistrationTokenCommandHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<CommandResult<RegistrationTokenResultDto>> Handle(RefreshRegistrationTokenCommand request, CancellationToken cancellationToken)
        {
            var user = _userDataManager.GetCurrentUser();
            if (user == null)
            {
                return new ErrorMessage
                {
                    ErrorCode = "TRANSACTION.REGISTRATION.REFRESH.USER.UNKOWN",
                    Message = "Please login",
                    StatusCode = System.Net.HttpStatusCode.Unauthorized
                }.ToCommand<RegistrationTokenResultDto>();
            }
            var registrations = from r in _registrationsRepo.Table
                                where r.Object.OriginalObjectId == request.ObjectId && r.RecipientLogin.UserId == Guid.Parse(user.UserId) &&
                                r.Status == ObjectRegistrationStatus.OK && r.ExpiresAtUtc > DateTime.UtcNow && r.ObjectReceiving == null
                                select r;

            if (!registrations.Any())
            {
                return new ErrorMessage
                {
                    ErrorCode = "TRANSACTION.REGISTRATION.REFRESH.NOT.VALID",
                    Message = "You have no valid registration",
                    StatusCode = System.Net.HttpStatusCode.BadRequest
                }.ToCommand<RegistrationTokenResultDto>();
            }



            var token = await _tokenManager.GenerateToken(registrations.FirstOrDefault().ObjectRegistrationId, TokenType.Receiving);

            return new CommandResult<RegistrationTokenResultDto>(new RegistrationTokenResultDto
            {
                CreatedAtUtc = token.IssuedAtUtc,
                RegistrationToken = token.Token,
                UseBeforeUtc = token.UseBeforeUtc
            });
        }

19 View Source File : RegistrationQueriesHandler.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<List<RegistrationDto>> Handle(RegisterationForUserQuery request, CancellationToken cancellationToken)
        {
            var user = _userDataManager.GetCurrentUser();
            if (user.UserId is null)
            {
                throw new UnauthorizedAccessException();
            }
            var userId = user.UserId;

            Expression<Func<ObjectRegistration, bool>> typeFilter = null;
            if (request.RegistrationType == RegistrationForUserType.UserAsOwner)
            {
                typeFilter = rg => rg.Object.OwnerUser.UserId == Guid.Parse(userId);
            }
            else if (request.RegistrationType == RegistrationForUserType.UserAsRecipient)
            {
                typeFilter = rg => rg.RecipientLogin.UserId == Guid.Parse(userId);
            }
            else if(request.RegistrationType == RegistrationForUserType.All)
            {
                typeFilter = rg => rg.RecipientLogin.UserId == Guid.Parse(userId) || rg.Object.OwnerUserId == Guid.Parse(userId);
            }

            var registrations = from rg in _registrationsRepo.Table
                                          .Where(typeFilter)
                                let isReceived = rg.ObjectReceiving != null
                                let isReturned = rg.ObjectReceiving != null && rg.ObjectReceiving.ObjectReturning != null
                                orderby rg.RegisteredAtUtc descending
                                select new RegistrationDto
                                {
                                    RegistrationId = rg.ObjectRegistrationId,
                                    ObjectId = rg.Object.OriginalObjectId,
                                    OwnerId = rg.Object.OwnerUserId.ToString(),
                                    ReceiverId = rg.RecipientLogin.UserId.ToString(),
                                    ReceivingId = rg.ObjectReceiving.ObjectReceivingId,
                                    ReturnId = isReturned ? rg.ObjectReceiving.ObjectReturning.ObjectReturningId : (Guid?)null,
                                    RegistredAtUtc = rg.RegisteredAtUtc,
                                    ReceivedAtUtc = isReceived ? rg.ObjectReceiving.ReceivedAtUtc : (DateTime?)null,
                                    ReturenedAtUtc = isReturned ? rg.ObjectReceiving.ObjectReturning.ReturnedAtUtc : (DateTime?)null,
                                    TranscationType = !rg.Object.ShouldReturn ? TransactionType.Free : rg.Object.HourlyCharge.HasValue ? TransactionType.Renting : TransactionType.Lending,
                                    HourlyCharge = rg.Object.HourlyCharge,
                                    ShouldReturnAfter = rg.ShouldReturnItAfter,
                                    TransactionStatus = rg.Status == ObjectRegistrationStatus.Canceled ? TransactionStatus.Canceled :
                                        isReturned ? TransactionStatus.Returned :
                                        isReceived ? TransactionStatus.Received :
                                        TransactionStatus.RegisteredOnly,
                                };

            return await registrations.SkipTakeAsync(_queryHelper, request);
        }

19 View Source File : OwnershipAuthorization.cs
License : MIT License
Project Creator : Abdulrhman5

public bool IsAuthorized(Expression<Func<T, bool>> identifiengEnreplacedyExpression, Expression<Func<T, User>> toUser)
        {
            var currentUser = _userDataManager.GetCurrentUser();
            if (currentUser is null) return false;

            var enreplacedy = _repo.Table.Where(identifiengEnreplacedyExpression).Select(toUser).Where(u => u.UserId == Guid.Parse(currentUser.UserId));
            if (enreplacedy.Any())
            {
                return true;
            }
            return false;
        }

19 View Source File : UserDataManager.cs
License : MIT License
Project Creator : Abdulrhman5

public virtual async Task<(Login, User)> AddUserIfNotExisted(Guid tokenId, string originUserId, string accessToken)
        {

            // if The user existed but the login does not exist
            var login = _loginRepo.Table.Include(login => login.User).SingleOrDefault(t => t.LoginId == tokenId);
            if (login is null)
            {
                // add the login 
                var loginInformation = await _loginInformationGetter.GetLoginInformation(tokenId.ToString());
                var userIdGuid = Guid.Parse(loginInformation.UserId);
                var theUser = _userRepo.Table.SingleOrDefault(u => u.UserId == userIdGuid);
                if (theUser is null)
                {
                    var userToBeAdded = new User
                    {
                        UserId = userIdGuid,
                        Status = UserStatus.Available,
                        UserName = loginInformation.Username,
                        Logins = new List<Login>
                        {
                            new Login
                            {
                                LoggedAt = loginInformation.LoggedAtUtc,
                                LoginId = Guid.Parse(loginInformation.TokenId),
                                LoginLocation = loginInformation.Longitude is null ? null : new Point(loginInformation.Longitude.Value, loginInformation.Lareplacedude.Value){SRID =4326 }
                            }
                        }
                    };

                    _userRepo.Add(userToBeAdded);
                    await _userRepo.SaveChangesAsync();

                    return (userToBeAdded.Logins.FirstOrDefault(), userToBeAdded);
                }
                else
                {
                    var loginToBeAdded = new Login
                    {
                        LoggedAt = loginInformation.LoggedAtUtc,
                        LoginId = Guid.Parse(loginInformation.TokenId),
                        UserId = theUser.UserId,
                        LoginLocation = loginInformation.Longitude is null ? null : new Point(loginInformation.Longitude.Value, loginInformation.Lareplacedude.Value) { SRID = 4326}
                    };

                    _loginRepo.Add(loginToBeAdded);
                    await _loginRepo.SaveChangesAsync();
                    return (loginToBeAdded, theUser);
                }
            }
            else
            {
                return (login, login.User);
            }
        }

19 View Source File : IssuedToken.cs
License : MIT License
Project Creator : actions

internal void GetUserData(IHttpResponse response)
        {
            IEnumerable<string> headerValues;
            if (response.Headers.TryGetValues(HttpHeaders.VssUserData, out headerValues))
            {
                string userData = headerValues.FirstOrDefault();

                if (!string.IsNullOrWhiteSpace(userData))
                {
                    string[] split = userData.Split(':');

                    if (split.Length >= 2)
                    {
                        UserId = Guid.Parse(split[0]);
                        UserName = split[1];
                    }
                }
            }
        }

19 View Source File : GuidComponent.xaml.cs
License : MIT License
Project Creator : ADeltaX

public byte[] GetValueData() 
            => FromGuid(Guid.Parse(guidBox.Text), _timestamp);

19 View Source File : Utils.cs
License : MIT License
Project Creator : adospace

public static object ConvertToSqlType(SyncItemValue value, SqlDbType dbType)
        {
            if (value.Value == null)
                return DBNull.Value;

            if (dbType == SqlDbType.UniqueIdentifier &&
                value.Value is string)
                return Guid.Parse(value.Value.ToString());

            return value.Value;
        }

19 View Source File : ActivityDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private IEnumerable<IAttachment> GetAnnotationsAsAttachmentCollection(EnreplacedyReference regarding, bool respectPermissions = true)
		{
			// Retrieve attachments
			var annotationDataAdapter = new AnnotationDataAdapter(_dependencies);
			var annotationCollection = annotationDataAdapter.GetAnnotations(regarding, respectPermissions: respectPermissions, privacy: AnnotationPrivacy.Any);

			// Filter and project into Attachment object
			return annotationCollection.Where(annotation => EnreplacedyContainsRequiredAnnotationFields(annotation.Enreplacedy.Attributes)).Select(annotation =>
			{
				var enreplacedy = annotation.Enreplacedy;
				var fileName = GetFieldValue(enreplacedy, "filename");
				var fileType = GetFieldValue(enreplacedy, "mimetype");
				ulong fileSize;
				if (!ulong.TryParse(GetFieldValue(enreplacedy, "filesize"), out fileSize))
				{
					fileSize = 0;
				}
				FileSize attachmentSize = new FileSize(fileSize);

				// Create CrmAnnotationFile for URL generation
				var crmAnnotationFile = new CrmAnnotationFile(fileName, fileType, new byte[0]);
				crmAnnotationFile.Annotation = new Enreplacedy("annotation")
				{
					Id = Guid.Parse(GetFieldValue(enreplacedy, "annotationid"))
				};

				var activityAttachment = new Attachment
				{
					AttachmentContentType = fileType,
					AttachmentFileName = fileName,
					AttachmentIsImage = (new List<string> { "image/jpeg", "image/gif", "image/png" }).Contains(fileType),
					AttachmentSize = attachmentSize,
					AttachmentSizeDisplay = attachmentSize.ToString(),
					AttachmentUrl = crmAnnotationFile.Annotation.GetFileAttachmentUrl(_dependencies.GetWebsite())
				};

				return activityAttachment;
			});
		}

19 View Source File : SqliteSyncProvider.cs
License : MIT License
Project Creator : adospace

private async Task InitializeStoreAsync(CancellationToken cancellationToken = default)
        {
            if (_initialized)
                return;

            using (var connection = new SqliteConnection(Configuration.ConnectionString))
            {
                await connection.OpenAsync(cancellationToken);

                using (var cmd = connection.CreateCommand())
                {
                    cmd.CommandText = [email protected]"CREATE TABLE IF NOT EXISTS __CORE_SYNC_CT 
(ID INTEGER PRIMARY KEY, TBL TEXT NOT NULL COLLATE NOCASE, OP CHAR NOT NULL, PK_{SqlitePrimaryColumnType.Int} INTEGER NULL, PK_{SqlitePrimaryColumnType.Text} TEXT NULL COLLATE NOCASE, PK_{SqlitePrimaryColumnType.Blob} BLOB NULL, SRC TEXT NULL COLLATE NOCASE)";
                    await cmd.ExecuteNonQueryAsync(cancellationToken);

                    cmd.CommandText = $"CREATE INDEX IF NOT EXISTS __CORE_SYNC_CT_PK_{SqlitePrimaryColumnType.Int}_INDEX ON __CORE_SYNC_CT(PK_{SqlitePrimaryColumnType.Int})";
                    await cmd.ExecuteNonQueryAsync(cancellationToken);
                    cmd.CommandText = $"CREATE INDEX IF NOT EXISTS __CORE_SYNC_CT_PK_{SqlitePrimaryColumnType.Text}_INDEX ON __CORE_SYNC_CT(PK_{SqlitePrimaryColumnType.Text})";
                    await cmd.ExecuteNonQueryAsync(cancellationToken);
                    cmd.CommandText = $"CREATE INDEX IF NOT EXISTS __CORE_SYNC_CT_PK_{SqlitePrimaryColumnType.Blob}_INDEX ON __CORE_SYNC_CT(PK_{SqlitePrimaryColumnType.Blob})";
                    await cmd.ExecuteNonQueryAsync(cancellationToken);

                    cmd.CommandText = $"CREATE TABLE IF NOT EXISTS __CORE_SYNC_REMOTE_ANCHOR (ID TEXT NOT NULL PRIMARY KEY, LOCAL_VERSION LONG NULL, REMOTE_VERSION LONG NULL)";
                    await cmd.ExecuteNonQueryAsync(cancellationToken);

                    cmd.CommandText = $"CREATE TABLE IF NOT EXISTS __CORE_SYNC_LOCAL_ID (ID TEXT NOT NULL PRIMARY KEY)";
                    await cmd.ExecuteNonQueryAsync(cancellationToken);

                    cmd.CommandText = $"SELECT ID FROM __CORE_SYNC_LOCAL_ID LIMIT 1";
                    var localId = await cmd.ExecuteScalarAsync(cancellationToken);
                    if (localId == null)
                    {
                        localId = Guid.NewGuid().ToString();
                        cmd.CommandText = $"INSERT INTO __CORE_SYNC_LOCAL_ID (ID) VALUES (@localId)";
                        cmd.Parameters.Add(new SqliteParameter("@localId", localId));
                        if (1 != await cmd.ExecuteNonQueryAsync(cancellationToken))
                        {
                            throw new InvalidOperationException();
                        }
                        cmd.Parameters.Clear();
                    }

                    _storeId = Guid.Parse((string)localId);

                    foreach (SqliteSyncTable table in Configuration.Tables)
                    {
                        cmd.CommandText = $"PRAGMA table_info('{table.Name}')";
                        using (var reader = await cmd.ExecuteReaderAsync(cancellationToken))
                        {
                            /*
                            cid         name        type        notnull     dflt_value  pk
                            ----------  ----------  ----------  ----------  ----------  ----------
                            */
                            while (await reader.ReadAsync(cancellationToken))
                            {
                                var colName = reader.GetString(1);
                                var colType = reader.GetString(2);
                                var pk = reader.GetBoolean(5);

                                if (string.CompareOrdinal(colName, "__OP") == 0)
                                {
                                    throw new NotSupportedException($"Unable to synchronize table '{table.Name}': one column has a reserved name '__OP'");
                                }

                                table.Columns.Add(colName, new SqliteColumn(colName, colType, pk));
                            }
                        }

                        if (table.Columns.Count == 0)
                        {
                            throw new InvalidOperationException($"Unable to configure table '{table}': does it exist with at least one column?");
                        }

                        if (table.Columns.Count(_ => _.Value.IsPrimaryKey) == 0)
                        {
                            throw new NotSupportedException($"Unable to configure table '{table}': no primary key defined");
                        }

                        if (table.Columns.Count(_ => _.Value.IsPrimaryKey) > 1)
                        {
                            throw new NotSupportedException($"Unable to configure table '{table}': it has more than one column as primary key");
                        }                        
                    }
                }
            }

            _initialized = true;
        }

19 View Source File : CommerceQuote.cs
License : MIT License
Project Creator : Adoxio

private void CreateQuotePayPal(Dictionary<string, string> values, IPortalContext xrm)
		{
			_context = xrm.ServiceContext;

			if (!values.ContainsKey("invoice"))
			{
				throw new Exception("no invoice found");
			}

			var shoppingCart =
				_context.CreateQuery("adx_shoppingcart").FirstOrDefault(
					q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"]));

			var quote = new Enreplacedy("quote");

			var orderGuid = Guid.NewGuid();

			quote.Attributes["quoteid"] = orderGuid;
			quote.Id = orderGuid;

			quote.Attributes["name"] = "quote created by: " + shoppingCart.GetAttributeValue<string>("adx_name");

			quote.Attributes["adx_shoppingcartid"] = shoppingCart.ToEnreplacedyReference();

			//Ensure that there is a customer
			var customer = GetQuoteCustomer(values, _context, shoppingCart);

			if (!_context.IsAttached(shoppingCart))
			{
				_context.Attach(shoppingCart);
			}

			shoppingCart.Attributes["adx_contactid"] = customer.ToEnreplacedyReference();

			quote.Attributes["customerid"] = customer.ToEnreplacedyReference();

			var priceLevel =
				_context.CreateQuery("pricelevel").FirstOrDefault(pl => pl.GetAttributeValue<string>("name") == "Web");

			if (priceLevel == null)
			{
                throw new Exception("price level null");
			}

			//Set the price level
			var priceLevelReference = priceLevel.ToEnreplacedyReference();

			quote.Attributes["pricelevelid"] = priceLevelReference;

			//Set the address for the order
			SetQuoteAddresses(values, quote, customer);

			//order.Attributes["adx_confirmationnumber"] = shoppingCart.GetAttributeValue<string>("adx_confirmationnumber");
			//order.Attributes["adx_receiptnumber"] = values.ContainsKey("ipn_trac_id") ? values["ipn_track_id"] : null;

			_context.AddObject(quote);

			_context.UpdateObject(shoppingCart);

			_context.SaveChanges();

			//Set the products of the order
			SetQuoteProducts(shoppingCart, _context, orderGuid);


			//Deactivate the shopping Cart
			shoppingCart =
				_context.CreateQuery("adx_shoppingcart").FirstOrDefault(
					q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"]));

			try
			{
				_context.SetState(1, 2, shoppingCart);
				_context.SaveChanges();
			}
			catch
			{
				//Unlikely that there is an issue, most likely it has already been deactiveated.
			}

			Enreplacedy = _context.CreateQuery("quote").FirstOrDefault(o => o.GetAttributeValue<Guid>("quoteid") == orderGuid);
			Id = Enreplacedy.Id;
		}

19 View Source File : CommerceOrder.cs
License : MIT License
Project Creator : Adoxio

private void CreateOrderPayPal(Dictionary<string, string> values, IPortalContext xrm, bool getCreateInvoiceSettingValue)
		{
			System.Diagnostics.Debug.Write("A commerce order is being created...");

			_context = xrm.ServiceContext;

			if (!values.ContainsKey("invoice"))
			{
				throw new Exception("no invoice found");
			}

			var shoppingCart =
				_context.CreateQuery("adx_shoppingcart").FirstOrDefault(
					q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"]));

			var order = new Enreplacedy("salesorder");

			var orderGuid = Guid.NewGuid();

			order.Attributes["salesorderid"] = orderGuid;
			order.Id = orderGuid;

			order.Attributes["name"] = "order created by: " + shoppingCart.GetAttributeValue<string>("adx_name");

			order.Attributes["adx_shoppingcartid"] = shoppingCart.ToEnreplacedyReference();

			System.Diagnostics.Debug.Write(string.Format("shopping cart ID:{0}", shoppingCart.Id.ToString()));

			var supportRequest = _context.CreateQuery("adx_supportrequest")
					.FirstOrDefault(sr => sr.GetAttributeValue<EnreplacedyReference>("adx_shoppingcartid").Id == shoppingCart.Id);
			if (supportRequest != null)
			{
				System.Diagnostics.Debug.Write(string.Format("Support Request ID:{0}", supportRequest.Id.ToString()));

				var supportPlanReference = supportRequest.GetAttributeValue<EnreplacedyReference>("adx_supportplan");

				System.Diagnostics.Debug.Write(string.Format("Support Reference:{0}", supportPlanReference));

				var supportPlan = _context.CreateQuery("adx_supportplan").FirstOrDefault(sc => sc.GetAttributeValue<Guid>("adx_supportplanid")
							== supportPlanReference.Id);

				order.Attributes["adx_supportplanid"] = supportPlan.ToEnreplacedyReference();
			}
			else
			{
				System.Diagnostics.Debug.Write("support request is null");
			}

			//Ensure that there is a customer
			var customer = GetOrderCustomer(values, _context, shoppingCart);

			if (!_context.IsAttached(shoppingCart))
			{
				_context.Attach(shoppingCart);
			}

			shoppingCart.Attributes["adx_contactid"] = customer.ToEnreplacedyReference();

			var parentCustomer = customer.GetAttributeValue<EnreplacedyReference>("parentcustomerid");

			var parentCustomerEnreplacedy =
				_context.CreateQuery("account").FirstOrDefault(pce => pce.GetAttributeValue<Guid>("accountid") == parentCustomer.Id);

			order.Attributes["customerid"] = (parentCustomerEnreplacedy != null) ? parentCustomerEnreplacedy.ToEnreplacedyReference() : customer.ToEnreplacedyReference();

			var priceLevel =
				_context.CreateQuery("pricelevel").FirstOrDefault(pl => pl.GetAttributeValue<string>("name") == "Web");

			if (priceLevel == null)
			{
				throw new Exception("price level null");
			}

			//Set the price level
			var priceLevelReference = priceLevel.ToEnreplacedyReference();

			order.Attributes["pricelevelid"] = priceLevelReference;

			//Set the address for the order
			SetOrderAddresses(values, order, customer);

			//order.Attributes["adx_confirmationnumber"] = shoppingCart.GetAttributeValue<string>("adx_confirmationnumber");
			order.Attributes["adx_receiptnumber"] = values.ContainsKey("ipn_trac_id") ? values["ipn_track_id"] : null;

			_context.AddObject(order);

			_context.UpdateObject(shoppingCart);

			_context.SaveChanges();

			//Set the products of the order
			SetOrderProducts(shoppingCart, _context, orderGuid, null);


			//Time to replacedociate order with support plan

			//sw.WriteLine("ok, we are at the weird part!");


			//Deactivate the shopping Cart
			shoppingCart =
				_context.CreateQuery("adx_shoppingcart").FirstOrDefault(
					q => q.GetAttributeValue<Guid>("adx_shoppingcartid") == Guid.Parse(values["invoice"]));


			try
			{
				_context.SetState(1, 2, shoppingCart);
				_context.SaveChanges();
			}
			catch
			{
				//Unlikely that there is an issue, most likely it has already been deactiveated.
			}

			//At this point we want to Create an Invoice, if that is indeed what we are doing.

			if (getCreateInvoiceSettingValue)
			{
				InvoiceEnreplacedy = CreateInvoiceFromOrder(_context, orderGuid);
			}

			Enreplacedy = _context.CreateQuery("salesorder").FirstOrDefault(o => o.GetAttributeValue<Guid>("salesorderid") == orderGuid);
			Id = Enreplacedy.Id;
		}

19 View Source File : PaypalHelper.cs
License : MIT License
Project Creator : Adoxio

private static bool ItemizedDataVerification(Dictionary<string, string> values, OrganizationServiceContext context)
		{
			System.Diagnostics.Debug.Write("We are performing itemized data verification...");
			//for itemized data
			int count = 1;

			while (values.ContainsKey(string.Format("item_number{0}", count)))
			{
				var guid = Guid.Parse(values[string.Format("item_number{0}", count)]);

				var quanreplacedy = decimal.Parse(values[string.Format("quanreplacedy{0}", count)] ?? "0.0");

				var gross = decimal.Parse(values[string.Format("mc_gross_{0}", count)] ?? "0.0");
				var shipping = decimal.Parse(values[string.Format("mc_shipping{0}", count)] ?? "0.0");
				var handling = decimal.Parse(values[string.Format("mc_handling{0}", count)] ?? "0.0");
				var tax = decimal.Parse(values[string.Format("tax{0}", count)] ?? "0.0");

				var price = gross - shipping - handling - tax;

				var quoteLineItem =
					context.CreateQuery("quotedetail").FirstOrDefault(
						sci => sci.GetAttributeValue<Guid>("quotedetailid") == guid);

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

				var quoteLineItemQuanreplacedy = quoteLineItem.GetAttributeValue<decimal?>("quanreplacedy").GetValueOrDefault(0);
				var quoteLineQuotedPrice = quoteLineItem.GetAttributeValue<Money>("priceperunit") == null ? 0 : quoteLineItem.GetAttributeValue<Money>("priceperunit").Value;

				if ((quoteLineItemQuanreplacedy != quanreplacedy) || (quoteLineQuotedPrice * quoteLineItemQuanreplacedy != price))
				{
					return false;
				}

				count++;
			}
			return true;
		}

19 View Source File : CrmEntityIndexSearcher.cs
License : MIT License
Project Creator : Adoxio

public IEnumerable<EnreplacedyReference> Search(Query query, int maxSearchResults)
		{
			var enreplacedies = new List<EnreplacedyReference>();

			var topDocs = this._searcher.Search(query, maxSearchResults);

			if (topDocs.ScoreDocs.Length < 1)
			{
				return enreplacedies;
			}

			foreach (var indexDoc in topDocs.ScoreDocs)
			{
				var doreplacedent = this._searcher.Doc(indexDoc.Doc);
				var enreplacedy = new EnreplacedyReference();

				var primaryFieldName = doreplacedent.GetField("_logicalname");
				var primaryKeyField = doreplacedent.GetField("_primarykey");

				enreplacedy.Id = Guid.Parse(primaryKeyField.StringValue);
				enreplacedy.LogicalName = primaryFieldName.StringValue;

				enreplacedies.Add(enreplacedy);
			}
			return enreplacedies;
		}

19 View Source File : SearchController.cs
License : MIT License
Project Creator : Adoxio

private JArray GetPartialLocalizedFacetViewJson(FacetView facetView, int initialConstraintsToLocalize, string localizedLabelEnreplacedyName, string localizedLabelField)
		{
			JArray facetViewJson = new JArray();
			ConstraintHit[] constraintHits = facetView.ConstraintHits.ToArray();
			var hitCountsEnabled = FeatureCheckHelper.IsFeatureEnabled(FeatureNames.CmsEnabledSearching);

			// Convert the received GUID strings into enreplacedy references
			IEnumerable<EnreplacedyReference> enreplacedyReferencesToLocalize =
				facetView.ConstraintHits
					.Take(initialConstraintsToLocalize)
					.Select(constraintHit => new EnreplacedyReference(localizedLabelEnreplacedyName, new Guid(constraintHit.ConstraintValue)));
			// Get the localized labels based off the enreplacedy references and the field to localize
			var localizedLabels = MapEnreplacedyReferencesToLocalizedLabels(enreplacedyReferencesToLocalize, localizedLabelField);

			foreach (ConstraintHit constraint in constraintHits)
			{
				string localizedConstraintName;
				localizedLabels.TryGetValue(Guid.Parse(constraint.ConstraintValue), out localizedConstraintName);

				// Set localized labels, keep all not-localized labels empty
				facetViewJson.Add(
					new JObject
						{
							{ "displayName", localizedConstraintName },
							{ "name",  constraint.ConstraintValue },
							{ "hitCount", hitCountsEnabled ? constraint.HitCount.ToString() : string.Empty }
						});
			}
		
			return facetViewJson;
		}

19 View Source File : ForumThread.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void MarkAsAnswer_OnCommand(object sender, CommandEventArgs e)
		{
			var forumPostId = Guid.Parse(e.CommandArgument.ToString());

			var dataAdapter = CreateForumThreadDataAdapter();

			dataAdapter.MarkAsAnswer(forumPostId);

			Response.Redirect(Request.Url.PathAndQuery);
		}

19 View Source File : ForumThread.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void UnmarkAsAnswer_OnCommand(object sender, CommandEventArgs e)
		{
			var forumPostId = Guid.Parse(e.CommandArgument.ToString());

			var dataAdapter = CreateForumThreadDataAdapter();

			dataAdapter.UnMarkAsAnswer(forumPostId);

			Response.Redirect(Request.Url.PathAndQuery);
		}

19 View Source File : ForumThread.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void UpdatePost_OnCommand(object sender, CommandEventArgs e)
		{
			var forumPostId = Guid.Parse(e.CommandArgument.ToString());
			var dataAdapter = CreateForumThreadDataAdapter();
			var forumPost = dataAdapter.SelectPost(forumPostId);

			if (forumPost == null)
			{
				throw new InvalidOperationException("Unable to retrieve the control with ID {0}.".FormatWith(forumPostId));
			}

			if (!forumPost.CanEdit)
			{
				throw new SecurityException("The current user does not have the necessary permissions to update this forum post.");
			}

			var content = ((Control)sender).FindControl("ForumPostContentUpdate") as ITextControl;

			if (content == null)
			{
				throw new InvalidOperationException("Unable to find control ForumPostContentUpdate.");
			}

			dataAdapter.UpdatePost(new HtmlForumPostUpdate(((IForumPostInfo)forumPost).EnreplacedyReference, htmlContent: content.Text));

			Response.Redirect(Request.Url.PathAndQuery);
		}

19 View Source File : PermitApplicationDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			var reference = Enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_enreplacedyform");

			var enreplacedyFormRecord = XrmContext.CreateQuery("adx_enreplacedyform").FirstOrDefault(ef => ef.GetAttributeValue<Guid>("adx_enreplacedyformid") == reference.Id);

			if (enreplacedyFormRecord != null)
			{
				var recordEnreplacedyLogicalName = enreplacedyFormRecord.GetAttributeValue<string>("adx_enreplacedyname");

				Guid recordId;

				if (Guid.TryParse(Request["id"], out recordId))
				{

					var metadataRequest = new RetrieveEnreplacedyRequest
					{
						LogicalName = recordEnreplacedyLogicalName,
						EnreplacedyFilters = EnreplacedyFilters.Attributes
					};

					var metadataResponse = (RetrieveEnreplacedyResponse)XrmContext.Execute(metadataRequest);

					var primaryFieldLogicalName = metadataResponse.EnreplacedyMetadata.PrimaryIdAttribute;

					var permitRecord = XrmContext.CreateQuery(recordEnreplacedyLogicalName).FirstOrDefault(r => r.GetAttributeValue<Guid>(primaryFieldLogicalName) == recordId);

					var permitTypeReference = permitRecord.GetAttributeValue<EnreplacedyReference>("adx_permittype");

					var permitType =
						XrmContext.CreateQuery("adx_permittype").FirstOrDefault(
							srt => srt.GetAttributeValue<Guid>("adx_permittypeid") == permitTypeReference.Id);

					var enreplacedyName = permitType.GetAttributeValue<string>("adx_enreplacedyname");

					RegardingContactFieldName = permitType.GetAttributeValue<string>("adx_regardingcontactfieldname");

					var trueMetadataRequest = new RetrieveEnreplacedyRequest
					{
						LogicalName = enreplacedyName,
						EnreplacedyFilters = EnreplacedyFilters.Attributes
					};

					var trueMetadataResponse = (RetrieveEnreplacedyResponse)XrmContext.Execute(trueMetadataRequest);

					var primaryFieldName = trueMetadataResponse.EnreplacedyMetadata.PrimaryIdAttribute;

					var enreplacedyId = permitRecord.GetAttributeValue<string>("adx_enreplacedyid");

					var trueRecordId = Guid.Parse(enreplacedyId);

					var trueRecord = XrmContext.CreateQuery(enreplacedyName).FirstOrDefault(r => r.GetAttributeValue<Guid>(primaryFieldName) == trueRecordId);

					Permit = trueRecord;

					var permitDataSource = CreateDataSource("PermitDataSource", enreplacedyName, primaryFieldName, trueRecordId);

					var permitFormView = new CrmEnreplacedyFormView() { FormName = "Details Form", Mode = FormViewMode.Edit, EnreplacedyName = enreplacedyName, CssClreplaced = "crmEnreplacedyFormView", AutoGenerateSteps = false };

					var languageCodeSetting = OrganizationServiceContextExtensions.GetSiteSettingValueByName(ServiceContext, Portal.Website, "Language Code");
					if (!string.IsNullOrWhiteSpace(languageCodeSetting))
					{
						int languageCode;
						if (int.TryParse(languageCodeSetting, out languageCode))
						{
							permitFormView.LanguageCode = languageCode;
							permitFormView.ContextName = languageCode.ToString(CultureInfo.InvariantCulture);
							permitDataSource.CrmDataContextName = languageCode.ToString(CultureInfo.InvariantCulture);
						}
					}

					CrmEnreplacedyFormViewPanel.Controls.Add(permitFormView);

					permitFormView.DataSourceID = permitDataSource.ID;

					var regardingContact = Permit.GetAttributeValue<EnreplacedyReference>(RegardingContactFieldName);

					if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id)
					{
						PermitControls.Enabled = false;
						PermitControls.Visible = false;
						AddNoteInline.Visible = false;
						AddNoteInline.Enabled = false;
					}
					else
					{
						var dataAdapterDependencies =
							new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
						var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
						var annotations = dataAdapter.GetAnnotations(Permit.ToEnreplacedyReference(),
							new List<Order> { new Order("createdon") }, respectPermissions: false);

						NotesList.DataSource = annotations;
						NotesList.DataBind();
					}
				}
			}
		}

19 View Source File : ServiceRequestDetails.aspx.cs
License : MIT License
Project Creator : Adoxio

protected void Page_Init(object sender, EventArgs e)
		{
			if (ServiceRequestRollupRecord != null)
			{

				var serviceRequestTypeReference =
					ServiceRequestRollupRecord.GetAttributeValue<EnreplacedyReference>("adx_servicerequesttype");

				var serviceRequestType =
					XrmContext.CreateQuery("adx_servicerequesttype").FirstOrDefault(
						srt => srt.GetAttributeValue<Guid>("adx_servicerequesttypeid") == serviceRequestTypeReference.Id);

				var enreplacedyName = serviceRequestType.GetAttributeValue<string>("adx_enreplacedyname");

				RegardingContactFieldName = serviceRequestType.GetAttributeValue<string>("adx_regardingcontactfieldname");

				var trueMetadataRequest = new RetrieveEnreplacedyRequest
											  {
												  LogicalName = enreplacedyName,
												  EnreplacedyFilters = EnreplacedyFilters.Attributes
											  };

				var trueMetadataResponse = (RetrieveEnreplacedyResponse)XrmContext.Execute(trueMetadataRequest);

				var primaryFieldName = trueMetadataResponse.EnreplacedyMetadata.PrimaryIdAttribute;

				var enreplacedyId = ServiceRequestRollupRecord.GetAttributeValue<string>("adx_enreplacedyid");

				var trueRecordId = Guid.Parse(enreplacedyId);

				var trueRecord =
					XrmContext.CreateQuery(enreplacedyName).FirstOrDefault(r => r.GetAttributeValue<Guid>(primaryFieldName) == trueRecordId);

				ServiceRequest = trueRecord;

				

				var regardingContact = ServiceRequest.GetAttributeValue<EnreplacedyReference>(RegardingContactFieldName);

				if (regardingContact == null || Contact == null || regardingContact.Id != Contact.Id)
				{
					AddANote.Enabled = false;
					AddANote.Visible = false;
					AddNoteInline.Visible = false;
					AddNoteInline.Enabled = false;

					RenderCrmEnreplacedyFormView(enreplacedyName, primaryFieldName, serviceRequestType, trueRecordId, FormViewMode.ReadOnly);

					var dataAdapterDependencies =
						new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
					var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
					var annotations = dataAdapter.GetAnnotations(ServiceRequest.ToEnreplacedyReference(),
						new List<Order> { new Order("createdon") }, respectPermissions: false);

					if (!annotations.Any())
					{
						NotesLabel.Visible = false;
						NotesList.Visible = false;
					}

					NotesList.DataSource = annotations;
					NotesList.DataBind();
				}
				else
				{
					RenderCrmEnreplacedyFormView(enreplacedyName, primaryFieldName, serviceRequestType, trueRecordId, FormViewMode.Edit);

					var dataAdapterDependencies =
						new PortalConfigurationDataAdapterDependencies(requestContext: Request.RequestContext, portalName: PortalName);
					var dataAdapter = new AnnotationDataAdapter(dataAdapterDependencies);
					var annotations = dataAdapter.GetAnnotations(ServiceRequest.ToEnreplacedyReference(),
						new List<Order> { new Order("createdon") },
						privacy: AnnotationPrivacy.Web | AnnotationPrivacy.Private | AnnotationPrivacy.Public, respectPermissions: false);

					NotesList.DataSource = annotations;
					NotesList.DataBind();
				}

				if (Request.IsAuthenticated && Contact != null)
				{
					var dataAdapter = CreateAlertDataAdapter();

					var hasAlert = dataAdapter.HasAlert(Contact.ToEnreplacedyReference());

					AddAlert.Visible = !hasAlert;
					RemoveAlert.Visible = hasAlert;
				}
				else
				{
					AddAlertLoginLink.Visible = true;
				}

				DisplaySlaDetails(serviceRequestType);

			}
		}

19 View Source File : SubmitConverter.cs
License : MIT License
Project Creator : afaniuolo

private void CreateAddressBookSender(Guid destSubmitActionItemId)
		{
			var desreplacedem = _destMasterRepository.GetSitecoreItem(destSubmitActionItemId);
			if (desreplacedem != null &&
			    desreplacedem.Fields.FirstOrDefault(f => f.FieldId == Guid.Parse(SubmitActionConstants.SubmitActionFieldId))?.Value ==
			    SubmitActionConstants.SubmitActionField_SendEmailActionValue)
			{
				var sendEmail = JsonConvert.DeserializeObject<SendEmailAction>(desreplacedem.Fields
					.First(f => f.FieldId == new Guid(SubmitActionConstants.ParametersFieldId)).Value);

				var emailFromValue = sendEmail.from;

				if (!string.IsNullOrEmpty(emailFromValue) && emailFromValue.IndexOf('@') > 0)
				{
					var emailAddressMetadata = _metadataProvider.GereplacedemMetadataByTemplateName("Email Address");
					var senderItems = _destMasterRepository.GetSitecoreDescendantsItems(
						emailAddressMetadata.destTemplateId,
						new Guid(EmailAddressConstants.EmailAddressSendersFolderId));

					
					if (!senderItems.Any(item => item.Fields.FirstOrDefault(f => f.FieldId == Guid.Parse(EmailAddressConstants.EmailAddressValueFieldId)) != null 
					                             && string.Equals(item.Fields.First(f => f.FieldId == Guid.Parse(EmailAddressConstants.EmailAddressValueFieldId)).Value, emailFromValue, StringComparison.InvariantCultureIgnoreCase)))
					{
						var addressSenderItemName = emailFromValue.Substring(0, emailFromValue.IndexOf('@'));

						// Set Email Address item fields
						var addressSenderItemFieldValues = new Dictionary<Guid, string>();
						addressSenderItemFieldValues.Add(new Guid(EmailAddressConstants.EmailAddressValueFieldId),
							emailFromValue); // Value field

						CreateEmailAddressItem("Email Address", addressSenderItemName, addressSenderItemFieldValues);
					}
				}
			}
		}

19 View Source File : SubmitConverter.cs
License : MIT License
Project Creator : afaniuolo

private Guid CreateEmailAddressItem(string metadataTemplateName, string desreplacedemName,
			Dictionary<Guid, string> destFieldValues)
		{
			var metadataTemplate = _metadataProvider.GereplacedemMetadataByTemplateName(metadataTemplateName);

			// Create Email Address Senders Folder (not in SQL anymore) with dummy field
			var addressSendersFolder = new SCItem()
			{
				ID = Guid.Parse(EmailAddressConstants.EmailAddressSendersFolderId),
				Fields = new List<SCField>()
				{
					new SCField()
					{
						Language = "en",
						Version = 1
					}
				}
			};

			

			foreach (var destFieldValue in destFieldValues)
			{
				metadataTemplate.fields.newFields.First(field => field.destFieldId == destFieldValue.Key).value = destFieldValue.Value;
			}

			// Create item
			return WriteNewItem(metadataTemplate.destTemplateId, addressSendersFolder, desreplacedemName, metadataTemplate);
		}

19 View Source File : SubmitConverter.cs
License : MIT License
Project Creator : afaniuolo

private void ConvertSaveActions(SCItem form, string tracking, SCItem buttonItem, bool saveToDatabaseActionCreated)
		{
			var formSaveActionField = form.Fields
				.FirstOrDefault(field => field.FieldId == new Guid(FormConstants.FormSaveActionFieldId));
			var formSaveActions = formSaveActionField?.Value;

			if (!string.IsNullOrEmpty(formSaveActions))
			{
				var saveActionElements = XmlHelper.GetXmlElementNodeList(XmlHelper.GetXmlElementNode(formSaveActions, "g").InnerXml, "li");
				List<SaveAction> saveActionItems = new List<SaveAction>();
				if (saveActionElements != null)
				{
					foreach (XmlNode saveActionElement in saveActionElements)
					{
						if (saveActionElement.Attributes != null)
						{
							var saveAction = new SaveAction()
							{
								Id = saveActionElement.Attributes["id"].Value,
								UnicId = saveActionElement.Attributes["unicid"].Value,
								Parameters = XmlHelper.GetXmlElementValue(saveActionElement.InnerXml, "parameters")
							};
							saveActionItems.Add(saveAction);
						}
					}

					foreach (var saveActionItem in saveActionItems)
					{
						if (saveActionItem.Id == FormConstants.FormSaveAction_RegisterCampaignValue)
						{
							var trackingCampaign = XmlHelper.GetXmlElementNodeList(tracking, "campaign");
							var xmlAttributeCollection = trackingCampaign[0].Attributes;
							if (xmlAttributeCollection != null)
							{
								var trackingCampaignId = trackingCampaign.Count > 0 ? xmlAttributeCollection["id"]?.Value : null;
								if (trackingCampaignId != null)
								{
									if (!_appSettings.enableReferencedItemCheck || _destMasterRepository.ItemExists(new Guid(trackingCampaignId)))
									{
										// Create Trigger Campaign Activity Save Action
										var triggerCampaignActivityValues = new Dictionary<Guid, string>();
										triggerCampaignActivityValues.Add(new Guid(SubmitActionConstants.SubmitActionFieldId),
											SubmitActionConstants.SubmitActionField_TriggerCampaignActivityActionValue);
										triggerCampaignActivityValues.Add(new Guid(SubmitActionConstants.ParametersFieldId),
											string.Format("{{\"referenceId\":\"{0}\"}}", trackingCampaignId));
										ConvertFieldsToSubmitActionItem("Trigger Campaign Activity", triggerCampaignActivityValues, buttonItem);
									}
								}
							}
						}
						else if (!saveToDatabaseActionCreated && saveActionItem.Id == FormConstants.FormSaveAction_SaveToDatabaseValue)
						{
							ConvertSaveDataAction(form, buttonItem);
						}
						else
						{
							// Convert other save actions if mapped in AppSettings.json
							var submitAction =
								_appSettings.submitActions.FirstOrDefault(s => s.sourceSaveActionId == Guid.Parse(saveActionItem.Id));

							if (submitAction != null)
							{
								IFieldConverter converter = IoC.CreateInstance(submitAction.destParametersConverterType);
								var submitActionValues = new Dictionary<Guid, string>();
								submitActionValues.Add(new Guid(SubmitActionConstants.SubmitActionFieldId),
									submitAction.destSubmitActionFieldValue);
								try
								{
									submitActionValues.Add(new Guid(SubmitActionConstants.ParametersFieldId),
										converter.ConvertValue(
											HttpUtility.HtmlDecode((saveActionItem.Parameters.Replace("&", "&")))));
								}
								catch (Exception ex)
								{
									_logger.Log(new LogEntry(LoggingEventType.Error, 
										string.Format("SubmitConverter - Failed to parse Xml value of Parameters field of Submit Action. FormID = {0} - FieldID = {1} - FieldValue = {2}",
											form.ID, formSaveActionField.Id, saveActionItem.Parameters), ex));
								}

								var destSubmitActionItemId = ConvertFieldsToSubmitActionItem(submitAction.destSubmitActionItemName, submitActionValues, buttonItem);

								// Only if Save Action is Send Email
								if (submitAction.sourceSaveActionId == Guid.Parse(FormConstants.FormSaveAction_SendEmailValue))
								{
									CreateAddressBookSender(destSubmitActionItemId);
								}
							}
							else
							{
								_replacedysisReporter.AddUnmappedSaveAction(formSaveActionField, form.ID, Guid.Parse(saveActionItem.Id));
							}
						}
					}
				}
			}
		}

19 View Source File : AnalysisReporter.cs
License : MIT License
Project Creator : afaniuolo

public void AddUnmappedFormFieldItem(Guid itemId, string sourceMappingFieldValue)
		{
			var isNotEmpty = !string.IsNullOrEmpty(sourceMappingFieldValue);

			AddReportingRecord(new ReportingRecord()
			{
				ItemId = itemId.ToString("B").ToUpper(),
				ItemName = _sourceMasterRepository.GetSitecoreItemName(itemId),
				ItemPath = _sourceMasterRepository.GereplacedemPath(itemId),
				ItemTemplateId = _sourceMasterRepository.GereplacedemTemplateId(itemId).ToString("B").ToUpper(),
				ItemTemplateName = _sourceMasterRepository.GetSitecoreItemName(_sourceMasterRepository.GereplacedemTemplateId(itemId)),
				Message = $"Form Field Item Not Mapped - Form Field Type Name = {(isNotEmpty ? _sourceMasterRepository.GetSitecoreItemName(Guid.Parse(sourceMappingFieldValue)) : sourceMappingFieldValue)}"
			});
		}

19 View Source File : SchemeChangeSubscriber.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async Task SubscribeAsync(CancellationToken cancellationToken)
        {
            var connection = _factory.GetConnection(cancellationToken);
            if (connection == null)
            {
                return;
            }

            connection.On<string>(nameof(IProviderHub.ProviderAdded), async scheme =>
            {
                _logger.LogInformation($"SignalR notification received: {nameof(IProviderHub.ProviderAdded)}({scheme})");
                var definition = await _store.FindBySchemeAsync(scheme).ConfigureAwait(false);
                await _manager.AddAsync(definition).ConfigureAwait(false);
            });

            connection.On<string>(nameof(IProviderHub.ProviderRemoved), async scheme =>
            {
                _logger.LogInformation($"SignalR notification received: {nameof(IProviderHub.ProviderRemoved)}({scheme})");
                await _manager.RemoveAsync(scheme).ConfigureAwait(false);
            });

            connection.On<string>(nameof(IProviderHub.ProviderUpdated), async scheme =>
            {
                _logger.LogInformation($"SignalR notification received: {nameof(IProviderHub.ProviderUpdated)}({scheme})");
                var definition = await _store.FindBySchemeAsync(scheme).ConfigureAwait(false);
                await _manager.UpdateAsync(definition).ConfigureAwait(false);
            });

            connection.On<string, string>(nameof(IProviderHub.KeyRevoked), (kind, id) =>
            {
                _logger.LogInformation($"SignalR notification received: {nameof(IProviderHub.KeyRevoked)}({kind}, {id})");
                var keyId = Guid.Parse(id);
                if (kind == nameof(IAuthenticatedEncryptorDescriptor))
                {
                    _dataProtectionKeyManagerWrapper.Manager.RevokeKey(keyId, "Revoked by another instance.");
                    return;
                }

                _signingKeyManagerWrapper.Manager.RevokeKey(keyId, "Revoked by another instance.");
            });

            await _factory.StartConnectionAsync(cancellationToken).ConfigureAwait(false);
        }

19 View Source File : Forwarder.cs
License : Apache License 2.0
Project Creator : airbus-cert

[TestMethod]
        public async Task TestForwardManifest()
        {
            ProviderGuid guid = null;
            replacedert.IsTrue(ProviderGuid.TryParse("Microsoft-Windows-WMI-Activity", out guid));
            var forwarder = Forwarder.Build(guid);

            var writer = new TestWriter();
            writer.OnWrite += async (Dictionary<string, object> eventData) =>
            {
                // Test if correctly parsed
                replacedert.AreEqual(eventData["Commandline"], "cmd.exe");
            };

            await forwarder.Forward(new TestEventRecord
            {
                Id = 23,
                ProviderName = "Microsoft-Windows-WMI-Activity",
                ProviderId = Guid.Parse("1418ef04-b0b4-4623-bf7e-d74ab47bbdaa"),
                Fields = new Dictionary<string, object>
                {
                    {"Commandline" , "cmd.exe" }
                }
            }, writer);
        }

19 View Source File : Forwarder.cs
License : Apache License 2.0
Project Creator : airbus-cert

[TestMethod]
        public async Task TestForwardManifestWithFilterKo()
        {
            ProviderGuid guid = null;
            replacedert.IsTrue(ProviderGuid.TryParse("Microsoft-Windows-WMI-Activity", out guid));
            var forwarder = Forwarder.Build(guid);

            var writer = new TestWriter();
            writer.OnWrite += async (Dictionary<string, object> eventData) =>
            {
                // this code does not be reached
                throw new replacedertFailedException();
            };

            forwarder.AddFilter("Commandline", "toto.exe");

            await forwarder.Forward(new TestEventRecord
            {
                Id = 23,
                ProviderName = "Microsoft-Windows-WMI-Activity",
                ProviderId = Guid.Parse("1418ef04-b0b4-4623-bf7e-d74ab47bbdaa"),
                Fields = new Dictionary<string, object>
                {
                    {"Commandline" , "cmd.exe" }
                }
            }, writer);
        }

See More Examples