Couchbase Lite 2.1 Replicator Issue .net - c#

We have just upgraded our SyncGatewaty to 2.1. So now I’m refactoring our client code to use CouchbaseLite 2.1. When I try to replicate I get the error:
Got LiteCore error: Not Found (6/404)
I originally got the error when connecting to our Dev Server, and then installed a local clean copy on my laptop and I get the same error when trying to connect to it too.
Log:
INFO) Couchbase 2019-01-10T10:56:47.8503147-07:00 (Startup) [1] CouchbaseLite/2.1.2 (.NET; Microsoft Windows 10.0.17763 ) Build/13 LiteCore/ (15) Commit/9aebf28
WARNING) LiteCore 2019-01-10T10:56:48.1943139-07:00 {C4SocketImpl#1}==> class litecore::repl::C4SocketImpl ws://localhost.com:443//_blipsync
WARNING) LiteCore 2019-01-10T10:56:48.1943139-07:00 {C4SocketImpl#1} Unexpected or unclean socket disconnect! (reason=WebSocket status, code=404)
ERROR) Sync 2019-01-10T10:56:48.1993137-07:00 {Repl#2}==> class litecore::repl::Replicator c:\temp\content_meta_data.cblite2\ ->ws://localhost:443//_blipsync
ERROR) Sync 2019-01-10T10:56:48.1993137-0
7:00 {Repl#2} Got LiteCore error: Not Found (6/404)
My code:
using System;
using System.IO;
using Couchbase.Lite;
using Couchbase.Lite.Support;
using Couchbase.Lite.Sync;
using NLog;
namespace ReplicatorExample
{
public class DatabaseManager
{
private static readonly Logger _log = LogManager.GetCurrentClassLogger();
public const string BUCKET_CONTENT_META_DATA = "content_meta_data";
private static DatabaseManager _instance;
public static DatabaseManager GetInstance()
{
NetDesktop.Activate();
NetDesktop.EnableTextLogging("logs");
return _instance ?? (_instance = new DatabaseManager());
}
public void InitializeBuckets()
{
try
{
var defaultAuthenticator = GetDefaultAuthenticator();
var dirInfo = new DirectoryInfo($"c:\\temp\\{BUCKET_CONTENT_META_DATA}");
if (!dirInfo.Parent.Exists)
{
dirInfo.Parent.Create();
}
var database = new Database(dirInfo.FullName);
// Create replicator to push and pull changes to and from the cloud
var targetEndpoint = new URLEndpoint(new Uri("ws://localhost:4985"));
var replConfig = new ReplicatorConfiguration(database, targetEndpoint)
{
Authenticator = defaultAuthenticator,
Continuous = true,
//Channels = new List<string>
//{
// "approved",
//
//}
};
var replicator = new Replicator(replConfig);
replicator.AddChangeListener((sender, args) =>
{
if (args.Status.Error != null)
{
_log.Error($"{args.Status.Error}");
}
else
{
_log.Debug(args.Status);
}
});
replicator.Start();
}
catch (Exception e)
{
_log.Error(e);
}
}
private Authenticator GetDefaultAuthenticator()
{
return new BasicAuthenticator("BigD","123456");
}
}
}

I believe you need to specify the database name in the URL for targetEndpoint.
E.g: var targetEndpoint = new URLEndpoint(new Uri("ws://localhost:4984/mydatabase"));

Related

Authenticating a Callback URL in a REST API

We are testing Azure Communication Services in a new project. Specifically, we are looking at the Azure Communication Services for Calling documented here and the quick start project found here.
The general pattern to utilize the service is shown in the following code.
public string AppCallbackUrl => $"{AppBaseUrl}/api/outboundcall/callback?{EventAuthHandler.GetSecretQuerystring}"
// Defined the call with a Callback URL
var source = new CommunicationUserIdentifier(callConfiguration.SourceIdentity);
var target = new PhoneNumberIdentifier(targetPhoneNumber);
var createCallOption = new CreateCallOptions(
new Uri(AppCallbackUrl),
new List<MediaType> { MediaType.Audio },
new List<EventSubscriptionType> { EventSubscriptionType.DtmfReceived });
// Initiate the call
var call = await callClient.CreateCallConnectionAsync(
source, new List<CommunicationIdentifier>() { target }, createCallOption, reportCancellationToken)
.ConfigureAwait(false);
// Register for call back events
RegisterToCallStateChangeEvent(call.Value.CallConnectionId);
The example uses a configuration value or hardcoded secret key to authenticate the Callback Url, as shown below.
[Route("api/[controller]")]
[ApiController]
public class OutboundCallController : ControllerBase
{
[AllowAnonymous]
[HttpPost("callback")]
public async Task<IActionResult> OnIncomingRequestAsync()
{
// Validating the incoming request by using secret set in app.settings
if (EventAuthHandler.Authorize(Request))
{
...
}
else
{
return StatusCode(StatusCodes.Status401Unauthorized);
}
}
}
public class EventAuthHandler
{
private static readonly string SecretKey = "secret";
private static readonly string SecretValue;
static EventAuthHandler()
{
SecretValue = ConfigurationManager.AppSettings["SecretPlaceholder"] ?? "h3llowW0rld";
}
public static bool Authorize(HttpRequest request)
{
if (request.QueryString.Value != null)
{
var keyValuePair = HttpUtility.ParseQueryString(request.QueryString.Value);
return !string.IsNullOrEmpty(keyValuePair[SecretKey]) && keyValuePair[SecretKey].Equals(SecretValue);
}
return false;
}
public static string GetSecretQuerystring => $"{SecretKey}={HttpUtility.UrlEncode(SecretValue)}";
}
Is there a better way to do this in a production environment? How can I incorporate ASP.NET Core authentication with a Callback?

How can I send traces to Jaeger from C#?

I'm trying to use the Jaeger package to send traces to Jaeger from a C# app.
There are no minimal examples in the jaeger-client-csharp documentation, but from what I read, I think this should work.
using Jaeger;
using Jaeger.Samplers;
namespace jaegertest
{
class Program
{
static void Main(string[] args)
{
var tracer = new Tracer.Builder("my-service")
.WithSampler(new ConstSampler(true))
.Build();
using (var scope = tracer.BuildSpan("foo").StartActive(true))
{
System.Threading.Thread.Sleep(1000);
}
}
}
}
I have jaeger-all-in-one.exe running but when I run this code there's no sign of any new traces. I've tried manually configuring samplers, senders, reporters, etc. but nothing I tried worked. What do I need to add to get my traces to appear in Jaeger?
This is the simplest working example that I was able to find.
using Jaeger;
using Jaeger.Reporters;
using Jaeger.Samplers;
using Jaeger.Senders.Thrift;
namespace jaegertest
{
class Program
{
static void Main(string[] args)
{
var tracer = new Tracer.Builder("my-service")
.WithSampler(new ConstSampler(true))
.WithReporter(new RemoteReporter.Builder()
.WithSender(new UdpSender())
.Build())
.Build();
using (var scope = tracer.BuildSpan("foo").StartActive(true))
{
System.Threading.Thread.Sleep(1000);
}
tracer.Dispose();
}
}
}
Here is a more realistic example that builds the tracer from a configuration.
using Jaeger;
using Jaeger.Samplers;
using Jaeger.Senders;
using Jaeger.Senders.Thrift;
using Microsoft.Extensions.Logging;
namespace jaegertest
{
class Program
{
static void Main(string[] args)
{
var loggerFactory = new LoggerFactory();
var samplerConfiguration = new Configuration.SamplerConfiguration(loggerFactory)
.WithType(ConstSampler.Type)
.WithParam(1);
var senderResolver = new SenderResolver(loggerFactory)
.RegisterSenderFactory<ThriftSenderFactory>();
var senderConfiguration = new Configuration.SenderConfiguration(loggerFactory)
.WithSenderResolver(senderResolver);
var reporterConfiguration = new Configuration.ReporterConfiguration(loggerFactory)
.WithSender(senderConfiguration)
.WithLogSpans(true);
var tracer = (Tracer)new Configuration("my-service", loggerFactory)
.WithSampler(samplerConfiguration)
.WithReporter(reporterConfiguration)
.GetTracer();
using (var scope = tracer.BuildSpan("foo").StartActive(true))
{
System.Threading.Thread.Sleep(1000);
}
tracer.Dispose();
}
}
}

Async API Request New

I am trying to make an API call in an ASP.NET web form. The request works fine in Console, but async requests are timing out and not working. Please advise.
Console App Code:
using System;
using System.Collections.Generic;
using System.Text;
using Newegg.Marketplace.SDK;
using Newegg.Marketplace.SDK.Base;
using Newegg.Marketplace.SDK.DataFeed;
using Newegg.Marketplace.SDK.DataFeed.Model;
using Newegg.Marketplace.SDK.Item;
using Newegg.Marketplace.SDK.Item.Model;
using Newegg.Marketplace.SDK.Order;
using Newegg.Marketplace.SDK.Order.Model;
using Newegg.Marketplace.SDK.Other;
using Newegg.Marketplace.SDK.Other.Model;
using Newegg.Marketplace.SDK.Report.Model;
using Newegg.Marketplace.SDK.RMA;
using Newegg.Marketplace.SDK.RMA.Model;
using Newegg.Marketplace.SDK.Seller;
using Newegg.Marketplace.SDK.Seller.Model;
using Newegg.Marketplace.SDK.Shipping.Model;
namespace example
{
public class Demo
{
private OrderCall ordercall;
private ItemCall itemCall;
private SellerCall sellerCall;
private DatafeedCall datafeedCall;
private RMACall rmaCall;
private ShippingCall shippingCall;
private ReportCall reportCall;
private OtherCall otherCall;
public Demo()
{
//Construct an APIConfig with SellerID, APIKey(Authorization) and SecretKey.
APIConfig config = new APIConfig("****", "********************************", "********-****-****-****-************");
// or load the config file to get it.
//APIConfig config = APIConfig.FromJsonFile("setting.json");
//Create a APIClient with the config
APIClient client = new APIClient(config);
//Create the Api Call object with he client.
ordercall = new OrderCall(client);
itemCall = new ItemCall(client);
sellerCall = new SellerCall(client);
datafeedCall = new DatafeedCall(client);
rmaCall = new RMACall(client);
shippingCall = new ShippingCall(client);
reportCall = new ReportCall(client);
otherCall = new OtherCall(client);
}
public void GetOrderStatus()
{
Console.WriteLine("GetOrderStatus");
// Send your request and get response
var orderstatus = ordercall.GetOrderStatus("105137040").Result;
// Use the data pre you business
Console.WriteLine(string.Format("There order status is {0}.", orderstatus.OrderStatusName));
}
}
My ASP.NET code
public partial class HomePage : System.Web.UI.Page
{
private OrderCall orderCall;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RegisterAsyncTask(new PageAsyncTask(LoadSomeData));
}
}
public async Task LoadSomeData()
{
string path = #"C:\Users\*****\source\repos\Orders\Settings\setting.json";
APIConfig config = APIConfig.FromJsonFile(path);
APIClient client = new APIClient(config);
orderCall = new OrderCall(client);
try
{
var orderstatus = await orderCall.GetOrderStatus("105137040");
Debug.Write(orderstatus.OrderStatusName);
Connect.BackColor = Color.Green;
}
catch (Exception ex)
{
Connect.BackColor = Color.Red;
Debug.WriteLine(ex.Message);
}
}
}
}
After using my code, the page freezes and eventually times out. The returned object is also null or returns an error.

NancyFX HEAD verb causing connection reset

I am having problems using fulfilling HEAD requests in NancyFX (0.23.2). I am using Nancy self-hosting and GET works fine, but HEAD just causes a dropped connection. From debugging the source, it seems that an exception is being thrown at NancyHost.OutputWithDefaultTransferEncoding (line 321), with additional information "An operation was attempted on a non-existent network connection"
Do I need to do anything special to support HEAD?
Thanks,
Jon
public class Program
{
static void Main(string[] args)
{
var hostConfiguration = new HostConfiguration();
hostConfiguration.UrlReservations.CreateAutomatically = true;
var _host = new NancyHost(hostConfiguration, new Uri("http://localhost:1010"));
_host.Start();
Console.ReadKey();
}
}
public class Module : NancyModule
{
public Module()
{
Get["/"] = x =>
{
return 201;
};
}
}

No clients available in SignalR Hub context

I am new to SignalR and am experimenting with setting up a self host service that I can use to send events to other applications. I am having a problem getting a method to be called on all clients. In the code below _context.Clients.All is always empty. Any Ideas?
Test Method:
var server = new SignalRServer();
server.Start("http://localhost:8555");
var hubConnection = new HubConnection("http://localhost:8555");
var proxy = hubConnection.CreateHubProxy("testHub");
var executed = false;
proxy.On("testMethod", () =>
{
executed = true;
});
hubConnection.Start().Wait();
var hub = new TestHubContext(GlobalHost.ConnectionManager.GetHubContext<TestHub>());
hub.Test();
hubConnection.Stop();
server.Stop();
Self host server:
public class SignalRServer
{
private IDisposable _signalR;
public void Start(string url)
{
_signalR = WebApp.Start<SignalRStartup>(url);
}
public void Stop()
{
_signalR.Dispose();
}
}
public class SignalRStartup
{
public static IAppBuilder App = null;
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
Hub:
public class TestHub : Hub
{
}
public class TestHubContext
{
private IHubContext _context;
public TestHubContext(IHubContext context)
{
_context = context;
}
public void Test()
{
if (_context != null)
{
// At this poing _context.Clients.All is always empty
_context.Clients.All.testMethod();
}
}
}
I think your context / client connections are fine. Without further information I'm guessing your problem is that you are closing your connection and server too quickly after calling hub.Test()
Comment out the two .Stop() calls (and stick a Console.ReadLine in there to keep the console open) and see what happens

Categories

Resources