C# 8.0 and .net 3.0 - .net-core-3.0

using (var db = new Northwind())
{
Console.WriteLine("Categories and how many products they have:");
IQueryable<Category> cats = db.Categories.Include(c => c.Products);
foreach (Category c in cats)
{
WriteLine($"{c.CategoryName} has {c.Products.Count} products.");
}
}
I am reading c # 8.0 .net core 3.0 by Mark J. Price, but I went to Working with Databases Using Entity Framework Core and I got an error during the query. The connection to the database is connected successfully.
The error is generated when I output cats (System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'). I cannot solve this problem, please help me.

Related

NewtonSoftJson DateTimeZoneHandling.Local net 3.1 vs net 5

I've migrated my application from net 3.1.8 to net 5.0.5
I'm using this configuration for pascal case and to automatically convert dates to local time:
services.AddControllersWithViews()
.AddNewtonSoftJson(opts => {
opts.SerializerSettings.ContractResolver = new DefaultContractResolver();
opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
opts.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local
}
My post action looks like this:
[HttpPost]
public async Task<IActionResult> ExportData([FromForm] DateTime reportDate)
{
}
Date format is 2021-04-15T21:00:00.000Z. In 3.1.8, reportDate was equal to 2021-04-16, but now in 5.0.5 it converts to 2021-04-15 and 9PM.
Any suggestions for the fix?
After some testing, apparently the DateTime model binder is different in 5.0.5.
Writing a custom model binder solved the problem for the [FromForm] parameter.
Looks like complex type parameters are handled by the Json.Net serializer global settings (opts.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local); so no problems there.

XSLT3 Options for .NET Core in 2019

Has anyone got XSLT3 transforms working in .NET Core 2.x+ in 2019?
Seems that the request to MS for XSLT2/3 support hasn't moved forwards, and the Saxon people have other priorities, especially given the IKVM closedown.
Are there any other alternatives for in-process XSLT transformation? At the moment, it seems my only choice is to wrap something up via an external service or some undesirable (for us) COM-style approach that would involve lots of marshalling of data, hurting performance.
Unfortunately IKVM has never supported .NET Core, so the .NET version of Saxon cannot be made to work in that environment. In Saxonica we've been exploring alternative avenues for .NET support, but we haven't found anything remotely promising. (Anyone fancy doing a Kotlin implementation for .NET?)
I don't know what's possible using XMLPrime or Exselt, both of which target .NET.
2021 Update
Saxonica now ships SaxonCS on .NET 5, this product is built by converting the Java code of SaxonJ to C# source code using a custom transpiler.
There is one way how to use Saxon on .NET Core: via Transform.exe running as a process.
You can use code similar to this:
/// <summary>Transform XML inputFile using xsltFile and parameters. Save the result to the outputFile.</summary>
public void Transform(string inputFile, string outputFile, string xsltFile, NameValueCollection parameters)
{
//Search for the instalation path on the system
string path = GetInstalPath(#"Software\Saxonica\SaxonHE-N\Settings", "InstallPath");
string exePath = Path.Combine(path, "bin", "Transform.exe");
string parametersCmd = null;
//Set indicidual parameters
foreach (string parameter in parameters)
{
parametersCmd += String.Format("{0}={1} ", parameter, parameters[parameter]);
}
//set arguments for Transform.exe
string arguments = string.Format("-s:\"{1}\" -xsl:\"{0}\" -o:\"{3}\" {2}", xsltFile, inputFile, parametersCmd, outputFile);
//https://stackoverflow.com/questions/5377423/hide-console-window-from-process-start-c-sharp
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = exePath;
startInfo.Arguments = arguments;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
int waitingTime = 5 * 60 * 1000; //5 minutes; time in milliseconds
Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
processTemp.Start();
processTemp.WaitForExit(waitingTime);
}
catch (Exception e)
{
throw;
}
}
static string GetInstalPath(string comName, string key)
{
RegistryKey comKey = Registry.CurrentUser.OpenSubKey(comName);
if (comKey == null)
return null;
string clsid = (string)comKey.GetValue(key);
return clsid;
}
SaxonCS EE has been released and works with .NET 5 and .NET 6 (RC/preview) and that way allows using XSLT 3, XPath 3.1 and XQuery 3.1 with .NET Core. It is only available under a commercial license however, but you can test it with a trial license, download from Saxonica is at https://www.saxonica.com/download/dotnet.xml, also on NuGet as https://www.nuget.org/packages/SaxonCS/.
In the meantime IKVM has been updated (https://www.nuget.org/packages/IKVM.Maven.Sdk) and is capable of producing .NET 3.1, .NET 5 and .NET 6 (aka .NET core) compatible cross-compilations. Using that I have managed to cross-compile Saxon HE 11.4 Java to .NET 6 and have published two command line apps/dotnet tools on NuGet to run XSLT 3.0 or XQuery 3.1:
XSLT 3.0: https://www.nuget.org/packages/SaxonHE11NetXslt/
XQuery 3.0: https://www.nuget.org/packages/SaxonHE11NetXQuery/
I have furthermore created an extension library to ease the use of the Java s9api from .NET code, it is on NuGet at https://www.nuget.org/packages/SaxonHE11s9apiExtensions/, the GitHub repository is at https://github.com/martin-honnen/SaxonHE11s9apiExtensions.
A simple example to run some XSLT 3.0 code with .NET 6, using the IKVM cross compiled Saxon HE 11, would be:
using net.sf.saxon.s9api;
using net.liberty_development.SaxonHE11s9apiExtensions;
//using System.Reflection;
// force loading of updated xmlresolver (no longer necessary with Saxon HE 11.5)
//ikvm.runtime.Startup.addBootClassPathAssembly(Assembly.Load("org.xmlresolver.xmlresolver"));
//ikvm.runtime.Startup.addBootClassPathAssembly(Assembly.Load("org.xmlresolver.xmlresolver_data"));
var processor = new Processor(false);
Console.WriteLine($"{processor.getSaxonEdition()} {processor.getSaxonProductVersion()}");
var xslt30Transformer = processor.newXsltCompiler().Compile(new Uri("https://github.com/martin-honnen/martin-honnen.github.io/raw/master/xslt/processorTestHTML5Xslt3InitialTempl.xsl")).load30();
xslt30Transformer.callTemplate(null, processor.NewSerializer(Console.Out));
A samples project showing various examples of XPath 3.1, XQuery 3.1 and XSLT 3.0 usage is at https://github.com/martin-honnen/SaxonHE11IKVMNet6SaxonCSSamplesAdapted.

Auto Fill Web Forms in .net-Core

I am new to .net core.
How can I auto fill forms and submit in dotnet core ?
Please find following sample URLs I want to try
https://mparivahan.in/uyt/?pur_cd=102
Value - 1 = "MH1R"
Value - 2 = "5656"
https://www.filegstrstnow.com/searchGSTTaxpayer
sample Value = "24AADCS0852Q1Z2"
With Regards
I guess you want to automate operations in browser. For this purpose you need a browser automation framework which can be used in you .NET Core 2.0 code. Something like Selenium WebDriver. In this case you code will look like this:
[Test]
public void TestWithFirefoxDriver()
{
using (var driver = new FirefoxDriver())
{
driver.Navigate().GoToUrl(#"https://parivahan.gov.in/rcdlstatus/?pur_cd=102");
driver.FindElement(By.Id("form_rcdl:tf_reg_no1")).Send("GJ01RR");
driver.FindElement(By.Id("form_rcdl:tf_reg_no2")).Send("5656");
driver.FindElement(By.Id("form_rcdl:j_idt36")).Click();
var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1));
// Find element with the result to retrieve value, and so on..
}
}
Note: I didn't check the code above in runtime, it is just for demonstration purposes.
To run Selenium automation code without opening the browser you could use PhantomJS driver instead of drivers for real browsers like FirefoxDriver. Change this line:
using (var driver = new FirefoxDriver())
to:
using (var driver = new PhantomJSDriver())

Xamarin.Forms Portable + Mono.Data.Sqlite.Portable

Good day to everyone,
I'm building an application in Xamarin.Forms Portable for iOS,Android,Windows Universal(10) .
I'm trying to use the Mono.Data.Sqlite.Portable, but I'm not able to create or connect to a local database, I've tried many solutions to fix the problem, but until now I dint find the solution..
The error is trow at "connection.open();"
The Code is :
var config = DependencyService.Get<DB.IConfig>();
var cnn = config.DirectoryDB;
using (var connection = new SqliteConnection("" +
new SqliteConnectionStringBuilder
{
DataSource = "URI=file::memory:",
Version=3,
}))
{
//connection.ChangeDatabase("hello.db");
connection.Open();
using (var transaction = connection.BeginTransaction())
{
var insertCommand = connection.CreateCommand();
insertCommand.Transaction = transaction;
insertCommand.CommandText = "CREATE TABLE TESTE(teste as varchar(10))";
insertCommand.ExecuteNonQuery();
transaction.Commit();
}
}
on the "DataSource" I've a local path, and other paths.
(Ex:. C:\Users\MyMachineName\AppData\Local\Packages\f736c883-f105-4d30-a719-4bf328872f5e_nh7s0b45jarrj\LocalState\hello.db)
The error is :
An exception of type 'System.NotImplementedException' occurred in Mono.Data.Sqlite.dll but was not handled in user code
Additional information: The method or operation is not implemented.
ImageError
Connection Extra Information
The last picture, it may give more information....
Thank you all in advance :)
I've found the solution,I hope it helps the people that may be looking for the same as I.
Just go to Nuget - And download the Portable.Data.Sqlite that relies on SQLitePCL (Latest version) .
This package (Portable.Data.Sqlite) it will use the connection and will create SqliteDataReader and other property's that we are used to use .
This will work on Visual Studio 2015 and the project must be in framework 4.51 +=
----Error Tips----
if you encounter this error : Cant use Temporary Database or Path, just download Sqlite.dll and place on the project BIN folder and System32/ SysWoW64 .

How can i fetch all images associated by category from database

Hi i have a table in database named images. I want to fetch image_path from this table as shown below by matching the Category to it.
Ex: if i select Web Development category it should fetch image_path related with that category.
I am working on asp.net web pages. please guide me how can i achieve it?
id Category image_path
4 New Websites img\images\1982d16f-1a85-49c3-b7ac-94e05152273d_01.jpg
6 Mobiles img\images\87678076-3f19-43c0-909f-eec172d69919_02.jpg
7 Web Development img\images\4fef0362-b5fd-43d1-b988-c5d7e674add0_03.jpg
8 Web Development img\images\5752419a-013d-4c09-99af-f28132102189_04.jpg
9 Web Development img\images\e4876bff-b647-48d6-a3a0-b1e7bfb6d60a_05.jpg
10 Web Designing img\images\e86c3edc-0591-4157-8525-33e52ca21f64_06.jpg
11 Mobiles img\images\2b6ccd51-77f1-4da8-9ed6-98c2b069e92d_07.jpg
12 Mobile apps img\images\44694e2e-24dc-4f06-bb8f-88b597322c0d_005.jpg
13 Mobile apps img\images\9d5ca99a-f6fd-43d7-8a05-a6671f73bd54_006.jpg
As your're saying that "if i select", so I'm assuming that you're having Drop down in your scenario.
It's simple follow the query that will pull all the records related to the selected item from database.
Select image_path from images where Category = '"+DropDown1.SelectedItem+"'
The above query will do the trick.
If you're beginner, learn ADO.NET. It will help you to proceed further.
Note: Dropdown is assumption. You can keep as per your requirement.
Here's a very straightfoward method to retrieve your image paths:
public List<string> GetImagePathsForCategory(string category)
{
const string DatabaseConnectionString = "MyConnectionString"; //probably use a setting from your web.config
const string CategoryParameterName = "#version";
const string ImagePathQuerySqlString = "Select image_path from images where Category = " + CategoryParameterName;
var imagePaths = new List<string>();
using (var dbConnection = new SqlConnection(DatabaseConnectionString))
{
dbConnection.Open();
using (var query = new SqlCommand(ImagePathQuerySqlString, dbConnection))
{
query.Parameters.Add(new SqlParameter() { ParameterName = CategoryParameterName, Value = category });
using (var reader = query.ExecuteReader())
{
while (reader.Read())
{
imagePaths.Add(reader.GetString(0));
}
}
}
}
return imagePaths;
}
While this is okay for a one off usage, if you're querying the database often then I'd look into either an ORM (like NHibernate or Entity Framework for instance) which will do the heavy lifting for you or - if you don't want to do that - then use ADO.Net to implement your own Data Access Layer or Repository Pattern.

Resources