How to load Resx Files under App_LocalResources to Iterate through it - asp.net

I need the ResX file for the current page which is saved under "App_LocalResources".
I need to iterate through it.
The Method "GetLocalResourceObject" only allows access to one key at the time.

Since a resx file is nothing more than a xml file, you can loop all the elements with XElement
string resxFile = Server.MapPath("/App_LocalResources/Default.aspx.resx");
foreach (XElement element in XElement.Load(resxFile).Elements("data"))
{
string currentItem = string.Format("Key: {0} Value: {1}", element.Attribute("name").Value, element.Element("value").Value);
}
Another option is with the ResXResourceReader. However you do need to add System.Windows.Forms as a reference to the project.
using System.Resources;
//define the filename and path for the resx file
string resxFile = Server.MapPath("/App_LocalResources/Default.aspx.resx");
//load the file into the reader
using (ResXResourceReader reader = new ResXResourceReader(resxFile))
{
//loop all the entries
foreach (DictionaryEntry entry in reader)
{
string currentItem = string.Format("Key: {0} Value: {1}", entry.Key, entry.Value);
}
}

Related

How to write/modify/add some text in a file stored in azure file storage?

My goal is to modify a .txt file in azure file storage using WindowsAzure.Storage API. I would like to know if there is any method to add some text in the file.
Is it easier to use the System.IO API?
I've already tried the cloudFileStream.Write() but it didn't work.
Thank you
The sample on https://github.com/Azure/azure-storage-net/blob/master/Test/WindowsRuntime/File/FileStreamTests.cs shows you how to do this.
public async Task FileOpenWriteTestAsync()
{
byte[] buffer = GetRandomBuffer(2 * 1024);
CloudFileShare share = GetRandomShareReference();
try
{
await share.CreateAsync();
CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1");
using (CloudFileStream fileStream = await file.OpenWriteAsync(2048))
{
Stream fileStreamForWrite = fileStream;
await fileStreamForWrite.WriteAsync(buffer, 0, 2048);
await fileStreamForWrite.FlushAsync();
byte[] testBuffer = new byte[2048];
MemoryStream dstStream = new MemoryStream(testBuffer);
await file.DownloadRangeToStreamAsync(dstStream, null, null);
MemoryStream memStream = new MemoryStream(buffer);
TestHelper.AssertStreamsAreEqual(memStream, dstStream);
}
}
finally
{
share.DeleteIfExistsAsync().Wait();
}
}
If you want to add some text(append to the existing data) to the file on azure file storage, there is no direct method. You need to download it and then upload with the text you want to append.
string accountName = "xxx";
string key = "xxx";
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var share = storageAccount.CreateCloudFileClient().GetShareReference("testfolder");
CloudFile file1 = share.GetRootDirectoryReference().GetFileReference("a.txt");
//if you want to append some text from local file
var stream1 = File.OpenRead("your file path in local, like d:\hello.txt");
string from_local_file = (new StreamReader(stream1)).ReadToEnd();
//if you just want to add some text from string, directly use the string
//string from_local_file ="the text I want to append to azure file";
//download the content of the azure file
string from_azure_file = file1.DownloadText();
//this does the trick like appending text to azure file, not overwrite
file1.UploadText(from_azure_file + from_local_file);
If you want to directly upload text to file stored on azure file storage, you should use one of the following methods: UploadText() / UploadFromFile() / UploadFromStream().
Note that this will overwrite the existing data in the azure file.
If you want to update the context of azure file, you can use WriteRange() method. But it has some limitations, if you're interesting about it, I can provide you some code.

How change server map path and file name when file uploaded in asp.net mvc?

I am trying to save picture in folder and store path in database using entity framework in asp.net mvc 5.
I did it but I have some problems .
image path in DB saved like this :
C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\2.jpg
How can I change it to: ~/Images/SubGoods/2.jpg ??
and I want to change image name to it's primary key id and I used pic =Convert.ToString( subgood.SubGoodID); to do it, but it saves Zero :
C:\Users\Shima\Documents\Visual Studio 2013\Projects\NP1\NP1\Images\SubGoods\0
It saves always 0 .I know that's because Primary key in that line not generated yet . where of my codes primary Key id generated ?
public ActionResult AddSubGood(SubGood subgood, HttpPostedFileBase UploadImage)
{
var MainGoodId = subgood.FKMainGoodID;
SubGoodRepositories blSubGood = new SubGoodRepositories();
string path="";
if (UploadImage != null)
{
string pic = System.IO.Path.GetFileName(UploadImage.FileName);
pic =Convert.ToString( subgood.SubGoodID);
path = System.IO.Path.Combine(
Server.MapPath("~/Images/SubGoods"), pic);
}
if (ModelState.IsValid)
{
subgood.FKMainGoodID = MainGoodId;
UploadImage.SaveAs(path);
subgood.SubGoodImage = path;
if (blSubGood.Add(subgood))
{
return JavaScript("alert('saved');");
}
else
{
return JavaScript("alert('didn't saved');");
}
}
else
{
return JavaScript("alert('error');");
}
}
You should save only the file name:
var fileName = Path.GetFileName(UploadImage.FileName);
Then when you want to fetch the file for user you can simply address the file name with specific path:
<img src="~/Content/Uploaded/#item.fileName" .../>
You can also generate a random file name using Guid:
var rondom = Guid.NewGuid() + fileName;
Server.MapPath will return you Virtual path(which you don't needed) , you can create another variable and concatenate like this :
string DbPath = "~/Images/SubGoods/"; // better to store in web.config file
DbPath = DbPath + ""//here you can query in table and find the last inserted primary key and increment it with '1'

saving document in space with blank character in alfresco

I work with alfresco 4.0
I have a problem to save document in special space in alfresco named in arabic language.
for this example I didn't have problem :
/app:company_home/cm:تجربة
but I have problem when the space witch is created in alfresco is named in arabic language and have blank character . like this :
/app:company_home/cm:تجربة ثانية
in this case I can't save document in alfresco
updated :
also I have the same problem when I have a folder named in english and have escape character like this :
His Excellency the Secretary
Reporter Secretariat
this is the document to save document in alfresco
public String saveDocument(File file, String name, String folderName, String userName, String pwd, String code)
throws Exception {
File file_BC = file;
try {
BarCodeEngine barCodeEngine = new BarCodeEngine(file, code);
file_BC = barCodeEngine.setBarCode();
} catch (Exception e) {
e.printStackTrace();
}
byte[] contentByte = IOUtils.toByteArray(new FileInputStream(file_BC));
// Start the session
AuthenticationUtils.startSession(userName, pwd);
try {
// Create a reference to the parent where we want to create content
Store storeRef = new Store(Constants.WORKSPACE_STORE, "SpacesStore");
ParentReference companyHomeParent = new ParentReference(storeRef, null, folderName, Constants.ASSOC_CONTAINS, null);
// Assign name
companyHomeParent.setChildName("cm:" + name);
// Construct CML statement to create content node
// Note: Assign "1" as a local id, so we can refer to it in subsequent
// CML statements within the same CML block
NamedValue[] contentProps = new NamedValue[1];
contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, name);
CMLCreate create = new CMLCreate("1", companyHomeParent, null, null, null, Constants.TYPE_CONTENT, contentProps);
// Construct CML statement to add titled aspect
NamedValue[] titledProps = new NamedValue[2];
titledProps[0] = Utils.createNamedValue(Constants.PROP_TITLE, name);
titledProps[1] = Utils.createNamedValue(Constants.PROP_DESCRIPTION, name);
CMLAddAspect addAspect = new CMLAddAspect(Constants.ASPECT_TITLED, titledProps, null, "1");
// Construct CML Block
CML cml = new CML();
cml.setCreate(new CMLCreate[] { create });
cml.setAddAspect(new CMLAddAspect[] { addAspect });
// Issue CML statement via Repository Web Service and retrieve result
// Note: Batching of multiple statements into a single web call
UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml);
Reference content = result[0].getDestination();
// Write some content
ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
//String text = "The quick brown fox jumps over the lazy dog";
ContentFormat contentFormat = new ContentFormat("text/plain", "UTF-8");
Content contentRef = contentService.write(content, Constants.PROP_CONTENT, contentByte, contentFormat);
System.out.println("Document are created successfully. UID:= " + content.getUuid());
return content.getUuid();
} catch (Throwable e) {
System.out.println(e.toString());
} finally {
// End the session
AuthenticationUtils.endSession();
//System.exit(0);
}
return null;
}
I try to replace espace with this character : + without success
saveAttachement(file,
fileName +
System.currentTimeMillis(), container.replace(" ","+"),
USER_NAME, PASSWORD,
code);
this is the old container with espace
/app:company_home/cm:His Excellency the Secretary/cm:Reporter Secretariat
and this is the container with +
/app:company_home/cm:His+Excellency+the Secretary/cm:Reporter+Secretariat
in alfresco's log I didn't find any error
Try encoding your folderName with ISO9075.encode(folderName).
Lucene search syntax needs encoding of spaces using ISO9075. I thik this is what happens somewhere behind the scenes of your ParentReference usage.

create Directory and if exist then rename it

i am developing application in which i want that if user create folder and if it is already present then folder should automatically renamed by appending number to folder name
suppose server has folder with name Time now if user again creates folder than it new folder will be Time1 again user creates folder with same name(Time or Time1) than new Folder should be created with Time2 and so on... This is what i have done so far but recursion always return wrong value.
public string checkIfExist(String path, String ProgramName, int itteration,out string strFolderName)
{
String uploadPath = "";
strFolderName = "";
String Mappath =HttpContext.Current.Server.MapPath(path);
if (Directory.Exists(Mappath))
{
String Path = HttpContext.Current.Server.MapPath((path + "" + ProgramName.Replace(" ", "_")));
// uploadPath += ++itteration ;
if (Directory.Exists(Path))
{
ProgramName += ++itteration;
strFolderName = ProgramName;
uploadPath = checkIfExist(path, ProgramName, itteration,out strFolderName);
}
}
return ProgramName;
}
Perhaps you could adapt this, to your need. I wrote it on the fly based on a piece of code I remember in an old file manager I was using in some projects, so please test it. This doesn't include creation and so on, based on your example I'm sure you can add that yourself but if you need help just comment below.
The idea is to pass the original name of the directory you want, and then return an appropriate new name if it exists, such as Test(1), Test(2), Test(n). Then once you get the name you need, you can create it directly.
protected string GetUniqueDirectoryName(string dirName)
{
string newDirName = dirName;
for (int i = 1; Directory.Exists(Server.MapPath("PATH_HERE") + newDirName); i++)
{
newDirName = string.Format("{0}({1})", dirName, i);
}
return newDirName;
}
Note: You will need to include System.IO and probably use HttpContext.Current.Server.MapPath instead of Server.MapPath
I don't know if I really understand what you are trying to do, but I think using recursion here is a little overkill. Try something like this:
string dirName = "Time";
int counter = 0;
string dir = dirName;
while(Directory.Exists(dir))
{
dir = String.Format("{0}{1}", dirName, (++counter).ToString());
}
Directory.CreateDirectory(dir);

MultipartFormDataStreamProvider Cleanup

If files are posted to my webapp, then I read them via MultipartFormDataStreamProvider.FileData.
I Initialize the provider like this:
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
And the provider nicely stores them as "~App_Data/BodyPart_{someguid}"
But how do I clean up those files after I'm done with them?
I know this question is old, but the best way I found to delete the temporary file was after processing it.
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
foreach (var file in provider.Files)
{
// process file upload...
// delete temporary file
System.IO.File.Delete(file.LocalFileName);
}
You could delete all files that are older than a certain timespan. e.g.
private void CleanTempFiles(string dir, int ageInMinutes)
{
string[] files = Directory.GetFiles(dir);
foreach (string file in files)
{
var time = File.GetCreationTime(file);
if (time.AddMinutes(ageInMinutes) < DateTime.Now)
{
File.Delete(file);
}
}
}
Then call it with something like:
CleanTempFiles(root, 60); // Delete all files older than 1 hour

Resources