Can you help me on file.encrypt? - c#

I would like to encrypt and decrypt files but this shows me an error "This request is not supported" and "Invalid descriptor".
Can you help me ?
I have two methods AddEncryption and RemoveEncryption which encrypts and decrypts the file passed in FileName.
public static void Main()
{
try
{
string FileName = "C:\Users\PORTABLEHP\Documents\a.txt";
Console.WriteLine("Encrypt" + FileName);
AddEncryption(FileName);
Console.WriteLine("Decrypt" + FileName);
RemoveEncryption(FileName);
Console.WriteLine("Done");
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
public static void AddEncryption(string FileName)
{
File.Encrypt(FileName);
}
public static void RemoveEncryption(string FileName)
{
File.Decrypt(FileName);
}

The limitation of File.Encrypt method has been described at File.Encrypt
Important
This API is only supported on Windows platforms that are able to use
the NTFS Encrypting File System (EFS). Any attempt to use this on
non-Windows systems, Windows Home Edition systems, or non-NTFS drives
results in a PlatformNotSupportedException or NotSupportedException,
depending on the situation.
Use of this API in .NET Core is not recommended; it is included to
enable portability for applications that move to .NET Core but still
explicitly target Windows.

Related

How can I acces microphone input in .Net MAUI?

I am developing .net maui app that measures sound volume and sends it with bluetooth to pc that logs data and makes graph as a hobby project. My problem is accesing microphone input. There seems to be no multiplatform way to do this in maui. So i tried to do it using platform specific android api, but when I tried so, it seemed like class that I needed was not fully implemented in maui Android namespace.
The part of my code I have trouble with is this:
using Android.Media;
using Java.Util;
public static class MicIn
{
static MediaRecorder mRecorder;
// Other functions
public static void startRecorder()
{
if (mRecorder == null)
{
mRecorder = new MediaRecorder();
mRecorder.SetAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.SetOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.SetAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.SetOutputFile("/dev/null");
try
{
mRecorder.Prepare();
}
catch (Java.IO.IOException ioe)
{
Debug.WriteLine("IO exception");
}
catch (Java.Lang.SecurityException e)
{
Debug.WriteLine("Security exception");
}
try
{
mRecorder.Start();
}
catch (Java.Lang.SecurityException e)
{
Debug.WriteLine("Security exception");
}
}
}
}
Visual studio gives me errors on MediaRecorder.AudioSource.MIC, MediaRecorder.OutputFormat.THREE_GPP and MediaRecorder.AudioEncoder.AMR_NB
It says that these classes do not have definition for MIC, THREE_GPP and AMR_NB constants, even if they are in official android api documentation.
Do you have any ideas what might be error or other ways of taking microphone input in .net maui? Thank you for help.
according to the docs
AudioSource Mic
OutputFormat ThreeGpp
AudioEncoder AmrNb

Unable to access file using .Net Core 3 or .Net Framework on Windows 10

My new projects generated by VS 2019 cannot read or write files. Even the following simple code does not work.
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("hello");
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
var folder = Path.GetDirectoryName(path);
var filePath = Path.Combine(folder, "test.txt");
Console.WriteLine(filePath);
// File.WriteAllLines(filePath, new[] { "hello" });
using (var f = new FileStream(filePath, FileMode.OpenOrCreate))
{
f.Write(new byte[] { 0x39 }, 0, 1);
}
}
}
Accessing files using
.Net Core 3.0 + debugger
.Net Core 3.0 + generated exe
.Net Framework 4.6.2, 4.8 (have not tested others)
gives the exception
Unhandled exception. System.UnauthorizedAccessException: Access to the path 'C:\Users\user\Documents\ConsoleApp1\ConsoleApp1\Debug\netcoreapp3.1\test.txt' is denied.
However, it works in .Net Core 2.2 or below or using dotnet ConsoleApp1.dll.
My other few years old projects work. I have never encountered such a problem before. What is the problem and how to fix it?
It turns out my anti-virus blocked the file access. There were no pop-ups the first day so I could not know. Later, there were finally popups.

AppDomain.CurrentDomain.BaseDirectory does not return same folder for UnitTesting project [duplicate]

I have a web project like:
namespace Web
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lbResult.Text = PathTest.GetBasePath();
}
}
}
The method PathTest.GetBasePath() is defined in another Project like:
namespace TestProject
{
public class PathTest
{
public static string GetBasePath()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
}
}
Why it's display ...\Web\ while the TestProject assembly is compiled into bin folder(in other words it should display ...\Web\bin in my thought).
Now I got a troublesome if I modified method into:
namespace TestProject
{
public class FileReader
{
private const string m_filePath = #"\File.config";
public static string Read()
{
FileStream fs = null;
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + m_filePath,FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fs);
return reader.ReadToEnd();
}
}
}
The File.config is created in TestProject. Now AppDomain.CurrentDomain.BaseDirectory + m_filePath will returen ..\Web\File.config (actually the file was be copied into ..\Web\bin\File.config), an exception will be thrown.
You could say that I should modified m_filePath to #"\bin\File.config". However If I use this method in a Console app in your suggest, AppDomain.CurrentDomain.BaseDirectory + m_filePath will return ..\Console\bin\Debug\bin\File.config (actually the file was copyed into .\Console\bin\Debug\File.config), an exception will be thrown due to surplus bin.
In other words, in web app, AppDomain.CurrentDomain.BaseDirectory is a different path where file be copyed into (lack of /bin), but in console app it's the same one path.
Any one can help me?
Per MSDN, an App Domain "Represents an application domain, which is an isolated environment where applications execute." When you think about an ASP.Net application the root where the app resides is not the bin folder. It is totally possible, and in some cases reasonable, to have no files in your bin folder, and possibly no bin folder at all. Since AppDomain.CurrentDomain refers to the same object regardless of whether you call the code from code behind or from a dll in the bin folder you will end up with the root path to the web site.
When I've written code designed to run under both asp.net and windows apps usually I create a property that looks something like this:
public static string GetBasePath()
{
if(System.Web.HttpContext.Current == null) return AppDomain.CurrentDomain.BaseDirectory;
else return Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"bin");
}
Another (untested) option would be to use:
public static string GetBasePath()
{
return System.Reflection.Assembly.GetExecutingAssembly().Location;
}
In case you want a solution that works for WinForms and Web Apps:
public string ApplicationPath
{
get
{
if (String.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath))
{
//exe folder for WinForms, Consoles, Windows Services
return AppDomain.CurrentDomain.BaseDirectory;
}
else
{
//bin folder for Web Apps
return AppDomain.CurrentDomain.RelativeSearchPath;
}
}
}
The above code snippet is for binaries locations.
The AppDomain.CurrentDomain.BaseDirectory is still a valid path for Web Apps, it's just the root folder where the web.config and Global.asax are, and is same as Server.MapPath(#"~\");
If you use AppDomain.CurrentDomain.SetupInformation.PrivateBinPath instead of BaseDirectory, then you should get the correct path.
When ASP.net builds your site it outputs build assemblies in its special place for them. So getting path in that way is strange.
For asp.net hosted applications you can use:
string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");

How can I export my c# code logic (if-else-loops) in to text files (e.g XML) and later import it back and run?

I have these requirements coming from client every week for some new logic or verification. For which I have to code new logic (basically some if-else and loops) and launch a new build for him. I want to avoid it by simply coding my logic in visual studio then writing a utility to export it to XML or something and send it to client via e-mail. He just have to place this file in some appropriate folder and the application will behave considering this logic.
Please suggest some solutions. My platform is C# Asp.Net.
Thanks
Using .NET 4.6 and the NuGetPackage Microsoft.CodeAnalysis.Scripting you could implement a scripting engine to run your c# code residing in a textfile without building an assembly.
Install NuGet Package:
Install-Package Microsoft.CodeAnalysis.Scripting.CSharp
Implement TestClass with some basic C#-Code-Content:
class Program
{
static void Main(string[] args)
{
TestScript();
}
private static async void TestScript()
{
// Code snippet: a class with one string-property.
string codeContent = #" using System;
public class ScriptedClass
{
public string HelloWorld { get; set; }
public ScriptedClass()
{
HelloWorld = ""Hello Roslyn!"";
}
}
new ScriptedClass().HelloWorld";
// Instanciate CSharpScriptEngine
var engine = new CSharpScriptEngine();
// Execute code and return string property (HelloWorld)
var scriptingState = await engine.ExecuteAsync(codeContent);
// Print return value from CSharpScript
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
Implement a ScriptingEngine:
internal sealed class CSharpScriptEngine
{
public async Task<ScriptState<object>> ExecuteAsync(string codeContent)
{
// Add references from calling assembly
ScriptOptions options = ScriptOptions.Default.AddReferences(Assembly.GetExecutingAssembly());
// Run codeContent with given options
return await CSharpScript.RunAsync(codeContent, options);
}
}
Read ScriptCode from textfile:
So basically you could read some csharpcode from a textfile of your choice and run them on the fly:
private static async void TestScript()
{
// Read in script file
string codeContent = File.ReadAllText(#"C:\Temp\CSharpScriptTest.cs");
var engine = new CSharpScriptEngine();
// Run script
var scriptingState = await engine.ExecuteAsync(codeContent);
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
In case you are wondering how all of this works under the hood, Roslyn will create a so called submission from your script code. A submission is an in memory assembly containing the types generated around your script code, which can be identified among the assemblies in the current AppDomain by a ℛ prefix in the name.
The precise implementation details are not important here (though, for example, scriptcs heavily relies on understanding in detail how Roslyn works to provide its extra features), but it's important to know that submissions can be chained together. When they are chained, variables, methods or classes defined in an earlier submission are available to use in subsequent submissions, creating a feature of a C# REPL (read-evaluate-print loop).
C# and Visual Basic - Use Roslyn to Write a Live Code Analyzer for Your API
Hope it helps

Setting Certificate Friendly Name

Im trying to set the certificate friendly name during the certificate request/acceptance process. I understand that this a property of the microsoft store rather than the certificate and an wondering what .net/c# technique might be used to set it.
Use X509Certificate2.FriendlyName. However, you must export the certificate as PFX/PKCS#12:
X509Certificate2 certificate = new X509Certificate2(...);
certificate.FriendlyName = "MyName";
File.WriteAllBytes(path, certificate.Export(X509ContentType.Pkcs12));
So here is a commmand line example of how to do this. You need CAPICOM from microsoft which wraps the CryptoAPI.
The friendly name is a property of the cert store rather than the certificate so this code imports a certificate to the cert store and sets the friendly name as it does so.
The code takes two parameters the path to the cert file and the friendly name you wish to set.
Code:-
using System;
using System.Collections.Generic;
using System.Text;
using CAPICOM;
using System.Collections;
using System.Runtime.InteropServices;
namespace CertTool
{
class Program
{
const uint CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x20000;
const int CAPICOM_PROPID_FRIENDLY_NAME = 11;
const int CAPICOM_ENCODE_BINARY = 1;
static private String _currStoreName = "My";
static private String _FriendlyName = "Not Set";
static private String _CertPath = "C:\\test.cer";
static StoreClass _oCurrStore;
static ExtendedPropertyClass _friendlyProp;
static CertificateClass _certificate;
static ExtendedProperties _extendedProp;
static void Main(string[] args)
{
try
{
//Friendly name Argument
if (args.Length > 0)
{
_FriendlyName = args[0];
}
//Certpath argument
if (args.Length > 1)
{
_CertPath = args[1];
}
//Set and open the Store
_oCurrStore = new StoreClass();
_oCurrStore.Open(
CAPICOM_STORE_LOCATION.CAPICOM_LOCAL_MACHINE_STORE,
_currStoreName,
CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_EXISTING_ONLY |
CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_MAXIMUM_ALLOWED);
//Call the import certificate function
importCert();
}
catch(Exception ex){
Console.WriteLine(ex.Message);
Console.WriteLine(args[0]);
}
}
//Function import the certificate to the machine store and sets the friendly name
static bool importCert()
{
try
{
//Create Certificate Object
_certificate = new CertificateClass();
//Load the certificate into the obejct from file
_certificate.Load(_CertPath, "", CAPICOM_KEY_STORAGE_FLAG.CAPICOM_KEY_STORAGE_EXPORTABLE, CAPICOM_KEY_LOCATION.CAPICOM_LOCAL_MACHINE_KEY);
//Create extended property Class for friendly name
_friendlyProp = new ExtendedPropertyClass();
_friendlyProp.PropID = CAPICOM_PROPID.CAPICOM_PROPID_FRIENDLY_NAME;
_friendlyProp.set_Value(CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BINARY, _FriendlyName);
//Add extendedProp on cert object
_extendedProp = _certificate.ExtendedProperties();
//Set extendded prop to friendly name object
_extendedProp.Add(_friendlyProp);
_oCurrStore.Add(_certificate);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(_CertPath);
return true;
}
}
}
}
Ok, found an answer to that here:
Hi,
Please have a look at this to check if it suits your need:
When you run the .net Code in X64 Environment you will get the following error message.
" Failed --Retrieving the COM class factory for component with CLSID ...."
E.g. in CMS Export / Import server side .net code = "ExportSiteContentIncremental(...) Failed --Retrieving the COM class factory for component with CLSID {CA0752B3-021C-4F99-82E3-2C0F19C5E953} failed due to the following error: 80040154."
WORKAROUND:
The possible workaround is modify your project's platform from 'Any CPU' to 'X86' (in Project's Properties, Build/Platform's Target)
ROOTCAUSE
The VSS Interop is a managed assembly using 32-bit Framework and the dll contains a 32-bit COM object. If you run this COM dll in 64 bit environment, you will get the error message.

Categories

Resources