Here are the examples of the csharp api System.Guid.Parse(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2207 Examples
19
Source : InstanceMockSI.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public Task<Instance> UpdateProcess(Instance instance)
{
ProcessState process = instance.Process;
string app = instance.AppId.Split("/")[1];
Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]);
string instancePath = GetInstancePath(app, instance.Org, int.Parse(instance.InstanceOwner.PartyId), instanceGuid);
if (File.Exists(instancePath))
{
string content = File.ReadAllText(instancePath);
Instance storedInstance = (Instance)JsonConvert.DeserializeObject(content, typeof(Instance));
// Archiving instance if process was ended
if (storedInstance?.Process?.Ended == null && process.Ended != null)
{
storedInstance.Status ??= new InstanceStatus();
storedInstance.Status.Archived = process.Ended;
}
storedInstance.Process = process;
storedInstance.LastChanged = DateTime.UtcNow;
File.WriteAllText(instancePath, JsonConvert.SerializeObject(storedInstance));
return Task.FromResult(storedInstance);
}
return Task.FromResult<Instance>(null);
}
19
Source : InstanceRepositoryMock.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private static void PostProcess(Instance instance)
{
Guid instanceGuid = Guid.Parse(instance.Id);
string instanceId = $"{instance.InstanceOwner.PartyId}/{instance.Id}";
instance.Id = instanceId;
if (instance.Data != null && instance.Data.Any())
{
SetReadStatus(instance);
}
(string lastChangedBy, DateTime? lastChanged) = InstanceHelper.FindLastChanged(instance);
instance.LastChanged = lastChanged;
instance.LastChangedBy = lastChangedBy;
}
19
Source : InstanceRepository.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private async Task PostProcess(Instance instance)
{
Guid instanceGuid = Guid.Parse(instance.Id);
string instanceId = $"{instance.InstanceOwner.PartyId}/{instance.Id}";
instance.Id = instanceId;
instance.Data = await _dataRepository.ReadAll(instanceGuid);
if (instance.Data != null && instance.Data.Any())
{
SetReadStatus(instance);
}
(string lastChangedBy, DateTime? lastChanged) = InstanceHelper.FindLastChanged(instance);
instance.LastChanged = lastChanged;
instance.LastChangedBy = lastChangedBy;
}
19
Source : AuthorizationHelper.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public async Task<bool> AuthorizeInstanceAction(ClaimsPrincipal user, Instance instance, string action)
{
string org = instance.Org;
string app = instance.AppId.Split('/')[1];
int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId);
XacmlJsonRequestRoot request;
if (instance.Id == null)
{
request = DecisionHelper.CreateDecisionRequest(org, app, user, action, instanceOwnerPartyId, null);
}
else
{
Guid instanceGuid = Guid.Parse(instance.Id.Split('/')[1]);
request = DecisionHelper.CreateDecisionRequest(org, app, user, action, instanceOwnerPartyId, instanceGuid);
}
XacmlJsonResponse response = await _pdp.GetDecisionForRequest(request);
if (response?.Response == null)
{
_logger.LogInformation($"// Authorization Helper // Authorize instance action failed for request: {JsonConvert.SerializeObject(request)}.");
return false;
}
bool authorized = DecisionHelper.ValidatePdpDecision(response.Response, user);
return authorized;
}
19
Source : InstanceRepository.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private async Task PostProcess(Instance instance)
{
Guid instanceGuid = Guid.Parse(instance.Id);
string instanceId = $"{instance.InstanceOwner.PartyId}/{instance.Id}";
instance.Id = instanceId;
instance.Data = await _dataRepository.ReadAll(instanceGuid);
if (instance.Data != null && instance.Data.Any())
{
SetReadStatus(instance);
}
(string lastChangedBy, DateTime? lastChanged) = InstanceHelper.FindLastChanged(instance);
instance.LastChanged = lastChanged;
instance.LastChangedBy = lastChangedBy;
}
19
Source : AddBookCommandHandler.cs
with MIT License
from andresantarosa
with MIT License
from andresantarosa
public async Task<AddBookCommandResponseViewModel> Handle(AddBookCommand request, CancellationToken cancellationToken)
{
AddBookCommandResponseViewModel result = new AddBookCommandResponseViewModel();
if (!request.ValidateAuthorGuid())
return result;
Author author = await _authorRepository.GetAuthorById(Guid.Parse(request.AuthorId));
if (!request.ValidateAuthorNotNul(author))
return result;
Book book = new Book(Guid.NewGuid(), request.replacedle, request.ReleaseYear, request.Edition, request.ISBN, author);
if (!book.Validate())
return result;
await _bookRepository.AddBook(book);
result.BookId = book.BookId;
result.replacedle = book.replacedle;
result.ReleaseYear = book.ReleaseYear;
result.Edition = book.Edition;
result.ISBN = book.ISBN;
result.AuthorName = book.Author.Name;
return result;
}
19
Source : RequestLoanCommandHandler.cs
with MIT License
from andresantarosa
with MIT License
from andresantarosa
public async Task<RequestLoanCommandResponseViewModel> Handle(RequestLoanCommand request, CancellationToken cancellationToken)
{
RequestLoanCommandResponseViewModel response = new RequestLoanCommandResponseViewModel();
if (!request.ValidateBookGuid())
return response;
Person person = await _personRepository.GetByDoreplacedent(request.PersonDoreplacedent,true);
if (!request.ValidatePersonNotNul(person))
return response;
Book book = await _bookRepository.GetById(Guid.Parse(request.BookId));
if (!request.ValidateBookNotNul(book))
return response;
BookLoan bookLoan = new BookLoan(Guid.NewGuid(), book, person);
if (!bookLoan.Validate())
return response;
if (!bookLoan.LendBook())
return response;
await _bookLoanRepository.Add(bookLoan);
response.LoanId = bookLoan.BookLoanId;
response.ExpectedReturnDate = bookLoan.ExpectedReturnDate;
LoanEffetivatedEvent loanEvent = new LoanEffetivatedEvent(person.Name, person.PhoneNumbers?.FirstOrDefault()?.PhoneNumber, book.replacedle, "", bookLoan.ExpectedReturnDate);
_eventDispatcher.AddAfterCommitEvent(loanEvent);
return response;
}
19
Source : Worker.cs
with MIT License
from AndrewBabbitt97
with MIT License
from AndrewBabbitt97
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Delay(1000, stoppingToken);
_logger.LogInformation(new EventId(0, "Logging"), "Initializing Aura Connect...");
await Task.Delay(1000, stoppingToken);
_rgbKit.Initialize();
_api.Init(Guid.Parse("e6bef332-95b8-76ec-a6d0-9f402bad244c"));
foreach (var deviceProvider in _rgbKit.DeviceProviders)
{
foreach (var device in deviceProvider.Devices)
{
_logger.LogInformation(new EventId(0, "Logging"), $"Found Device: {deviceProvider.Name} - {device.Name} - {device.Lights.Count()} Lights");
}
}
_logger.LogInformation(new EventId(0, "Logging"), "Aura Connect started successfully!");
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
}
}
19
Source : ReturnBookCommandHandler.cs
with MIT License
from andresantarosa
with MIT License
from andresantarosa
public async Task<ReturnBookCommandResponseViewModel> Handle(ReturnBookCommand request, CancellationToken cancellationToken)
{
ReturnBookCommandResponseViewModel response = new ReturnBookCommandResponseViewModel();
if (!request.ValidateBookLoanGuid())
return response;
BookLoan bookLoan = await _bookLoanRepository.GetByLoanId(Guid.Parse(request.LoanId), true);
if (!request.ValidateBookLoanExists(bookLoan))
return response;
if (!bookLoan.ReturnBook())
return response;
_bookLoanRepository.Update(bookLoan);
return response;
}
19
Source : GuidId.cs
with MIT License
from andrewlock
with MIT License
from andrewlock
public override GuidId Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options)
{
return new GuidId(System.Guid.Parse(reader.GetString()));
}
19
Source : BacklogItemId.cs
with Apache License 2.0
from aneshas
with Apache License 2.0
from aneshas
public static BacklogItemId Parse(string id) => new BacklogItemId(Guid.Parse(id));
19
Source : OAuthController.cs
with GNU General Public License v3.0
from AniAPI-Team
with GNU General Public License v3.0
from AniAPI-Team
[AllowAnonymous]
[EnableCors("CorsEveryone")]
[HttpGet, MapToApiVersion("1")]
[ApiExplorerSettings(IgnoreApi = true)]
public IActionResult Index(string client_id, string redirect_uri, string response_type, string state)
{
if(string.IsNullOrEmpty(client_id) ||
string.IsNullOrEmpty(redirect_uri) ||
string.IsNullOrEmpty(response_type))
{
return BadRequest("missing required field");
}
if(response_type != "token" && response_type != "code")
{
return BadRequest("response_type content not expected");
}
OAuthRequest request = new OAuthRequest()
{
ClientID = client_id,
RedirectURI = redirect_uri,
ResponseType = response_type,
State = state
};
HttpContext.Session.SetString("oauth", JsonConvert.SerializeObject(request));
List<OAuthClient> clients = _oAuthClientCollection.GetList(new OAuthClientFilter()
{
client_id = Guid.Parse(request.ClientID)
}).Doreplacedents;
if(clients.Count == 0)
{
return NotFound();
}
OAuthClient client = clients[0];
if(redirect_uri != client.RedirectURI)
{
return Forbid("redirect_uri content mismatch from registered client");
}
return View(client);
}
19
Source : OAuthController.cs
with GNU General Public License v3.0
from AniAPI-Team
with GNU General Public License v3.0
from AniAPI-Team
[AllowAnonymous]
[Route("token")]
[EnableCors("CorsEveryone")]
[HttpPost, MapToApiVersion("1")]
public APIResponse Token(string client_id, string client_secret, string code, string redirect_uri)
{
if (string.IsNullOrEmpty(client_id) ||
string.IsNullOrEmpty(redirect_uri) ||
string.IsNullOrEmpty(client_secret) ||
string.IsNullOrEmpty(code))
{
return APIManager.ErrorResponse(new APIException(
System.Net.HttpStatusCode.BadRequest,
"Bad request",
"Missing required field"));
}
List<OAuthClient> clients = _oAuthClientCollection.GetList(new OAuthClientFilter()
{
client_id = Guid.Parse(client_id)
}).Doreplacedents;
if (clients.Count == 0)
{
return APIManager.ErrorResponse(new APIException(
System.Net.HttpStatusCode.NotFound,
"Not found",
"client_id not found"));
}
OAuthClient client = clients[0];
if(Guid.Parse(client_secret) != client.ClientSecret)
{
return APIManager.ErrorResponse(new APIException(
System.Net.HttpStatusCode.Forbidden,
"Forbidden",
"client_secret content mismatch from registered client"));
}
if (redirect_uri != client.RedirectURI)
{
return APIManager.ErrorResponse(new APIException(
System.Net.HttpStatusCode.Forbidden,
"Forbidden",
"redirect_uri content mismatch from registered client"));
}
if(!_cache.TryGetValue(code, out string token))
{
return APIManager.ErrorResponse(new APIException(
System.Net.HttpStatusCode.Forbidden,
"Forbidden",
"code not valid"));
}
return APIManager.SuccessResponse("Code verified", token);
}
19
Source : OrdersController.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<OrderSummary>), (int)HttpStatusCode.OK)]
public async Task<ActionResult<IEnumerable<OrderSummary>>> GetOrdersAsync()
{
var userid = _idenreplacedyService.GetUserIdenreplacedy();
var orders = await _orderQueries.GetOrdersFromUserAsync(Guid.Parse(userid));
return Ok(orders);
}
19
Source : WavePlayer.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public IWavePlayer CreatePlayer(
WavePlayerTypes playerType = WavePlayerTypes.WASAPI,
string deviceID = null)
{
var deviceEnumrator = new MMDeviceEnumerator();
var player = default(IWavePlayer);
switch (playerType)
{
case WavePlayerTypes.WaveOut:
player = deviceID == null ?
new WaveOut() :
new WaveOut()
{
DeviceNumber = int.Parse(deviceID),
DesiredLatency = PlaybackLatency,
};
break;
case WavePlayerTypes.DirectSound:
player = deviceID == null ?
new DirectSoundOut() :
new DirectSoundOut(Guid.Parse(deviceID), PlaybackLatency);
break;
case WavePlayerTypes.WASAPI:
var device = deviceID switch
{
PlayDevice.DefaultDeviceID => deviceEnumrator
.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console),
PlayDevice.DefaultComDeviceID => deviceEnumrator
.GetDefaultAudioEndpoint(DataFlow.Render, Role.Communications),
_ => deviceEnumrator
.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active)
.FirstOrDefault(x => x.ID == deviceID)
};
player = device == null ?
new WasapiOut() :
new WasapiOut(
device,
AudioClientShareMode.Shared,
false,
PlaybackLatency);
break;
}
19
Source : ClientServiceTest.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
[Fact]
public async void GetClient()
{
await _fixture.CreateTest()
.UseClaims(
new Claim("client_id", "D6E29710-B68F-4D2D-9471-273DECF9C4B7"),
new Claim("creator_id", "1"))
.RunAsync<IClientServiceClient>(async client =>
{
var result = await client.GetClient(Guid.Parse("D6E29710-B68F-4D2D-9471-273DECF9C4B7"));
replacedert.NotNull(result);
});
}
19
Source : ClientServiceTest.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
[Fact]
public async void GetClient_RequestPolicyFail()
{
await _fixture.CreateTest()
.UseClaims(
new Claim("client_id", "D6E29718-B68F-4D2D-9471-273DECF9C4B7"),
new Claim("creator_id", "1"))
.RunAsync<IClientServiceClient>(async client =>
{
var result = await replacedert.ThrowsAsync<ApiException>(() => client.GetClient(Guid.Parse("D6E29710-B68F-4D2D-9471-273DECF9C4B7")));
replacedert.NotNull(result);
replacedert.Equal(HttpStatusCode.Forbidden, result.StatusCode);
});
}
19
Source : ClientServiceTest.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
[Fact]
public async void GetClient_ResultPolicyFail()
{
await _fixture.CreateTest()
.UseClaims(
new Claim("client_id", "D6E29710-B68F-4D2D-9471-273DECF9C4B7"),
new Claim("creator_id", "2"))
.RunAsync<IClientServiceClient>(async client =>
{
var result = await replacedert.ThrowsAsync<ApiException>(() => client.GetClient(Guid.Parse("D6E29710-B68F-4D2D-9471-273DECF9C4B7")));
replacedert.NotNull(result);
replacedert.Equal(HttpStatusCode.Forbidden, result.StatusCode);
});
}
19
Source : ProtobufMappingExtensions.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public static Cybtans.Tests.Grpc.Models.HelloModel ToPocoModel(this global::Cybtans.Tests.Grpc.HelloModelModel model)
{
if(model == null) return null;
global::Cybtans.Tests.Grpc.Models.HelloModel result = new global::Cybtans.Tests.Grpc.Models.HelloModel();
result.Id = !string.IsNullOrEmpty(model.Id) ? Guid.Parse(model.Id) : Guid.Empty;
result.Message = model.Message;
return result;
}
19
Source : RequerimentHandlers.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ClientPolicyRequirement requirement, ClientRequest resource)
{
if (context.User.HasClaim(x => x.Type == "client_id"))
{
var userId = Guid.Parse(context.User.Claims.First(x => x.Type == "client_id").Value);
if (resource.Id == userId)
{
context.Succeed(requirement);
}
}
if (resource.Id == Guid.Empty)
{
resource.Id = Guid.Parse("D6E29710-B68F-4D2D-9471-273DECF9C4B7");
context.Succeed(requirement);
}
return Task.CompletedTask;
}
19
Source : RequerimentHandlers.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ClientPolicyRequirement requirement, ClientRequest resource)
{
if (context.User.HasClaim(x => x.Type == "client_id"))
{
var userId = Guid.Parse(context.User.Claims.First(x => x.Type == "client_id").Value);
if (resource.Id == userId)
{
context.Succeed(requirement);
}
}
if (resource.Id == Guid.Empty)
{
resource.Id = Guid.Parse("D6E29710-B68F-4D2D-9471-273DECF9C4B7");
context.Succeed(requirement);
}
return Task.CompletedTask;
}
19
Source : AmqpMessageIdHelper.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static object ToIdObject(string origId)
{
if (origId == null) {
return null;
}
if (!HasMessageIdPrefix(origId)) {
// We have a string without any "ID:" prefix, it is an
// application-specific String, use it as-is.
return origId;
}
try
{
if (HasAmqpNoPrefix(origId, NMS_ID_PREFIX_LENGTH))
{
// Prefix telling us there was originally no "ID:" prefix,
// strip it and return the remainder
return origId.Substring(NMS_ID_PREFIX_LENGTH + AMQP_NO_PREFIX_LENGTH);
}
else if (HasAmqpStringPrefix(origId, NMS_ID_PREFIX_LENGTH))
{
return origId.Substring(NMS_ID_PREFIX_LENGTH + AMQP_STRING_PREFIX_LENGTH);
}
else if (HasAmqpBinaryPrefix(origId, NMS_ID_PREFIX_LENGTH))
{
string hexString = origId.Substring(NMS_ID_PREFIX_LENGTH + AMQP_BINARY_PREFIX_LENGTH).ToUpper();
return ConvertHexStringToBinary(hexString, origId);
}
else if (HasAmqpUlongPrefix(origId, NMS_ID_PREFIX_LENGTH))
{
string ulongString = origId.Substring(NMS_ID_PREFIX_LENGTH + AMQP_ULONG_PREFIX_LENGTH);
return Convert.ToUInt64(ulongString);
}
else if (HasAmqpUuidPrefix(origId, NMS_ID_PREFIX_LENGTH))
{
string guidString = origId.Substring(NMS_ID_PREFIX_LENGTH + AMQP_UUID_PREFIX_LENGTH);
return Guid.Parse(guidString);
}
else
{
// We have a string without any encoding prefix needing processed,
// so transmit it as-is, including the "ID:"
return origId;
}
}
catch (Exception e)
{
throw new NMSException("Id Conversion Failure. Provided Id: " + origId, e);
}
}
19
Source : StoryDetailViewModel.cs
with MIT License
from AppCreativity
with MIT License
from AppCreativity
public async override void OnNavigatedTo(INavigationParameters parameters)
{
string stringID = parameters["id"] as string;
if (!string.IsNullOrEmpty(stringID) && Guid.Parse(stringID) is Guid id)
Story = await BirdAtlasAPI.GetStoryAsync(id);
}
19
Source : GuidDynamicFieldMapping.cs
with MIT License
from aquilahkj
with MIT License
from aquilahkj
public override object ToProperty (object value)
{
if (Equals (value, DBNull.Value) || Equals (value, null)) {
return null;
}
if (value is string valueString)
{
value = Guid.Parse(valueString);
}
else if (value is byte[] valueBuffer)
{
value = new Guid(valueBuffer);
}
return value;
}
19
Source : GuidFieldMapping.cs
with MIT License
from aquilahkj
with MIT License
from aquilahkj
public override object ToProperty(object value)
{
if (Equals(value, DBNull.Value) || Equals(value, null))
{
return null;
}
if (value is string valueString)
{
value = Guid.Parse(valueString);
}
else if (value is byte[] valueBuffer)
{
value = new Guid(valueBuffer);
}
return value;
}
19
Source : GuidDataDefine.cs
with MIT License
from aquilahkj
with MIT License
from aquilahkj
public override object LoadData(DataContext context, IDataReader dataReader, object state)
{
var value = dataReader[0];
if (Equals(value, DBNull.Value) || Equals(value, null))
{
if (!IsNullable) {
return _defaultValue;
}
return null;
}
if (value is string valueString)
{
value = Guid.Parse(valueString);
}
else if (value is byte[] valueBuffer)
{
value = new Guid(valueBuffer);
}
return value;
}
19
Source : GuidDataDefine.cs
with MIT License
from aquilahkj
with MIT License
from aquilahkj
public override object LoadData(DataContext context, IDataReader dataReader, string name, object state)
{
var value = dataReader[name];
if (Equals(value, DBNull.Value) || Equals(value, null))
{
if (!IsNullable) {
return _defaultValue;
}
return null;
}
if (value is string valueString)
{
value = Guid.Parse(valueString);
}
else if (value is byte[] valueBuffer)
{
value = new Guid(valueBuffer);
}
return value;
}
19
Source : ProjectManagerTest.cs
with MIT License
from arasplm
with MIT License
from arasplm
[Test]
[TestCase("B69B1AC9-3D7E-4553-9786-A852B873DF01")]
[TestCase("AEA8535B-C666-4112-9BDD-5ECFA4934B47")]
[TestCase("DB77AE9E-9CB5-4C13-9EB3-ED388DC94B66")]
[TestCase("E15DDF0A-1B6E-46A8-8B78-AEC2A7BB4922")]
public void IsCommandForMethod_ShouldReturnTrue(string commandId)
{
//Arange
//Act
bool result = this.projectManager.IsCommandForMethod(Guid.Parse(commandId));
//replacedert
replacedert.IsTrue(result);
}
19
Source : BaseGuildSubEndpointClientTests.cs
with MIT License
from Archomeda
with MIT License
from Archomeda
[Fact]
public override void ArgumentNullConstructorTest()
{
replacedertArguments.ThrowsWhenNullConstructor(
this.Client.GetType(),
new[] { typeof(IConnection), typeof(IGw2Client), typeof(Guid) },
new object[] { new Connection(), new Gw2Client(), Guid.Parse("11111111-2222-3333-4444-abcdeffedcba") },
new[] { true, true, false });
}
19
Source : PvpSeasonsLeaderboardsIdClientTests.cs
with MIT License
from Archomeda
with MIT License
from Archomeda
[Fact]
public override void ArgumentNullConstructorTest()
{
replacedertArguments.ThrowsWhenNullConstructor(
this.Client.GetType(),
new[] { typeof(IConnection), typeof(IGw2Client), typeof(Guid), typeof(string) },
new object[] { new Connection(), new Gw2Client(), Guid.Parse("11111111-2222-3333-4444-abcdeffedcba"), "ladder" },
new[] { true, true, false, true });
}
19
Source : PvpSeasonsLeaderboardsRegionIdClientTests.cs
with MIT License
from Archomeda
with MIT License
from Archomeda
[Fact]
public override void ArgumentNullConstructorTest() =>
replacedertArguments.ThrowsWhenNullConstructor(
this.Client.GetType(),
new[] { typeof(IConnection), typeof(IGw2Client), typeof(Guid), typeof(string), typeof(string) },
new object[] { new Connection(), new Gw2Client(), Guid.Parse("11111111-2222-3333-4444-abcdeffedcba"), "ladder", "eu" },
new[] { true, true, false, true, true });
19
Source : AzureServiceBusSystemPropertiesTests.cs
with MIT License
from arcus-azure
with MIT License
from arcus-azure
[Theory]
[InlineData(null)]
[InlineData("465924F2-D386-407F-826A-573144085682")]
public void CreateProperties_FromMessage_replacedignsLockTokenCorrectly(string lockToken)
{
// Arrange
Guid.TryParse(lockToken, out Guid expected);
AmqpAnnotatedMessage amqpMessage = CreateAmqpMessage();
ServiceBusReceivedMessage message = CreateServiceBusReceivedMessage(amqpMessage);
SetLockToken(message, expected);
// Act
var systemProperties = AzureServiceBusSystemProperties.CreateFrom(message);
// replacedert
replacedert.Equal(expected, Guid.Parse(systemProperties.LockToken));
replacedert.Equal(expected != null, systemProperties.IsLockTokenSet);
}
19
Source : ProjectManager.cs
with GNU General Public License v3.0
from armandoalonso
with GNU General Public License v3.0
from armandoalonso
private static void ReadMetadataJson(C3Addon addon, string fullpath)
{
try
{
var text = File.ReadAllLines(fullpath);
addon.Id = Guid.Parse(text[1].Split('|')[1].Trim());
addon.Name = text[2].Split('|')[1].Trim();
addon.Clreplaced = text[3].Split('|')[1].Trim();
addon.Company = text[4].Split('|')[1].Trim();
addon.Author = text[5].Split('|')[1].Trim();
addon.MajorVersion = int.Parse(text[6].Split('|')[1].Trim());
addon.MinorVersion = int.Parse(text[7].Split('|')[1].Trim());
addon.RevisionVersion = int.Parse(text[8].Split('|')[1].Trim());
addon.BuildVersion = int.Parse(text[9].Split('|')[1].Trim());
addon.Description = text[10].Split('|')[1].Trim();
addon.AddonCategory = text[11].Split('|')[1].Trim();
addon.Type = (PluginType)Enum.Parse(typeof(PluginType), text[12].Split('|')[1].Trim());
addon.CreateDate = DateTime.Parse(text[13].Split('|')[1].Trim());
addon.LastModified = DateTime.Parse(text[14].Split('|')[1].Trim());
if (text.Length == 16)
{
addon.AddonId = text[15].Split('|')[1].Trim();
}
else
{
addon.AddonId = $"{addon.Author}_{addon.Clreplaced}";
}
}
catch (Exception ex)
{
LogManager.AddErrorLog(ex);
throw;
}
}
19
Source : ExampleData.cs
with Apache License 2.0
from aruss
with Apache License 2.0
from aruss
public IEnumerable<UserAccount> GetUserAccounts(
ICryptoService cryptoService,
ApplicationOptions options)
{
DateTime now = DateTime.UtcNow;
var users = new List<UserAccount>
{
// Active user account with local account but no external accounts
new UserAccount
{
Id = Guid.Parse("0c2954d2-4c73-44e3-b0f2-c00403e4adef"),
Email = "alice@localhost",
PreplacedwordHash = cryptoService.HashPreplacedword(
"alice@localhost",
options.PreplacedwordHashingIterationCount),
CreatedAt = now,
UpdatedAt = now,
IsEmailVerified = true,
IsActive = true,
Claims = new List<UserAccountClaim>
{
new UserAccountClaim(JwtClaimTypes.Name,
"Alice Smith"),
new UserAccountClaim(JwtClaimTypes.GivenName,
"Alice"),
new UserAccountClaim(JwtClaimTypes.FamilyName,
"Smith"),
new UserAccountClaim(JwtClaimTypes.Email,
"alice@localhost"),
new UserAccountClaim(JwtClaimTypes.EmailVerified,
"true",
ClaimValueTypes.Boolean),
new UserAccountClaim(JwtClaimTypes.Role, "Admin"),
new UserAccountClaim(JwtClaimTypes.Role, "Geek"),
new UserAccountClaim(JwtClaimTypes.WebSite,
"http://alice.com"),
new UserAccountClaim(JwtClaimTypes.Address,
@"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }",
IdenreplacedyServerConstants.ClaimValueTypes.Json)
}
},
// Active user account
new UserAccount
{
Id = Guid.Parse("28575826-68a0-4a1d-9428-674a2eb5db95"),
Email = "bob@localhost",
PreplacedwordHash = cryptoService.HashPreplacedword(
"bob@localhost",
options.PreplacedwordHashingIterationCount),
CreatedAt = now,
UpdatedAt = now,
IsEmailVerified = true,
IsActive = true,
Claims = new List<UserAccountClaim>
{
new UserAccountClaim(JwtClaimTypes.Name,
"Bob Smith"),
new UserAccountClaim(JwtClaimTypes.GivenName,
"Bob"),
new UserAccountClaim(JwtClaimTypes.FamilyName,
"Smith"),
new UserAccountClaim(JwtClaimTypes.Email,
"bob@localhost"),
new UserAccountClaim(JwtClaimTypes.EmailVerified,
"true",
ClaimValueTypes.Boolean),
new UserAccountClaim(JwtClaimTypes.Role,
"Developer"),
new UserAccountClaim(JwtClaimTypes.Role,
"Geek"),
new UserAccountClaim(JwtClaimTypes.WebSite,
"http://bob.com"),
new UserAccountClaim(JwtClaimTypes.Address,
@"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }",
IdenreplacedyServerConstants.ClaimValueTypes.Json)
}
},
// Inactive user account
new UserAccount
{
Id = Guid.Parse("6b13d17c-55a6-482e-96b9-dc784015f927"),
Email = "jim@localhost",
PreplacedwordHash = cryptoService.HashPreplacedword(
"jim@localhost",
options.PreplacedwordHashingIterationCount),
CreatedAt = now,
UpdatedAt = now,
IsEmailVerified = true,
EmailVerifiedAt = now,
IsActive = false,
Claims = CreateClaims("Jim Panse", "Jim", "Panse"),
},
// Active user account with not verified email
// http://localhost:5000/register/confirm?key=e41935fbff4d4c61176fa0a50491963ffd192fa26f709e2c99034e33b0d386b9&clientId=mvc&culture=en-US
// http://localhost:5000/register/cancel?key=e41935fbff4d4c61176fa0a50491963ffd192fa26f709e2c99034e33b0d386b9&clientId=mvc&culture=en-US
new UserAccount
{
Id = Guid.Parse("13808d08-b1c0-4f28-8d3e-8c9a4051efcb"),
Email = "paul@localhost",
PreplacedwordHash = cryptoService.HashPreplacedword(
"paul@localhost",
options.PreplacedwordHashingIterationCount),
CreatedAt = now,
UpdatedAt = now,
IsEmailVerified = false,
IsActive = true,
Claims = CreateClaims("Paul Panzer", "Paul", "Panzer"),
VerificationKey = "e41935fbff4d4c61176fa0a50491963ffd192fa26f709e2c99034e33b0d386b9",
VerificationKeySentAt = now,
VerificationPurpose = 3,
VerificationStorage =
"/connect/authorize/callback?client_id=mvc&redirect_uri=http%3A%2F%2Flocalhost%3A5002%2Fsignin-oidc&response_type=code%20id_token&scope=openid%20profile%20email%20api1%20idbase%20offline_access&response_mode=form_post&nonce=636797153419167400.MGFjMWNjYmYtMTE1YS00YWY1LWI2ZWMtMzdkZjEzY2Q5OGY3MWNmYzI4MmYtZGE3NS00MGE1LWJkNzgtZGQzZTYzNzY0MjZm&culture=en-US&state=CfDJ8JQ-mps0lj9HjFm5hrrJZyhB2X5bLQyFqkdLryEawVpBjagMoql-6iZVsSXWZxS77aNnlb4Mti_i57k6c8_Z7iUWsuCNrq1gfL9zWygRrfUHpAHPI5HvEC0tnEANmhzuFaorgsli0Ij3q4p2pxqKYja34_sqyD-_zNffMnnfKDj2d5oqsnPCuUL4a5690I8IFZ_7jpFz3SQkWlnEJPL7P2dKS7faO0K0cfZXeY06HGTaY34LpuDIwHgts39lZNGzR6pZ2RZhV2pvxuheWzZg-tC2jPDnYDYmBAPQ52G_B8ETYzfIrbg-5NOre5bVr757Y8ibpO5Fne-mybTR2rhtHTM&x-client-SKU=ID_NETSTANDARD1_4&x-client-ver=5.2.0.0"
},
// User account with preplacedword reset confirmation
// http://localhost:5000/recover/confirm?key=de638ef442b0095a0d99031898d6b6a311358d481669a85bb7ed78b2b3504d43&clientId=mvc&culture=en-US
// http://localhost:5000/recover/cancel?key=de638ef442b0095a0d99031898d6b6a311358d481669a85bb7ed78b2b3504d43&clientId=mvc&culture=en-US
new UserAccount
{
Id = Guid.Parse("e738f782-ed25-4fd2-8c46-9bc36fdd70a0"),
Email = "jack@localhost",
PreplacedwordHash = cryptoService.HashPreplacedword(
"jack@localhost",
options.PreplacedwordHashingIterationCount),
CreatedAt = now,
UpdatedAt = now,
IsEmailVerified = false,
IsActive = true,
Claims = CreateClaims("Jack Bauer", "Jack", "Bauer"),
VerificationKey = "de638ef442b0095a0d99031898d6b6a311358d481669a85bb7ed78b2b3504d43",
VerificationKeySentAt = now,
VerificationPurpose = 0,
VerificationStorage =
"/connect/authorize/callback?client_id=mvc&redirect_uri=http%3A%2F%2Flocalhost%3A5002%2Fsignin-oidc&response_type=code%20id_token&scope=openid%20profile%20email%20api1%20idbase%20offline_access&response_mode=form_post&nonce=636797178235288011.NWNiNDk2ZWQtN2MwNC00OTA5LTljNWQtNmJmOGQ1NDY5ZGIzMzRiNGM0OTEtMmVkNy00Y2ZkLTlkM2QtMmFlMDk0YzhhNjE3&culture=en-US&state=CfDJ8JQ-mps0lj9HjFm5hrrJZyggvttdEHRL23FvYe60bS3vgeYNJ9amoa1_Dp8jcwT8KOZGTNC85gJJOQ_iFeGGDXxuJxW_MayOPkHFWaeoBvH2pBS-AqArBg0TPprN6NzcV8x7p_JaSREvmTU9pz-aMsmKeWrcgq5L5_Vbw-P8Zv8QrfqtSlY7QXkzgsMiZm6bLvPhSGzUODv_hPHK2PTIJq4_gqwiq7FRk2d6XEpTBaMfwl_C4qx1Vbe4OkpWylCi6IYu8xN0yrMusKgHqMNHr2EfTNPW4DwL6sC-QeBIxXzQU0Eey17zLrZQEtJwVKNQfOAFzL43zvcyj0WUPZebRbs&x-client-SKU=ID_NETSTANDARD1_4&x-client-ver=5.2.0.0"
},
// User account with only external user account
new UserAccount
{
Id = Guid.Parse("58631b04-9be5-454a-aa1d-f679cd454fa6"),
Email = "bill@localhost",
CreatedAt = now,
UpdatedAt = now,
// had never confirmed the email, since he got via facebook
IsEmailVerified = false,
// is allowed to login since he registed via facebook
IsActive = true,
Claims = CreateClaims("Bill Smith", "Bill", "Smith"),
Accounts = new List<ExternalAccount>()
{
new ExternalAccount
{
CreatedAt = now,
Email = "bill@localhost",
Subject = "123456789",
Provider = "facebook"
}
}
}
};
return users;
}
19
Source : AuthenticationService.cs
with Apache License 2.0
from aruss
with Apache License 2.0
from aruss
public async Task<UserAccount> GetAuthenticatedUserAccountAsync()
{
ClaimsPrincipal user = this._httpContextAccessor.HttpContext.User;
if (!user.Idenreplacedy.IsAuthenticated)
{
return null;
}
Claim subjectClaim = user.FindFirst("sub");
if (subjectClaim == null)
{
throw new ApplicationException(
"Authenticated user does not have a sub claim"
);
}
Guid userId = Guid.Parse(subjectClaim.Value);
UserAccount userAccount = await this._userAccountStore
.LoadByIdAsync(userId);
return userAccount;
}
19
Source : ProfileService.cs
with Apache License 2.0
from aruss
with Apache License 2.0
from aruss
public Task GetProfileDataAsync(ProfileDataRequestContext context)
{
Guid userAccountId = Guid.Parse(context.Subject
.FindFirst(JwtClaimTypes.Subject).Value);
UserAccount userAccount = this._userAccountStore
.LoadByIdAsync(userAccountId).Result;
// TODO: get claims from db user
List<Claim> claims = new List<Claim>
{
new Claim(JwtClaimTypes.Subject, userAccount.Id.ToString()),
new Claim(JwtClaimTypes.Email, userAccount.Email),
new Claim(
JwtClaimTypes.EmailVerified,
userAccount.IsEmailVerified.ToString().ToLower(),
ClaimValueTypes.Boolean
)
};
context.IssuedClaims = claims;
return Task.FromResult(0);
}
19
Source : ProfileService.cs
with Apache License 2.0
from aruss
with Apache License 2.0
from aruss
public Task IsActiveAsync(IsActiveContext context)
{
Guid userId = Guid.Parse(context.Subject
.FindFirst(JwtClaimTypes.Subject).Value);
UserAccount user = this._userAccountStore
.LoadByIdAsync(userId).Result;
context.IsActive = user != null && user.IsActive;
return Task.FromResult(0);
}
19
Source : RuntimeGuardInstances.cs
with MIT License
from ashmind
with MIT License
from ashmind
[EditorBrowsable(EditorBrowsableState.Never)]
public static RuntimeGuard Get(string idString) {
if (!_instances.TryGetValue(Guid.Parse(idString), out RuntimeGuard guard))
throw new GuardException(GuardException.NoScopeMessage);
return guard;
}
19
Source : LocationService.cs
with MIT License
from AspNetMonsters
with MIT License
from AspNetMonsters
[JSInvokable]
public static void ReceiveResponse(
string id,
double lareplacedude,
double longitude,
double accuracy)
{
TaskCompletionSource<Location> pendingTask;
var idVal = Guid.Parse(id);
pendingTask = _pendingRequests.First(x => x.Key == idVal).Value;
pendingTask.SetResult(new Location
{
Lareplacedude = Convert.ToDecimal(lareplacedude),
Longitude = Convert.ToDecimal(longitude),
Accuracy = Convert.ToDecimal(accuracy)
});
}
19
Source : LocationService.cs
with MIT License
from AspNetMonsters
with MIT License
from AspNetMonsters
[JSInvokable]
public static void ReceiveWatchResponse(
string id,
double lareplacedude,
double longitude,
double accuracy)
{
Action<Location> callback;
var idVal = Guid.Parse(id);
callback = _watches[idVal];
callback(new Location
{
Lareplacedude = Convert.ToDecimal(lareplacedude),
Longitude = Convert.ToDecimal(longitude),
Accuracy = Convert.ToDecimal(accuracy)
});
}
19
Source : AmbientLightSensorService.cs
with MIT License
from AspNetMonsters
with MIT License
from AspNetMonsters
[JSInvokable]
public void ReceiveResponse(
string id,
string hasReading,
string activated,
string illuminance)
{
AmbientLightSensor sensor;
var idVal = Guid.Parse(id);
sensor = _activeSensors.First(x => x.Key == idVal).Value;
sensor.HasReading = Convert.ToBoolean(hasReading);
sensor.Activated = Convert.ToBoolean(activated);
sensor.Illuminance = Convert.ToDecimal(illuminance);
sensor.OnReading();
}
19
Source : MsiApi.cs
with GNU General Public License v3.0
from atomex-me
with GNU General Public License v3.0
from atomex-me
public static List<MsiProduct> GetRelatedProducts(Guid upgradeCode)
{
var products = new List<MsiProduct>();
var productCode = new StringBuilder(39);
while (true)
{
var result = MsiEnumRelatedProducts($"{{{upgradeCode}}}", 0, products.Count, productCode);
if (result == EnumRelatedProductsError.NoMoreItems)
break;
if (result != EnumRelatedProductsError.Success)
throw new Exception(Enum.GetName(result.GetType(), result));
products.Add(new MsiProduct(Guid.Parse(productCode.ToString())));
}
return products;
}
19
Source : MsiApi.cs
with GNU General Public License v3.0
from atomex-me
with GNU General Public License v3.0
from atomex-me
public static List<MsiProduct> GetAllProducts()
{
var products = new List<MsiProduct>();
var productCode = new StringBuilder(39);
while (true)
{
var result = MsiEnumProducts(products.Count, productCode);
if (result == EnumProductsError.NoMoreItems)
break;
if (result != EnumProductsError.Success)
throw new Exception(Enum.GetName(result.GetType(), result));
products.Add(new MsiProduct(Guid.Parse(productCode.ToString())));
}
return products;
}
19
Source : ComputerVision.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public List<string> ExtractOCRTextFromLocalFile(string localFile, string language = "en")
{
var textHeaders = _client.ReadInStreamAsync(File.OpenRead(localFile), language: language).Result;
// After the request, get the operation location (operation ID)
string operationLocation = textHeaders.OperationLocation;
Thread.Sleep(2000);
// Retrieve the URI where the recognized text will be stored from the Operation-Location header.
// We only need the ID and not the full URL
const int numberOfCharsInOperationId = 36;
string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
// Extract the text
ReadOperationResult results;
do
{
results = _client.GetReadResultAsync(Guid.Parse(operationId)).Result;
}
while (results.Status == OperationStatusCodes.Running || results.Status == OperationStatusCodes.NotStarted);
List<string> foundTextSnippets = new List<string>();
var textUrlFileResults = results.replacedyzeResult.ReadResults;
foreach (ReadResult page in textUrlFileResults)
{
foreach (Line line in page.Lines)
{
foundTextSnippets.Add(line.Text);
}
}
return foundTextSnippets;
}
19
Source : ParseExtensions.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
public static Guid ToGuide(this string value)
{
return Guid.Parse(value);
}
19
Source : NativeTestsRunnerPluginService.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
private List<MSTestTestCase> ConvertTestRunToMsTestCases(TestRun testRun)
{
var testCases = new List<MSTestTestCase>();
foreach (var unitTest in testRun.TestDefinitions)
{
var currentTestCase = new MSTestTestCase
{
FullName = $"{unitTest.TestMethod.clreplacedName}.{unitTest.TestMethod.name}",
ClreplacedName = unitTest.TestMethod.clreplacedName,
Id = Guid.Parse(unitTest.id),
};
testCases.Add(currentTestCase);
}
return testCases;
}
19
Source : NativeTestsRunnerPluginService.cs
with Apache License 2.0
from AutomateThePlanet
with Apache License 2.0
from AutomateThePlanet
private List<NUnitTestCase> ConvertTestRunToNUnitCases(TestRun testRun)
{
var testCases = new List<NUnitTestCase>();
foreach (var unitTest in testRun.TestDefinitions)
{
var currentTestCase = new NUnitTestCase
{
FullName = $"{unitTest.TestMethod.clreplacedName}.{unitTest.TestMethod.name}",
ClreplacedName = unitTest.TestMethod.clreplacedName,
Id = Guid.Parse(unitTest.id),
};
testCases.Add(currentTestCase);
}
return testCases;
}
19
Source : CosmosDbValue.cs
with MIT License
from Avanade
with MIT License
from Avanade
void ICosmosDbValue.PrepareAfter()
{
if (Value == default)
return;
switch (Value)
{
case IStringIdentifier isi:
isi.Id = Id!;
break;
case IInt32Identifier iii:
iii.Id = Id == null ? 0 : int.Parse(Id, System.Globalization.CultureInfo.InvariantCulture);
break;
case IInt64Identifier ili:
ili.Id = Id == null ? 0 : long.Parse(Id, System.Globalization.CultureInfo.InvariantCulture);
break;
case IGuidIdentifier igi:
igi.Id = Id == null ? Guid.Empty : Guid.Parse(Id);
break;
default:
throw new InvalidOperationException("Value is an unknown IIdentifier.");
}
if (Value is IETag etag)
etag.ETag = ETag;
}
19
Source : frmManager.cs
with MIT License
from AyrA
with MIT License
from AyrA
private void btnImportId_Click(object sender, EventArgs e)
{
try
{
if (Clipboard.ContainsText())
{
var Id = Clipboard.GetText();
//{12345678-1234-1234-1234-123456789012}
var M = Regex.Match(Id, @"[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}", RegexOptions.IgnoreCase);
if (M.Success)
{
var MapId = Guid.Parse(M.Value);
var Res = SMRAPI.API.Details(MapId);
if (!Res.success)
{
throw new Exception(Res.msg);
}
if (MessageBox.Show($"Do you want to import '{Res.data.name}' from user '{Res.data.user.name}'?", "Map Import", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
bool Result;
string NewName = Tools.GetNewName(Path.Combine(Program.SaveDirectory, Res.data.name));
using (var FS = File.Create(NewName))
{
Result = SMRAPI.API.Download(MapId, FS);
}
if (!Result)
{
try
{
File.Delete(NewName);
}
catch
{
//Don't care. It will show up under invalids and can be removed later.
}
throw new Exception("Problem downloading the map. Please try again later");
}
else
{
Tools.I($"Import of {Path.GetFileName(NewName)} successful", "Map Import", this);
InitFiles();
}
}
}
else
{
throw new FormatException("Your clipboard doesn't contains a map id.");
}
}
else
{
throw new Exception("No Map Id found in your clipboard");
}
}
catch (Exception ex)
{
Tools.E("Error importing map.\r\n" + ex.Message, "Map Import", this);
}
}
19
Source : ObjectValueConversion.cs
with MIT License
from azist
with MIT License
from azist
public static Guid AsGUID(this object val, Guid dflt, ConvertErrorHandling handling = ConvertErrorHandling.ReturnDefault)
{
try
{
if (val == null) return dflt;
if (val is string)
{
var sval = (string)val;
return Guid.Parse(sval);
}
else if (val is byte[])
{
var arr = (byte[])val;
return arr.GuidFromNetworkByteOrder();
}
else
return (Guid)val;
}
catch
{
if (handling != ConvertErrorHandling.ReturnDefault) throw;
return dflt;
}
}
See More Examples