When I run the section of my project in C# nothing happens for about 30 seconds and it sends that error message in the title above, I am currently using .NET 5 Framework, the latest mongo drivers and my own Mongo Host (I tried Mongo atlas and it didnt work either). I have no clue as to why this doesnt work and was wondering if anyone knew why.
MongoClientSettings settings = new MongoClientSettings();
settings.ConnectTimeout = new TimeSpan(1000);
settings.WaitQueueTimeout = new TimeSpan(0, 2, 0);
settings.MinConnectionPoolSize = 1;
settings.MaxConnectionPoolSize = 25;
settings.Server = new MongoServerAddress("139.99.197.10");
Console.WriteLine(" connected");
MongoClient client = new MongoClient(settings);
database = client.GetDatabase(name);
public static bool DoesUserExist(String paramLicense)
{
List<Profile> records = GetMongo().Load<Profile>("Users");
bool correctCredentials = false;
foreach (var record in records)
{
if (record.licenseKey.Equals(paramLicense, StringComparison.InvariantCultureIgnoreCase))
{
correctCredentials = true;
break;
}
}
if (correctCredentials) {
return true;
}
return false;
}
Related
I would like to use a c# language server client to connect and communicate with a language server. The language server client I found is here (https://github.com/OmniSharp/csharp-language-server-protocol). In the examples I found code to create a client.
protected virtual ILanguageClient CreateClient(Action<LanguageClientOptions> clientOptionsAction = null)
{
_client = LanguageClient.Create(
options => {
var (reader, writer) = SetupServer();
options
.WithInput(reader)
.WithOutput(writer)
.WithLoggerFactory(TestOptions.ClientLoggerFactory)
.WithAssemblies(TestOptions.Assemblies)
.WithAssemblies(typeof(LanguageProtocolTestBase).Assembly, GetType().Assembly)
.ConfigureLogging(x => x.SetMinimumLevel(LogLevel.Trace))
.WithInputScheduler(options.InputScheduler)
.WithOutputScheduler(options.OutputScheduler)
.WithDefaultScheduler(options.DefaultScheduler)
.Services
.AddTransient(typeof(IPipelineBehavior<,>), typeof(SettlePipeline<,>))
.AddSingleton(Events as IRequestSettler);
clientOptionsAction?.Invoke(options);
}
);
Disposable.Add(_client);
return _client;
}
But it is not clear to me how I can establish a connection to a language server (that is, to a language-server.exe). I found this example here (https://gist.github.com/tintoy/a2ec9424d17fe9ef17db0621479a7b43) but I think it's never has been working or with a very old version of the omnisharp language server client. But in general this is what I want to do. May be someone can give me a working example that can do the same thing like the example just mentioned.
Best regards,
Basti
I found the solution myself. With this example you can request code completion.
ILanguageClient _client;
ProcessStartInfo info = new ProcessStartInfo();
var programPath = #"path\to\language-server.exe";
info.FileName = programPath;
info.WorkingDirectory = Path.GetDirectoryName(programPath);
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process process = new Process
{
StartInfo = info
};
process.Start();
_client = LanguageClient.Create(
options =>
{
.WithInput(process.StandardOutput.BaseStream)
.WithOutput(process.StandardInput.BaseStream)
.WithCapability(
new CompletionCapability
{
CompletionItem = new CompletionItemCapabilityOptions
{
DeprecatedSupport = true,
DocumentationFormat = new Container<MarkupKind>(MarkupKind.Markdown, MarkupKind.PlainText),
PreselectSupport = true,
SnippetSupport = true,
TagSupport = new CompletionItemTagSupportCapabilityOptions
{
ValueSet = new[] { CompletionItemTag.Deprecated }
},
CommitCharactersSupport = true
}
}
);
}
);
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
await _client.Initialize(cancellationTokenSource.Token);
try
{
var actualCompletions = await _client.TextDocument.RequestCompletion(
new CompletionParams
{
TextDocument = #"path\to\someScript.py",
Position = (23, 11),
}, cancellationTokenSource.Token
);
System.Threading.Thread.Sleep(1000);
var items = actualCompletions.Items;
Console.WriteLine("items.Count: {0}", items?.Count());
Console.WriteLine("actualCompletions: {0}", string.Join(",", items?.Select(p => p.Label)));
}
catch (Exception ex)
{
Console.WriteLine("Exception thrown: {0}", ex.Message);
}
I use this code to get pending windows updates and also most of the informations of the update:
static List<PendingUpdate> GetPendingUpdates()
{
var updateSession = new UpdateSession();
var updateSearcher = updateSession.CreateUpdateSearcher();
updateSearcher.Online = false; //set to true if you want to search online
List<PendingUpdate> pendingUpdates = new List<PendingUpdate>();
try
{
var searchResult = updateSearcher.Search("IsInstalled=0 And IsHidden=0");
if (searchResult.Updates.Count > 0)
{
Console.WriteLine("There are updates available for installation");
foreach (IUpdate windowsUpdate in searchResult.Updates)
{
PendingUpdate update = new PendingUpdate();
update.Title = windowsUpdate.Title;
update.Description = windowsUpdate.Description;
update.Downloaded = windowsUpdate.IsDownloaded;
update.Urls = new List<string>();
foreach (string url in windowsUpdate.MoreInfoUrls)
{
update.Urls.Add(url);
}
foreach (dynamic category in windowsUpdate.Categories)
{
update.Categories += category.Name + ", ";
}
pendingUpdates.Add(update);
}
}
}
catch (Exception ex)
{
Console.WriteLine("ERROR");
throw ex;
}
return pendingUpdates;
}
I also use this code to get to know if the computer currently needs a restart to finish installed updates:
static bool needsRestart()
{
ISystemInformation systemInfo = new SystemInformation();
return systemInfo.RebootRequired;
}
Now my question is, is it possible to get to know if an pending update needs a computer restart to finish? In the first code I get a IUpdate object but I dont see informations about a needed restart after installing this update. I there a way to get this information?
For the asynchronous installation I use something like this:
rebootRequired = false;
UpdateSession updateSession = new UpdateSession();
updateSession.ClientApplicationID = SusClientID;
IUpdateInstaller updatesInstaller = updateSession.CreateUpdateInstaller();
IInstallationJob job = updatesInstaller.BeginInstall(InstallProgressCallback, installComplete, installState);
// here is your installer code and the checking if the installation is completed
IInstallationProgress jobProgress = job.GetProgress();
for (int updateindex = 0; updateindex < updatesInstaller.Updates.Count; updateindex++)
{
IUpdateInstallationResult updateInstallResult = jobProgress.GetUpdateResult(updateindex);
rebootRequired |= updateInstallResult.RebootRequired;
}
if(rebootRequired)
{
// any of the updates need a reboot
}
I'm using the SAS Integration Technologies COM components to connect to SAS Server from a C# .NET project. I want to submit statements to a SAS Workspace then load the output dataset from SAS using the OLE DB provider (SAS.IOMProvider). I am able to do this successfully using code like this:
static int Main(string[] args)
{
var keeper = new ObjectKeeper();
var factory = new ObjectFactoryMulti2();
var server = new ServerDef()
{
MachineDNSName = "sas.server.com",
Protocol = Protocols.ProtocolBridge,
Port = 8591,
BridgeSecurityPackage = "Negotiate",
};
var workspace = (IWorkspace)factory.CreateObjectByServer("Workspace1", true, server, null, null);
keeper.AddObject(1, workspace.UniqueIdentifier, workspace);
try
{
using (var conn = new OleDbConnection("Provider=SAS.IOMProvider.1; Data Source=iom-id://" + workspace.UniqueIdentifier))
{
// success
conn.Open();
}
}
catch (Exception ex)
{
System.Console.Error.WriteLine(ex.ToString());
return 1;
}
finally
{
keeper.RemoveObject(workspace);
workspace.Close();
}
return 0;
}
However, when I try using the ObjectPool feature of ObjectFactoryMulti2, the OLE DB connection doesn't work. It always throws "The object could not be found; make sure it was previously added to the object keeper." Here is the code that does not work:
static int Main(string[] args)
{
var keeper = new ObjectKeeper();
var factory = new ObjectFactoryMulti2();
var server = new ServerDef()
{
MachineDNSName = "sas.server.com`",
Protocol = Protocols.ProtocolBridge,
Port = 8591,
BridgeSecurityPackage = "Negotiate",
MaxPerObjectPool = Environment.ProcessorCount,
RunForever = true,
RecycleActivationLimit = 100,
};
var login = new LoginDef();
var pool = factory.ObjectPools.CreatePoolByServer("Pool1", server, login);
var lease = pool.GetPooledObject(null, null, 5000);
var workspace = (IWorkspace)lease.SASObject;
keeper.AddObject(1, workspace.UniqueIdentifier, workspace);
try
{
using (var conn = new OleDbConnection("Provider=SAS.IOMProvider.1; Data Source=iom-id://" + workspace.UniqueIdentifier))
{
// throws System.Data.OleDb.OleDbException: 'The object 1EFCE532-99BA-4A27-AF37-574EAE1CD04C could not be found; make sure it was previously added to the object keeper.'
conn.Open();
}
}
catch (Exception ex)
{
System.Console.Error.WriteLine(ex.ToString());
return 1;
}
finally
{
keeper.RemoveObject(workspace);
lease.ReturnToPool();
pool.Shutdown();
}
return 0;
}
Is there a way to use SAS connection pooling with the SAS OLE DB provider?
Got a good answer to this question from SAS Support. When using a connection pool, you have to cast the workspace to IServerStatus and connect using its ServerStatusUniqueID property instead of IWorkspace.UniqueIdentifier.
var pool = factory.ObjectPools.CreatePoolByServer("Pool1", server, login);
var lease = pool.GetPooledObject(null, null, 5000);
var workspace = (IWorkspace)lease.SASObject;
var status = (IServerStatus)lease.SASObject;
keeper.AddObject(1, workspace.UniqueIdentifier, workspace);
using (var conn = new OleDbConnection("Provider=SAS.IOMProvider.1; Data Source=iom-id://" + status.ServerStatusUniqueID))
{
// success
conn.Open();
}
keeper.RemoveObject(workspace);
lease.ReturnToPool();
Trying to get all the categories from Ebay to shove into the database. I've tried increasing the timeout value of the underlying api context, but I still get a timeout after about two minutes - what else do I need to do?
var c = new eBay.Service.Call.GetCategoriesCall(this.apiContext);
c.CategorySiteID = ((int)siteId).ToString(); // siteId is an eBay SiteCode enum value
var version = c.GetCategoriesVersion();
c.DetailLevelList = new DetailLevelCodeTypeCollection();
c.DetailLevelList.Add(DetailLevelCodeType.ReturnAll);
c.ViewAllNodes = !onlyLeafCategories;
c.Timeout = 1000*60*20;
c.GetCategories(); // this causes a connection closed / timeout
Try this code, it works for me :
// get all categories from eBay
ApiContext context = GetApiContext();
GetCategoriesCall apiCall = new GetCategoriesCall(context)
{
EnableCompression = true,
ViewAllNodes = true
};
apiCall.DetailLevelList.Add(DetailLevelCodeType.ReturnAll);
apiCall.GetCategories();
public static ApiContext GetApiContext()
{
//apiContext is a singleton,
//to avoid duplicate configuration reading
if (apiContext != null)
{
return apiContext;
}
else
{
apiContext = new ApiContext();
//set Api Server Url
apiContext.SoapApiServerUrl = "https://api.ebay.com/wsapi";
//set Api Token to access eBay Api Server
ApiCredential apiCredential = new ApiCredential();
apiCredential.eBayToken ="YOUR_TOKEN";
apiContext.ApiCredential = apiCredential;
//set eBay Site target to US
apiContext.Site = eBay.Service.Core.Soap.SiteCodeType.US;
return apiContext;
}
}
I am making a Bloomberg web service GetData call for the "DEBT_TO_EQUITY_FUNDAMENTALS_TKR" field. I am setting secmaster = true and asking for a single instrument with a CUSIP identifier (with yellowkey = MarketSector.Corp).
This strikes me as a fairly lightweight call having seen people asking for thousands of instruments and dozens of fields at once.
I have played around with setting lots of different settings but I just can't get this request to return in a few seconds. It gives me the correct return value but it takes longer than 60 seconds.
Any idea if it is possible to get such a request to execute and return in a few seconds?
Thanks
EDIT - Here is the code I am running:
public string GetFundamentalTicker(string identifier, InstrumentType identifierType = InstrumentType.CUSIP)
{
PerSecurityWS ps = new PerSecurityWS();
try
{
log.DebugFormat("Cert path is: {0}", CertPath);
X509Certificate2 clientCert = new X509Certificate2(CertPath, "<password_redacted>");
ps.ClientCertificates.Add(clientCert);
}
catch (Exception e)
{
log.ErrorFormat("Error in cert setup - {0} - {1}", e.Message, e.InnerException == null ? "" : e.InnerException.Message);
return null;
}
//Set request header
GetDataHeaders getDataHeaders = new GetDataHeaders();
getDataHeaders.secmaster = true;
getDataHeaders.secmasterSpecified = true;
//getDataHeaders.fundamentals = true;
//getDataHeaders.fundamentalsSpecified = true;
//getDataHeaders.programflag = ProgramFlag.oneshot;//unnecessary - defaults to this anyway
//getDataHeaders.programflagSpecified = true;
//getDataHeaders.pricing = true;
getDataHeaders.secid = identifierType;
getDataHeaders.secidSpecified = true;
SubmitGetDataRequest sbmtGtDtreq = new SubmitGetDataRequest();
sbmtGtDtreq.headers = getDataHeaders;
sbmtGtDtreq.fields = new string[] {
"DEBT_TO_EQUITY_FUNDAMENTALS_TKR"
};
int currentFundYear = DateTime.Now.Year;
//var fundYears = new List<int>();
List<Instrument> fundYearInstruments = new List<Instrument>();
Instrument fundYearInstrument = null;
fundYearInstrument = new Instrument();
fundYearInstrument.id = identifier;
fundYearInstrument.typeSpecified = true;
fundYearInstrument.type = identifierType;
fundYearInstrument.yellowkey = MarketSector.Corp;
fundYearInstrument.yellowkeySpecified = true;
//fundYearInstrument.overrides = new Override[] {};//{ new Override() { field = "EQY_FUND_YEAR", value = currentFundYear.ToString() } };
fundYearInstruments.Add(fundYearInstrument);
//fundYears.Add(-1);
Instrument[] instr = fundYearInstruments.ToArray();
Instruments instrs = new Instruments();
instrs.instrument = instr;
sbmtGtDtreq.instruments = instrs;
try
{
SubmitGetDataResponse sbmtGtDtResp = ps.submitGetDataRequest(sbmtGtDtreq);
RetrieveGetDataRequest rtrvGtDrReq = new RetrieveGetDataRequest();
rtrvGtDrReq.responseId = sbmtGtDtResp.responseId;
RetrieveGetDataResponse rtrvGtDrResp;
do
{
System.Threading.Thread.Sleep(POLL_INTERVAL);
rtrvGtDrResp = ps.retrieveGetDataResponse(rtrvGtDrReq);
}
while (rtrvGtDrResp.statusCode.code == DATA_NOT_AVAILABLE);
if (rtrvGtDrResp.statusCode.code == SUCCESS)
{
for (int i = 0; i < rtrvGtDrResp.instrumentDatas.Length; i++)
{
for (int j = 0; j < rtrvGtDrResp.instrumentDatas[i].data.Length; j++)
{
if (rtrvGtDrResp.instrumentDatas[i].data[j].value == "N.A." || rtrvGtDrResp.instrumentDatas[i].data[j].value == "N.S." || rtrvGtDrResp.instrumentDatas[i].data[j].value == "N.D.")
rtrvGtDrResp.instrumentDatas[i].data[j].value = null;
return rtrvGtDrResp.instrumentDatas[i].data[j].value;
}
}
return null;
}
else if (rtrvGtDrResp.statusCode.code == REQUEST_ERROR)
{
log.ErrorFormat("Error in the submitted request: {0}", rtrvGtDrResp.statusCode.description);
return null;
}
}
catch (Exception e)
{
log.ErrorFormat("Error in GetData - {0} - {1}", e.Message, e.InnerException == null ? "" : e.InnerException.Message);
return null;
}
return null;
}
Poll interval is 5 seconds and the SOAP web service url is:
https://software.bloomberg.com/datalicensewp/dlws.wsdl
I am having the same issue. I found out that there is a difference between making the same call to Bloomberg API from, for example, console app (works very fast) and web service (takes a lot of time to start session). And the difference is that console app runs under the same user as bbcomm process, whereas web service (or actually iis process) runs under System account. You can try to log out all users on the PC where web service is hosted and then try to make the call. In this case, I guess, bbcomm goes under System account as no one else is logged in and works fast. It worked for me and the call was answered instantly.