How to read Html files by using XmlReader - c#-4.0

I want to read HTML file by using XMLReader. So I wrote some codes, but it throws only XmlException. So please give me any suggestion about how to read the HTML file (and tags) line by line using C#.
public class HtmlReader
{
public List<HtmlDocument> Read(string path)
{
List<HtmlDocument> html = new List<HtmlDocument>();
HtmlDocument h1 = new HtmlDocument();
using (XmlReader reader = XmlReader.Create(path.ToString()))
{
try
{
while (reader.Read())
{
if (reader.IsStartElement())
{
if (reader.Name == "title" || reader.Name == "body")
{
switch (reader.Name)
{
case "title":
if (reader.Read())
{
h1.Title = reader.Value.Trim();
}
break;
case "body":
if (reader.Read())
{
}
break;
}
}
}
}
}
catch(XmlException)
{
}
}
return html;
}
}
}
class Program
{
static void Main(string[] args)
{
HtmlReader readerObject = new HtmlReader();
List<HtmlDocument> employeeCollection = readerObject.Read("E:/workoutsPrograms/ConsoleApplication4/Table.html");
}
}
I tried this, but I was not able to read the Html tags line by line. Apart from my expectation, it throws only Exception.

I find the answer for above question. Following codes you can use.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Ignore;
settings.IgnoreWhitespace = true;
XmlRederSettings is enabled set features of XmlReader. In that Html file have DOCTYPe, For that avoid we want use the Dtdprocessing.Ignore.

Related

What is the new button name for Base.Actions["LSPOReceiptLine_binLotSerial"].Press()?

I have inherited an older customization to the Purchase Receipts / PO302000 screen that I'm trying to upgrade, and it had customization code to import Lot/Serial nbrs from an Excel spreadsheet. It all seems to work alright, except that at the end, it errors out when pressing a button as follows:
Base.Actions["LSPOReceiptLine_binLotSerial"].Press();
Here's the entire code:
public virtual void importAllocations()
{
try
{
if (Base.transactions.Current != null)
{
var siteid = Base.transactions.Current.SiteID;
if (Base.splits.Select().Count == 0)
{
if (this.NewRevisionPanel.AskExt() == WebDialogResult.OK)
{
const string PanelSessionKey = "ImportStatementProtoFile";
PX.SM.FileInfo info = PX.Common.PXContext.SessionTyped<PXSessionStatePXData>().FileInfo[PanelSessionKey] as PX.SM.FileInfo;
System.Web.HttpContext.Current.Session.Remove(PanelSessionKey);
if (info != null)
{
byte[] filedata = info.BinData;
using (NVExcelReader reader = new NVExcelReader())
{
Dictionary<UInt32, string[]> data = reader.loadWorksheet(filedata);
foreach (string[] textArray in data.Values)
{
if (textArray[0] != GetInventoryCD(Base.transactions.Current.InventoryID))
{
throw (new Exception("InventoryID in file does not match row Inventory ID"));
}
else
{
//Find the location ID based on the location CD provided by the Excel sheet...
INLocation inloc = PXSelect<INLocation,
Where<INLocation.locationCD, Equal<Required<INLocation.locationCD>>,
And<INLocation.siteID, Equal<Required<INLocation.siteID>>>>>.Select(Base
, textArray[1]
, Base.transactions.Current.SiteID);
Base.splits.Insert(new POReceiptLineSplit()
{
InventoryID = Base.transactions.Current.InventoryID,
LocationID = inloc.LocationID, //Convert.ToInt32(textArray[1]), //Base.transactions.Current.LocationID,
LotSerialNbr = textArray[2],
Qty = Decimal.Parse(textArray[3])
});
}
}
}
}
}
}
}
Base.Actions["LSPOReceiptLine_binLotSerial"].Press();
}
catch (FileFormatException fileFormat)
{
// Acuminator disable once PX1053 ConcatenationPriorLocalization [Justification]
throw new PXException(String.Format("Incorrect file format. File must be of type .xlsx", fileFormat.Message));
}
catch (Exception ex)
{
throw ex;
}
}
Now, there seems to be no such button - and I have no idea what it would be called now, or if it even still exists. I don't even really know what this action did.
Any ideas?
Thanks much...
That logic has been moved into the PX.Objects.PO.GraphExtensions.POReceiptEntryExt.POReceiptLineSplittingExtension. That action was doing the following in the PX.Objects.PO.LSPOReceiptLine
// PX.Objects.PO.LSPOReceiptLine
// Token: 0x0600446F RID: 17519 RVA: 0x000EE86C File Offset: 0x000ECA6C
public override IEnumerable BinLotSerial(PXAdapter adapter)
{
if (base.MasterCache.Current != null)
{
if (!this.IsLSEntryEnabled((POReceiptLine)base.MasterCache.Current))
{
throw new PXSetPropertyException("The Line Details dialog box cannot be opened because changing line details is not allowed for the selected item.");
}
this.View.AskExt(true);
}
return adapter.Get();
}
Now it is called ShowSplits and is part of the POReceiptLineSplittingExtension extension.
// PX.Objects.PO.GraphExtensions.POReceiptEntryExt.POReceiptLineSplittingExtension
// Token: 0x06005359 RID: 21337 RVA: 0x00138621 File Offset: 0x00136821
public override IEnumerable ShowSplits(PXAdapter adapter)
{
if (base.LineCurrent == null)
{
return adapter.Get();
}
if (!this.IsLSEntryEnabled(base.LineCurrent))
{
throw new PXSetPropertyException("The Line Details dialog box cannot be opened because changing line details is not allowed for the selected item.");
}
return base.ShowSplits(adapter);
}
Given the fact that ShowSplits is defined in the LineSplittingExtension originally it may be referred to as "LineSplittingExteions_ShowSplits" or "POReceiptLineSplittingExtension_ShowSplits". I would suggest including that POReceiptLineSplittingExtension as part of your extension and simply call the Base1.ShowSplits

Testing for file upload in Spring MVC

Project setup:
<java.version>1.8</java.version>
<spring.version>4.3.9.RELEASE</spring.version>
<spring.boot.version>1.4.3.RELEASE</spring.boot.version>
We have a REST controller that has a method to upload file like this:
#PostMapping("/spreadsheet/upload")
public ResponseEntity<?> uploadSpreadsheet(#RequestBody MultipartFile file) {
if (null == file || file.isEmpty()) {
return new ResponseEntity<>("please select a file!", HttpStatus.NO_CONTENT);
} else if (blueCostService.isDuplicateSpreadsheetUploaded(file.getOriginalFilename())) {
return new ResponseEntity<>("Duplicate Spreadsheet. Please select a different file to upload",
HttpStatus.CONFLICT);
} else {
try {
saveUploadedFiles(Arrays.asList(file));
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity("Successfully uploaded - " + file.getOriginalFilename(), new HttpHeaders(),
HttpStatus.OK);
}
}
UPDATE:
I've tried this approach from an old example I found, but it doesn't compile cleanly, the MockMvcRequestBuilders.multipart method is not defined....
#Test
public void testUploadSpreadsheet_Empty() throws Exception {
String fileName = "EmptySpreadsheet.xls";
String content = "";
MockMultipartFile mockMultipartFile = new MockMultipartFile(
"emptyFile",
fileName,
"text/plain",
content.getBytes());
System.out.println("emptyFile content is '" + mockMultipartFile.toString() + "'.");
mockMvc.perform(MockMvcRequestBuilders.multipart("/bluecost/spreadsheet/upload")
.file("file", mockMultipartFile.getBytes())
.characterEncoding("UTF-8"))
.andExpect(status().isOk());
}
I believe MockMvcRequestBuilders.multipart() is only available since Spring 5. What you want is MockMvcRequestBuilders.fileUpload() that is available in Spring 4.

Getting code from all (closed) files in solution in Visual Studio SDK

I'm trying to get and edit the code of all the html-files in the project
i found a way to loop over all ProjectItems
IEnumerator Projects = _applicationObject.Solution.Projects.GetEnumerator();
while (Projects.MoveNext())
{
IEnumerator Items = ((Project)Projects.Current).ProjectItems.GetEnumerator();
Queue<ProjectItem> ProjectItems = new Queue<ProjectItem>();
while (Items.MoveNext())
{
ProjectItem SubItem = (ProjectItem)Items.Current;
try
{
if (SubItem.Document != null) DocumentIndex.Add(SubItem.Document);
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
ProjectItems.Enqueue(SubItem);
}
//follow the tree down
while (ProjectItems.Count != 0)
{
ProjectItem ProjectItem = ProjectItems.Dequeue();
if (ProjectItem.ProjectItems != null)
{
foreach (ProjectItem SubItem in ProjectItem.ProjectItems)
{
ProjectItems.Enqueue(SubItem);
try
{
try
{
SubItem.Open(SubItem.Kind);
DocumentIndex.Add(SubItem.Document);
}catch(Exception Ex){
Console.WriteLine(Ex.Message);
}
}
catch (Exception Exception)
{
Console.WriteLine(Exception.Message);
//ignore
}
}
}
}
}
now i can't get to the code of the files that are not open in an editor window.
how do i get and edit the code of "not opened" projectItems?
how do i detect if a file is a code file? (eg: .cs, .html, .htm, .asp, ....
You must open the ProjectItem that you want to read or edit
DTE dte = (DTE)Package.GetGlobalService(typeof(DTE));
var project = dte.Solution.Projects.Item(1);
var projectItems = project.ProjectItems;
var anyItem = projectItems.Item(0);
Window anyItemWindow = anyItem.open()
var selection = anyItem.Document.Selection as TextSelection;
selection.SelectAll();
Console.WriteLine(selection.Text) // All code
anyItem.Document.Close() //Close Document
if you don't open the ProjectItem anyItem.Doument is null.
Note: selection.Insert("") can be used to change the code

Set file permission in java 5

I am using the below code to upload image. The problem is that after uploading the image i cant change the file permission. my file permission set by default is rw-r--r-- (0644). Is it possible to change the file permission or set it as 0777 by default? It works fine in my local system. But not able to change the permission in my linux server.
<%
try
{
int filesize=0;
String fieldname="",fieldvalue="",filename="",content="",bookid="",bkdescription="";
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
fieldname = item.getFieldName();
fieldvalue = item.getString();
if(fieldname.equals("homeid")){
bookid=fieldvalue;
}
if(fieldname.equals("bkdescription")){
bkdescription=fieldvalue;
}
} else {
try{
fieldname = item.getFieldName();
filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
filesize=(int)item.getSize();
filename="literal_"+bookid+".jpg";
if(filesize>0){
byte[] b=new byte[filesize];
int c=0;
File f=new File(getServletConfig().getServletContext().getRealPath("/")+"/imagesX");
String filePah=getServletConfig().getServletContext().getRealPath("/")+"/imagesX";
if(f.isDirectory())
{
String fl[]=f.list();
for(int i=0;i<fl.length;i++)
{
File fd=new File(getServletConfig().getServletContext().getRealPath("/")+"/imagesX/"+fl[i]);
if(fd.getName().equals(filename))
fd.delete();
}
}
if(!f.exists())
{
new File(filePah).mkdir();
f.mkdir()
}
java.io.FileOutputStream fout=new java.io.FileOutputStream(getServletConfig().getServletContext().getRealPath("/")+"/imagesX/"+filename);
while((c = filecontent.read(b)) != -1 )
{
fout.write(b, 0, c);
}
fout.close();
filecontent.close();
}
}catch (Exception e) {
System.out.println("Exception in creation of file :"+e);
}
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
}
catch(Exception exp)
{
out.println(exp);
}
%>
You cannot change the file permission from inside java code.
Your system's default umask is set to 0644 for new file. It wouldn't be good idea to change the default umask.
What you need is to do is set the permission of your directory to 0777 and then redefine your directory's ACL to recursive, so all new file created inside will inherit the same permission.
Heres a link which shows how to go about -
https://superuser.com/questions/151911/how-to-make-new-file-permission-inherit-from-the-parent-directory
An alternative solution is to change the permissions externally with a system command, chmod.
Example:
public static void runCmd (String[] cmd) {
try {
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader r = new BufferedReader(
new InputStreamReader (
p.getInputStream()
)
);
} catch(Exception e) {
}
}
runCmd(new String[] {
"/bin/chmod",
"755",
"/path/to/your/script"
});
P.S. were you also trying to call Java from a stored proc in an Oracle database?

Get item’s metadata with Entity Framework?

I'm working with Sharepoint 2010.
I need to know the date of creation/edition and the author/editor of items in my sharepoint's Lists, but I didn't find a solution to map these columns with Entity Framework.
I tried this kind of code :
[Microsoft.SharePoint.Linq.ColumnAttribute(Name = "tp_author", Storage = "_author", ReadOnly = true, FieldType = "User")]
public SPUser Author
{
get
{
return this._author;
}
set
{
if (!value.Equals(this._author))
{
this.OnPropertyChanging("Author", this._author);
this._author = value;
this.OnPropertyChanged("Author");
}
}
}
But with that code, Sharepoint give me this error:
Invalid transfer type Microsoft.SharePoint.SPUser
I also tried with other types for _author, but it doesn't change anything.
Is there a way to make this mapping?
SPMetal generates the following code for a user field
[Microsoft.SharePoint.Linq.ColumnAttribute(Name="AssignedTo", Storage="_assignedToId", FieldType="User", IsLookupId=true)]
public System.Nullable<int> AssignedToId {
get {
return this._assignedToId;
}
set {
if ((value != this._assignedToId)) {
this.OnPropertyChanging("AssignedToId", this._assignedToId);
this._assignedToId = value;
this.OnPropertyChanged("AssignedToId");
}
}
}
[Microsoft.SharePoint.Linq.ColumnAttribute(Name="AssignedTo", Storage="_assignedTo", ReadOnly=true, FieldType="User", IsLookupValue=true)]
public string AssignedTo {
get {
return this._assignedTo;
}
set {
if ((value != this._assignedTo)) {
this.OnPropertyChanging("AssignedTo", this._assignedTo);
this._assignedTo = value;
this.OnPropertyChanged("AssignedTo");
}
}
}

Resources