sqlite-net fails to create database in MonoDroid application - xamarin.android

I start Xamarin Studio 4.0.3 and create a new solution for MonoDroid application. I am targetting version 2.3 or higher. I include Sqlite.cs from the sqlite-net (latest from site) project. I make sure I have a reference to Mono.Data.SQLite in the project. Then in the OnCreate of the default MainActivity I try to use the code shown in the readme to make a database connection:
string path = Android.OS.Environment.DataDirectory.ToString();
string dbname = path + "/" + "test.db3";
var db = new SQLiteConnection(dbname, SQLiteOpenFlags.Create|SQLiteOpenFlags.ReadWrite ,true);
However it always fails with an exception saying it can't open the database. If I follow Greg Shackles example and use SqliteDbHelper method it works, but I would like to understand what I am doing wrong that sqlite-net connection method is not working. I have a feeling I am missing something simple. I did also try just passing in a filename to SQLiteConnection() as well but when it failed I added the OpenFlags to see if that was the issue.

I just found out that apparently you're supposed to use the personal folder, instead of the databases folder:
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var db = new SQLiteConnection(Path.Combine(folder, "mydb.db"));

Related

Get Resources\Raw Path in .NET Maui

I have an application which uses a SQLite database to store data locally. I get the path to and open the database using:
string dbPath = System.IO.Path.Combine(FileSystem.AppDataDirectory, "mydatabase")
db = new SQLiteConnection(dbPath);
I have created an example database (example.db3) and copied this to the Resources\Raw folder with the Build Action MauiAsset.
My question is how do I get the path to this database file so I can use
string dbPath = System.IO.Path.Combine("*path to Resources\Raw foldder*", "example.db3");
to get the full path to open the example database.
I have tried searching but the best I can get is using FileSystem.Current.OpenAppPackageFileAsync but this opens the file for stream reading whereas I need to get the path.
Ideally the method would work on all platforms.
It is a known issue about this problem.
You can follow it up here: https://github.com/dotnet/maui/issues/3270.
Thanks for your feedback and support.

Calling Another Project's Controller From A Project In The Same Solution (.NET Core )

There are 2 projects in the same solution. First project is a .NET Core project and it has all the codes(controllers, models etc.) related to packages. I need to get the information (id, name, description) of the packages and display it in the second project(.NET Core Web App with Razor). Is it possible to do it without changing the first project? I only want to show the package list on a single web page.
I tried calling the first project's controller but it didn't work. Maybe I missed a point. Any help is appreciated.
This requirement can be achieved, please see the gif image below.
Tips
If you want to call another project's controller from a project in the same solution, you need to make sure there is in HomeController in both project. I mean the name of any class should be unique in both projects.
Otherwise you will face the same issue like my homepage.
Test Code:
public List<PackageReference> GetPackageList5(string projectname)
{
List<PackageReference> list = new List<PackageReference>();
PackageReference p = null;
XDocument doc = XDocument.Load(_webHostEnvironment.ContentRootPath+ "/"+ projectname + ".csproj");
var packageReferences = doc.XPathSelectElements("//PackageReference")
.Select(pr => new PackageReference
{
Include = pr.Attribute("Include").Value,
Version = pr.Attribute("Version").Value
});
Console.WriteLine($"Project file contains {packageReferences.Count()} package references:");
foreach (var packageReference in packageReferences)
{
p = new PackageReference();
p.Version= packageReference.Version;
p.Include= packageReference.Include;
list.Add(packageReference);
//Console.WriteLine($"{packageReference.Include}, version {packageReference.Version}");
}
return list;
}
My Test Steps:
create two project, Net5MVC,Net6MVC
add project reference.
My .net6 project references a .net5 project. So in my HomeController (.net), I add below:
using Net5MVC.ForCore6;
using Net5MVC.Models;
Suggestion
When we reference the .net5 project in .net6 project, we can build success, but when we deploy it, it always failed. The reason is some file was multiple publish output files with the same relative path.
Found multiple publish output files with the same relative path:
D:\..\Net6\Net6\Net5MVC\appsettings.Development.json,
D:\..\Net6\Net6\Net6MVC\appsettings.Development.json,
D:\..\Net6\Net6\Net5MVC\appsettings.json,
D:\..\Net6\Net6\Net6MVC\appsettings.json.
And usually will add class library to current project, not add a web project.
As we know we can find packages info in .csproj file, so we need copy and paste .csproj file to publish folder.
I still recommend using the GetPackageList5 method above as an interface for your project, using HttpClient for requests.

ActionFilterAttribute for Twilio RequestValidation example not working - why?

First, I'm newish to MVC so bear with me. I'm following the Twilio example located here to validate that status callbacks from Twilio are authentic: https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-csharp-aspnet-app-by-validating-incoming-twilio-requests#create-a-custom-filter-attribute
The code provided as-is should be reviewed by Twilio as the constructor name has a typo in it as they have "RequestAttribute" in it twice.
My issue is that I cannot for the life of me get the Attribute to resolve when I place it on my controller. I noticed the example Action Filter has a namespace ending ".Filters" and I noticed that my MVC application does not have a "Filters" directory. Some googling indicated that may be a difference between MVC4 and 5 - from what I can tell I'm using MVC5 as that's the listed version number on the System.Web.Mvc reference (version 5.2.2.0 specifically if that matters).
Anyway, Twilio linked to Microsoft documentation on creating the Custom Action Filter here: https://learn.microsoft.com/en-us/previous-versions/aspnet/dd410056(v=vs.98)?redirectedfrom=MSDN
Microsoft suggests creating the Action Filter class directly in the "Controllers" directory - so that's where I placed mine. Here is how that class reads currently:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Twilio.Security;
using System.Net;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
namespace SMSStatusWS.Controllers
{
public class ValidateTwilioRequestAttribute : System.Web.Mvc.ActionFilterAttribute
{
private readonly RequestValidator _requestValidator;
public ValidateTwilioRequestAttribute()
{
var authToken = "<--------REMOVED------->";
_requestValidator = new Twilio.Security.RequestValidator(authToken);
}
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
var context = actionContext.HttpContext;
if (!IsValidRequest(context.Request))
{
actionContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
}
base.OnActionExecuting(actionContext);
}
private bool IsValidRequest(HttpRequestBase request)
{
var signature = request.Headers["X-Twilio-Signature"];
var requestUrl = request.Url.AbsoluteUri;
return _requestValidator.Validate(requestUrl, request.Form, signature);
}
}
}
Then my attempt to use it...
[HttpPost]
[ValidateTwilioRequest ]
public ActionResult UpdateSmsStatus(string dbContext, string smsQueueId)
{
// Controller code here...
}
The attribute [ValidateTwilioRequest ] is highlighted in red in Visual Studio... meaning it can't resolve it (I guess) but I'm not sure why as the namespace is the same in both my controller class and the action filter class...
namespace SMSStatusWS.Controllers
So at this point, I'm not sure what's wrong here. As far as I can tell, the custom action filter was created correctly, and I'm using it as Twilio shows, but yet it doesn't work. Even though the filter does not seem to resolve, the project builds and runs... but of course it never hits the code in the action filter.
Is there some other way I need to reference this Action Filter that the docs are not telling me? Thoughts on what to try or look for that I may be overlooking?
UPDATE 10/13/21:
I have made some progress... turns out the attribute not resolving was related to Visual Studio. Not able to figure out why it wasn't resolving, I closed the solution and restarted Visual Studio and when I reopened it, it started resolving the attribute immediately. However, I'm not positive it's working as I can't hit a breakpoint in the OnActionExecuting override and Visual Studio says no symbols have loaded.
So new question now, how do you debug custom Action Filters? Shouldn't I be able to step into the code with the debugger?
You could you try using System.Diagnostics.Debug.WriteLine in the OnActionExecuting function and using that rather than the break point. That should write out to the output window and let you know if that code is running. After adding that code your OnActionExecuting function would look like this.
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
string controller = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string action = actionContext.ActionDescriptor.ActionName;
System.Diagnostics.Debug.WriteLine("Controller-" + controller + ", Action-" + action);
var context = actionContext.HttpContext;
if (!IsValidRequest(context.Request))
{
actionContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
}
base.OnActionExecuting(actionContext);
}
Wow... learned a bit about Visual Studio and debugging today.The MVC project I have created for all of this had the project output set to a bin directory 2 levels up from my project. I'll call this the "global bin" - we use our global bin as a place for a lot of other projects to write their output to and that one location is referenced in our nightly build.
What I noticed is that my local project bin directory had an old DLL and PDB file in it, presumably from a build prior to changing the output directory to our global bin (global bin has the current dll and pdb). When debugging, I would notice that the debugger would load the dll and pdb from the "Temporary Asp.Net files" path (you can find this info in the "Module" window while debugging in Visual Studio) - this temp directory had those same old versions of the pdb in it and that is ultimately why I was unable to debug my Action Filter Attribute - it had an outdated pdb that did not have symbols for my latest code changes in it.
My band-aid for now is to set the output directory of my Project back to it's own local bin directory, and in web.config, disable shadowCopyBinAssemblies - which prevents the debugger from using the outdated pdb in the Temporary Asp.Net files directory and instead uses the pdb in the local bin.
That looks like this in web.config...
<system.web>
<hostingEnvironment shadowCopyBinAssemblies="false"/>
<system.web
I'm confused as to why Visual Studio doesn't shadowCopy the dll and pdb from our defined global bin (when it's defined as the project's output directory) to the Temporary Asp.Net files directory. That would solve all of this but I don't know if that can be configured anywhere.
As soon as I changed this to output to the project's bin directory and disabled the shadowCopy in web.config, the debugger loaded symbols from the correct dll and pdb and my breakpoints hit immediately.
I guess I'll add a post-build event or something to copy the dll & pdb files to our global bin so this doesn't break our nightly build, but this feels like a hack. If the default shadowCopy settings for the Temporary Asp.Net Files directory can't be changed I don't know what else to do about it. Is this a Visual Studio bug perhaps... shadowCopying from the project bin always, even if the output is configured to be written elsewhere?

how to upload files to rackspace cloud using windows services

using my windows service (target framework=.Net framework 4.0 client profile) I am trying to upload files to rackspace cloudfiles.
I found out some asp.net c# apis here https://github.com/rackspace/csharp-cloudfiles
but looks like they are not compatible with windows services.
any clues how to make this work together?
It's perfect library for work with rackspce. I am use it. And i am sure that it's not problem to use this library inside of windows service. But i think possible problems with .net framework client profile and com.mosso.cloudfiles.dll. But try first with client profile.
Also i use following code to upload files to Rackspace(Configuration it's my configuration class. Instead of 'Configuration.RackSpaceUserName' and 'Configuration.RackSpaceKey' use yous own creadentials):
private Connection CreateConnection()
{
var userCredentials = new UserCredentials(Configuration.RackSpaceUserName, Configuration.RackSpaceKey);
return new Connection(userCredentials);
}
public void SaveUniqueFile(string containerName, string fileName, Guid guid, byte[] buffer)
{
string extension = Path.GetExtension(fileName);
Connection connection = CreateConnection();
MemoryStream stream = new MemoryStream(buffer);
string uniqueFileName = String.Format("{0}{1}", guid, extension);
connection.PutStorageItem(containerName, stream, uniqueFileName);
}
Configuration something like this:
public class Configuration
{
public static string RackSpaceUserName = "userName";
public static string RackSpaceKey= "rackspaceKey";
}
I you don't want to use com.mosso.cloudfiles.dll very easy create you own driver for rackspace. Because actually for upload file to rackspace you just need send put request with 'X-Auth-Token' header. Also you can check request structure using plugin for firefox to view and upload files to Rackspace and firebug.
I have some example in C# using that same library here :
https://github.com/chmouel/upload-to-cf-cs
this is a pretty simple CLI but hopefully that should give an idea how to use it.
I've been around this for about one hour and weird things are happening into VS2010. Although I have referenced the dll and intellisense is working, cannot compile.
It looks like the referenced dll disappears. So, my recomendation in case you go into the same issue, use rack space for .NET 3.5: csharp-cloudfiles-DOTNETv3.5-bin-2.0.0.0.zip
Just be sure to change your project to the same framework version. It works really good.
For your reference, the downloads page is here: https://github.com/rackspace/csharp-cloudfiles/downloads

How do you SetMaxAttachmentSize in TFS 2010?

I want to set the maximum work item attachment size. From old blogs I have found that it is possible by calling SetMaxAttachmentSize, but the blogs are for older versions of TFS. I have found the new webservice path for TFS 2010.
http://localhost:8080/tfs/_tfs_resources/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx/SetMaxAttachmentSize
Unfortunately when I call it like that I receive this error: This request can only be made against a project collection. The (.asmx) file should be located in the project directory (usually _tfs_resources under the application root).
I don't know how to format the call via a browser to target a specific project collection. Any thoughts?
Apparently SetMaxAttachmentSize web service was not leveraged on TFS 2010 therefore you need to do this programmatically, try running the following code:
TeamFoundationServer tfs = TeamFoundationServerFactory.GetServer(#"http://yourtfsserver:8080/tfs/DefaultCollection");
ITeamFoundationRegistry rw = tfs.GetService<ITeamFoundationRegistry>();
RegistryEntryCollection rc = rw.ReadEntries(#"/Service/WorkItemTracking/Settings/MaxAttachmentSize");
RegistryEntry re = new RegistryEntry(#"/Service/WorkItemTracking/Settings/MaxAttachmentSize", "20971520"); //20MB
if (rc.Count != 0)
{
re = rc.First();
re.Value = "20971520";
}
rw.WriteEntries(new List<RegistryEntry>() { re });
I hope it works for you
Regards,
Randall Rosales
I have found that this works. It is easier than writing code.
Go to this url replacing <Collection> with your project collection: http://localhost:8080/tfs/<Collection>/WorkItemTracking/v1.0/ConfigurationSettingsService.asmx
Choose SetMaxAttachmentSize
You can test to make sure you set it correctly by going to the same url above and then selecting GetMaxAttachmentSize.

Resources