Retrieve a connection string from appsetting.json in a simple console app (Core 3.1) - configuration

I'm writing a very simple console app that needs to dig into a database and read values. I'm having issues getting the connection string from the appsettings.json. After a whole load of googling I've found a bunch of solutions, each of which with their own issues such as being out of date or just returning null values with no obvious reason why. The main (and most common) method i've found to do it is as below:
static void Main()
{
var configuration = GetConfiguration();
var connectionString = configuration.GetSection("ConnectionsStrings").GetSection("DbName");
}
public static IConfigurationRoot GetConfiguration()
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return builder.Build();
}
This somewhat works but just returns a null value where I'd expect the connection string.
The appsettings.json is as below:
{
"ConnectionStrings": {
"DbName": "Connection string"
}
}
If anyone can spot anything obvious and help me along, it'd be much appreciated.

Warning to everyone out there. Don't be like me. Don't add your appsettings.json then for 17 hours completely forget to check the properties and make it an embedded resource while getting annoyed that your returned value is just null all the time. You would think after years of coding I'd learn my lesson....

Related

Xamarin.Forms Plugin.Geofence giving System.InvalidCastException: Specified cast is not valid

I am using Plugin.Geofence i Implemented its interface,Installed its dependencies i.e. .NETStandard 2.0 and Xamarin.GooglePlayServices.Location.
I am getting this exceptions System.InvalidCastException: Specified cast is not valid. when i run StartMonitoring method.
I am calling this method in the App() Constructor.
public App ()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
CrossGeofence.Current.StartMonitoring(new GeofenceCircularRegion("MyRegion", 31.475085, 74.305833, 200)
{
//To get notified if user stays in region for at least 5 minutes
NotifyOnStay = true,
StayedInThresholdDuration = TimeSpan.FromMinutes(5)
});
}
Tried everything but couldn't resolve this
For anyone looking for a solution to this, ensure that before calling "CrossGeofence.Current" that the correct permissions have been requested and granted. If not, you'll see this error.

javax.money throws javax.money.MonetaryException: No MonetaryAmountFormat for AmountFormatQuery

I've got an existing servlet application using tomcat 8 and java 8.
I've been using org.javamoney.moneta.Money for some time.
Today I wanted to add a new pattern and I started getting the following exception:
javax.money.MonetaryException: No MonetaryAmountFormat for
AmountFormatQuery AmountFormatQuery (
{pattern=$0.00, Query.formatName=default,
org.javamoney.moneta.format.CurrencyStyle=NAME, java.util.Locale=en})
at javax.money.spi.MonetaryFormatsSingletonSpi.getAmountFormat(MonetaryFormats
SingletonSpi.java:71) ~[money-api-1.0.3.jar:1.0.3]
at javax.money.format.MonetaryFormats.getAmountFormat(MonetaryFormats.java:112) ~[money-api-1.0.3.jar:1.0.3]
at au.org.noojee.auditor.util.Formatters.format(Formatters.java:92) ~[classes/:?]
at au.org.noojee.auditor.util.Formatters.format(Formatters.java:81) ~[classes/:?]
at au.org.noojee.auditor.entities.Customer.getNotices(Customer.java:242) ~[classes/:?]
at au.org.noojee.auditor.entities.Customer.getWorstError(Customer.java:307) ~[classes/:?]
So I reverted to the original pattern but the exception continues.
I've traced the code through and the problem appears to stem from the fact that the following call to getServices returns an empty list.
Bootstrap.getServices(MonetaryAmountFormatProviderSpi.class)
So the strange thing is that if I set up a unit test in the same project everything works fine.
I've now upgraded to money 1.3 but I'm getting the same errors (and the unit test still works).
The code that fails (when running under tomcat) is:
Note: I hard coded the amount in case the passed money1 was causing an issue (but of course the exception is thrown before its used so wouldn't be the issue anyway).
public static String format(Money money1, String pattern)
{
MonetaryAmount money = Money.of(12345.67, "AUD");
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(
AmountFormatQueryBuilder.of(Locale.ENGLISH)
.set(CurrencyStyle.NAME)
.set("pattern", "$0.00")
.build());
String result;
if (money == null)
result = "";
else
result = customFormat.format(money);
return result;
}
The Unit test that works is:
static public final CurrencyUnit LOCAL_CURRENCY = Monetary.getCurrency(Locale.getDefault());
#Test
public void test()
{
MonetaryAmount amount = Money.of(12345.67, "AUD");
MonetaryAmountFormat customFormat = MonetaryFormats.getAmountFormat(
AmountFormatQueryBuilder.of(Locale.ENGLISH)
.set(CurrencyStyle.NAME)
.set("pattern", "$0.00")
.build());
String formatted = customFormat.format(amount); //00,01,23,45.67 US Dollar
System.out.println(formatted);
}
Note: the call to getCurrency is also in the tomcat servlet app but in a different class. I've ran the unit test with and without that line but no differences.
I've checked my pom in case there were any conflicts but it reports that moneta 1.3 and money-api 1.0.3 are in use which I belive is correct.
I've rebooted my dev environment incase something went funny with the systems locale settings (but that makes no sense anyway given the unit test works).
Any hints where to look would be greatly appreciated.
Not a solution but I did develop a work around:
public static String format(Money money)
{
long cents = money.scaleByPowerOfTen(2).getNumber().longValueExact();
return String.format("$%,1d.%02d", cents / 100, cents % 100);
}
The result:
MonetaryAmount amount = Money.of(99999125.67, "AUD");
System.out.println(format(amount));
$99,999,125.67

How can I get a report URL via the SSRS Web Service?

In my project I have a web reference to SSRS (2005). I would like to display links that can take users directly to rendered reports. I know I can provide a link such as this one:
http://server/ReportServer/Pages/ReportViewer.aspx?/path/to/report&rs:Command=Render&rc:parameters=false&rs:format=HTML4.0
The question is how can I get that URL from the web service? And if the report takes parameters is there a way to provide values to the web service and have it format the URL for me?
I know I can build the URL myself, but I don't like reinventing wheels.
There are a few things to think of about HOW SSRS works and HOW MUCH TIME you want to invest in monkeying with it.
I. You can traverse the root but I highly doubt you meant that. From the root you can add items whether they are directories or reports. And to add to that you can add the parameter directly to the Rest URI to render a report and you may also output a value as well. For example:
Main part of address root:
http:// <server>/ReportServer/Pages/ReportViewer.aspx?
path to directory:
%2fTest
path to report (labeled it the same name lol)
%2fTest
what to do with it? (render it)
&rs:Command=Render
Put a paremeter in and execute it as well (Yes I called my parameter Test too!)
&Test=Value
Put it all together:
http:// <servername>/ReportServer/Pages/ReportViewer.aspx?%2fTest%2fTest&rs:Command=Render&Test=Value
II. You have a database you can query for traversing things but I believe MS does NOT document it well. Generally it is a SQL Server database named 'ReportServer' on whatever server you installed SSRS on. Generally most items are in the table 'dbo.Catalog' with 'Type' of 2 for reports. You can get their info and even parameters from them there.
III. You want to go full bore and dive into .NET and just talk to the service directly? You can do that too. You need the two main services though to do that:
A: http://<Server Name>/reportserver/reportservice2010 (gets info on existing items on server)
B: http:// <Server Name>reportserver/reportexecution2005 (gets info for in code creating reports to types directly in code)
I had another thread on exporting this here: Programmatically Export SSRS report from sharepoint using ReportService2010.asmx; but you will to get info as well probably. ONCE you have created the proxy classes (or made a reference to the web services) you can do code in .NET like so. These services do all the magic so without them you can't really model much in SSRS. Basically I create a class that you pass the 'SERVER' you need to reference to the class like 'http:// /ReportServer'.
private ReportingService2010 _ReportingService = new ReportingService2010();
private ReportExecutionService _ReportingExecution = new ReportExecutionService();
private string _server { get; set; }
public ReaderWriter(string server)
{
_server = server;
_ReportingService.Url = _server + #"/ReportService2010.asmx";
_ReportingService.Credentials = System.Net.CredentialCache.DefaultCredentials;
_ReportingExecution.Url = _server + #"/ReportExecution2005.asmx";
_ReportingExecution.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
public List<ItemParameter> GetReportParameters(string report)
{
try
{
return _ReportingService.GetItemParameters(report, null, false, null, null).ToList();
}
catch (Exception ex)
{
MessageBox.Show("Getting Parameter info threw an error:\n " + ex.Message);
return new List<ItemParameter> { new ItemParameter { Name = "Parameter Not Found" } };
}
}
public List<CatalogItem> GetChildInfo(string dest)
{
try
{
return _ReportingService.ListChildren("/" + dest, false).ToList();
}
catch (Exception ex)
{
MessageBox.Show("Getting Child info of location threw an error:\n\n" + ex.Message);
return new List<CatalogItem> { new CatalogItem { Name = "Path Does Not exist", Path = "Path Does not exist" } };
}
}
ListChildren is the way to go. You can always set the second parameter to true to return all catalog items when you have reports in many folders.
Dim items As CatalogItem() = rs.ListChildren(reportPath, True)

Bundle Helper for bundling and splitting coffeescript

I was experimenting with Bundle and Minification in MVC4 and came across an interesting problem.
I am using Coffeescript and I would like a Render helper that works a bit like the #Scripts.Render() method.
For example, let's say I have this bundle config:
new ScriptBundle("~/bundle/appfiles").Include(
"~/Scripts/app/sample.js",
"~/Scripts/app/myApp.js");
In the cshtml, when I do #Scripts.Render() I get different results based on the debug setting in the web.config. If debug is true I get one script tag per file, otherwise I get a single script tag that returns the bundled and minified js. This is fine.
Let-s assume now that I want to do the same with my Coffeescripts. I create a bundle like this:
new Bundle("~/bundle/appfiles", new CoffeeBundler(), new JsMinify()).Include(
"~/Scripts/app/sample.coffee",
"~/Scripts/app/myApp.coffee");
The problem now is that if I use #Scripts.Render() I get, while in debug, one script per file but this is not transformed at all. The only use I could do is this:
<script type="text/javascript" src="#(BundleTable.Bundles.ResolveBundleUrl("~/bundle/appfiles"))"></script>
But this will, even in debug mode, bundle everything together and then minify, which of course is not what I want.
I have tried to create a Coffee.Render() helper similar to the Scripts one but it uses the AssetManager class which is internal to the System.Web.Optimization assembly.
I was wondering if you have an idea on how to do this in a clean way (i.e: using the available public classes, not copying and pasting the whole AssetManager code, not doing fancy Directory.EnumerateFiles when creating the bundle).
Thanks!
PS: I know that a quicker solution would be to use Mindscape Workbench and bundle the generated js files, I am looking for something that uses what the framework has, maybe also avoiding to have to tell the team to install a tool that people may not like...
In the end I went for a HtmlHelper solution for this. Still in early stage but working as I would like. It is detailed in a blog post for the time being.
Here is the full Helper code in case the blog goes lost...
public static class HtmlHelperExtensions
{
public static MvcHtmlString RenderCoffeeBundle(this HtmlHelper htmlHelper, string virtualPath)
{
if (String.IsNullOrEmpty(virtualPath))
throw new ArgumentException("virtualPath must be defined", "virtualPath");
var list = GetPathsList(virtualPath);
//TODO: Nice and cleaner EliminateDuplicatesAndResolveUrls(list);
var stringBuilder = new StringBuilder();
foreach (string path in list)
{
stringBuilder.Append(RenderScriptTag(path));
stringBuilder.Append(Environment.NewLine);
}
return MvcHtmlString.Create(stringBuilder.ToString());
}
private static IEnumerable<string> GetPathsList(string virtualPath)
{
var list = new List<string>();
if (BundleResolver.Current.IsBundleVirtualPath(virtualPath))
{
if (!BundleTable.EnableOptimizations)
{
foreach (var path in BundleResolver.Current.GetBundleContents(virtualPath))
{
var bundlePath = "~/autoBundle" + ResolveVirtualPath(path.Replace("coffee", "js"));
BundleTable.Bundles.Add(new Bundle(bundlePath, new CoffeeBundler()).Include(path));
// TODO: Get the actual CustomTransform used in the Bundle
// rather than forcing "new CoffeeBundler()" like here
list.Add(bundlePath);
}
}
else
list.Add(BundleResolver.Current.GetBundleUrl(virtualPath));
}
else
list.Add(virtualPath);
return list.Select(ResolveVirtualPath).ToList();
}
private static string RenderScriptTag(string path)
{
return "<script src=\"" + HttpUtility.UrlPathEncode(path) + "\"></script>";
}
private static string ResolveVirtualPath(string virtualPath)
{
return VirtualPathUtility.ToAbsolute(virtualPath);;
}
}
I'm sorry I'm not addressing your exact question, but I do want to speak to your PS at the end of the post.
At this time, I don't really think we have a "no tools" story, but I do agree with the sentiment of "using what the framework has".
To that end, I would strongly recommend using TypeScript. You don't have to learn a new language (like you do with CoffeeScript) and yet it gives you a strongly-typed version of JavaScript that you can use a lot more like c# (with type validation etc.).
It will take you 20 mins to go through some of the tutorials:
http://www.typescriptlang.org/Playground/
Or, better yet, have a look at the BUILD session from the fall:
http://channel9.msdn.com/Events/Build/2012/3-012
Btw...if this isn't a direction you are wanting to go, no worries...I just find a lot of devs don't even know about TypeScript yet as an option.
Hope this helps in your quest to simplify things for your team.
Cheers.

"index is out of bounds" error when using readObject with Sockets

I'm trying to build a simple as3 server/client app.
When the client has connected to the server, it should send a message like "1" to the server.
The server does the following:
private function onConnect(e:ServerSocketConnectEvent):void
{
incomingSocket = e.socket;
incomingSocket.addEventListener(ProgressEvent.SOCKET_DATA, onData);
// You can now read and write data from the socket instance
trace("looks like a connection happened!");
}
private function onData(e: ProgressEvent):void {
var s:String = incomingSocket.readObject();
interrupt(s);
}
So flash throws me the error:
RangeError: Error #2006: The supplied
index is out of bounds. at
flash.net::Socket/readObject()
The line number flash provides me, shows that the problem is
var s:String = incomingSocket.readObject();
Has anyone an idea whats going on here?
Thank you!
n
readObject is used to read a serialized object on the socket.
If you sent a string, use readUTF, or readUTFBytes if you know the length the string should have.
If you sent a Int, use readInt, or the corresponding method.