System.Text.Encoding.GetBytes(char*, int, byte*, int)

Here are the examples of the csharp api System.Text.Encoding.GetBytes(char*, int, byte*, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5374 Examples 7

19 View Source File : AppManager.cs
License : MIT License
Project Creator : admaiorastudio

private async Task ConnectAsync()
        {
            if (_isConnected)
                return;

            // Emulators loopback addresses
            IPAddress[] loopbackAddresses = new[]
            {
                IPAddress.Parse("127.0.0.1"),
                IPAddress.Parse("10.0.2.2"),
                IPAddress.Parse("10.0.3.2"),
                IPAddress.Parse("169.254.80.80")
            };

            // Check if we are an emulator instance
            List<Task<string>> waitTasks = new List<Task<string>>();
            CancellationTokenSource cts = new CancellationTokenSource();

            // Look for server using localhost (an emulator device)
            foreach (var ipAddress in loopbackAddresses.Take(1))
            {
                waitTasks.Add(Task.Run<string>(
                    async () =>
                    {
                        try
                        {
                            bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
                            if (!isPortOpen)
                                return null;

                            var connection = new HubConnectionBuilder()
                                .WithUrl($"http://{ipAddress.ToString()}:5001/hub")
                                .Build();

                            await connection.StartAsync(cts.Token);
                            if (cts.IsCancellationRequested)
                                return null;

                            _useLocalHost = true;
                            _hubConnection = connection;

                            cts.Cancel();
                            return ipAddress.ToString();
                        }
                        catch (Exception ex)
                        {
                            return null;
                        }

                    }, cts.Token));
            }

            // Look for server using broadcast (a real device)
            waitTasks.Add(Task.Run<string>(
                async () =>
                {
                    // Discover the server
                    using (UdpClient client = new UdpClient())
                    {
                        client.EnableBroadcast = true;

                        byte[] requestData = Encoding.ASCII.GetBytes($"AreYouTheServer?");
                        Task<int> sendTask = client.SendAsync(requestData, requestData.Length, new IPEndPoint(IPAddress.Broadcast, 5002));
                        await Task.WhenAny(new[] { sendTask, Task.Delay(300) });
                        if (sendTask.IsCompleted)
                        {
                            if (cts.IsCancellationRequested)
                                return null;

                            Task<UdpReceiveResult> receiveTask = client.ReceiveAsync();
                            await Task.WhenAny(new[] { receiveTask, Task.Delay(300) });
                            if (receiveTask.IsCompleted)
                            {
                                if (cts.IsCancellationRequested)
                                    return null;

                                UdpReceiveResult serverResponseData = receiveTask.Result;
                                string serverResponse = Encoding.ASCII.GetString(serverResponseData.Buffer);
                                if (serverResponse == "YesIamTheServer!")
                                {
                                    string ipAddress = serverResponseData.RemoteEndPoint.Address.ToString();
                                    _useLocalHost = false;
                                    _hubConnection = null;

                                    cts.Cancel();
                                    return ipAddress.ToString();

                                }
                            }
                        }

                        client.Close();
                    }

                    return null;
                }));

            // Timeout task 
            waitTasks.Add(Task.Run<string>(
                async () =>
                {
                    try
                    {
                        await Task.Delay(5000, cts.Token);
                        cts.Cancel();
                        return null;
                    }
                    catch
                    {
                        return null;
                    }
                }));

            try
            {
                string ipAddress = await WaitForAnyGetHostIpTaskAsync(waitTasks);
                if (ipAddress != null)
                {
                    if (_hubConnection == null)
                    {
                        string port = _useLocalHost ? "5001" : "5002";
                        _hubConnection = new HubConnectionBuilder()
                            .WithUrl($"http://{ipAddress.ToString()}:{port}/hub")
                            .Build();

                        await _hubConnection.StartAsync();
                    }

                    _isConnected = true;
                    _serverAddress = ipAddress;

                    _hubConnection.Closed +=
                        async (error) =>
                        {
                            System.Diagnostics.Debug.WriteLine("Connection with RealXaml has been lost.");                            

                            while(_hubConnection.State == HubConnectionState.Disconnected)
                            {
                                bool isPortOpen = TryPing(ipAddress.ToString(), 5001, 300);
                                if (isPortOpen)
                                {
                                    System.Diagnostics.Debug.WriteLine("Trying to reconnect again...");
                                    await _hubConnection.StartAsync();
                                    if (_hubConnection.State == HubConnectionState.Connected)
                                    {
                                        await Task.Delay(300);
                                        await _hubConnection.SendAsync("NotifyIde", "Connection was lost. Here I'am again.");

                                        System.Diagnostics.Debug.WriteLine($"Successfully restored lost to the RealXaml server.");
                                        break;
                                    }
                                }

                                System.Diagnostics.Debug.WriteLine("Unable to connect. Retrying in 5secs.");
                                await Task.Delay(5000);
                            }
                        };                    

                    _hubConnection.On<string, byte[], bool>("ReloadXaml", 
                        async (pageId, data, refresh) => await WhenReloadXaml(pageId, data, refresh));

                    _hubConnection.On<string, byte[]>("Reloadreplacedembly", 
                        async (replacedemblyName, data) => await WhenReloadreplacedembly(replacedemblyName, data));

                    string clientId = $"RXID-{DateTime.Now.Ticks}";
                    await _hubConnection.SendAsync("RegisterClient", clientId);

                    System.Diagnostics.Debug.WriteLine($"Successfully connected to the RealXaml server.");
                    System.Diagnostics.Debug.WriteLine($"Your client ID is {clientId}");

                    return;
                }
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error while trying to connect to the RealXaml server.");
                System.Diagnostics.Debug.WriteLine(ex);
            }       
        }

19 View Source File : HttpURLConnectionClient.cs
License : MIT License
Project Creator : Adyen

public HttpWebRequest GetHttpWebRequest(string endpoint, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
        {
            //Add default headers
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(endpoint);
            httpWebRequest.Method = "POST";
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add("Accept-Charset", "UTF-8");
            httpWebRequest.Headers.Add("Cache-Control", "no-cache");
            httpWebRequest.UserAgent = $"{config.ApplicationName} {ClientConfig.UserAgentSuffix}{ClientConfig.LibVersion}";
            if (!string.IsNullOrWhiteSpace(requestOptions?.IdempotencyKey))
            {
                httpWebRequest.Headers.Add("Idempotency-Key", requestOptions?.IdempotencyKey);
            }
            //Use one of two authentication method.
            if (isApiKeyRequired || !string.IsNullOrEmpty(config.XApiKey))
            {
                httpWebRequest.Headers.Add("x-api-key", config.XApiKey);
            }
            else if (!string.IsNullOrEmpty(config.Preplacedword))
            {
                var authString = config.Username + ":" + config.Preplacedword;
                var bytes = Encoding.UTF8.GetBytes(authString);
                var credentials = Convert.ToBase64String(bytes);
                httpWebRequest.Headers.Add("Authorization", "Basic " + credentials);
                httpWebRequest.UseDefaultCredentials = true;
            }
            if (config.Proxy != null)
            {
                httpWebRequest.Proxy = config.Proxy;
            }
            httpWebRequest.ServerCertificateValidationCallback = ServerCertificateValidationCallback;
            return httpWebRequest;
        }

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

public static AuthenticationBuilder AddCustomAuthentication(this IServiceCollection builder)
        {
            return builder.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority = "http://localhost:20000";
                options.RequireHttpsMetadata = false;

                options.Audience = "ProfileManagement";
                options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
                {
                    OnChallenge = async cc =>
                    {
                        cc.Response.StatusCode = 401;
                        var message = new ErrorMessage
                        {
                            ErrorCode = "NOT.AUTHORIZED",
                            Message = "You are not authorized to make this request",
                            StatusCode = System.Net.HttpStatusCode.Unauthorized
                        };
                        var serialized = JsonConvert.SerializeObject(message);
                        var asBytes = Encoding.UTF8.GetBytes(serialized);
                        cc.Response.ContentType = "application/json";
                        await cc.Response.Body.WriteAsync(asBytes);
                        cc.HandleResponse();
                    }
                };
            });
        }

19 View Source File : FileLoggerProcessor.cs
License : MIT License
Project Creator : adams85

private async ValueTask WriteEntryAsync(LogFileInfo logFile, FileLogEntry entry, CancellationToken cancellationToken)
        {
            const int checkFileState = 0;
            const int tryOpenFileState = 1;
            const int retryOpenFileState = 2;
            const int writeState = 3;
            const int idleState = 4;

            int state = checkFileState;
            IFileInfo fileInfo = null;
            for (; ; )
                switch (state)
                {
                    case checkFileState:
                        try
                        {
                            if (UpdateFilePath(logFile, entry, cancellationToken) && logFile.IsOpen)
                                logFile.Close();

                            if (!logFile.IsOpen)
                            {
                                // GetFileInfo behavior regarding invalid filenames is inconsistent across .NET runtimes (and operating systems?)
                                // e.g. PhysicalFileProvider returns NotFoundFileInfo in .NET 5 but throws an exception in previous versions on Windows
                                fileInfo = logFile.FileAppender.FileProvider.GetFileInfo(Path.Combine(logFile.BasePath, logFile.CurrentPath));
                                state = tryOpenFileState;
                            }
                            else
                                state = writeState;
                        }
                        catch (Exception ex) when (!(ex is OperationCanceledException))
                        {
                            ReportFailure(logFile, entry, ex);

                            // discarding entry when file path is invalid
                            if (logFile.CurrentPath.IndexOfAny(s_invalidPathChars.Value) >= 0)
                                return;

                            state = idleState;
                        }
                        break;
                    case tryOpenFileState:
                        try
                        {
                            logFile.Open(fileInfo);

                            state = writeState;
                        }
                        catch (Exception ex) when (!(ex is OperationCanceledException))
                        {
                            state = retryOpenFileState;
                        }
                        break;
                    case retryOpenFileState:
                        try
                        {
                            await logFile.FileAppender.EnsureDirAsync(fileInfo, cancellationToken).ConfigureAwait(false);
                            logFile.Open(fileInfo);

                            state = writeState;
                        }
                        catch (Exception ex) when (!(ex is OperationCanceledException))
                        {
                            ReportFailure(logFile, entry, ex);

                            // discarding entry when file path is invalid
                            if (logFile.CurrentPath.IndexOfAny(s_invalidPathChars.Value) >= 0)
                                return;

                            state = idleState;
                        }
                        break;
                    case writeState:
                        try
                        {
                            try
                            {
                                if (logFile.ShouldEnsurePreamble)
                                    await logFile.EnsurePreambleAsync(cancellationToken).ConfigureAwait(false);

                                await logFile.WriteBytesAsync(logFile.Encoding.GetBytes(entry.Text), cancellationToken).ConfigureAwait(false);

                                if (logFile.AccessMode == LogFileAccessMode.KeepOpenAndAutoFlush)
                                    logFile.Flush();
                            }
                            finally
                            {
                                if (logFile.AccessMode == LogFileAccessMode.OpenTemporarily)
                                    logFile.Close();
                            }

                            return;
                        }
                        catch (Exception ex) when (!(ex is OperationCanceledException))
                        {
                            ReportFailure(logFile, entry, ex);

                            state = idleState;
                        }
                        break;
                    case idleState:
                        // discarding failed entry on forced complete
                        if (Context.WriteRetryDelay > TimeSpan.Zero)
                            await Task.Delay(Context.WriteRetryDelay, cancellationToken).ConfigureAwait(false);
                        else
                            cancellationToken.ThrowIfCancellationRequested();

                        state = checkFileState;
                        break;
                }

            void ReportFailure(LogFileInfo logFile, FileLogEntry entry, Exception exception)
            {
                Context.ReportDiagnosticEvent(new FileLoggerDiagnosticEvent.LogEntryWriteFailed(this, logFile, entry, exception));
            }
        }

19 View Source File : XmlPartConverter.cs
License : MIT License
Project Creator : action-bi-toolkit

public Func<Stream> ToPackagePart(XDoreplacedent content)
        {
            if (content == null) return null;
            return () => new MemoryStream(_encoding.GetBytes(content.ToString(SaveOptions.DisableFormatting)));
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

private void WriteStringBytesImpl<T>(string value, SerializationContext context, List<T> referenceTable)
        {
            if (value is T tValue)
            {
                var refIndex = referenceTable.IndexOf(tValue);
                if (refIndex >= 0)
                {
                    var header = (uint)refIndex << 1;
                    WriteU29BytesImpl(header, context);
                    return;
                }
                else
                {
                    var byteCount = (uint)Encoding.UTF8.GetByteCount(value);
                    var header = (byteCount << 1) | 0x01;
                    WriteU29BytesImpl(header, context);
                    var backend = _arrayPool.Rent((int)byteCount);
                    try
                    {
                        Encoding.UTF8.GetBytes(value, backend);
                        context.Buffer.WriteToBuffer(backend.replacedpan(0, (int)byteCount));
                    }
                    finally
                    {
                        _arrayPool.Return(backend);
                    }

                    if (value.Any())
                    {
                        referenceTable.Add(tValue);
                    }
                }
            }
            else
            {
                Contract.replacedert(false);
            }
        }

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

public IAnnotationResult CreateAnnotation(IAnnotation note, IAnnotationSettings settings = null)
		{
			var serviceContext = _dependencies.GetServiceContext();
			var serviceContextForWrite = _dependencies.GetServiceContextForWrite();

			if (settings == null)
			{
				settings = new AnnotationSettings(serviceContext);
			}
			
			var storageAccount = GetStorageAccount(serviceContext);
			if (settings.StorageLocation == StorageLocation.AzureBlobStorage && storageAccount == null)
			{
				settings.StorageLocation = StorageLocation.CrmDoreplacedent;
			}

			AnnotationCreateResult result = null;

			if (settings.RespectPermissions)
			{
				var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
				result = new AnnotationCreateResult(enreplacedyPermissionProvider, serviceContext, note.Regarding);
			}

			// ReSharper disable once PossibleNullReferenceException
			if (!settings.RespectPermissions ||
				(result.PermissionsExist && result.PermissionGranted))
			{
				var enreplacedy = new Enreplacedy("annotation");

				if (note.Owner != null)
				{
					enreplacedy.SetAttributeValue("ownerid", note.Owner);
				}

				enreplacedy.SetAttributeValue("subject", note.Subject);
				enreplacedy.SetAttributeValue("notetext", note.NoteText);
				enreplacedy.SetAttributeValue("objectid", note.Regarding);
				enreplacedy.SetAttributeValue("objecttypecode", note.Regarding.LogicalName);

				if (note.FileAttachment != null)
				{
					var acceptMimeTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptMimeTypes);
					var acceptExtensionTypes = AnnotationDataAdapter.GetAcceptRegex(settings.AcceptExtensionTypes);
					if (!(acceptExtensionTypes.IsMatch(Path.GetExtension(note.FileAttachment.FileName).ToLower()) ||
							acceptMimeTypes.IsMatch(note.FileAttachment.MimeType)))
					{
						throw new AnnotationException(settings.RestrictMimeTypesErrorMessage);
					}

					if (settings.MaxFileSize.HasValue && note.FileAttachment.FileSize > settings.MaxFileSize)
					{
						throw new AnnotationException(settings.MaxFileSizeErrorMessage);
					}

					note.FileAttachment.Annotation = enreplacedy;

					switch (settings.StorageLocation)
					{
					case StorageLocation.CrmDoreplacedent:
						var crmFile = note.FileAttachment as CrmAnnotationFile;
						if (crmFile == null)
						{
							break;
						}

						if (!string.IsNullOrEmpty(settings.RestrictedFileExtensions))
						{
							var blocked = new Regex(@"\.({0})$".FormatWith(settings.RestrictedFileExtensions.Replace(";", "|")));
							if (blocked.IsMatch(crmFile.FileName))
							{
								throw new AnnotationException(settings.RestrictedFileExtensionsErrorMessage);
							}
						}

						enreplacedy.SetAttributeValue("filename", crmFile.FileName);
						enreplacedy.SetAttributeValue("mimetype", crmFile.MimeType);
						enreplacedy.SetAttributeValue("doreplacedentbody", Convert.ToBase64String(crmFile.Doreplacedent));
						break;
					case StorageLocation.AzureBlobStorage:
						enreplacedy.SetAttributeValue("filename", note.FileAttachment.FileName + ".azure.txt");
						enreplacedy.SetAttributeValue("mimetype", "text/plain");
						var fileMetadata = new
						{
							Name = note.FileAttachment.FileName,
							Type = note.FileAttachment.MimeType,
							Size = (ulong)note.FileAttachment.FileSize,
							Url = string.Empty
						};
						enreplacedy.SetAttributeValue("doreplacedentbody",
							Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
						break;
					}
				}

				// Create annotaion but skip cache invalidation.
				var id = (serviceContext as IOrganizationService).ExecuteCreate(enreplacedy, RequestFlag.ByPreplacedCacheInvalidation);

				if (result != null) result.Annotation = note;

				note.AnnotationId = enreplacedy.Id = id;
				note.Enreplacedy = enreplacedy;

				if (note.FileAttachment is AzureAnnotationFile && settings.StorageLocation == StorageLocation.AzureBlobStorage)
				{
					var container = GetBlobContainer(storageAccount, _containerName);

					var azureFile = (AzureAnnotationFile)note.FileAttachment;

					azureFile.BlockBlob = UploadBlob(azureFile, container, note.AnnotationId);

					var fileMetadata = new
					{
						Name = azureFile.FileName,
						Type = azureFile.MimeType,
						Size = (ulong)azureFile.FileSize,
						Url = azureFile.BlockBlob.Uri.AbsoluteUri
					};
					enreplacedy.SetAttributeValue("doreplacedentbody",
						Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
					serviceContextForWrite.UpdateObject(enreplacedy);
					serviceContextForWrite.SaveChanges();

					// NB: This is basically a hack to support replication. Keys are gathered up and stored during replication, and the
					// actual blob replication is handled here.
					var key = note.AnnotationId.ToString("N");
					if (HttpContext.Current.Application.AllKeys.Contains(NoteReplication.BlobReplicationKey))
					{
						var replication =
							HttpContext.Current.Application[NoteReplication.BlobReplicationKey] as Dictionary<string, Tuple<Guid, Guid>[]>;
						if (replication != null && replication.ContainsKey(key))
						{
							CopyBlob(note, replication[key]);
							replication.Remove(key);
						}
					}
				} 
			}

			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
			{
				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "create_note", 1, note.Enreplacedy.ToEnreplacedyReference(), "create");
			}

			return result;
		}

19 View Source File : PlyHandler.cs
License : MIT License
Project Creator : 3DBear

private static PlyResult ParseBinaryLittleEndian(string path, PlyHeader header)
        {
            var headerAsText = header.RawHeader.Aggregate((a, b) => $"{a}\n{b}") + "\n";
            var headerAsBytes = Encoding.ASCII.GetBytes(headerAsText);
            var withoutHeader = File.ReadAllBytes(path).Skip(headerAsBytes.Length).ToArray();
            var colors = new List<Color>();
            var vertices = GetVertices(withoutHeader, header, out colors);
            var triangles = GetTriangles(withoutHeader, header);
            return new PlyResult(vertices, triangles, colors);
        }

19 View Source File : TransactionResultAppService.cs
License : MIT License
Project Creator : AElfProject

private Hash GetHashCombiningTransactionAndStatus(Hash txId,
            TransactionResultStatus executionReturnStatus)
        {
            // combine tx result status
            var rawBytes = txId.ToByteArray().Concat(Encoding.UTF8.GetBytes(executionReturnStatus.ToString()))
                .ToArray();
            return HashHelper.ComputeFrom(rawBytes);
        }

19 View Source File : TLV_030F.cs
License : MIT License
Project Creator : 499116344

public byte[] Get_Tlv(QQUser user)
        {
            var data = new BinaryWriter(new MemoryStream());
            data.BeWrite((ushort) Encoding.UTF8.GetBytes(user.TXProtocol.BufComputerName).Length);
            data.Write(Encoding.UTF8.GetBytes(user.TXProtocol.BufComputerName));
            FillHead(Command);
            FillBody(data.BaseStream.ToBytesArray(), data.BaseStream.Length);
            SetLength();
            return GetBuffer();
        }

19 View Source File : RegisterConfirmation.cshtml.cs
License : MIT License
Project Creator : ADefWebserver

public async Task<IActionResult> OnGetAsync(string email)
        {
            if (email == null)
            {
                return RedirectToPage("/Index");
            }

            var user = await _userManager.FindByEmailAsync(email);
            if (user == null)
            {
                return NotFound($"Unable to load user with email '{email}'.");
            }

            Email = email;
            // Once you add a real email sender, you should remove this code that lets you confirm the account
            DisplayConfirmAccountLink = true;
            if (DisplayConfirmAccountLink)
            {
                var userId = await _userManager.GetUserIdAsync(user);
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                EmailConfirmationUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { area = "Idenreplacedy", userId = userId, code = code },
                    protocol: Request.Scheme);
            }

            return Page();
        }

19 View Source File : DownloadPersonalData.cshtml.cs
License : MIT License
Project Creator : ADefWebserver

public async Task<IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            _logger.LogInformation("User with ID '{UserId}' asked for their personal data.", _userManager.GetUserId(User));

            // Only include personal data for download
            var personalData = new Dictionary<string, string>();
            var personalDataProps = typeof(ApplicationUser).GetProperties().Where(
                            prop => Attribute.IsDefined(prop, typeof(PersonalDataAttribute)));
            foreach (var p in personalDataProps)
            {
                personalData.Add(p.Name, p.GetValue(user)?.ToString() ?? "null");
            }

            Response.Headers.Add("Content-Disposition", "attachment; filename=PersonalData.json");
            return new FileContentResult(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(personalData)), "text/json");
        }

19 View Source File : AuthConfigurer.cs
License : MIT License
Project Creator : 52ABP

public static void Configure(IServiceCollection services, IConfiguration configuration)
        {
            if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"]))
            {
                services.AddAuthentication(options => {
                    options.DefaultAuthenticateScheme = "JwtBearer";
                    options.DefaultChallengeScheme = "JwtBearer";
                }).AddJwtBearer("JwtBearer", options =>
                {
                    options.Audience = configuration["Authentication:JwtBearer:Audience"];

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        // The signing key must match!
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])),

                        // Validate the JWT Issuer (iss) claim
                        ValidateIssuer = true,
                        ValidIssuer = configuration["Authentication:JwtBearer:Issuer"],

                        // Validate the JWT Audience (aud) claim
                        ValidateAudience = true,
                        ValidAudience = configuration["Authentication:JwtBearer:Audience"],

                        // Validate the token expiry
                        ValidateLifetime = true,

                        // If you want to allow a certain amount of clock drift, set that here
                        ClockSkew = TimeSpan.Zero
                    };

                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = QueryStringTokenResolver
                    };
                });
            }
        }

19 View Source File : ViewerServer.cs
License : MIT License
Project Creator : admaiorastudio

public void Start()
        {
            _cts = new CancellationTokenSource();


            Task.Run(() =>
            {
                UdpClient server = new UdpClient(5002);
                byte[] responseData = Encoding.ASCII.GetBytes("YesIamTheServer!");
                while (!_cts.IsCancellationRequested)
                {
                    IPEndPoint clientEp = new IPEndPoint(IPAddress.Any, 0);
                    byte[] clientRequestData = server.Receive(ref clientEp);
                    string clientRequest = Encoding.ASCII.GetString(clientRequestData);

                    if (clientRequest.Contains("AreYouTheServer?"))
                    {                        
                        System.Diagnostics.Debug.WriteLine($"A new peer is connecting @ {clientEp.Address.ToString()}:{clientEp.Port}");
                        server.Send(responseData, responseData.Length, clientEp);
                    }
                }

            }, _cts.Token);
            
            _host = WebHost.CreateDefaultBuilder()
                .UseKestrel()               
                .UseUrls($"http://localhost:5001", $"http://{GetLocalIPAddress()}:5002")
                .UseStartup<Startup>()
                .Build();

            _host.Run();
        }

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

[Fact]
		public void MGet() {
			rds.Set("TestMGet_null1", base.Null);
			rds.Set("TestMGet_string1", base.String);
			rds.Set("TestMGet_bytes1", base.Bytes);
			rds.Set("TestMGet_clreplaced1", base.Clreplaced);
			rds.Set("TestMGet_null2", base.Null);
			rds.Set("TestMGet_string2", base.String);
			rds.Set("TestMGet_bytes2", base.Bytes);
			rds.Set("TestMGet_clreplaced2", base.Clreplaced);
			rds.Set("TestMGet_null3", base.Null);
			rds.Set("TestMGet_string3", base.String);
			rds.Set("TestMGet_bytes3", base.Bytes);
			rds.Set("TestMGet_clreplaced3", base.Clreplaced);

			replacedert.Equal(4, rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1").Length);
			replacedert.Equal("", rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[0]);
			replacedert.Equal(base.String, rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[1]);
			replacedert.Equal(Encoding.UTF8.GetString(base.Bytes), rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[2]);
			replacedert.Equal(base.Clreplaced.ToString(), rds.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[3]);

			replacedert.Equal(4, rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1").Length);
			replacedert.Equal(new byte[0], rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[0]);
			replacedert.Equal(Encoding.UTF8.GetBytes(base.String), rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[1]);
			replacedert.Equal(base.Bytes, rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[2]);
			replacedert.Equal(Encoding.UTF8.GetBytes(base.Clreplaced.ToString()), rds.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_clreplaced1")[3]);

			replacedert.Equal(3, rds.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3").Length);
			replacedert.Equal(base.Clreplaced.ToString(), rds.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[0]?.ToString());
			replacedert.Equal(base.Clreplaced.ToString(), rds.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[1]?.ToString());
			replacedert.Equal(base.Clreplaced.ToString(), rds.MGet<TestClreplaced>("TestMGet_clreplaced1", "TestMGet_clreplaced2", "TestMGet_clreplaced3")[2]?.ToString());
		}

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

private void CopyBlob(IAnnotation note, IEnumerable<Tuple<Guid, Guid>> newNoteInfos)
		{
			var azureBlob = note.FileAttachment as AzureAnnotationFile;

			if (azureBlob == null)
			{
				return;
			}

			var fileName = azureBlob.FileName;
			var fromBlob = azureBlob.BlockBlob;
			if (fromBlob.Exists())
			{
				var context = _dependencies.GetServiceContextForWrite();
				foreach (var newNoteInfo in newNoteInfos)
				{
					var newNoteId = newNoteInfo.Item2;

					var storageAccount = GetStorageAccount(context);
					var container = GetBlobContainer(storageAccount, _containerName);
					var toBlob = container.GetBlockBlobReference("{0:N}/{1}".FormatWith(newNoteId.ToString("N"), fileName));
					toBlob.DeleteIfExists();
					toBlob.StartCopy(fromBlob);
					
					var azureFile = note.FileAttachment as AzureAnnotationFile;

					var enreplacedy = new Enreplacedy("annotation")
					{
						Id = newNoteId
					};

					var fileMetadata = new
					{
						Name = azureFile.FileName,
						Type = azureFile.MimeType,
						Size = (ulong)azureFile.FileSize,
						Url = toBlob.Uri.AbsoluteUri
					};
					enreplacedy.SetAttributeValue("doreplacedentbody",
						Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
					context.Attach(enreplacedy);
					context.SaveChanges();
				}
			}
		}

19 View Source File : SessionClient.cs
License : Apache License 2.0
Project Creator : AantCoder

public bool Connect(string addr, int port = 0)
        {
            ErrorMessage = null;
            if (port == 0) port = DefaultPort;
            try
            {
                IsLogined = false;
                if (Client != null) Client.Dispose();
            }
            catch
            { }

            try
            {
                //Loger.Log("Client Connect1");
                // Generate open-close keys  KClose-KOpen
                //Генерим рандомную пару КЗакр-КОткр
                var crypto = new CryptoProvider();
                if (UseCryptoKeys) crypto.GenerateKeys();

                //Loger.Log("Client Connect2");
                Client = new ConnectClient(addr, port);

                //Loger.Log("Client Connect3");//Строго первый пакет: Передаем серверу КОткр
                if (UseCryptoKeys)
                    Client.SendMessage(Encoding.UTF8.GetBytes(crypto.OpenKey));
                else
                    Client.SendMessage(new byte[1] { 0x00 });

                //Loger.Log("Client Connect4");
                //Строго первый ответ: Передаем клиенту КОткр(Сессия)
                var rc = Client.ReceiveBytes();
                if (UseCryptoKeys)
                    Key = crypto.Decrypt(rc);
                else
                    Key = rc;

                //Loger.Log("Client Connect5");
                //Обмен по протоколу ниже: Передаем серверу Сессия(Логин - Пароль или запрос на создание)

                //Запускаем таймер фоново поддерживающий открытое соединение при простое
                ConnectSaver.AddClient(Client, (cl) =>
                {
                    lock (LockObj)
                    {
                        cl.SendMessage(new byte[1] { 0x00 });
                        cl.ReceiveBytes();
                    }
                });

                return true;
            }
            catch (Exception e)
            {
                ErrorMessage = e.Message
                    + (e.InnerException == null ? "" : " -> " + e.InnerException.Message);
                ExceptionUtil.ExceptionLog(e, "Client");
                return false;
            }
        }

19 View Source File : Startup.cs
License : MIT License
Project Creator : adrianoc

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseWebSockets();
            app.UseCookiePolicy();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
            
            app.Use(async (context, next) =>
            {
                if (context.Request.Path == "/ws")
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        var webSocket = await context.WebSockets.AcceptWebSocketAsync();
                        CecilifyCode(webSocket);
                    }
                    else
                    {
                        context.Response.StatusCode = 400;
                    }
                }
                else
                {
                    await next();
                }

            });

            void CecilifyCode(WebSocket webSocket)
            {
                var buffer = ArrayPool<byte>.Shared.Rent(64 * 1024);
                var memory = new Memory<byte>(buffer);
                var received = webSocket.ReceiveAsync(memory, CancellationToken.None).Result;
                while (received.MessageType != WebSocketMessageType.Close)
                {
                    CecilifierApplication.Count++;
                    var toBeCecilified = JsonSerializer.Deserialize<CecilifierRequest>(memory.Span[0..received.Count]);
                    var bytes = Encoding.UTF8.GetBytes(toBeCecilified.Code);
                    using (var code = new MemoryStream(bytes, 0, bytes.Length))
                    {
                        try
                        {
                            var deployKind = toBeCecilified.WebOptions.DeployKind;
                            var cecilifiedResult = Core.Cecilifier.Process(code, new CecilifierOptions
                            {
                                References = GetTrustedreplacedembliesPath(), 
                                Naming = new DefaultNameStrategy(toBeCecilified.Settings.NamingOptions, toBeCecilified.Settings.ElementKindPrefixes.ToDictionary(entry => entry.ElementKind, entry => entry.Prefix))
                            });
                            
                            SendTextMessageToChat("One more happy user (project)",  $"Total so far: {CecilifierApplication.Count}\n\n***********\n\n```{toBeCecilified.Code}```", "4437377");
                            
                            if (deployKind == 'Z')
                            {
                                var responseData = ZipProject(
                                    ("Program.cs", cecilifiedResult.GeneratedCode.ReadToEnd()),
                                    ("Cecilified.csproj", ProjectContents),
                                    NameAndContentFromResource("Cecilifier.Web.Runtime")
                                );

                                var output = new Span<byte>(buffer);
                                var ret = Base64.EncodeToUtf8(responseData.Span, output, out var bytesConsumed, out var bytesWritten);
                                if (ret == OperationStatus.Done)
                                {
                                    output = output[0..bytesWritten];
                                }

                                var dataToReturn = JsonSerializedBytes(Encoding.UTF8.GetString(output), 'Z', cecilifiedResult);
                                webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
                            }
                            else
                            {
                                var dataToReturn = JsonSerializedBytes(cecilifiedResult.GeneratedCode.ReadToEnd(), 'C', cecilifiedResult);
                                webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
                            }
                        }
                        catch (SyntaxErrorException ex)
                        {
                            var source = ((toBeCecilified.Settings.NamingOptions & NamingOptions.IncludeSourceInErrorReports) == NamingOptions.IncludeSourceInErrorReports) ? toBeCecilified.Code : string.Empty;  
                            SendMessageWithCodeToChat("Syntax Error", ex.Message, "15746887", source);

                            var dataToReturn = Encoding.UTF8.GetBytes($"{{ \"status\" : 1,  \"syntaxError\": \"{HttpUtility.JavaScriptStringEncode(ex.Message)}\"  }}").AsMemory();
                            webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
                        }
                        catch (Exception ex)
                        {
                            SendExceptionToChat(ex, buffer, received.Count);

                            var dataToReturn = Encoding.UTF8.GetBytes($"{{ \"status\" : 2,  \"error\": \"{HttpUtility.JavaScriptStringEncode(ex.ToString())}\"  }}").AsMemory();
                            webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
                        }
                        finally
                        {
                            ArrayPool<byte>.Shared.Return(buffer);
                        }
                    }

                    received = webSocket.ReceiveAsync(memory, CancellationToken.None).Result;
                }
                webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);

                Memory<byte> ZipProject(params (string fileName, string contents)[] sources)
                {
                    /*
                    //TODO: For some reason this code produces an invalid stream. Need to investigate.
                    using var zipStream = new MemoryStream();
                    using var zipFile = new ZipArchive(zipStream, ZipArchiveMode.Create);
                    foreach (var source in sources)
                    {
                        var entry = zipFile.CreateEntry(source.fileName, CompressionLevel.Fastest);
                        using var entryWriter = new StreamWriter(entry.Open());
                        entryWriter.Write(source.contents);
                    }

                    zipStream.Position = 0;
                    Memory<byte> s = zipStream.GetBuffer();
                    Console.WriteLine($"Stream Size = {zipStream.Length}");
                    return s.Slice(0, (int)zipStream.Length);
                    */
                    
                    var tempPath = Path.GetTempPath();
                    var replacedetsPath = Path.Combine(tempPath, "output");
                    if (Directory.Exists(replacedetsPath))
                        Directory.Delete(replacedetsPath, true);
                    
                    Directory.CreateDirectory(replacedetsPath);
                    
                    foreach (var source in sources)
                    {
                        File.WriteAllText(Path.Combine(replacedetsPath, $"{source.fileName}"), source.contents);
                    }
                    
                    var outputZipPath = Path.Combine(tempPath, "Cecilified.zip");
                    if (File.Exists(outputZipPath))
                        File.Delete(outputZipPath);

                    ZipFile.CreateFromDirectory(replacedetsPath, outputZipPath, CompressionLevel.Fastest, false);
                    return File.ReadAllBytes(outputZipPath);
                }
            }
            
            IReadOnlyList<string> GetTrustedreplacedembliesPath()
            {
                return ((string) AppContext.GetData("TRUSTED_PLATFORM_replacedEMBLIES")).Split(Path.PathSeparator).ToList();
            }
        }

19 View Source File : StringInputDataSource.cs
License : MIT License
Project Creator : 1996v

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public unsafe UInt64BytesISegment GetCurrentSegmentFromMap2StringKey()
        {
            if (!curIsMapKey)
            {
                BssomSerializationOperationException.InputTypeAndDataIsInconsistent(GetCurrentSegmentString(), "Map");
            }

            byte[] buffer = GetBuffer(UTF8Encoding.UTF8.GetMaxByteCount(mapKeyLength));
            fixed (char* pChar = _str) fixed (byte* pByte = &buffer[0])
            {
                int length = UTF8Encoding.UTF8.GetBytes(pChar + mapKeyIndex, mapKeyLength, pByte, buffer.Length);
                return new UInt64BytesISegment(buffer, length);
            }
        }

19 View Source File : CryptoHelperTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public void Decrypt_Message_Test()
        {
            var alice = CryptoHelper.GenerateKeyPair();
            var bob = CryptoHelper.GenerateKeyPair();
            var sam = CryptoHelper.GenerateKeyPair();

            // Alice want to transmit plain text "aelf" to Bob.

            var plainText = Encoding.UTF8.GetBytes(HashHelper.ComputeFrom("hash").ToHex());
            var cipherText = CryptoHelper.EncryptMessage(alice.PrivateKey, bob.PublicKey, plainText);

            // Bob decrypt the message.
            var decrypt = CryptoHelper.DecryptMessage(alice.PublicKey, bob.PrivateKey, cipherText);
            replacedert.True(decrypt.BytesEqual(plainText));

            // Sam can't decrypt this message.
            var func = new Func<byte[]>(() => CryptoHelper.DecryptMessage(alice.PublicKey, sam.PrivateKey,
                cipherText));
            replacedert.Throws<VirgilCryptoException>(func);
        }

19 View Source File : PlayerCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[CommandHandler("reportbug", AccessLevel.Player, CommandHandlerFlag.RequiresWorld, 2,
            "Generate a Bug Report",
            "<category> <description>\n" +
            "This command generates a URL for you to copy and paste into your web browser to submit for review by server operators and developers.\n" +
            "Category can be the following:\n" +
            "Creature\n" +
            "NPC\n" +
            "Item\n" +
            "Quest\n" +
            "Recipe\n" +
            "Landblock\n" +
            "Mechanic\n" +
            "Code\n" +
            "Other\n" +
            "For the first three options, the bug report will include identifiers for what you currently have selected/targeted.\n" +
            "After category, please include a brief description of the issue, which you can further detail in the report on the website.\n" +
            "Examples:\n" +
            "/reportbug creature Drudge Prowler is over powered\n" +
            "/reportbug npc Ulgrim doesn't know what to do with Sake\n" +
            "/reportbug quest I can't enter the portal to the Lost City of Frore\n" +
            "/reportbug recipe I cannot combine Bundle of Arrowheads with Bundle of Arrowshafts\n" +
            "/reportbug code I was killed by a Non-Player Killer\n"
            )]
        public static void HandleReportbug(Session session, params string[] parameters)
        {
            if (!PropertyManager.GetBool("reportbug_enabled").Item)
            {
                session.Network.EnqueueSend(new GameMessageSystemChat("The command \"reportbug\" is not currently enabled on this server.", ChatMessageType.Broadcast));
                return;
            }

            var category = parameters[0];
            var description = "";

            for (var i = 1; i < parameters.Length; i++)
                description += parameters[i] + " ";

            description.Trim();

            switch (category.ToLower())
            {
                case "creature":
                case "npc":
                case "quest":
                case "item":
                case "recipe":
                case "landblock":
                case "mechanic":
                case "code":
                case "other":
                    break;
                default:
                    category = "Other";
                    break;
            }

            var sn = ConfigManager.Config.Server.WorldName;
            var c = session.Player.Name;

            var st = "ACE";

            //var versions = ServerBuildInfo.GetVersionInfo();
            var databaseVersion = DatabaseManager.World.GetVersion();
            var sv = ServerBuildInfo.FullVersion;
            var pv = databaseVersion.PatchVersion;

            //var ct = PropertyManager.GetString("reportbug_content_type").Item;
            var cg = category.ToLower();

            var w = "";
            var g = "";

            if (cg == "creature" || cg == "npc"|| cg == "item" || cg == "item")
            {
                var objectId = new ObjectGuid();
                if (session.Player.HealthQueryTarget.HasValue || session.Player.ManaQueryTarget.HasValue || session.Player.CurrentAppraisalTarget.HasValue)
                {
                    if (session.Player.HealthQueryTarget.HasValue)
                        objectId = new ObjectGuid((uint)session.Player.HealthQueryTarget);
                    else if (session.Player.ManaQueryTarget.HasValue)
                        objectId = new ObjectGuid((uint)session.Player.ManaQueryTarget);
                    else
                        objectId = new ObjectGuid((uint)session.Player.CurrentAppraisalTarget);

                    //var wo = session.Player.CurrentLandblock?.GetObject(objectId);

                    var wo = session.Player.FindObject(objectId.Full, Player.SearchLocations.Everywhere);

                    if (wo != null)
                    {
                        w = $"{wo.WeenieClreplacedId}";
                        g = $"0x{wo.Guid:X8}";
                    }
                }
            }

            var l = session.Player.Location.ToLOCString();

            var issue = description;

            var urlbase = $"https://www.accpp.net/bug?";

            var url = urlbase;
            if (sn.Length > 0)
                url += $"sn={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sn))}";
            if (c.Length > 0)
                url += $"&c={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(c))}";
            if (st.Length > 0)
                url += $"&st={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(st))}";
            if (sv.Length > 0)
                url += $"&sv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sv))}";
            if (pv.Length > 0)
                url += $"&pv={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(pv))}";
            //if (ct.Length > 0)
            //    url += $"&ct={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(ct))}";
            if (cg.Length > 0)
            {
                if (cg == "npc")
                    cg = cg.ToUpper();
                else
                    cg = char.ToUpper(cg[0]) + cg.Substring(1);
                url += $"&cg={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(cg))}";
            }
            if (w.Length > 0)
                url += $"&w={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(w))}";
            if (g.Length > 0)
                url += $"&g={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(g))}";
            if (l.Length > 0)
                url += $"&l={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(l))}";
            if (issue.Length > 0)
                url += $"&i={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(issue))}";

            var msg = "\n\n\n\n";
            msg += "Bug Report - Copy and Paste the following URL into your browser to submit a bug report\n";
            msg += "-=-\n";
            msg += $"{url}\n";
            msg += "-=-\n";
            msg += "\n\n\n\n";

            session.Network.EnqueueSend(new GameMessageSystemChat(msg, ChatMessageType.AdminTell));
        }

19 View Source File : JsonPartConverter.cs
License : MIT License
Project Creator : action-bi-toolkit

public Func<Stream> ToPackagePart(JObject content)
        {
            if (content == null) return null;
            return () => new MemoryStream(_encoding.GetBytes(content.ToString(Formatting.None)));
        }

19 View Source File : BssomBinaryPrimitives.cs
License : MIT License
Project Creator : 1996v

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public static unsafe void WriteString(IBssomBufferWriter writer, string value)
        {
            DEBUG.replacedert(value != null);

            int maxSize = UTF8Encoding.UTF8.GetMaxByteCount(value.Length);
            long pos = writer.Position;
            WriteFixNumber(writer, (uint)maxSize);

            if (!writer.CanGetSizeRefForProvidePerformanceInTryWrite(maxSize))
            {
                WriteStringWithNotPredictingLength(writer, value, pos);
                return;
            }

            int count = 0;
            ref byte refb = ref writer.GetRef(maxSize);
            fixed (char* pValue = value)
            fixed (byte* pRefb = &refb)
            {
                count = UTF8Encoding.UTF8.GetBytes(pValue, value.Length, pRefb, maxSize);
            }
            writer.Seek(pos, BssomSeekOrgin.Begin);
            WriteBackFixNumber(writer, (uint)count);
            writer.Advance(count);
        }

19 View Source File : GrandIdApiClient.cs
License : MIT License
Project Creator : ActiveLogin

private static string? GetBase64EncodedString(string? value)
        {
            if (value == null)
            {
                return null;
            }

            return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static List<byte[]> WriteSnippet(TextSnippet snippet, int length)
        {
            // TODO: 富文本支持
            var ret = new List<byte[]>();
            var bw = new BinaryWriter(new MemoryStream());
            switch (snippet.Type)
            {
                case MessageType.Normal:
                {
                    if (length + 6 >= 699) // 数字应该稍大点,但是我不清楚具体是多少
                    {
                        length = 0;
                        ret.Add(new byte[0]);
                    }

                    bw.BaseStream.Position = 6;
                    foreach (var chr in snippet.Content)
                    {
                        var bytes = Encoding.UTF8.GetBytes(chr.ToString());
                        // 705 = 699 + 6个byte: (byte + short + byte + short)
                        if (length + bw.BaseStream.Length + bytes.Length > 705)
                        {
                            var pos = bw.BaseStream.Position;
                            bw.BaseStream.Position = 0;
                            bw.Write(new byte[]
                            {
                                0x01
                            });
                            bw.BeWrite((ushort) (pos - 3)); // 本来是+3和0的,但是提前预留了6个byte给它们,所以变成了-3和-6。下同理。
                            bw.Write(new byte[]
                            {
                                0x01
                            });
                            bw.BeWrite((ushort) (pos - 6));
                            bw.BaseStream.Position = pos;
                            ret.Add(bw.BaseStream.ToBytesArray());
                            bw = new BinaryWriter(new MemoryStream());
                            bw.BaseStream.Position = 6;
                            length = 0;
                        }

                        bw.Write(bytes);
                    }

                    // 在最后一段的开头补充结构 
                    {
                        var pos = bw.BaseStream.Position;
                        bw.BaseStream.Position = 0;
                        bw.Write(new byte[]
                        {
                            0x01
                        });
                        bw.BeWrite((ushort) (pos - 3));
                        bw.Write(new byte[]
                        {
                            0x01
                        });
                        bw.BeWrite((ushort) (pos - 6));
                        bw.BaseStream.Position = pos;
                    }
                    break;
                }
                case MessageType.At:
                    break;
                case MessageType.Emoji:
                {
                    if (length + 12 > 699)
                    {
                        ret.Add(new byte[0]);
                    }

                    var faceIndex = Convert.ToByte(snippet.Content);
                    if (faceIndex > 199)
                    {
                        faceIndex = 0;
                    }

                    bw.Write(new byte[]
                    {
                        0x02,
                        0x00,
                        0x14,
                        0x01,
                        0x00,
                        0x01
                    });
                    bw.Write(faceIndex);
                    bw.Write(new byte[]
                    {
                        0xFF,
                        0x00,
                        0x02,
                        0x14
                    });
                    bw.Write((byte) (faceIndex + 65));
                    bw.Write(new byte[]
                    {
                        0x0B,
                        0x00,
                        0x08,
                        0x00,
                        0x01,
                        0x00,
                        0x04,
                        0x52,
                        0xCC,
                        0x85,
                        0x50
                    });
                    break;
                }
                case MessageType.Picture:
                    break;
                case MessageType.Xml:
                    break;
                case MessageType.Json:
                    break;
                case MessageType.Shake:
                    break;
                case MessageType.Audio:
                    break;
                case MessageType.Video:
                    break;
                case MessageType.ExitGroup:
                    break;
                case MessageType.GetGroupImformation:
                    break;
                case MessageType.AddGroup:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            if (bw.BaseStream.Position != 0)
            {
                ret.Add(bw.BaseStream.ToBytesArray());
            }

            return ret;
        }

19 View Source File : Register.cshtml.cs
License : MIT License
Project Creator : ADefWebserver

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            var GeneralSettings = await _generalSettingsService.GetGeneralSettingsAsync();

            if (GeneralSettings.AllowRegistration)
            {
                returnUrl = returnUrl ?? Url.Content("~/");
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
                if (ModelState.IsValid)
                {
                    var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, NewsletterSubscriber = true };
                    var result = await _userManager.CreateAsync(user, Input.Preplacedword);
                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with preplacedword.");

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Idenreplacedy", userId = user.Id, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                            $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        if (GeneralSettings.VerifiedRegistration)
                        {
                            return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
                        }
                        else
                        {
                            // Set confirm Email for user
                            user.EmailConfirmed = true;
                            await _userManager.UpdateAsync(user);

                            // Log user in
                            await _signInManager.SignInAsync(user, isPersistent: false);
                            return LocalRedirect(returnUrl);
                        }
                    }
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Registration Not Allowed in Administration Settings");
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }

19 View Source File : ForgotPassword.cshtml.cs
License : MIT License
Project Creator : ADefWebserver

public async Task<IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);
                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return RedirectToPage("./ForgotPreplacedwordConfirmation");
                }

                // For more information on how to enable account confirmation and preplacedword reset please 
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePreplacedwordResetTokenAsync(user);
                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/Account/ResetPreplacedword",
                    pageHandler: null,
                    values: new { area = "Idenreplacedy", code },
                    protocol: Request.Scheme);

                await _emailSender.SendEmailAsync(
                    Input.Email,
                    "Reset Preplacedword",
                    $"Please reset your preplacedword by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                return RedirectToPage("./ForgotPreplacedwordConfirmation");
            }

            return Page();
        }

19 View Source File : BookListWebCoreModule.cs
License : MIT License
Project Creator : 52ABP

private void ConfigureTokenAuth()
        {
            IocManager.Register<TokenAuthConfiguration>();
            var tokenAuthConfig = IocManager.Resolve<TokenAuthConfiguration>();

            tokenAuthConfig.SecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appConfiguration["Authentication:JwtBearer:SecurityKey"]));
            tokenAuthConfig.Issuer = _appConfiguration["Authentication:JwtBearer:Issuer"];
            tokenAuthConfig.Audience = _appConfiguration["Authentication:JwtBearer:Audience"];
            tokenAuthConfig.SigningCredentials = new SigningCredentials(tokenAuthConfig.SecurityKey, SecurityAlgorithms.HmacSha256);
            tokenAuthConfig.Expiration = TimeSpan.FromDays(1);
        }

19 View Source File : VimeoVideoIdExtension.cs
License : MIT License
Project Creator : adamfisher

public object ProvideValue(IServiceProvider serviceProvider)
        {
            try
            {
                Debug.WriteLine($"Acquiring Vimeo stream source URL from VideoId='{VideoId}'...");
                var videoInfoUrl = $"https://player.vimeo.com/video/{VideoId}/config";

                using (var client = new HttpClient())
                {
                    var videoPageContent = client.GetStringAsync(videoInfoUrl).Result;
                    var videoPageBytes = Encoding.UTF8.GetBytes(videoPageContent);

                    using (var stream = new MemoryStream(videoPageBytes))
                    {
                        var serializer = new DataContractJsonSerializer(typeof(VimeoVideo));
                        var metaData = (VimeoVideo)serializer.ReadObject(stream);
                        var files = metaData.request.files.progressive;

                        // Exact match
                        var url = files.OrderByDescending(s => s.width).Select(s => s.url).FirstOrDefault();

                        Debug.WriteLine($"Stream URL: {url}");
                        return VideoSource.FromUri(url);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error occured while attempting to convert Vimeo video ID into a remote stream path.");
                Debug.WriteLine(ex);
            }

            return null;
        }

19 View Source File : MyStringExtendTest.cs
License : MIT License
Project Creator : 1996v

public unsafe void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, string value)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            int valueUtf8Size = context.ContextDataSlots.PopMyStringSize();

            writer.WriteBuildInType(BssomType.StringCode);
            writer.WriteVariableNumber(valueUtf8Size);

            ref byte refb = ref writer.BufferWriter.GetRef(valueUtf8Size);
            fixed (char* pValue = value)
            fixed (byte* pRefb = &refb)
            {
                UTF8Encoding.UTF8.GetBytes(pValue, value.Length, pRefb, valueUtf8Size);
            }
            writer.BufferWriter.Advance(valueUtf8Size);
        }

19 View Source File : AppManager.cs
License : MIT License
Project Creator : admaiorastudio

private byte[] CompressXaml(string xaml)
        {
            return CompressData(Encoding.ASCII.GetBytes(xaml));
        }

19 View Source File : TelloUdpClient.cs
License : MIT License
Project Creator : 8bitbytes

public SdkWrapper.SdkReponses SendMessage(actions.Action action)
        {
            if(action.Type == actions.Action.ActionTypes.CommandMode && _commandMode)
            {
                return SdkWrapper.SdkReponses.OK;
            }
            if (_client == null)
            {
                return SdkWrapper.SdkReponses.FAIL;
            }
            _client.Connect(_endpoint);
            var data = Encoding.ASCII.GetBytes(action.Command);
            _client.Send(data, data.Length);
            _client.Client.ReceiveTimeout = 2500;
            var receiveBytes = _client.Receive(ref _remoteIpEndPoint);
            _serverReponse = Encoding.ASCII.GetString(receiveBytes);

            if(action.Type == actions.Action.ActionTypes.Read)
            {
                return _serverReponse == "FAIL" ? SdkWrapper.SdkReponses.FAIL
                                                : SdkWrapper.SdkReponses.OK;
            }
            if(action.Type == actions.Action.ActionTypes.CommandMode && _serverReponse == "OK")
            {
                _commandMode = true;
            }
            return _serverReponse == "OK" ? SdkWrapper.SdkReponses.OK
                                          : SdkWrapper.SdkReponses.FAIL;
        }

19 View Source File : UpdateManager.cs
License : MIT License
Project Creator : admaiorastudio

private byte[] CompressXaml(string xaml)
        {            
            return CompressData(Encoding.ASCII.GetBytes(xaml));
        }

19 View Source File : StringInputDataSource.cs
License : MIT License
Project Creator : 1996v

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public unsafe Raw64BytesISegment GetCurrentSegmentFromMap1StringKey()
        {
            if (!curIsMapKey)
            {
                BssomSerializationOperationException.InputTypeAndDataIsInconsistent(GetCurrentSegmentString(), "Map");
            }

            byte[] buffer = GetBuffer(UTF8Encoding.UTF8.GetMaxByteCount(mapKeyLength));
            fixed (char* pChar = _str) fixed (byte* pByte = &buffer[0])
            {
                int length = UTF8Encoding.UTF8.GetBytes(pChar + mapKeyIndex, mapKeyLength, pByte, buffer.Length);
                return new Raw64BytesISegment(buffer, length);
            }
        }

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

public IAnnotationResult UpdateAnnotation(IAnnotation note, IAnnotationSettings settings = null)
		{
			var serviceContext = _dependencies.GetServiceContext();
			var serviceContextForWrite = _dependencies.GetServiceContextForWrite();

			if (settings == null)
			{
				settings = new AnnotationSettings(serviceContext);
			}
			
			var storageAccount = GetStorageAccount(serviceContext);
			if (settings.StorageLocation == StorageLocation.AzureBlobStorage && storageAccount == null)
			{
				settings.StorageLocation = StorageLocation.CrmDoreplacedent;
			}

			AnnotationUpdateResult result = null;

			if (settings.RespectPermissions)
			{
				var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
				result = new AnnotationUpdateResult(note, enreplacedyPermissionProvider, serviceContext);
			}

			var isPostedByCurrentUser = false;
			var noteContact = AnnotationHelper.GetNoteContact(note.Enreplacedy.GetAttributeValue<string>("subject"));
			var currentUser = _dependencies.GetPortalUser();
			if (noteContact != null && currentUser != null && currentUser.LogicalName == "contact" &&
				currentUser.Id == noteContact.Id)
			{
				isPostedByCurrentUser = true;
			}

			// ReSharper disable once PossibleNullReferenceException
			if (!settings.RespectPermissions || (result.PermissionsExist && result.PermissionGranted && isPostedByCurrentUser))
			{
				var enreplacedy = new Enreplacedy("annotation")
				{
					Id = note.AnnotationId
				};

				enreplacedy.SetAttributeValue("notetext", note.NoteText);
				enreplacedy.SetAttributeValue("subject", note.Subject);
				enreplacedy.SetAttributeValue("isdoreplacedent", note.FileAttachment != null);
				
				if (note.FileAttachment != null)
				{
					var accept = GetAcceptRegex(settings.AcceptMimeTypes);
					if (!accept.IsMatch(note.FileAttachment.MimeType))
					{
						throw new AnnotationException(settings.RestrictMimeTypesErrorMessage);
					}

					if (settings.MaxFileSize.HasValue && note.FileAttachment.FileSize > settings.MaxFileSize)
					{
						throw new AnnotationException(settings.MaxFileSizeErrorMessage);
					}

					note.FileAttachment.Annotation = enreplacedy;
					
					switch (settings.StorageLocation)
					{
					case StorageLocation.CrmDoreplacedent:
						var crmFile = note.FileAttachment as CrmAnnotationFile;
						if (crmFile == null || crmFile.Doreplacedent == null || crmFile.Doreplacedent.Length == 0)
						{
							break;
						}

						if (!string.IsNullOrEmpty(settings.RestrictedFileExtensions))
						{
							var blocked = new Regex(@"\.({0})$".FormatWith(settings.RestrictedFileExtensions.Replace(";", "|")));
							if (blocked.IsMatch(crmFile.FileName))
							{
								throw new AnnotationException(settings.RestrictedFileExtensionsErrorMessage);
							}
						}

						enreplacedy.SetAttributeValue("filename", crmFile.FileName);
						enreplacedy.SetAttributeValue("mimetype", crmFile.MimeType);
						enreplacedy.SetAttributeValue("doreplacedentbody", Convert.ToBase64String(crmFile.Doreplacedent));
						break;
					case StorageLocation.AzureBlobStorage:
						enreplacedy.SetAttributeValue("filename", note.FileAttachment.FileName + ".azure.txt");
						enreplacedy.SetAttributeValue("mimetype", "text/plain");
						var fileMetadata = new
						{
							Name = note.FileAttachment.FileName,
							Type = note.FileAttachment.MimeType,
							Size = (ulong)note.FileAttachment.FileSize,
							Url = string.Empty
						};
						enreplacedy.SetAttributeValue("doreplacedentbody",
							Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
						break;
					}
				}

				serviceContextForWrite.Attach(enreplacedy);
				serviceContextForWrite.UpdateObject(enreplacedy);
				serviceContextForWrite.SaveChanges();

				if (note.FileAttachment is AzureAnnotationFile && settings.StorageLocation == StorageLocation.AzureBlobStorage)
				{
					var azureFile = note.FileAttachment as AzureAnnotationFile;

					if (azureFile.GetFileStream() != null)
					{
						var container = GetBlobContainer(storageAccount, _containerName);

						var oldName = note.Enreplacedy.GetAttributeValue<string>("filename");
						var oldBlob = container.GetBlockBlobReference("{0:N}/{1}".FormatWith(enreplacedy.Id.ToString(), oldName));
						oldBlob.DeleteIfExists();

						azureFile.BlockBlob = UploadBlob(azureFile, container, note.AnnotationId);

						var fileMetadata = new
						{
							Name = azureFile.FileName,
							Type = azureFile.MimeType,
							Size = (ulong)azureFile.FileSize,
							Url = azureFile.BlockBlob.Uri.AbsoluteUri
						};
						enreplacedy.SetAttributeValue("doreplacedentbody",
							Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fileMetadata, Formatting.Indented))));
						serviceContextForWrite.UpdateObject(enreplacedy);
						serviceContextForWrite.SaveChanges();
					}
				}
			}

			if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
			{
				PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "edit_note", 1, new EnreplacedyReference("annotation", note.AnnotationId), "edit");
			}

			return result;
		}

19 View Source File : Amf0Writer.cs
License : MIT License
Project Creator : a1q123456

private void WriteStringBytesImpl(string str, SerializationContext context, out bool isLongString, bool marker = false, bool forceLongString = false)
        {
            var bytesNeed = 0;
            var headerLength = 0;
            var bodyLength = 0;

            bodyLength = Encoding.UTF8.GetByteCount(str);
            bytesNeed += bodyLength;

            if (bodyLength > ushort.MaxValue || forceLongString)
            {
                headerLength = Amf0CommonValues.LONG_STRING_HEADER_LENGTH;
                isLongString = true;
                if (marker)
                {
                    context.Buffer.WriteToBuffer((byte)Amf0Type.LongString);
                }

            }
            else
            {
                isLongString = false;
                headerLength = Amf0CommonValues.STRING_HEADER_LENGTH;
                if (marker)
                {
                    context.Buffer.WriteToBuffer((byte)Amf0Type.String);
                }
            }
            bytesNeed += headerLength;
            var bufferBackend = _arrayPool.Rent(bytesNeed);
            try
            {
                var buffer = bufferBackend.replacedpan(0, bytesNeed);
                if (isLongString)
                {
                    NetworkBitConverter.TryGetBytes((uint)bodyLength, buffer);
                }
                else
                {
                    var contractRet = NetworkBitConverter.TryGetBytes((ushort)bodyLength, buffer);
                    Contract.replacedert(contractRet);
                }

                Encoding.UTF8.GetBytes(str, buffer.Slice(headerLength));

                context.Buffer.WriteToBuffer(buffer);
            }
            finally
            {
                _arrayPool.Return(bufferBackend);
            }

        }

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

private void Save(string folderPath, CacheItemTelemetry telemetry)
		{
			if (telemetry.Request != null)
			{
				var request = CrmJsonConvert.SerializeObject(telemetry.Request);
				var key = request.GetHashCode();
				var filename = string.Format(this.Settings.FilenameFormat, key);
				var fullPath = Path.Combine(folderPath, filename);
				var bytes = MachineKey.Protect(Encoding.UTF8.GetBytes(request), this.Settings.GetType().ToString());

				ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Writing: " + fullPath);

				this.Settings.AppDataRetryPolicy.WriteAllBytes(fullPath, bytes);
			}
		}

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

void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			var files = Directory.GetFiles(templateDirectory);
			foreach (var file in files) {
				var fi = new FileInfo(file);
				if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
					var outputExtension = "." + fi.Name.Split('.')[1];
					if (fi.Name.StartsWith("for-table.")) {
						foreach (var table in tables) {
							var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
							if (result.EndsWith("return;")) continue;
							var outputName = table.Name + outputExtension;
							var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
							if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
							var outputStream = Encoding.UTF8.GetBytes(result);
							var fullname = outputDirectory + "/" + outputName;
							if (File.Exists(fullname)) File.Delete(fullname);
							using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
								outfs.Write(outputStream, 0, outputStream.Length);
								outfs.Close();
							}
						}
						continue;
					} else {
						var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
						var outputName = fi.Name;
						var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
						if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
						var outputStream = Encoding.UTF8.GetBytes(result);
						var fullname = outputDirectory + "/" + outputName;
						if (File.Exists(fullname)) File.Delete(fullname);
						using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
							outfs.Write(outputStream, 0, outputStream.Length);
							outfs.Close();
						}
					}
				}
				File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
			}
			var dirs = Directory.GetDirectories(templateDirectory);
			foreach(var dir in dirs) {
				BuildEachDirectory(dir, outputDirectory +  dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
			}
		}

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

public override void Render(Context context, TextWriter result)
		{
			var html = context.Registers["htmlHelper"] as HtmlHelper;

			if (html == null)
			{
				return;
			}

			var source = NodeList.Cast<string>().Aggregate(new StringBuilder(), (sb, token) => sb.Append(token));
			var viewSupportsDonuts = context.ViewSupportsDonuts();

			context.Stack(() =>
			{
				// If donuts are supported then call the LiquidSubsreplacedution action, otherwise render the liquid code directly.
				if (viewSupportsDonuts)
				{
					var encodedSource = Convert.ToBase64String(Encoding.UTF8.GetBytes(source.ToString()));
					result.Write(html.Action("LiquidSubsreplacedution", "Layout", new { encodedSource }, viewSupportsDonuts));
				}
				else
				{
					html.RenderLiquid(source.ToString(), "Subsreplacedution string, but donuts not supported", result);
				}
			});
		}

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

public void Publish(IntegrationEvent @event)
        {
            if (!_persistentConnection.IsConnected)
            {
                _persistentConnection.TryConnect();
            }

            var policy = RetryPolicy.Handle<BrokerUnreachableException>()
                .Or<SocketException>()
                .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
                {
                    _logger.LogWarning(ex, "Could not publish event: {EventId} after {Timeout}s ({ExceptionMessage})", @event.Id, $"{time.TotalSeconds:n1}", ex.Message);
                });

            var eventName = @event.GetType().Name;

            _logger.LogTrace("Creating RabbitMQ channel to publish event: {EventId} ({EventName})", @event.Id, eventName);

            using (var channel = _persistentConnection.CreateModel())
            {

                _logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id);

                channel.ExchangeDeclare(exchange: BROKER_NAME, type: "direct");

                var message = JsonConvert.SerializeObject(@event);
                var body = Encoding.UTF8.GetBytes(message);

                policy.Execute(() =>
                {
                    var properties = channel.CreateBasicProperties();
                    properties.DeliveryMode = 2; // persistent

                    _logger.LogTrace("Publishing event to RabbitMQ: {EventId}, Body: {body}", @event.Id, body);

                    channel.BasicPublish(
                        exchange: BROKER_NAME,
                        routingKey: eventName,
                        mandatory: true,
                        basicProperties: properties,
                        body: body);
                });
            }
        }

19 View Source File : JsonBase64Converter.cs
License : MIT License
Project Creator : Adyen

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var json = JsonConvert.SerializeObject(value, Formatting.None,
                            new JsonSerializerSettings
                            {
                                NullValueHandling = NullValueHandling.Ignore
                            });

            writer.WriteValue(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(json)));
        }

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

public static MkhAuthBuilder UseJwt(this MkhAuthBuilder builder, Action<JwtBearerOptions> configure = null)
    {
        var services = builder.Services;

        //添加Jwt配置项
        var jwtOptions = builder.Configuration.Get<JwtOptions>("Mkh:Auth:Jwt");
        services.AddSingleton(jwtOptions);

        //添加凭证构造器
        services.AddScoped<ICredentialBuilder, JwtCredentialBuilder>();

        //添加身份认证服务
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                //配置令牌验证参数
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ClockSkew = TimeSpan.Zero,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions!.Key)),
                    ValidIssuer = jwtOptions.Issuer,
                    ValidAudience = jwtOptions.Audience
                };

                //自定义配置
                configure?.Invoke(options);
            });


        return builder;
    }

19 View Source File : IRCompiler.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

byte[] ReadDataContent(Node node) {
			var content = node[1];
			if (content.Id == (int)IRConstants.DATA_STRING) {
				var str = ((Token)content[0]).Image;
				return Encoding.UTF8.GetBytes(str.Substring(1, str.Length - 2));
			}
			if (content.Id == (int)IRConstants.DATA_BUFFER) {
				var bytes = new List<byte>();
				for (int i = 0; i < content.Count; i++) {
					if (content[i].Id == (int)IRConstants.NUM)
						bytes.Add(ParseByte((Token)content[i]));
				}
				return bytes.ToArray();
			}
			Debug.replacedert(false);
			return null;
		}

19 View Source File : Register.cshtml.cs
License : Apache License 2.0
Project Creator : acblog

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (_options.DisableRegisterNewUser)
            {
                ModelState.AddModelError(string.Empty, "Registering new user is disabled.");
            }
            else if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Preplacedword);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with preplacedword.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Idenreplacedy", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return RedirectToPage("RegisterConfirmation", new { email = Input.Email });
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        return LocalRedirect(returnUrl);
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }

19 View Source File : CredSSP.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

private static byte[] WriteTSCredentials()
        {
            RdpPacket packet = new RdpPacket();
            ASN1.WriteTag(packet, ASN1.SequenceTag(0), "SEQ_TSCRED");
            ASN1.WriteTag(packet, ASN1.ContextTag(0), "CTX_credType");
            ASN1.WriteInteger(packet, 1);
            ASN1.CloseTag(packet, "CTX_credType");
            ASN1.WriteTag(packet, ASN1.ContextTag(1), "CTX_credentials");
            ASN1.WriteTag(packet, ASN1.OctetStringTag(), "CTX_OctetString");
            ASN1.WriteTag(packet, ASN1.SequenceTag(0), "SEQ_Credentials");
            ASN1.WriteTag(packet, ASN1.ContextTag(0), "CTX_domain");
            ASN1.WriteTag(packet, ASN1.OctetStringTag(), "OctectString");
            byte[] bytes = Encoding.Unicode.GetBytes(Options.Domain);
            packet.Write(bytes, 0, bytes.Length);
            ASN1.CloseTag(packet, "OctectString");
            ASN1.CloseTag(packet, "CTX_domain");
            ASN1.WriteTag(packet, ASN1.ContextTag(1), "CTX_user");
            ASN1.WriteTag(packet, ASN1.OctetStringTag(), "OctectString");
            byte[] buffer = Encoding.Unicode.GetBytes(Options.Username);
            packet.Write(buffer, 0, buffer.Length);
            ASN1.CloseTag(packet, "OctectString");
            ASN1.CloseTag(packet, "CTX_user");
            ASN1.WriteTag(packet, ASN1.ContextTag(2), "CTX_preplacedword");
            ASN1.WriteTag(packet, ASN1.OctetStringTag(), "OctectString");
            byte[] buffer3 = Encoding.Unicode.GetBytes(Options.Preplacedword);
            packet.Write(buffer3, 0, buffer3.Length);
            ASN1.CloseTag(packet, "OctectString");
            ASN1.CloseTag(packet, "CTX_preplacedword");
            ASN1.CloseTag(packet, "SEQ_Credentials");
            ASN1.CloseTag(packet, "CTX_OctetString");
            ASN1.CloseTag(packet, "CTX_credentials");
            ASN1.CloseTag(packet, "SEQ_TSCRED");
            byte[] buffer4 = new byte[packet.Length];
            packet.Position = 0L;
            packet.Read(buffer4, 0, buffer4.Length);

            return m_NTLMAuthenticate.EncryptMessage(buffer4);
        }

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 : BssomBinaryPrimitives.cs
License : MIT License
Project Creator : 1996v

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static unsafe void WriteStringWithNotPredictingLength(IBssomBufferWriter writer, string value, long writeBackExactStringCountQuanreplacedyPos)
        {
            DEBUG.replacedert(value != null);

            int len = UTF8Encoding.UTF8.GetByteCount(value);
            writer.Seek(writeBackExactStringCountQuanreplacedyPos, BssomSeekOrgin.Begin);//Simulate StringSize, consistent with WriteString behavior
            WriteBackFixNumber(writer, (uint)len);
            ref byte refb = ref writer.GetRef(len);
            fixed (char* pValue = value)
            fixed (byte* pRefb = &refb)
            {
                UTF8Encoding.UTF8.GetBytes(pValue, value.Length, pRefb, len);
            }
            writer.Advance(len);
        }

19 View Source File : CosmosItem.cs
License : MIT License
Project Creator : 1iveowl

public virtual async Task<Stream> ToStream(string parreplacedionKeyHeader, string parreplacedionKey, CancellationToken ct = default)
        {
            // Using NewtonSoft Json.NET here to utilize the ContractResolver option.
            var customJsonSerializer = new JsonSerializerSettings
            {
                ContractResolver = new ParreplacedionKeyContractResolver<T>(parreplacedionKeyHeader, nameof(REPLACE_WITH_PARreplacedION_KEY_HEADER))
            };

            REPLACE_WITH_PARreplacedION_KEY_HEADER = parreplacedionKey;

            var cosmosItemJson = JsonConvert.SerializeObject(this, Formatting.None, customJsonSerializer);

            await _memoryStream.WriteAsync(Encoding.UTF8.GetBytes(cosmosItemJson), ct);

            return _memoryStream;
        }

19 View Source File : Send_0x0002.cs
License : MIT License
Project Creator : 499116344

protected override void PutBody()
        {
            var dateTime = Util.GetTimeSeconds(DateTime.Now);
            var group = ConvertQQGroupId(_group);
            switch (Message.Snippets[0].Type)
            {
                case MessageType.At:
                case MessageType.Normal:
                case MessageType.Emoji:
                {
                    BodyWriter.Write((byte) 0x2A);
                    BodyWriter.BeWrite(group);
                    BodyWriter.BeWrite((ushort) (_data.Length + 50)); // 字符串长度 + 56,但是_data里面包含了和长度有关的额外六个byte
                    BodyWriter.Write(new byte[]
                    {
                        0x00, 0x01, _packetCount, _packetIndex, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4D, 0x53,
                        0x47, 0x00,
                        0x00, 0x00, 0x00, 0x00
                    });
                    BodyWriter.BeWrite(dateTime);
                    BodyWriter.Write(Util.RandomKey(4));
                    BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x86, 0x00 });
                    BodyWriter.Write(new byte[] { 0x00, 0x0C });
                    BodyWriter.Write(new byte[]
                        { 0xE5, 0xBE, 0xAE, 0xE8, 0xBD, 0xAF, 0xE9, 0x9B, 0x85, 0xE9, 0xBB, 0x91 });
                    BodyWriter.Write(new byte[] { 0x00, 0x00 });
                    BodyWriter.Write(_data);
                    break;
                }
                case MessageType.Xml:
                {
                    BodyWriter.Write((byte) 0x2A);
                    BodyWriter.BeWrite(group);
                    var compressMsg = GZipByteArray.CompressBytes(Message.Snippets[0].Content);
                    BodyWriter.BeWrite((ushort) (compressMsg.Length + 64));
                    BodyWriter.Write(new byte[]
                    {
                        0x00, 0x01, _packetCount, _packetIndex, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4D, 0x53,
                        0x47, 0x00,
                        0x00, 0x00, 0x00, 0x00
                    });
                    BodyWriter.BeWrite(dateTime);
                    BodyWriter.Write(SendXml(compressMsg));
                    break;
                }
                case MessageType.Picture:
                {
                    HttpUpLoadGroupImg(_group, User.Ukey, Message.Snippets[0].Content);
                    BodyWriter.Write((byte) 0x2A);
                    BodyWriter.BeWrite(group);
                    var guid = Encoding.UTF8.GetBytes(Util.GetMD5ToGuidHashFromFile(Message.Snippets[0].Content));
                    BodyWriter.Write(new byte[]
                    {
                        0x00, 0x01, _packetCount, _packetIndex, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4D, 0x53,
                        0x47, 0x00,
                        0x00, 0x00, 0x00, 0x00
                    });
                    BodyWriter.BeWrite(dateTime);
                    BodyWriter.Write(Util.RandomKey(4));
                    BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x86, 0x00 });
                    BodyWriter.Write(new byte[]
                        { 0xE5, 0xBE, 0xAE, 0xE8, 0xBD, 0xAF, 0xE9, 0x9B, 0x85, 0xE9, 0xBB, 0x91 });
                    BodyWriter.Write(new byte[] { 0x00, 0x00, 0x03, 0x00, 0xCB, 0x02 });
                    BodyWriter.Write(new byte[] { 0x00, 0x2A });
                    BodyWriter.Write(guid);
                    BodyWriter.Write(new byte[] { 0x04, 0x00, 0x04 });
                    BodyWriter.Write(new byte[]
                    {
                        0x9B, 0x53, 0xB0, 0x08, 0x05, 0x00, 0x04, 0xD9, 0x8A, 0x5A, 0x70, 0x06, 0x00,
                        0x04, 0x00, 0x00, 0x00, 0x50, 0x07, 0x00, 0x01, 0x43, 0x08, 0x00, 0x00, 0x09, 0x00, 0x01,
                        0x01,
                        0x0B,
                        0x00, 0x00, 0x14, 0x00, 0x04, 0x11, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x00, 0x02,
                        0xBC,
                        0x16,
                        0x00, 0x04, 0x00, 0x00, 0x02, 0xBC, 0x18, 0x00, 0x04, 0x00, 0x00, 0x7D, 0x5E, 0xFF, 0x00,
                        0x5C,
                        0x15,
                        0x36, 0x20, 0x39, 0x32, 0x6B, 0x41, 0x31, 0x43, 0x39, 0x62, 0x35, 0x33, 0x62, 0x30, 0x30,
                        0x38,
                        0x64,
                        0x39, 0x38, 0x61, 0x35, 0x61, 0x37, 0x30
                    });
                    BodyWriter.Write(new byte[]
                    {
                        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x35, 0x30, 0x20, 0x20, 0x20, 0x20, 0x20,
                        0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20
                    });
                    BodyWriter.Write(guid);
                    BodyWriter.Write(0x41);
                    break;
                }
                case MessageType.AddGroup:
                {
                    BodyWriter.Write(new byte[] { 0x08 });
                    BodyWriter.BeWrite(group);
                    BodyWriter.Write(new byte[] { 0x01 });
                    BodyWriter.BeWrite((ushort) User.AddFriend0020Value.Length);
                    BodyWriter.Write(User.AddFriend0020Value);
                    BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00 });
                    //备注信息
                    var messageData = Encoding.UTF8.GetBytes(Message.Snippets[0].Content);
                    Writer.BeWrite((ushort) messageData.Length);
                    Writer.Write(messageData);
                    BodyWriter.Write(new byte[] { 0x01, 0x00, 0x01, 0x00, 0x04, 0x00, 0x01, 0x00, 0x09 });
                    break;
                }
                case MessageType.GetGroupImformation:
                {
                    BodyWriter.Write(new byte[] { 0x72 });
                    BodyWriter.BeWrite(group);
                    break;
                }
                case MessageType.ExitGroup:
                {
                    BodyWriter.Write(new byte[] { 0x09 });
                    BodyWriter.BeWrite(group);
                    break;
                }
                default:
                {
                    throw new NotImplementedException();
                }
            }
        }

19 View Source File : Login.cshtml.cs
License : MIT License
Project Creator : ADefWebserver

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable preplacedword failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PreplacedwordSignInAsync(Input.Email, Input.Preplacedword, Input.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                if (result.IsNotAllowed)
                {
                    _logger.LogWarning("User account IsNotAllowed.");
                    var user = await _userManager.FindByEmailAsync(Input.Email);
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Idenreplacedy", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    return RedirectToPage("RegisterConfirmation", new { email = Input.Email }); 
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }

See More Examples