Request App_GlobalResources directory on Application_Start - c#

Question what do you do for request in Application_Start global asax i want to replace my path to my App_GlobalResources directory but i tried using request and it didn't work am i missing an assembly reference is there another way of doing it.
Updated Code:
List<string> languages = new List<string>
foreach (var file in Directory.EnumerateFiles(HttpContext.Current.Request.MapPath("App_GlobalResources"), "*.resx"))
{
string resource = Path.GetFileNameWithoutExtension(file);
if (resource.Length > 9)
{
string filename = resource.Substring(resource.IndexOf(".") + 1, resource.Length - resource.IndexOf(".") - 1);
RegionInfo regionInfo = new RegionInfo(filename);
if (!string.IsNullOrEmpty(filename))
{
llanguages.Add(filename);
} // error here
}
}
HttpContext.Current.Application.Add("Cultures", languages.ToArray());

List<string> languages = new List<string>();
foreach (var file in Directory.EnumerateFiles("C:\\Users\\KIRK\\Documents\\Visual Studio 2010\\WebSites\\WebSite2\\App_GlobalResources", "*.resx"))
{
string resource = Path.GetFileNameWithoutExtension(file);
if (resource.Length > 9) {
string filename = resource.Substring(resource.IndexOf(".") + 1, resource.Length - resource.IndexOf(".") - 1);
RegionInfo regionInfo = new RegionInfo(filename);
if (!string.IsNullOrEmpty(filename))
{ languages.Add(filename);
}
}
}
HttpContext.Current.Application.Add("Cultures", languages.ToArray());

Related

Using powershell reflection to perform database updates

I'm editing my question to make it more readily understood.
Here is an example solution: https://github.com/mckenn55/PowershellTest
I created a brand new net47 MVC project. I added an area called "Database" and a controller within that area called "Update". Within that controller, I have the following:
public ActionResult Index()
{
return View(Execute());
}
public static List<string> Execute()
{
var returnable = new List<string>();
var assembly = Assembly.GetExecutingAssembly();
string codeBase = assembly.CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
var assemblyLocation = Path.GetDirectoryName(path);
string resourcePath = "";
string ModuleName = assembly.ManifestModule.Name;
ModuleName = ModuleName.Substring(0, ModuleName.LastIndexOf("."));
ModuleName = ModuleName.Replace(' ', '_').Replace(".", "");
string FolderPath = "Areas.Database.SQL";
FolderPath = FolderPath.Replace(' ', '_');
if (FolderPath != null && FolderPath.Length > 0 && FolderPath[FolderPath.Length - 1] == '.')
FolderPath = FolderPath.Substring(0, FolderPath.Length - 1);
StringBuilder filepath = new StringBuilder();
filepath.Append(ModuleName);
if (FolderPath != null && FolderPath.Length > 0)
{
filepath.Append('.' + FolderPath);
filepath.Append('.');
}
resourcePath = filepath.ToString();
string[] resourceNames = assembly.GetManifestResourceNames();
foreach (var resourceName in resourceNames)
{
if (Regex.Match(resourceName, "^" + resourcePath).Success)
{
returnable.Add(resourceName);
}
}
var orderedFileNames = new List<string>();
if (returnable != null && returnable.Any())
{
orderedFileNames = returnable.OrderBy(q => q).ToList();
}
else
{
returnable.Add("No files found");
}
return returnable;
}
Within the Database area, I have a directory called "SQL" and within that directory, I have a single file, TestFile.sql, included in the solution as an embedded resource. The results of the Execute() method, when viewed using the index action is "PSTest.Areas.Database.SQL.TestFile.sql". I would like to see the same thing in Powershell. I have tried the following:
> Add-Type -path "C:\Temp\PSTest\PSTest\bin\PSTest.dll"
> [PSTest.Areas.Database.UpdateController]::Execute()
No Files Found
Is my goal possible through powershell and if so, how?
I was not able to find a solution to this using powershell alone. I wrote a C# console app that is able to perform these actions without any issue.

uri formats are not supported for Ip address in C#

In my Web.Config file I have add my IP address in file path. when i try to access all files of that folder then it gives an error uri format not supported. but if i give local file path then it works fine.
string pathdata = Utility.GetConfigValue("DevSubmittedStateTaxForms");
string uploadPath = Utility.GetConfigValue("DevUploadFiles");
DirectoryInfo d = new DirectoryInfo(pathdata);
FileInfo[] Files = d.GetFiles("*.pdf");
var status = new List<Object>();
int i = 1;
foreach (FileInfo filename in Files)
{
status.Add(new {ID = i, Name = filename.Name, URL = pathdata + filename.Name + ".pdf" });
i++;
}
using System;
using System.IO;
namespace Test
{
public class Program
{
static void Main(string[] args)
{
string pathdata = #"\\192.168.1.27\Temp\";
var d = new DirectoryInfo(pathdata);
var files = d.GetFiles("*.pdf");
foreach (var filename in files)
{
Console.WriteLine(pathdata + filename.Name + ".pdf");
}
Console.ReadLine();
}
}
}
The above code does work (on my machine - that is my current IP address and a folder I have shared on my machine). Your code likely doesn't work for one of two reasons:
Your path is not valid (e.g. using / instead of \)
CBR folder is not shared

Get files from a folder that I have created in Xamarin.Android

I want get all files from an external storage folder(wall_e_imgs)..Here are codes-
public void getImages()
{
var path1 = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath.ToString();
string path = System.IO.Path.Combine(path1, "wall_e_imgs");
//var files= System.IO.Directory.GetFiles(Android.OS.Environment.ExternalStorageDirectory.ToString() + "wall_e_imgs");
//var files = System.IO.Directory.GetFiles(path);
//string path = Android.OS.Environment.ExternalStorageDirectory.ToString() + "/wall_e_imgs";
//File directory=new File(path);
Java.IO.File directory = new Java.IO.File(path);
Java.IO.File[] files = directory.ListFiles();//always count is 0 even though there are lot files there
foreach (var i in files)
{
FileInfo info = new FileInfo(i.Name);
if (info.Name.Contains("Wall_e"))
{
di.Add(new DownloadedImages { Path1 = info.DirectoryName, Name1 = info.FullName });
}
}
}
But it always give 0 files even though there are lot of files.
Try this
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "yourfoldername";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var filesList = Directory.GetFiles(folder);
foreach (var file in filesList)
{
var filename = Path.GetFileName(file);
}
Try something like this:
// Use whatever folder path you want here, the special folder is just an example
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "wall_e_imgs");
if (Directory.Exists(folderPath))
{
var files = Directory.EnumerateFiles(folderPath);
foreach (var file in files)
{
// Do your stuff
}
}
Please note that this uses the Directory class from System.IO, not Java.IO
ffilelist will contain a list of mp3 files in "/storage/emulated/0/Music/"
string phyle;
string ffilelist = "";
public void listfiles()
{
try
{
var path1 = "/storage/emulated/0/Music/";
var mp3Files = Directory.EnumerateFiles(path1, "*.mp3", SearchOption.AllDirectories);
foreach (string currentFile in mp3Files)
{
phyle = currentFile;
ffilelist = ffilelist + "\n" + phyle;
}
//playpath(phyle); // play the last file found
}
catch (Exception e9)
{
Toast.MakeText(ApplicationContext, "ut oh\n"+e9.Message , ToastLength.Long).Show();
}
}

How to remove guid from file name when creating zip file?

When user uploads multiple documents I am storing their files in my project like this:
Guid id;
id = Guid.NewGuid();
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(id + item.FileName));
item.SaveAs(filePath);
So files are saved like this in my project:
1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt
bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt
Now when creating zip files I am getting same name of this files when extracting zip files but I don't want guid in my file name after user downloads file.
However I have tried to remove guid from my file name but getting error System.IO.FileNotFoundException.
This is my code:
using (var zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
string[] str1 = str .Split(',');
foreach (var item in str1)
{
string filePath = Server.MapPath("~/Uploads/" + item.Substring(36));//as guid are of 36 digits
zip.AddFile(filePath, "files");
}
zip.Save(memoryStream);//Getting error here
}
ZipFile is throwing an exception because it can't find the file on disk as you have given it a name of a file that does not exist (by doing a .Substring()). To make it work you would have to rename the file using File.Copy with your new file name and then give that same file name to Zip.AddFile().
var orgFileName = "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt";
var newFileName = orgFileName.Substring (36);
File.Copy (orgFileName, newFileName, true);
zip.AddFile (newFileName);
You should use archive and ArchiveEntry. The rough code snipets how to do it (i don't test it):
using(var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) {
{
//using(var zip = new ZipFile()) {
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
//string[] str = str.Split(',');
foreach(var item in str) {
using(var entryStream = archive.CreateEntry("files/" + item.Substring(36)).Open()) {
string filePath = Server.MapPath("~/Uploads/" + item);
var content = File.ReadAllBytes(filePath);
entryStream.Write(content, 0, content.Length);
}
}
}
}
sample for using DotNetZip:
using (ZipFile zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" };
foreach(var item in str) {
string filePath = Server.MapPath("~/Uploads/" + item);
var content = File.ReadAllLines(filePath);
ZipEntry e = zip.AddEntry("files/" + item.Substring(36), content);
}
}
zip.Save(memoryStream);
}
Taking source from #kevin answer i have manage to solve this:
List<string> newfilename1 = new List<string>();
using (var zip = new ZipFile())
{
var str = new string[] { "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt", "bdb31966-e3c4-4344-b02c-305c0eb0fa0aLogging.txt" }; //file name are Log.txt and Logging.txt
string[] str1 = str .Split(',');
foreach (var item in str1)
{
string filePath = Server.MapPath("~/Uploads/" + item);
string newFileName = Server.MapPath("~/Uploads/" + item.Substring(36));
newfilename1.Add(newFileName);
System.IO.File.Copy(filePath,newFileName);
zip.AddFile(newFileName,"");
}
zip.Save(memoryStream);
foreach (var item in newfilename1)
{
System.IO.File.Delete(item);
}
}

Finding the user who modified the shared drive folder files

I have a shared drive which is elsewhere on a server. I want to get a notification which gives me the user name of the person who has modified any file present in the shared drive.
Currently I am using the FileSystemWatcher to get the notification and the code provided by Stack overflow question "Find out username(who) modified file in C#" to find the user name.
But Instead I get the name of the computer on which the shared drive is at the moment. I want the username who had modified the file on the shared drive.
My piece of code is :
private string GetSpecificFileProperties(string file, params int[] indexes)
{
string fileName = Path.GetFileName(file);
string folderName = Path.GetDirectoryName(file);
Shell32.Shell shell = new Shell32.Shell();
Shell32.Folder objFolder;
objFolder = shell.NameSpace(folderName);
StringBuilder sb = new StringBuilder();
foreach (Shell32.FolderItem2 item in objFolder.Items())
{
if (fileName == item.Name)
{
for (int i = 0; i < indexes.Length; i++)
{
sb.Append(objFolder.GetDetailsOf(item, indexes[i]) + ",");
}
break;
}
}
string result = sb.ToString().Trim();
if (result.Length == 0)
{
return string.Empty;
}
return result.Substring(0, result.Length - 1);
}
string Type = GetSpecificFileProperties(filePath, 2);
string ObjectKind = GetSpecificFileProperties(filePath, 11);
DateTime CreatedDate = Convert.ToDateTime(GetSpecificFileProperties(filePath, 4));
DateTime LastModifiedDate = Convert.ToDateTime(GetSpecificFileProperties(filePath, 3));
DateTime LastAccessDate = Convert.ToDateTime(GetSpecificFileProperties(filePath, 5));
string LastUser = GetSpecificFileProperties(filePath, 10);
string ComputerName = GetSpecificFileProperties(filePath, 53);
string FileSize = GetSpecificFileProperties(filePath, 1);
I have got the fix to that,
It can be achieved using the ObjectSecurity Class of .NET. In that we can use the GetOwner.
It fetches the owner of the file who has modified / created a file.
This is the piece of code which would help:
string owner = System.IO.File.GetAccessControl(e.FullPath).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
Console.WriteLine(owner);

Categories