Save text file with code page UTF-8 in Axapta 3.0 - axapta

How do I make a text file with code page UTF-8 in Axapta 3.0?
I cannot use
myFile = new CommaIo(myFileName, 'W', 65001);
as we can in newer versions of Axapta. In Axapta 3.0 new CommaIo only have the first two parameters.

I've not worked in 3.0, but I have a few ideas for you that might send you the right way.
1) Do you have CommaTextIo or TextIo? Those are the objects where you can specify a code page.
2) Look in the AOT and see if you have a macro called #File, and inside if you have #utf8Format(65001), use the X-Ref (or Ctrl+F) to find other places in the system that use it. Then you can see how they might accomplish UTF-8
3) See if you can combine CommaIo with some .NET code, or just manually generated a CSV. Perhaps generate your CSV and write it, then read it and re-write it using a method like below (from MetadataXMLGenerator job):
void write(str _directory, str _name, str _text)
{
str path;
;
_text = System.Text.RegularExpressions.Regex::Replace(_text, '\n', '\r\n');
if (!System.IO.Directory::Exists(_directory))
{
System.IO.Directory::CreateDirectory(_directory);
}
path = System.IO.Path::Combine(_directory, _name);
System.IO.File::WriteAllText(path, _text, System.Text.Encoding::get_UTF8());
}

Related

Save an Image with a new file name [ImageSharp]

I have upgraded my project from .net framework to .net 6 (core). In my project, there are many places where Bitmap is used. I have read in the microsoft documentations that System.Drawing.Common will only support the Windows platform and even after adding the EnableUnixSupport configuration, it will not be supported in net7.So, now I am using ImageSharp.Web. I have the scenario where I save a file as Image (the format is .tiff) then I read from that path as bitmap and save as PNG ( due to some business rule)
Following is the line of code I am trying change:
Bitmap.FromFile(completePath).Save(pngPath, ImageFormat.Png);
This is the code I have converted into. The only issue is how to save as a new file name as the Tiff file has tiff in the file name.
string extension = _GetExtension(img.ContentType);
if (extension == Constants.TiffExtension)
{
fileName = fileName.Replace(Constants.TiffExtension, "PNG");
using (var outputStream = new FileStream(completePath, FileMode.CreateNew))
{
var image = SixLabors.ImageSharp.Image.Load(completePath);
image.SaveAsync(outputStream, new PngEncoder()); //how to save new file name?
}
}
You can use the image.Save(fileName); overload to save a image to a file. The file name overload that takes just a path will automatically choose the correct encoder based on the file extension.
I was using the ImageSharp.Web package while the one I needed was the basic ImageSharp package. Special thanks to #James South for correcting me and #tocsoft for the guidance.
I have fixed it by the following code which is working:
if (extension == Constants.Conversion.TiffExtension)
{
using (SixLabors.ImageSharp.Image image = SixLabors.ImageSharp.Image.Load(completePath))
{
string pngPath = completePath.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
image.Save(pngPath);
fileName = fileName.Replace(Constants.Conversion.TiffExtension, Conversion.DefaultExtension);
}
}

Why is TrimStart not recognised in VisualStudio for ASP.NET?

I whant to use TrimStart for my string value like this: How to remove all zeros from string's beginning?
But TrimStart syntax is not recognise in VisualStudio. How to corectly generate it?
my code:
string str = parameters.Internal;
string s = str;
string no_start_zeros = s.TrimStart('0');
At the top of your .CS file do you have: using system; the string.TrimStart(); method is found in the system namespace, which is contained inside mscorlib.dll - you can also try referencing mscorlib.dll directly.
TrimStart() function is used to Removes all leading occurrences of a set of characters specified in an array from the current String object.
when visual studio version you are using ? as far as I know trimStart() support in almost all version from 1.1 to 4.5
check out below snippet for more detail
string szInput = "000YTHLKJH";
string output = szInput.TrimStart('0');
//output will be : YTHLKJH
Hope it helps

PDF content search in asp.net c#

Actually my requirement is to search pdf files using the pdf content.
I have a folder with a lot of PDF files.
I would like to develop an ASP.net application that enables the user to
search pdf using the content provided by them inside a textbox.
how to perform this task?
thank u in advance.
Your task may be split into following subtasks:
Develop indexer that will index all of your PDF files
Develop the code to locate relevant PDF whenever a search performed (using the index, of course)
Develop functionality that will open relevant PDF or show a warning if nothing was found
To build index you may use some integrated solution like Apache Lucene or Lucene.Net or convert each PDF into text and build index from the text yourselves.
You may try Docotic.Pdf library for the indexer part (disclaimer: I work for Bit Miracle).
The library could be used to extract text from PDFs. It can extract text with or without formatting. The extracted text can be used to create an index.
The library can also retrieve a collection of words with their bounding rectangles from PDFs. This might be useful if you need to know exact position of a text in a file.
If you don't want to build an index then you still can use Docotic.Pdf to perform searches using a code like the following:
PdfDocument doc = new PdfDocument("file.pdf");
string textToSearch = "some text";
for (int i = 0; i < doc.Pages.Count; i++)
{
string pageText = doc.Pages[i].GetText();
int count = 0;
int lastStartIndex = pageText.IndexOf(textToSearch, 0, StringComparison.CurrentCultureIgnoreCase);
while (lastStartIndex != -1)
{
count++;
lastStartIndex = pageText.IndexOf(textToSearch, lastStartIndex + 1, StringComparison.CurrentCultureIgnoreCase);
}
if (count != 0)
Console.WriteLine("Page {0}: '{1}' found {2} times", i, textToSearch, count);
}
You can use any library for that, try iTextSharp its a free one.
You can read pdf as text like this:
public string ReadPdfFile(string fileName)
{
StringBuilder text = new StringBuilder();
if (File.Exists(fileName))
{
PdfReader pdfReader = new PdfReader(fileName);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
}
pdfReader.Close();
}
return text.ToString();
}
try Zoom Search it has a plugin for extracting pdf documents text (which you can search against) , and its easy to customize your search.You will need the standard edition which is not free (about $49).Zoom search does the searching for you out of the box, you do not need to do any complicated stuff eg if you prefer to extract the text from the pdf and then some how index it in a database for search or trying to use Lucene search engine which will require you to do implement /and customise(a bit of work).
Zoom works well with ASP.NET and you just need to use the GUI for customizing your search(not a lot of coding is required).

Add filter to FileUpload Control

How to add filter to the fileupload control in asp.net? I want a filter for Word Template File (.dot).
You could also do a javascript alternative to filtering it server side (you'd probably want to do that as well) but this saves the client from spending the time waiting on an upload to finish just to find out it was the wrong type.
http://javascript.internet.com/forms/upload-filter.html
So basically you just run a javascript function on submit that parses off the extension of the uploaded file and gives them an alert if its not of the right type.
You could also use document.forms[0].submit(); instead of passing the form reference through (as ASP.NET really only uses a single form (unless your doing something funky))
string fileName = fuFiles.FileName;
if(fileName.Contains(".dot"))
{
fuFiles.SaveAs(Server.MapPath("~/Files/" + fileName));
}
If you mean to filter the file extensions client/side, with the standard browser's file selector, isn't possible.
To do that you have to use a mixed type of upload, such as SWFUpload, based on a flash uploader system (that's a really nice techinque: it allows you to post more than a file at time).
The only thing you can do in standard mode is to filter the already posted file, and I suggest to use System.IO.Path namespace utility:
if (Path.GetExtension(upFile.FileName).ToUpper().CompareTo(".DOT") == 0)
{
/* do what you want with file here */
}
Check the filename of the uploaded file serverside:
FileUpload1.PostedFile.FileName
Unless you want to use java or something similar on the client, there's really not much you can do for filtering uploaded files before they're sent to the server.
Here I have a small method that I used to filter which types of files can be uploaded by the fileupload control named fuLogo.
if (fuLogo.HasFile)
{
int counter = 0;
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]);
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++;
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
fuLogo.SaveAs(logo);
}
basically, I first Iterates through the directory to see if a file already exists. Should the file exist, (example picture0.gif) , it will increase the counter (to picture1.gif). It prevents that different users will overwrite each other's pictures should their pictures have the same name.

Convert CSV file or Excel spreadsheet to RESX File

I am looking for a solution or recommendation to a problem I am having. I have a bunch of ASPX pages that will be localized and have a bunch of text that needs to be supported in 6 languages.
The people doing the translation will not have access to Visual Studio and the likely easiest tool is Excel. If we use Excel or even export to CSV, we need to be able to import to move to .resx files. So, what is the best method for this?
I am aware of this question, Convert a Visual Studio resource file to a text file? already and the use of Resx Editor but an easier solution would be preferred.
I'm not sure how comprehensive an answer you're looking for, but if you're really just using [string, string] pairs for your localization, and you're just looking for a quick way to load resource (.resx) files with the results of your translations, then the following will work as a fairly quick, low-tech solution.
The thing to remember is that .resx files are just XML documents, so it should be possible to manually load your data into the resource from an external piece of code. The following example worked for me in VS2005 and VS2008:
namespace SampleResourceImport
{
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
string filePath = #"[file path to your resx file]";
doc.Load(filePath);
XmlElement root = doc.DocumentElement;
XmlElement datum = null;
XmlElement value = null;
XmlAttribute datumName = null;
XmlAttribute datumSpace = doc.CreateAttribute("xml:space");
datumSpace.Value = "preserve";
// The following mocks the actual retrieval of your localized text
// from a CSV or ?? document...
// CSV parsers are common enough that it shouldn't be too difficult
// to find one if that's the direction you go.
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Label1", "First Name");
d.Add("Label2", "Last Name");
d.Add("Label3", "Date of Birth");
foreach (KeyValuePair<string, string> pair in d)
{
datum = doc.CreateElement("data");
datumName = doc.CreateAttribute("name");
datumName.Value = pair.Key;
value = doc.CreateElement("value");
value.InnerText = pair.Value;
datum.Attributes.Append(datumName);
datum.Attributes.Append(datumSpace);
datum.AppendChild(value);
root.AppendChild(datum);
}
doc.Save(filePath);
}
}
}
Obviously, the preceding method won't generate the code-behind for your resource, however opening the resource file in Visual Studio and toggling the accessibility modifier for the resource will (re)generate the static properties for you.
If you're looking for a completely XML-based solution (vs. CSV or Excel interop), you could also instruct your translators to store their translated content in Excel, saved as XML, then use XPath to retrieve your localization info. The only caveat being the file sizes tend to become pretty bloated.
Best of luck.
I ran into similar problem and realized that the simplest way to create a .resx file from excel file is using a concatenate function of excel to generate "<"data">".."<"/data">" node for the .resx file and then manually copying the generated rows to the .resx file in any text editor. So lets say that you have "Name" in column A of an excel document and "value" in Column B of the excel document. Using following formula in Column C
=CONCATENATE("<data name=","""",A14,""" xml:space=""preserve"">","<value>", B14, "</value>", "</data>")
you will get the data node for resource. You can then copy this formula to all the rows and then copy the contents of Column C in your .resx file.
If it's in csv here's a quick Ruby script to generate the data elements.
require 'csv'
require 'builder'
file = ARGV[0]
builder = Builder::XmlMarkup.new(:indent => 2)
CSV.foreach(file) do |row|
builder.data(:name => row[0], "xml:space" => :preserve) {|d| d.value(row[1]) }
end
File.open(file + ".xml", 'w') { |f| f.write(builder.target!) }

Resources