Want to check IF File.Exists to define StreamReader, to then searching for specific line - readline

I don't write code often and my knowledge is still low-level. I need help for something that I can't figure out
public static void SearchScriptEnd()
{
int counter = 0;
string line;
Report.Log(ReportLevel.Info, "Read Log", "Starting to find: Test Suite Ended");
var text = "Test Suite Ended";
if (File.Exists(ConfigController.Home + TestSuite.Current.Parameters["LogPath"]))
{
StreamReader file =
new StreamReader(ConfigController.Home + TestSuite.Current.Parameters["LogPath"]);
}else{
StreamReader file =
new StreamReader(TestSuite.Current.Parameters["LogPath"]);
}
while ((line = file.ReadLine()) != null)
{
if (line.Contains(text))
{
Report.Log(ReportLevel.Info, "Read Log", "[Success] Script End String has been found");
Report.Log(ReportLevel.Info, "Read Log", string.Format("Line number: '{0}'", counter));
return;
}
counter++;
}
Report.Log(ReportLevel.Failure, "Read Log", "[Missing] Anvil Script End String NOT found");
file.Close();
}
At first, the while was in both statement and was working well, but I want to use the While outside of that statement, but I'm getting The name 'file' does not exist in the current context (CS0103) and I don't know how to get the value of file out of my If statement.

You need to get the variable out of the if-scope. Try this:
StreamReader file;
if (File.Exists(ConfigController.Home + TestSuite.Current.Parameters["LogPath"]))
{
file = new StreamReader(ConfigController.Home + TestSuite.Current.Parameters["LogPath"]);
}else{
file = new StreamReader(TestSuite.Current.Parameters["LogPath"]);
}
That way you have a value in file for sure. Happy coding.

Related

Apache Beam TextIO.Read with line number

Is it possible to get access to line numbers with the lines read into the PCollection from TextIO.Read? For context here, I'm processing a CSV file and need access to the line number for a given line.
If not possible through TextIO.Read it seems like it should be possible using some kind of custom Read or transform, but I'm having trouble figuring out where to begin.
You can use FileIO to read the file manually, where you can determine the line number when you read from the ReadableFile.
A simple solution can look as follows:
p
.apply(FileIO.match().filepattern("/file.csv"))
.apply(FileIO.readMatches())
.apply(FlatMapElements
.into(strings())
.via((FileIO.ReadableFile f) -> {
List<String> result = new ArrayList<>();
try (BufferedReader br = new BufferedReader(Channels.newReader(f.open(), "UTF-8"))) {
int lineNr = 1;
String line = br.readLine();
while (line != null) {
result.add(lineNr + "," + line);
line = br.readLine();
lineNr++;
}
} catch (IOException e) {
throw new RuntimeException("Error while reading", e);
}
return result;
}));
The solution above just prepends the line number to each input line.

JavaMail MIME attachment link by cid

Background
I have banged my head against this for a while and not made much progress. I am generating MPEG_4 / AAC files in Android and sending them by email as .mp3 files. I know they aren't actually .mp3 files, but that allows Hotmail and Gmail to play them in Preview. They don't work on iPhone though, unless they are sent as .m4a files instead which breaks the Outlook / Gmail Preview.
So I have thought of a different approach which is to attach as a .mp3 file but have an HTML link in the email body which allows the attached file to be downloaded and specifies a .m4a file name. Gmail / Outlook users can click the attachment directly whereas iPhone users can use the HTML link.
Issue
I can send an email using JavaMail with HTML in it including a link which should be pointing at the attached file to allow download of that file by the link. Clicking on the link in Gmail (Chrome on PC) gives a 404 page and iPhone just ignores my clicking on the link.
Below is the code in which I generate a multipart message and assign a CID to the attachment which I then try to access using the link in the html part. It feels like I am close, but maybe that is an illusion. I'd be massively grateful if someone could help me fix it or save me the pain if it isn't possible.
private int send_email_temp(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtp_host_setting);
//props.put("mail.debug", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", smtp_port_setting);
session = Session.getInstance(props);
ActuallySendAsync_temp asy = new ActuallySendAsync_temp(true);
asy.execute();
return 0;
}
class ActuallySendAsync_temp extends AsyncTask<String, String, Void> {
public ActuallySendAsync_temp(boolean boo) {
// something to do before sending email
}
#Override
protected Void doInBackground(String... params) {
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipient_email_address));
message.setSubject(email_subject);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
String file = mFileName;
/**/
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
/* /
File ff = new File(file);
try {
messageBodyPart.attachFile(ff);
} catch(IOException eio) {
Log.e("Message Error", "Old Macdonald");
}
/* /
messageBodyPart = new PreencodedMimeBodyPart("base64");
byte[] file_bytes = null;
File ff = new File(file);
try {
int length = (int) ff.length();
BufferedInputStream reader = new BufferedInputStream(new FileInputStream(ff));
file_bytes = new byte[length];
reader.read(file_bytes, 0, length);
reader.close();
} catch (IOException eio) {
Log.e("Message Error", "Old Macdonald");
}
messageBodyPart.setText(Base64.encodeToString(file_bytes, Base64.DEFAULT));
messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");
/**/
messageBodyPart.setFileName( DEFAULT_AUDIO_FILENAME );//"AudioClip.mp3");
//messageBodyPart.setContentID("<audio_clip>");
String content_id = UUID.randomUUID().toString();
messageBodyPart.setContentID("<" + content_id + ">");
messageBodyPart.setDisposition(Part.ATTACHMENT);//INLINE);
messageBodyPart.setHeader("Content-Type", "audio/mp4");
multipart.addBodyPart(messageBodyPart);
MimeBodyPart messageBodyText = new MimeBodyPart();
//final String MY_HTML_MESSAGE = "<h1>My HTML</h1><a download=\"AudioClip.m4a\" href=\"cid:audio_clip\">iPhone Download</a>";
final String MY_HTML_MESSAGE = "<h1>My HTML</h1><a download=\"AudioClip.m4a\" href=\"cid:" + content_id + "\">iPhone Download</a>";
messageBodyText.setContent( MY_HTML_MESSAGE, "text/html");
multipart.addBodyPart(messageBodyText);
message.setContent(multipart);
Print_Message_To_Console(message);
Transport transport = session.getTransport("smtp");
transport.connect(smtp_host_setting, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// something to do after sending email
}
}
int Print_Message_To_Console(Message msg) {
int ret_val = 0;
int line_num = 0;
InputStream in = null;
InputStreamReader inputStreamReader = null;
BufferedReader buff_reader = null;
try {
in = msg.getInputStream();
inputStreamReader = new InputStreamReader(in);
buff_reader = new BufferedReader(inputStreamReader);
String temp = "";
while ((temp = buff_reader.readLine()) != null) {
Log.d("Message Line " + Integer.toString(line_num++), temp);
}
} catch(Exception e) {
Log.d("Message Lines", "------------ OOPS! ------------");
ret_val = 1;
} finally {
try {
if (buff_reader != null) buff_reader.close();
if (inputStreamReader != null) inputStreamReader.close();
if (in != null) in.close();
} catch(Exception e2) {
Log.d("Message Lines", "----------- OOPS! 2 -----------");
ret_val = 2;
}
}
return ret_val;
}
You need to create a multipart/related and set the main text part as the first body part.

Is it possible to subcribe to a sentence of an epl module?

I have deployed an epl module with the code:
InputStream inputFile = this.getClass().getClassLoader().getResourceAsStream("Temperature.epl");
if (inputFile == null) {
inputFile = this.getClass().getClassLoader().getResourceAsStream("etc/Temperature.epl");
}
if (inputFile == null) {
throw new RuntimeException("Failed to find file 'Temperature.epl' in classpath or relative to classpath");
}
try {
epService.getEPAdministrator().getDeploymentAdmin().readDeploy(inputFile, null, null, null);
// subscribers Ok, tested before whith epService.getEPAdministrator().createEPL ()
// sentences ok, printed
EPStatement statement;
statement = epService.getEPAdministrator().getStatement("Monitor");
System.out.println(statement.getText() + ";");
statement.setSubscriber(new MonitorEventSubscriber());
statement = epService.getEPAdministrator().getStatement("Warning");
System.out.println(statement.getText() + ";");
statement.setSubscriber(new WarningEventSubscriber());
statement = epService.getEPAdministrator().getStatement("Error");
System.out.println(statement.getText() + ";");
statement.setSubscriber(new ErrorEventSubscriber());
}
catch (Exception e) {
throw new RuntimeException("Error deploying EPL from 'Temperature.epl': " + e.getMessage(), e);
}
I can get the sentences by statement.getText(), but the subscribers are not activated. What it's wrong?
I'm working with Esper 5.0.0
Seeing that your code uses the current classloader, you'd want to make sure the classloader is the same else you can get different engine instances.
Also have your code actually send an event to see if it matches since this code doesn't send events.

ASP.NET MVC Return Excel File

I have a requriement to upload a file and modify and then return the same. I dont need to save the file to any location but manipulate it and return. However I am not knowing how to return the file.
The below code allows the file to save, I even wrote code with out saving file. only problem is I am getting an error that this file is already open by someother user.
The process cannot access the file 'D:\Places\places\App_Data\877d36d3-ce29-48d1-995a-ea6652a528a7C2.xlsx' because it is being used by another process.
Can you please help me
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string path = string.Empty;
var fileName = Path.GetFileName(uploadFile.FileName);
path = Path.Combine(Server.MapPath("~/App_Data/"), Guid.NewGuid() + fileName);
uploadFile.SaveAs(path);
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count;
(xlRange.Cells[4, 5] as Excel.Range).Value2 = "asdF";
(xlRange.Cells[4, 6] as Excel.Range).Value2 = "asdF";
(xlRange.Cells[4, 7] as Excel.Range).Value2 = "asdF";
(xlRange.Cells[4, 8] as Excel.Range).Value2 = "asdF";
releaseObject(xlWorksheet);
releaseObject(xlWorkbook);
releaseObject(xlApp);
GC.Collect();
uploadFile.InputStream.Dispose();
return File(path, "application/text");
}
else
{
return View();
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
//MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{enter code here
GC.Collect();
}
}
in the action you can return a FileStreamResult
return new FileStreamResult([memory stream], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
You also might want to close and save the workbook to a temp area before returning. From the error it looks like the file is still open.
It's because probably you are not closing your file. You should use something like xlWorkbook.Close before trying to use it again, or you can use the using() statement.
http://msdn.microsoft.com/en-us/library/system.io.file.open(v=vs.71).aspx

How to identify correct url

I have list of URL in txt file I am using it for performance test, since URL were not formed correctly java.IO.exeption were thrown,I would like to know how to check correctness of URL? and whether it is working fine? I have more than 35 K url checking manually will consume lot's of time.
To check whether URL are properly formed try casting the string to an URI object.
eg:
public void validURLs(List<string> urlList)
{
int line = 1;
for(string s : urlList)
{
try
{
URI test = new URI(s);
}
catch(Exception e)
{
System.err.println(s + " is not a valid URL, item " + line);
}
line ++;
}
}

Resources