I am trying to use an existing sqlite database in my app. Not sure how to do that.
I have seen a few suggestion online but didn't find anything helpful.
According to your description, you add one sqlite database in Assest in Android project, now you want to use this sqlite.
Firstly,install Sqlite.net.core in all three PCL, Android and IOS Projects, SQLite.Net.Platform.XamarinAndroid in Android Project.
Then you create interface IDatabase.cs in PCL:
public interface IDatabase
{
SQLite.Net.SQLiteConnection createconnection();
}
Implementing this interface in Android to get SqliteConnection.
public class GetDatabase : IDatabase
{
public SQLite.Net.SQLiteConnection createconnection()
{
var fileName = "SQLite.db3";
var documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var path = Path.Combine(documentPath, fileName);
if(!File.Exists(path))
{
using (BinaryReader br = new BinaryReader(Android.App.Application.Context.Assets.Open(fileName)))
{
using (BinaryWriter bw = new BinaryWriter(new FileStream(path, FileMode.Create)))
{
byte[] buffer = new byte[2048];
int len = 0;
while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write(buffer, 0, len);
}
}
}
}
var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var conn = new SQLite.Net.SQLiteConnection(plat, path);
return conn;
//var plat = new SQLite.Net.Plataform.XamarinAndroid.SqlitePlatformAndroid();
}
Please note: SQLite.Net.Platform.XamarinAndroid earlier versions installation was successful. However, it will throw and error “Package SQLite.Net.Platform.XamarinAndroidN 3.1.1 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0)” and package installation will fail. It’s a bug and solution is not available of today.You can copy this dll from this link to add your android project.
More detailed info, please take a look:
Use a local database in Xamarin
Related
I am trying to write a Blazor WebAssembly (WASM) app that accepts some code (from some text input field) and compiles the code using Roslyn.
I'm using Roslyn's CSharpCompilation class to create the compilation. Its Create method takes four parameters, one of which is a list of MetadataReferences (aka assembly references). In other (non-blazor) type applications, like a C# console app, you could get these MetadataReferences based on Asssembly Location, like this:
var locatedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !string.IsNullOrEmpty(a.Location)).ToArray();
foreach (var assembly in locatedAssemblies)
{
MetadataReference reference = MetadataReference.CreateFromFile(assembly.Location);
}
This unfortunately no longer works in Blazor WASM, because the Locations of the assemblies are empty.
I had tried getting assemblies in different ways, like AppDomain.CurrentDomain.GetAssemblies() and Assembly.GetEntryAssembly().GetReferencedAssemblies(), but all had empty Locations. I also tried calling Assembly.Load(), but to no avail.
Does anyone know how to get MetadataReferences in Blazor WASM, or how I would otherwise create a compilation in Blazor WASM?
(I'm also aware of MetadataReference.CreateFromStream() that I'll probably need to use, but it still requires the assembly location).
Thanks in advance.
I also wanted to compile C# inside a Blazor WASM app and found your question without an answer. After some digging I was able to create a working demo (repo link below.) Basically get the bytes for each assembly with HttpClient and use MetadataReference.CreateFromImage(bytes).
Full basic example repo I created: https://github.com/LostBeard/BlazorWASMScriptLoader
ScriptLoaderService.cs source:
using Microsoft.AspNetCore.Components;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Immutable;
using System.Reflection;
namespace BlazorWASMScriptLoader
{
// requires "Microsoft.CodeAnalysis.CSharp"
// can be added via nuget
public class ScriptLoaderService
{
HttpClient _httpClient = new HttpClient();
public ScriptLoaderService(NavigationManager navigationManager)
{
_httpClient.BaseAddress = new Uri(navigationManager.BaseUri);
}
async Task<MetadataReference?> GetAssemblyMetadataReference(Assembly assembly)
{
MetadataReference? ret = null;
var assmeblyName = assembly.GetName().Name;
var assemblyUrl = $"./_framework/{assmeblyName}.dll";
try
{
var tmp = await _httpClient.GetAsync(assemblyUrl);
if (tmp.IsSuccessStatusCode)
{
var bytes = await tmp.Content.ReadAsByteArrayAsync();
ret = MetadataReference.CreateFromImage(bytes);
}
}
catch { }
return ret;
}
public async Task<Assembly?> CompileToDLLAssembly(string sourceCode, string assemblyName = "")
{
if (string.IsNullOrEmpty(assemblyName)) assemblyName = Path.GetRandomFileName();
var codeString = SourceText.From(sourceCode);
var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp11);
var parsedSyntaxTree = SyntaxFactory.ParseSyntaxTree(codeString, options);
var appAssemblies = Assembly.GetEntryAssembly()?.GetReferencedAssemblies().Select(o => Assembly.Load(o)).ToList();
appAssemblies.Add(typeof(object).Assembly);
var references = new List<MetadataReference>();
foreach (var assembly in appAssemblies)
{
var metadataReference = await GetAssemblyMetadataReference(assembly);
if (metadataReference == null)
{
// assembly may be located elsewhere ... handle if needed
continue;
}
var metadataReferene = metadataReference;
references.Add(metadataReferene);
}
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { parsedSyntaxTree },
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
concurrentBuild: false,
optimizationLevel: OptimizationLevel.Debug
)
);
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
return null;
}
else
{
ms.Seek(0, SeekOrigin.Begin);
var assembly = Assembly.Load(ms.ToArray());
return assembly;
}
}
}
}
}
I've added a GhostScript.NET to my application, and have been able to successfully print PDFs using GSPrint on my local machine. Unfortunately, after deploying the updated application to the server as well as installing GSView (includes GSPrint), the function to print just hangs without any errors.
My first guess is that since I am writing to the filesystem in order for GSPrint to print the file, is that it has something to do with access security rights. I'm using IIS 8 on windows server 2012. If anyone has any experience with deploying GSPrint or on how to troubleshoot this issue, I'd appreciate it.
Here's the code:
public static void PrintingQueue(Queue<byte[]> printQueue, string printer, int copies)
{
Parallel.ForEach(printQueue, (currentFile) =>
{
PrintWithGSPrint(currentFile, printer, copies);
});
printQueue.Clear();
}
private static void PrintWithGSPrint(byte[] pdfFormBytes, string printer, int copies)
{
try
{
var fileName = Path.GetTempFileName();
using (var file = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
{
file.Write(pdfFormBytes, 0, pdfFormBytes.Length);
//this uses GSPrint, which console commands are different from vanilla ghostscript.
var gsArguments = $"-noquery -portrait -printer\"{printer}\" \"{fileName}\"";
var gsLocation = #"C:\Program Files\Ghostgum\gsview\gsprint.exe";
var gsProcessInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = gsLocation,
Arguments = gsArguments
};
var gsProcess = Process.Start(gsProcessInfo);
gsProcess.WaitForExit();
file.Close();
}
File.Delete(fileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I made a feedback project. I made it on ASP.NET MVC 5 it also has crystal reports. reports were working fine, but suddenly they stopped to work. I don't what happened with them. but since last week I tried hard to find solution but unfortunately could not get the right one who solved the solution. I downloaded different run times but all went vain. this is the bottom line of error.
"Method not found: 'CrystalDecisions.ReportAppServer.DataDefModel.PropertyBag CrystalDecisions.ReportAppServer.ReportDefModel.ISCRExportOptions.get_ExportOptionsEx()'"
this is the code:
public CrystalReportFeedback UserFeedbackDateWise(FeedbackReport be){
if (Session["CurrentUser"] != null && Convert.ToInt32(Session["User_Id"]) != 0)
{
string reportPath = Path.Combine(Server.MapPath("~/Reports"), "UserFeedbackReport.rpt");
if (ModelState.IsValid)
{
be.FromDate = Convert.ToDateTime(TempData["UserFromDate"]);
be.ToDate = Convert.ToDateTime(TempData["UserToDate"]);
be.User_Id = Convert.ToInt32(Session["User_Id"]);
}
return new CrystalReportFeedback(reportPath, be);
}
else
{
return null;
//new CrystalReportFeedback(reportPath, be);
}
}
Init of the report :
public CrystalReportFeedback(string reportPath, FeedbackReport be)//, object dataSet)
{
//int[] array;
string strConnect = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["TSC"]);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(strConnect);
string _username = builder.UserID;
string _pass = builder.Password;
string _server = builder.DataSource;
string _database = builder.InitialCatalog;
ReportDocument reportDocument = new ReportDocument();
//
reportDocument.Load(reportPath);
reportDocument.SetDatabaseLogon(_username, _pass, _server, _database);
if (be.Region_Id != 0)
{
reportDocument.SetParameterValue("#Region_Id", be.Region_Id);
}
if (be.User_Id != 0)
{
reportDocument.SetParameterValue("#User_Id", be.User_Id);
}
reportDocument.SetParameterValue("#FromDate", be.FromDate);
reportDocument.SetParameterValue("#ToDate", be.ToDate);
//reportDocument.ExportToDisk(ExportFormatType.PortableDocFormat, "C:\report.pdf");
_contentBytes = StreamToBytes(reportDocument.ExportToStream(ExportFormatType.PortableDocFormat));
}
Export method :
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.ApplicationInstance.Response;
response.Clear();
response.Buffer = false;
response.ClearContent();
response.ClearHeaders();
response.Cache.SetCacheability(HttpCacheability.Public);
response.ContentType = "application/pdf";
using (var stream = new MemoryStream(_contentBytes))
{
stream.WriteTo(response.OutputStream);
stream.Flush();
}
}
private static byte[] StreamToBytes(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Hope that I will get my solution at earliest.
this is modified code:
[HttpGet]
public FileResult UserFeedbackDateWise(FeedbackReport be)
{
if (Session["CurrentUser"] != null && Convert.ToInt32(Session["User_Id"]) != 0)
{
string reportPath = Path.Combine(Server.MapPath("~/Reports"), "UserFeedbackReport.rpt");
if (ModelState.IsValid)
{
be.FromDate = Convert.ToDateTime(TempData["UserFromDate"]);
be.ToDate = Convert.ToDateTime(TempData["UserToDate"]);
be.User_Id = Convert.ToInt32(Session["User_Id"]);
}
string strConnect = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["TSC"]);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(strConnect);
string _username = builder.UserID;
string _pass = builder.Password;
string _server = builder.DataSource;
string _database = builder.InitialCatalog;
ReportDocument reportDocument = new ReportDocument();
//
reportDocument.Load(reportPath);
reportDocument.SetDatabaseLogon(_username, _pass, _server, _database);
if (be.Region_Id != 0)
{
reportDocument.SetParameterValue("#Region_Id", be.Region_Id);
}
if (be.User_Id != 0)
{
reportDocument.SetParameterValue("#User_Id", be.User_Id);
}
reportDocument.SetParameterValue("#FromDate", be.FromDate);
reportDocument.SetParameterValue("#ToDate", be.ToDate);
Stream stream = reportDocument.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
//Here i have my stream with my pdf report, i just create a new FileStreamResult and return it to my client like that :
FileStreamResult myfile = new FileStreamResult(stream, "application/pdf");
return myfile;
//new CrystalReportFeedback(reportPath, be);
}
else
{
return null;
//new CrystalReportFeedback(reportPath, be);
}
}
This isn't a coding issue, it's a runtime issue. The version of the crystal runtime or the bitness of your application.
One thing to try first is to upgrade both your development version and ensure you're running the same version in production. See https://apps.support.sap.com/sap/support/knowledge/public/en/2148492 for more details
It says:
Compile your application either to 'X86 mode' or 'X64 mode'
Install the particular versions of runtimes on deployment machine.
i.e. If the application is compiled as 32 bit, then install the 32bit runtimes.
I'll try my best to help you exporting your report, but your post is not very clear. For your next post try to be very specific and provide as much information as you can.
I currently made a MVC project and export a crystalreport report from my controller to my client.
I think that your ExecuteResult method can work, but working with the httpcontext is useless, Crystalreport and .NET provide some useful methods to do the same.
So i'll show you how i create and export my report so you can copy / paste and modify your code.
Here is my controller method, called from a button :
[HttpGet]
public FileResult InitReport()
{
//I create my report here
FileImportReport rptH = new FileImportReport();
// Some configuration on the report, datasource, databaselogon .. etc
...
//
//Then I export my report to a pdf stream like that :
Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
//Here i have my stream with my pdf report, i just create a new FileStreamResult and return it to my client like that :
FileStreamResult myfile = new FileStreamResult(stream, "application/pdf");
return myfile;
}
My method is called from a button but it can work like you want, or the file can be saved in any known path.
You can test to reproduce my code, in your CrystalReportFeedback method use my code with your reportDocument object, you don't need to use your StreamToBytes method.
Regards,
EDIT : Useful links with your error :
Crystal Reports exception in Visual Studio 2013
https://www.arcanadev.com/support/kb/K00000499.aspx
I'm currently saving my local sqlite db in Environment.GetFolderPath(Environment.SpecialFolder.Personal) with this code.
Now i'm trying to copy the Db to my PC so i can watch what's inside it. But i'm not able to see this Folder unless it's rooted.
Where is the best place to save the DB so i can view it every now and then?
Here is my android DB code:
[assembly: Dependency(typeof(SQLite_Android))]
namespace AppName.Droid
{
public class SQLite_Android : ILocalDb.Interfaces.ILocalDb
{
#region ISQLite implementation
public SQLite.SQLiteConnection GetConnection()
{
var sqliteFilename = "MyDb.db3";
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(documentsPath, sqliteFilename);
// Create the connection
var conn = new SQLite.SQLiteConnection(path);
// Return the database connection
return conn;
}
#endregion
}
}
You can use external storage option:
var sqliteFilename = "MyDb.db3";
var extStoragePath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var path = Path.Combine(extStoragePath, "MyNewFolder");
var filename = Path.Combine(path, sqliteFilename);
// Create the connection
var conn = new SQLite.SQLiteConnection(path);
// Return the database connection
return conn;
This way file will be visible via file explorer
PackageInstaller (https://developer.android.com/reference/android/content/pm/PackageInstaller.html) seems to have been added starting in API 21 (Lollipop), however I have not found any solid code examples on how to install an APK via this API. Any code help would be appreciated.
I’m investigating COSU/Kiosk apps for Android M Preview and was trying to implement the new feature "Silent install and uninstall of apps by Device Owner” (https://developer.android.com/preview/api-overview.html#afw) via the PackageInstaller API.
Found these, but not helpful: How to install/update/remove APK using "PackageInstaller" class in Android L?
What's "PackageInstaller" class on Lollipop, and how to use it?
Did not find any Android sample apps either.
Thanks in advance.
This is possible from Android 6.0 and up.
Make your app the Device owner.
Once your app gets the Device owner permission, we can install, uninstall and update silently without any user intervention.
public static boolean installPackage(Context context, InputStream in, String packageName)
throws IOException {
PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
PackageInstaller.SessionParams.MODE_FULL_INSTALL);
params.setAppPackageName(packageName);
// set params
int sessionId = packageInstaller.createSession(params);
PackageInstaller.Session session = packageInstaller.openSession(sessionId);
OutputStream out = session.openWrite("COSU", 0, -1);
byte[] buffer = new byte[65536];
int c;
while ((c = in.read(buffer)) != -1) {
out.write(buffer, 0, c);
}
session.fsync(out);
in.close();
out.close();
session.commit(createIntentSender(context, sessionId));
return true;
}
private static IntentSender createIntentSender(Context context, int sessionId) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context,
sessionId,
new Intent(ACTION_INSTALL_COMPLETE),
0);
return pendingIntent.getIntentSender();
}
Uninstall:
String appPackage = "com.your.app.package";
Intent intent = new Intent(getActivity(), getActivity().getClass());
PendingIntent sender = PendingIntent.getActivity(getActivity(), 0, intent, 0);
PackageInstaller mPackageInstaller = getActivity().getPackageManager().getPackageInstaller();
mPackageInstaller.uninstall(appPackage, sender.getIntentSender());
Complete device owner demo app in this repo.
Figured it out, here's the code:
try
{
PackageInstaller pi = app.getPackageManager().getPackageInstaller();
int sessId = pi.createSession(new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL));
PackageInstaller.Session session = pi.openSession(sessId);
// .. write updated APK file to out
long sizeBytes = 0;
final File file = new File(filepathApk);
if (file.isFile())
{
sizeBytes = file.length();
}
InputStream in = null;
OutputStream out = null;
in = new FileInputStream(filepathApk);
out = session.openWrite("my_app_session", 0, sizeBytes);
int total = 0;
byte[] buffer = new byte[65536];
int c;
while ((c = in.read(buffer)) != -1)
{
total += c;
out.write(buffer, 0, c);
}
session.fsync(out);
in.close();
out.close();
System.out.println("InstallApkViaPackageInstaller - Success: streamed apk " + total + " bytes");
// fake intent
Context app = this;
Intent intent = new Intent(app, AlarmReceiver.class);
PendingIntent alarmtest = PendingIntent.getBroadcast(app,
1337111117, intent, PendingIntent.FLAG_UPDATE_CURRENT);
session.commit(alarmtest.getIntentSender());
session.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}