I'm trying to set up RavenDb 3.5 and NServiceBus 6. After I senter the saga that I have set up in my NServiceBus endpoint, I enter a handler. Once this handler is finished, I get this error:
System.FormatException: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
My code:
public static class AutoFacConfig
{
public static IContainer ConfigureAutofac()
{
var builder = new ContainerBuilder();
var resourceManagerId = new Guid("6c9abcbb-c7ca-4a67-a149-5142f633f535");
var dtcRecoveryBasePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
var recoveryPath = Path.Combine(dtcRecoveryBasePath, "NServiceBus.RavenDB", resourceManagerId.ToString());
builder.Register(x =>
{
var store = new DocumentStore
{
ConnectionStringName = "RavenDB",
ResourceManagerId = resourceManagerId,
TransactionRecoveryStorage = new LocalDirectoryTransactionRecoveryStorage(recoveryPath)
};
store.DefaultDatabase = "MyDB";
store.Initialize();
store.Conventions.IdentityPartsSeparator = "-";
return store;
})
.As<IDocumentStore>()
.SingleInstance();
builder.Register<IFilesStore>(x =>
{
var fileStore = new FilesStore()
{
Url = "http://localhost:40000",
DefaultFileSystem = "MyFS",
}.Initialize();
return fileStore;
}).SingleInstance();
return builder.Build();
}
}
In the saga:
protected override void ConfigureHowToFindSaga(SagaPropertyMapper<FileToOrderSagaData> mapper)
{
mapper.ConfigureMapping<StartFileToOrderSagaCommand>(m => m.DataId)
.ToSaga(s => s.DataId);
}
public async Task Handle(StartFileToOrderSagaCommand message, IMessageHandlerContext context)
{
// Do Validation ValidateXmlCommand
Data.DataId = message.DataId;
await context.Send<ValidateXmlCommand>( x => { x.Filename = message.Filename; x.CustomerId = message.CustomerId; });
}
Here's the stack trace:
at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult& result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult& result)
at System.Guid..ctor(String g)
at Raven.Client.Converters.GuidConverter.ConvertTo(String value) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Converters\GuidConverter.cs:line 51
at Raven.Client.Document.GenerateEntityIdOnTheClient.SetPropertyOrField(Type propertyOrFieldType, Object entity, Action`1 setIdentifier, String id) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:line 170
at Raven.Client.Document.GenerateEntityIdOnTheClient.TrySetIdentity(Object entity, String id) in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:line 143
at Raven.Client.Document.InMemoryDocumentSessionOperations.<GenerateDocumentKeyForStorageAsync>d__99.MoveNext() in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Document\InMemoryDocumentSessionOperations.cs:line 833
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Raven.Client.Document.InMemoryDocumentSessionOperations.<StoreAsyncInternal>d__96.MoveNext() in C:\Builds\RavenDB-Stable-3.5\Raven.Client.Lightweight\Document\InMemoryDocumentSessionOperations.cs:line 803
Any help guys?
After removing
store.Conventions.IdentityPartsSeparator = "-";
the issue was fixed.
See HadiEskandari's comment above and this link for more info: Exception in RavenDB.SagaPersister.Save, "Guid should contain 32 digits with 4 dashes". Guid is empty in Raven
Related
I'm trying to write a contract test using PactNet for the following method:
public async Task<IEnumerable<Models.RefData.Instrument> GetInstruments(string issuerCountry, string instrumentType)
{
ValidateNotNullOrWhiteSpaceParameter(issuerCountry, nameof(issuerCountry));
ValidateNotNullOrWhiteSpaceParameter(instrumentType, nameof(instrumentType)); ;
var queryString = $"instruments?issuerCountry={HttpUtility.UrlEncode(issuerCountry)}&instrumentType={HttpUtility.UrlEncode(instrumentType)}";
int pageNo = 0;
int pageSize = 20;
_logger.LogDebug($"GetInstruments Request:{queryString}");
var httpResponseMessage = await _client.GetAsync(queryString + $"&page={pageNo}&size={pageSize}");
_logger.LogDebug($"GetInstruments Response Status Code:{httpResponseMessage.StatusCode}");
switch (httpResponseMessage.StatusCode)
{
case HttpStatusCode.OK:
var content = await httpResponseMessage.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<GetInstrumentsResponse>(content);
// if there are no results, return Empty
if (result.Metadata.TotalElements == 0)
{
return Enumerable.Empty<Models.RefData.Instrument>();
}
var instruments = new List<Models.RefData.Instrument>();
instruments.AddRange(result.Embedded.Instruments);
for (pageNo = 1; pageNo < result.Metadata.TotalPages; pageNo++)
{
var innerQueryString = queryString + $"&page={pageNo}&size={pageSize}";
_logger.LogDebug($"GetInstruments Request Additional Page:{innerQueryString}");
var httpResponseMessage2 = await _client.GetAsync(innerQueryString);
if (httpResponseMessage2.StatusCode != HttpStatusCode.OK)
{
_logger.LogError($"The requested page number {pageNo} gets response error {httpResponseMessage2.StatusCode.ToString()}.");
throw new UnexpectedResponseException(httpResponseMessage.StatusCode);
}
var content2 = await httpResponseMessage2.Content.ReadAsStringAsync();
var result2 = JsonConvert.DeserializeObject<GetInstrumentsResponse>(content2);
if (result2.Embedded.Instruments != null && result2.Embedded.Instruments.Any())
{
instruments.AddRange(result2.Embedded.Instruments);
}
}
if (instruments.Count != result.Metadata.TotalElements)
{
_logger.LogWarning($"Total number of instruments is different from MetaData. MetaData states {result.Metadata.TotalElements}, however only {instruments.Count} instruments retrieved.");
}
_logger.LogDebug($"GetInstruments Result:{instruments.ToJson()}");
return instruments;
default:
throw new UnexpectedResponseException(httpResponseMessage.StatusCode);
}
}
I created the following ConsumerPactTests.cs and ConsumerPactClassFixture.cs using this as a guide.
public class ConsumerPactTests : IClassFixture<ConsumerPactClassFixture>
{
private IMockProviderService _mockProviderService;
private string _mockProviderServiceBaseUri;
public ConsumerPactTests(ConsumerPactClassFixture fixture)
{
_mockProviderService = fixture.MockProviderService;
_mockProviderService.ClearInteractions(); //NOTE: Clears any previously registered interactions before the test is run
_mockProviderServiceBaseUri = fixture.MockProviderServiceBaseUri;
}
[Fact]
public void ItHandlesInvalidDateParam()
{
// Arange
var invalidRequestMessage = "issuerCountry or instrumentType is not valid";
_mockProviderService.Given("There is data")
.UponReceiving("A invalid GET request for Date Validation with invalid date parameter")
.With(new ProviderServiceRequest
{
Method = HttpVerb.Get,
Path = "/api/v2",
Query = "issuerCountry=USA&instrumentType=foo"
})
.WillRespondWith(new ProviderServiceResponse
{
Status = 400,
Headers = new Dictionary<string, object>
{
{ "Content-Type", "application/json; charset=utf-8" }
},
Body = new
{
message = invalidRequestMessage
}
});
// Act
RefDataHttpService sut = new RefDataHttpServiceBuilder().Build();
var result = sut.GetInstruments("USA", "foo").GetAwaiter().GetResult();
var resultBodyText = result.GetEnumerator();
// Assert
Assert.NotNull(resultBodyText);
}
}
public class ConsumerPactClassFixture : IDisposable
{
public IPactBuilder PactBuilder { get; private set; }
public IMockProviderService MockProviderService { get; private set; }
public int MockServerPort { get { return 9222; } }
public string MockProviderServiceBaseUri { get { return String.Format("http://localhost:{0}", MockServerPort); } }
public ConsumerPactClassFixture()
{
var pactConfig = new PactConfig
{
SpecificationVersion = "2.0.0",
PactDir = #"..\..\..\..\..\pacts",
LogDir = #".\pact_logs"
};
PactBuilder = new PactBuilder(pactConfig);
PactBuilder.ServiceConsumer("Consumer")
.HasPactWith("Provider");
MockProviderService = PactBuilder.MockService(MockServerPort);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// This will save the pact file once finished.
PactBuilder.Build();
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion
}
When I run my test I get this error:
dotnet test --filter "FullyQualifiedName=Bond.Publisher.Tests.ContractTest.ConsumerPactTests.ItHandlesInvalidDateParam"
Test run for c:\Workspace\prod\test\Bond.Publisher.Tests\bin\Debug\netcoreapp3.1\Bond.Publisher.Tests.dll(.NETCoreApp,Version=v3.1)
Microsoft (R) Test Execution Command Line Tool Version 16.7.0
Copyright (c) Microsoft Corporation. All rights reserved.
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:10.95] Bond.Publisher.Tests.ContractTest.ConsumerPactTests.ItHandlesInvalidDateParam [FAIL]
X Bond.Publisher.Tests.ContractTest.ConsumerPactTests.ItHandlesInvalidDateParam [4s 196ms]
Error Message:
System.Net.Http.HttpRequestException : No connection could be made because the target machine actively refused it.
---- System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it.
Stack Trace:
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Bond.Publisher.HttpMessageHandlers.UnoAuthorisationHeaderMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in c:\Workspace\usprod\src\Bond.Publisher\HttpMessageHandlers\UnoAuthorisationHeaderMessageHandler.cs:line 37
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at Bond.Publisher.Services.RefDataHttpService.GetInstruments(String issuerCountry, String instrumentType) in c:\Workspace\prod\src\Bond.Publisher\Services\RefDataHttpService.cs:line 52
at Bond.Publisher.Tests.ContractTest.ConsumerPactTests.ItHandlesInvalidDateParam() in c:\Workspace\prod\test\Bond.Publisher.Tests\ContractTest\ConsumerPactTests.cs:line 52
----- Inner Stack Trace -----
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
Test Run Failed.
I suspect it may be some sort of authentication issue as UnoAuthorisationHeaderMessageHandler.cs deals with that. What have I done wrong with this?
For me the path was too long. When I moved the project to a folder closer to C:\ the test ran.
The System.Net.Sockets.SocketException : No connection could be made because the target machine actively refused it. usually happens when there is no server listening on the url you are sending.
Check if the ruby service is up and running (the test runner starts it), you should see it in Task Manager under Visual Studio
Alernatively, before you call pactBuilder.Build(), you should be able to do an HTTP request through PostMan to http://localhost:9222/instruments...
I have a web application which runs in IIS 7 and using SQL Server 2014 & web API2 in SOLID principle.
I have a Order Table which contains 51 column, where I save orders details from multiple client.
Firstly i validate the order details(duplicate,order id existence etc) and then I save it to the same table.
My MVC controller are decorated with Asynchronous type.
I am using transaction & logging in stored procedure where I wrote Insert query.
I googled the same issue,but a bit confused who to implement a quick solution for this.
My questions are:
What should be the right System design to handle such concurrent order request.
How should I design my database tables or stored procedure so that order can be saved successfully.
How should I optimize or introduce any new coding technique to solve such concurrent traffic at least 500 orders per sec.
I would be very glad if somebody can help me out with an example.
Error occurred on 10/5/2020 10:43:12.968, at bookingController/CacheOrderDetails Action
System.InvalidOperationException: BeginExecuteReader requires an open and available
Connection. The connection's current state is connecting.
at System.Data.SqlClient.SqlCommand.<>c.<ExecuteDbDataReaderAsync>b__174_0(Task`1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Dapper.SqlMapper.<QueryAsync>d__23`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at DAL.DbHelper.<StoredProcWithParamsAsync>d__20`1.MoveNext() in D:\SamWorkspace\DMS_Live_28\DAL\DbHelper.cs:line 303
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Repository.Impl.ApiIntegration.<CacheOrderDetails>d__1.MoveNext() in D:\SamWorkspace\DMS_Live_28\Repository\Impl\ApiIntegration.cs:line 25
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at bookingController.<CacheOrderDetails>d__59.MoveNext() in c:\DMS\LIVE_CODE\DmsLive_PublishCode\App_Code\api\bookingController.cs:line 1357
ActionMethod
public async Task<string> CacheOrderDetails(modelManifest Obj, Int64 UserId, Int64 CustId)
{
try
{
StringBuilder message = new StringBuilder("");
#region declare payload for Save Manifest
var data = new
{
CreatedById = UserId,
CustId = CustId,
AwbNo = Obj.AWB_NUMBER,
OrderNo = Obj.ORDER_NUMBER,
ProductType = Obj.PRODUCT,
Consignee = Obj.CONSIGNEE,
ConsigneeAdd1 = Obj.CONSIGNEE_ADDRESS1,
ConsigneeAdd2 = Obj.CONSIGNEE_ADDRESS2,
ConsigneeAdd3 = Obj.CONSIGNEE_ADDRESS3,
DestCity = Obj.DESTINATION_CITY,
DestPin = Obj.PINCODE,
State = Obj.STATE,
Mobile = Obj.MOBILE,
Telephone = Obj.TELEPHONE,
ItemDesc = Obj.ITEM_DESCRIPTION,
Pieces = Obj.PIECES,
Colvalue = Obj.COLLECTABLE_VALUE,
DeclValue = Obj.DECLARED_VALUE,
ActualWeight = Obj.ACTUAL_WEIGHT,
VolmWeight = Obj.VOLUMETRIC_WEIGHT,
Length = Obj.LENGTH,
Breadth = Obj.BREADTH,
height = Obj.HEIGHT,
PickupName = Obj.PICKUP_NAME,
PickupAdd1 = Obj.PICKUP_ADDRESS_LINE1,
PickupAdd2 = Obj.PICKUP_ADDRESS_LINE2,
PickupPin = Obj.PICKUP_PINCODE,
PickupPhone = Obj.PICKUP_PHONE,
PickupMobile = Obj.PICKUP_MOBILE,
ReturnPin = Obj.RETURN_PINCODE,
ReturnName = Obj.RETURN_NAME,
ReturnAdd1 = Obj.RETURN_ADDRESS_LINE1,
ReturnAdd2 = Obj.RETURN_ADDRESS_LINE2,
ReturnPhone = Obj.RETURN_PHONE,
ReturnMobile = Obj.RETURN_MOBILE,
VendorCode = Obj.VENDOR_CODE,
};
#endregion
if (data != null)
{
// Int32? ShipmentId = client.CreateShipment_ApiOnly(data);
Int32? ShipmentId = await client.CacheOrderDetails(data);
if (ShipmentId > 0 & Obj.PRODUCT.Contains("REV"))
{
#region declare payload for Save Manifest (QC params)
var QcParam = new
{
// ShipmentId = ShipmentId,
TempId = ShipmentId,
DrsUid = 0,
QC1_Text = Obj.QC1_Text,
QC2_Text = Obj.QC2_Text,
QC3_Text = Obj.QC3_Text,
QC4_Text = Obj.QC4_Text,
QC5_Text = Obj.QC5_Text,
QC6_Text = Obj.QC6_Text,
QC7_Text = Obj.QC7_Text,
QC8_Text = Obj.QC8_Text,
QC9_Text = Obj.QC9_Text,
QC10_Text = Obj.QC10_Text,
QC1_Val = Obj.QC1_Val,
QC2_Val = Obj.QC2_Val,
QC3_Val = Obj.QC3_Val,
QC4_Val = Obj.QC4_Val,
QC5_Val = Obj.QC5_Val,
QC6_Val = Obj.QC6_Val,
QC7_Val = Obj.QC7_Val,
QC8_Val = Obj.QC8_Val,
QC9_Val = Obj.QC9_Val,
QC10_Val = Obj.QC10_Val
};
#endregion
int? QcResult = DbCust.SaveShipmentQC_Details(QcParam);
if (QcResult == 0 || QcResult == null)
{
message.Append("Unable to update QC records");
}
else
message.Append("SUCCESS");
}
else
{
if (ShipmentId != null && ShipmentId > 0 && !Obj.PRODUCT.Contains("REV"))
{
message.Append("SUCCESS");
}
else
message.Append("Record already exists");
}
return message.ToString();
}
else
return "FAILURE";
}
catch (Exception ex)
{
log.LogError("bookingController/CacheOrderDetails Action", ex);
return "FAILURE";
}
}
Implementation Class
public async Task<Int32> CacheOrderDetails(object o)
{
// return DbHelper.StoredProcWithParamsAsync<Int32>("SaveOrderDetails", o).FirstOrDefault();
var res = await DbHelper.StoredProcWithParamsAsync<Int32>("SaveOrderDetails", o);
return res.FirstOrDefault();
}
DB Helper Class
public static async Task<List<T>> StoredProcWithParamsAsync<T>(string procname, dynamic parms, string connectionName = null)
{
using (SqlConnection connection = GetOpenConnectionAsync(connectionName))
{
var res= await connection.QueryAsync<T>(procname, (object)parms, commandType: CommandType.StoredProcedure);
return res.ToList();
}
}
Connection String Declaration
public static SqlConnection GetOpenConnectionAsync(string name = null)
{
string connString = "";
connString = ConfigurationManager.ConnectionStrings["connstr1"].ConnectionString;
var connection = new SqlConnection(connString);
connection.OpenAsync();
return connection;
}
I have the following issue using Azure Data Factory version 1 (ADF1).
I have a DotNetActivity which I use to load info from atlas.microsoft.com.
Since two days ago the activity is failing returning the following message:
Error in Activity: Unknown error in module: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Wen.Logging.Http.HttpClientExtensions.Send(HttpClient client, HttpMethod method, String url, HttpContent data, Dictionary`2 headers)
at Wen.Logging.Http.HttpClientExtensions.Get(HttpClient client, String url, Dictionary`2 headers)
at Delfos.CodeActivities.Activities.AzureMapClient.GetTimeZonesIds() in C:\projects\delfos\src\Delfos.CodeActivities\Activities\AzureMapClient.cs:line 52
at Delfos.CodeActivities.Activities.AzureMaps.LoadTimeZones.AdjustTimeZones(String connectionString) in C:\projects\delfos\src\Delfos.CodeActivities\Activities\AzureMaps\LoadTimeZones.cs:line 39
at Delfos.CodeActivities.Activities.AzureMaps.LoadTimeZones.Execute(IEnumerable`1 linkedServices, IEnumerable`1 datasets, Activity activity, IActivityLogger logger) in C:\projects\delfos\src\Delfos.CodeActivities\Activities\AzureMaps\LoadTimeZones.cs:line 32
at Microsoft.Azure.Management.DataFactories.Runtime.ActivityExecutor.Execute(Object job, String configuration, Action`1 logAction)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.DataPipeline.Compute.HDInsightJobExecution.ReflectingActivityWrapper.Execute()
at Microsoft.DataPipeline.Compute.HDInsightJobExecution.JobWrapper.RunJob()
at Microsoft.DataPipeline.Compute.HDInsightJobExecution.Launcher.Main(String[] args)..
This is my Dot Net Activity:
using System;
using System.Collections.Generic;
using Microsoft.Azure.Management.DataFactories.Models;
using Microsoft.Azure.Management.DataFactories.Runtime;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
namespace Delfos.CodeActivities.Activities.AzureMaps
{
public class LoadTimeZones : IDotNetActivity
{
private readonly DateTime startDate = new DateTime(2012, 1, 1);
public IDictionary<string, string> Execute(IEnumerable<LinkedService> linkedServices,
IEnumerable<Dataset> datasets,
Activity activity,
IActivityLogger logger)
{
var odsStagingSqlInputDataset = datasets
.Where(dataset => dataset.Name == "dim-date-staging")
.First();
var odsStagingSqlInputLinkedService = linkedServices.Where(
linkedService =>
linkedService.Name ==
odsStagingSqlInputDataset.Properties.LinkedServiceName).First().Properties.TypeProperties
as AzureSqlDatabaseLinkedService;
AdjustTimeZones(odsStagingSqlInputLinkedService.ConnectionString);
return new Dictionary<string, string>();
}
public void AdjustTimeZones(string connectionString)
{
var transitionsYears = DateTime.Now.AddYears(1).Subtract(startDate).Days / 365;
var timeZonesIds = AzureMapClient.GetTimeZonesIds();
var usTimeZonesIds = timeZonesIds.Where(zone => zone.Id.StartsWith("US/") && zone.Id != "US/Arizona");
var timeZoneTable = CreateTimeZoneDataTable();
var marked = new Dictionary<string, bool>();
foreach (var zoneId in usTimeZonesIds)
{
var timeZone = AzureMapClient.GetTimeZone(zoneId.Id, startDate, transitionsYears);
if (marked.ContainsKey(timeZone.Names.Generic))
continue;
marked.Add(timeZone.Names.Generic, true);
timeZone.TimeTransitions.ForEach(t => timeZoneTable.Rows.Add(
timeZone.Names.Generic,
t.UtcStart,
t.UtcEnd,
t.StandardOffset.Add(t.DaylightSavings).Hours,
t.DaylightSavings.Hours > 0 ? true : false
));
}
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
Util.ExecuteUpsertStoredProcedure("ods_ui.LoadTimeZones", "TimeZones", timeZoneTable, connection);
}
}
private DataTable CreateTimeZoneDataTable()
{
var table = new DataTable();
table.Columns.Add("TimeZone", typeof(string));
table.Columns.Add("StartDate", typeof(DateTime));
table.Columns.Add("EndDate", typeof(DateTime));
table.Columns.Add("UTCdifferenceHours", typeof(int));
table.Columns.Add("IsDaylightSavings", typeof(bool));
return table;
}
}
}
and this is the class I use as helper:
using Delfos.CodeActivities.Models.AzureMaps;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net;
using Wen.Logging.Http;
namespace Delfos.CodeActivities.Activities
{
public static class AzureMapClient
{
private const string atlasUrl = "https://atlas.microsoft.com";
private const string subscriptionKey = "<replaced_actual_value>";
public static Models.AzureMaps.TimeZone GetTimeZone(string zone,
DateTime transitionsFrom,
int transitionsYears = 1,
string options = "all")
{
var baseUrl = new Uri(atlasUrl);
var endpoint = $#"timezone/byId/json?subscription-key={subscriptionKey}&api-version=1.0&options={options}&query={zone}&transitionsFrom={transitionsFrom.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'")}&transitionsYears={transitionsYears}";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
using (var client = new HttpClient())
{
var response = client.Get(baseUrl.AbsoluteUri + endpoint);
if (!response.IsSuccessStatusCode)
return new Models.AzureMaps.TimeZone();
var respContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var timeZonesContent = JObject.Parse(respContent).SelectToken("TimeZones").ToString();
var timeZones = JsonConvert.DeserializeObject<List<Models.AzureMaps.TimeZone>>(timeZonesContent);
return timeZones.FirstOrDefault();
}
}
public static List<TimeZoneId> GetTimeZonesIds()
{
var baseUrl = new Uri(atlasUrl);
var endpoint = $"timezone/enumIana/json?subscription-key={subscriptionKey}&api-version=1.0";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
using (var client = new HttpClient())
{
var response = client.Get(baseUrl.AbsoluteUri + endpoint);
if (!response.IsSuccessStatusCode)
return new List<TimeZoneId>();
var respContent = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
var timeZonesIds = JsonConvert.DeserializeObject<List<TimeZoneId>>(respContent);
return timeZonesIds;
//return new List<TimeZoneId>();
}
}
}
}
this line:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
was my last try, since I found that enforcing SecurityProtocol to TLS1.2 allowed me to run the whole code from my local project, but once in the cloud failures continued.
While using the code base from the project to create a reminder, I get the following error:
Error at Alexa.NET.Response.RemindersClient.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at AlexaWebAPI.Controllers.ReminderController.d__0.MoveNext()
Sample code I am using:
try
{
var reminder = new Reminder
{
RequestTime = DateTime.UtcNow,
Trigger = new RelativeTrigger(12 * 60 * 60),
AlertInformation = new AlertInformation(new[] {new SpokenContent("it's a test", "en-GB") }),
PushNotification = PushNotification.Disabled
};
var client = new RemindersClient(RemindersClient.ReminderDomain,input.Session.User.AccessToken);
var alertDetail = await client.Create(reminder);
Trace.TraceInformation(alertDetail.AlertToken);
return ResponseBuilder.Tell($"I would to create a reminder on ${date} .");
}
catch(Exception ex)
{
Trace.TraceError(ex.StackTrace);
return ResponseBuilder.Ask("Some error occured while creating reminder", null);
}
I'm trying to write a simple windows store app that forces a user to login right away. I'm following these guides:
http://msdn.microsoft.com/en-us/library/live/hh968445.aspx
And
http://msdn.microsoft.com/en-us/library/live/hh826543.aspx#csharp
and I've added the following:
public LiveConnectSession Session
{
get
{
return _session;
}
set
{
_session = value;
}
}
private async void InitAuth()
{
if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
try
{
authClient = new LiveAuthClient();
List<string> perms = new List<string>() { "wl.signin", "wl.basic", "wl.skydrive" };
LiveLoginResult authResult = await authClient.LoginAsync(perms);
if (authResult.Status == LiveConnectSessionStatus.Connected)
{
this.Session = authResult.Session;
}
}
catch (Exception e)
{
String message = e.Message;
}
}
}
I call InitAuth() from the App() constructor.
I get an "Element Not Found" Excetion, and the following stack trace:
at Microsoft.Live.LiveAuthClient.<ExecuteAuthTaskAsync>d__4.MoveNext()
End of stack trace from previous location where exception was thrown
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at TuneHoc.App.<InitAuth>d__1.MoveNext() in <filename>
Does anyone know the problem?