c# - why always null get resource embedded file in sfx folder? - c#

why always get null get resource embedded file in my project 'Kriptografi'. My folder is sfx. I tried file in build action 'embedded resource'. Anyone can resolve it ?
Thanks
void test()
{
var ConfigXml = "Kriptografi.sfx.Config.xml";
Stream cfg = Assembly.GetExecutingAssembly().GetManifestResourceStream(ConfigXml);
if (cfg == null)
{
MessageBox.Show("Nothing");
}
else
{
MessageBox.Show("Exist");
}
}

Related

Cannot load nlog.config in Xamarin

I cannot read nlog.config file in asset folder of android platform
NLog.LogManager.Configuration = new XmlLoggingConfiguration("NLog.config");
How to read nlog file and also this file is in android asset.
You can also make use of Xamarin resource. Put the NLog.config file into the library project, then edit file's properties - change the build action to embedded resource.
public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName)
{
var resourcePaths = assembly.GetManifestResourceNames()
.Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase))
.ToList();
if (resourcePaths.Count == 1)
{
return assembly.GetManifestResourceStream(resourcePaths.Single());
}
return null;
}
var nlogConfigFile = GetEmbeddedResourceStream(myAssembly, "NLog.config");
if (nlogConfigFile != null)
{
var xmlReader = System.Xml.XmlReader.Create(nlogConfigFile);
NLog.LogManager.Configuration = new XmlLoggingConfiguration(xmlReader, null);
}
See also: https://github.com/NLog/NLog/wiki/Explicit-NLog-configuration-loading#loading-nlog-configuration-from-xamarin-resource
you could also try to use this (nlog.config file with a Build Action as an AndroidAsset):
NLog.LogManager.Configuration = new XmlLoggingConfiguration (XmlTextReader.Create(Assets.Open ("NLog.config")), null);
refer to:
https://github.com/NLog/NLog/blob/master/src/NLog/Config/LoggingConfigurationFileLoader.cs#L101-L120
You can add an extension method to your context class that gets you the required asset as a stream:
public static class Utils
{
public static Stream GetFromAssets(this Context context, string assetName)
{
AssetManager assetManager = context.Assets;
Stream inputStream;
try
{
using (inputStream = assetManager.Open(assetName))
{
return inputStream;
}
}
catch (Exception e)
{
return null;
}
}
}
And then in your activity context access it like:
var Asset= context.GetFromAssets("AssetName");
Note that this will return a System.IO.Stream.
Good luck
Revert in case of queries.
For Xamarin Android "NLog.config" (in this casing) in the assets folder will be loaded automatically. If the file name is different, then use:
LogManager.Configuration = new XmlLoggingConfiguration("assets/someothername.config");
Thanks for your response. I resolved this issue by setting autoReload="false" throwExceptions="false". Due to these two my config file was not visible. I dont know how they affect the file visibility but setting above two to false i can get config file now
Thanks,

Costura not loading Native Dll

I am unable to get Costura to load a Native dll that my project needs to run. This is a full native dll so it is not a reference in the project.
I have added the dll to the costura32 folder in my project and set it as an embedded resource.
When I run the project I can see that costura has extracted the dll to %temp%\costura\1D5629B8D94FC3E9B53C7AB358A0E123\32\native.dll
The project is still unable to find the file with the error Unable to load DLL
When looking in procmon I can see that it looks for the file in the local folder then in %temp%\costura\1D5629B8D94FC3E9B53C7AB358A0E123\native.dll and cannot find it. It doesn't seem to be looking for it in the "32" folder.
I have tried several options in the config file Unmanaged32Assemblies, PreloadOrder but they all have the same result.
I cannot see what I am doing wrong here.
In my case I tried to access temp path for setting library path with below code and it worked.
private bool SetupSevenZipLibrary()
{
string costuraExtractionPath = null;
try
{
DirectoryInfo di = null;
string costuraTempPath = Path.Combine(
Path.GetTempPath(),
"Costura" //ex: Costura
);
di = new DirectoryInfo(costuraTempPath);
if (!di.Exists)
return false;
costuraExtractionPath = di.GetDirectories().First().FullName;
if (!Directory.Exists(costuraExtractionPath))
throw new Exception();
string sevenZipPath = Path.Combine(
costuraExtractionPath,
Environment.Is64BitProcess ? "64" : "32", "7z.dll"
);
if (!File.Exists(sevenZipPath))
throw new Exception();
SevenZipBase.SetLibraryPath(sevenZipPath);
return true;
}
catch { return false; }
}

HttpContext.Current.Request.Url.IsFile Returns False When Url is ASPX Page

I'm hitting a local URL of the form: http://localhost/example.dev/eu/default.aspx.
My goal is to determine when the request is an aspx file inside of the global.asax file, and subsequently do stuff if it is an aspx file (and only an aspx file) using:
HttpContext.Current.Request.Url.IsFile
It's consistently resolving to false however and I'm not sure why. My complete global.asax code is:
if(HttpContext.Current.Request.Url.IsFile)
{
if(File.Exists(HttpContext.Current.Request.Url.LocalPath))
{
if(new FileInfo(HttpContext.Current.Request.Url.LocalPath).Extension.Equals("aspx"))
{
DoSomethingWithThePagesURL();
}
}
}
Did you take a look at the Documentation for IsFile Property?. It seems very clear from the documentation that Http: is not File:.
The IsFile property is true when the Scheme property equals UriSchemeFile.
DotNetFiddle Example
using System;
public class Program
{
public static void Main()
{
Uri uriAddress2 = new Uri("file://server/filename.ext");
Console.WriteLine(uriAddress2.LocalPath);
Console.WriteLine("Uri {0} a UNC path", uriAddress2.IsUnc ? "is" : "is not");
Console.WriteLine("Uri {0} a local host", uriAddress2.IsLoopback ? "is" : "is not");
Console.WriteLine("Uri {0} a file", uriAddress2.IsFile ? "is" : "is not");
}
}
Results:
\server\filename.ext
Uri is a UNC path
Uri is not a local host
Uri is a file
I use Nuget package walter.web.firewall that inject a IPageRequest in each request, this contains access to the requests underlying resource and will provide access via IPageRequest.LocalFile
However if you do need a firewall and it has been a while since this was asked, and lot's of framework changes have taken place since the question was asked so let my try and answer it in a way that uses no framework classes hoping it will work for all that try and implement it in the future.
here's the code:
public enum FileLocation
{
NotSet,
Disk,
Resource,
}
private static readonly string[] FileExtenstions = new[] {
".js"
,".ts"
,".vue"
,".css"
,".jpg"
,".png"
,".gif"
,".ico"
,".svg"
,".ttf"
,".eot"
,".ttf"
,".woff"
,".woff2"
,".mp4"
,".mp3"
,".emf"
};
public FileLocation IsMappedTo(Uri uri)
{
if (uri is null)
{
throw new ArgumentNullException(nameof(uri));
}
//make sure we support .net default URI contract
if (uri.IsFile)
return FileLocation.Disk;
//now assume you are looking in a web application
var path = uri.AbsolutePath;
if (path.Length == 0 || path.Equals("/",StringComparison.Ordinal) || path.Length< FileExtenstions.Min(s=>s.Length))
return FileLocation.NotSet;
//get the directory normally one would use IWebHostEnvironment.ContentRootPath different versions .net will have other methods
var dir = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
//get all resources names from the assembly hosting this class out side if the loop from this assembly you can also use
//you can also use GetManifestResourceNames() to use the web application's assembly
var resourceNames = new HashSet<string>(this.GetType().Assembly.GetManifestResourceNames());
var entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null && entryAssembly != this.GetType().Assembly)
{
foreach (var entry in entryAssembly.GetManifestResourceNames())
{
if (string.IsNullOrEmpty(entry))
resourceNames.Add(entry);
}
}
for (var i = 0; i < FileExtenstions.Length; i++)
{
if (FileExtenstions[i].Equals(path[FileExtenstions[i].Length..], StringComparison.OrdinalIgnoreCase) || path.Contains(FileExtenstions[i], StringComparison.OrdinalIgnoreCase))
{
//exists on disk
if (File.Exists(Path.Combine(dir, path.Replace("/", #"\"))))
return FileLocation.Disk;
//has a file as an embedded resource with the same name (ignores the path) so you might have duplicates names
if (resourceNames.Any(a => a.EndsWith(path.Split('/')[^1], StringComparison.OrdinalIgnoreCase)))
return FileLocation.Resource;
}
}
return FileLocation.NotSet;
}

Files that are upload does not show up in the Project solution(Mvc5)

I have implement the following code to upload a file. The file is upload to the location ("../App_Data/uploads") but it does not show up in the project. I have to include the file manually in the project. Why is the file not showing up?
public ActionResult ChangeSetting(SettingViewModel setting)
{
string userId = User.Identity.GetUserId();
ApplicationUser currentUser = this._appUserRepo.Find(e => e.Id.Equals(userId)).FirstOrDefault();
if (setting.PictureUrl != null)
{
if (setting.PictureUrl.ContentLength > 0)
{
string fileName = Path.GetFileName(setting.PictureUrl.FileName);
if (fileName != null)
{
string path = Path.Combine(Server.MapPath("../App_Data/uploads"), fileName);
setting.PictureUrl.SaveAs(path);
if (currentUser != null)
{
currentUser.PictureUrl = path;
currentUser.PictureSmalUrl = path;
currentUser.PictureBigUrl = path;
}
}
}
}
if (setting.FirstName != null)
{
if (currentUser != null) currentUser.FirstName = setting.FirstName;
}
_appUserRepo.Update(currentUser);
return RedirectToAction("index", "Admin");
}
Why is the file not showing up?
Because that's how Visual Studio projects work - only files that you manually include into the project are shown in the solution explorer. Files that get added dynamically to folders afterwards by eternal processes do not show up in Visual Studio (unless you manually include them and make them part of the solution). But that's probably not something you should be worried about. The files uploaded by users won't automagically appear in your Visual Studio project. The important thing is that they are present at the expected location and that your web application is capable of accessing them at runtime. Just open the physical location of the folder in Windows Explorer to confirm that your code is working as expected.

Open A PDF file on button click

I want to open a pdf file in winRT app(metro style app) by clicking on a button the file should open in windows8 default reader. I tried this code, where button click method name is DefaultLaunch_click():
async void DefaultLaunch_click()
{
// Path to the file in the app package to launch
string imageFile = #"images\ret.png";
// Get the image file from the package's image directory
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
// Set the recommended app
var options = new Windows.System.LauncherOptions();
options.PreferredApplicationPackageFamilyName = “Contoso.FileApp_8wknc82po1e”;
options.PreferredApplicationDisplayName = “Contoso File App”;
// Launch the retrieved file pass in the recommended app
// in case the user has no apps installed to handle the file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}
It worked for .png file but i want for .pdf file i replaced 1.png with M.pdf(after including it in images folder) and set the build content of M.pdf to Embedded Resource , run the program but it showed error that
**The system cannot find the file specified. (Exception from HRESULT: 0x80070002)**
This code works for me after I set PDF file build action to content and copy always to output directory.
private async void Button_Click(object sender, RoutedEventArgs e)
{
string imageFile = #"images\somepdffile.pdf";
// Get the image file from the package's image directory
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}

Categories