Im a beginner in coding so please bare with my lack of knowledge, thank you.
i have a code initially looking like this in my catch block
catch (Exception ex)
{
String[] msg = ex.Message.Split(new char[] { '|' });
if (msg[0] == "EXIST")
{
lblStatus.CssClass = "Error";
lblStatus.Text = "<span class='" + Resources.Resource.LangParam2 + "'>" + Resources.Resource.UserNameAlreadyExists + "</span>";
return;
}
else
{
throw ex;
}
}
i am trying to make the code in the catch function into a library function as many code will use it.
for example I am trying smth like this
catch (Exception ex)
{
String[] msg = ex.Message.Split(new char[] { '|' });
Util.GetErrorMessage("SubUser1");
else
{
throw ex;
}
}
and inside my Util.cs code is as below
public static void GetErrorMessage(string acc)
{
if(acc == "SubUser1")
{
String[] msg = new string[] { };
if (msg[0] == "EXIST")
{
string Class = "Error";
string Text = "<span class='" + Resources.Resource.LangParam2 + "'>" + Resources.Resource.UserNameAlreadyExists + "</span>";
return;
}
}
}
any idea that i can make this happen? thank you!
Related
I am using the following code in window service to download zip file with particular format from email attachments:
Method to get Emails:
public void GetdownloadfromGmail()
{
try
{
ConfigDetails ConfigDetails = new ConfigDetails();
DataTable SecTable = ConfigDetails.GetConfigTableCol(Constant.Seccurity);
using (IDbConnection con = Connections.Getsynchconnection())
{
try
{
con.Open();
ConnectionState state = con.State;
con.Close();
if (state == ConnectionState.Open)
{
SentmailCount = 0;
}
}
catch (Exception ex)
{
Common.Synch.Factory.LogHelpFactory.log.Error(ex.Message.ToString());
if (SentmailCount == 0)
{
string ContentMessage = "SqlConnection is Not Open :" + ex.Message.ToString();
Process SharedProc = new Process();
string EmailID = SharedProc.GetReceipientmailid(new Context(new MailContext()), "", 3);
string[] Receipients = EmailID.Split(',');
//time being profile,pwd is hard coded
GmailClient.GmailClient gc = new GmailClient.GmailClient();
/*Sending attachment(s) with the mail*/
gc.SMTPHost = SecTable.Rows[0]["SmtpHost"].ToString();
gc.SMTPPortNumber = Convert.ToInt32(SecTable.Rows[0]["SmtpPort"].ToString());
bool IsEnableSsl = Convert.ToBoolean(SecTable.Rows[0]["IsEnableSsl"].ToString());
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(SecTable.Rows[0]["Username"].ToString(), SecTable.Rows[0]["Password"].ToString());
System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(SecTable.Rows[0]["Username"].ToString(), SecTable.Rows[0]["DisplayName"].ToString());
gc.sendMail("Connection", Receipients, ContentMessage, null, "", credentials, address, true, IsEnableSsl);
SentmailCount = 1;
}
return;
}
}
Common.Synch.Factory.LogHelpFactory.log.Info("Start Download Mails From Mailbox");
//ConfigDetails ConfigDetails = new ConfigDetails();
//time being profile,pwd is hard coded
// DataTable SecTable = ConfigDetails.GetConfigTableCol(Constant.Seccurity);
if (SecTable.Columns["UserName"] == null && SecTable.Columns["Password"] == null)
{
throw (new Exception("Invalid Profile settings"));
}
using (GmailClient.GmailClient gc = new GmailClient.GmailClient())
{
gc.UseSSL = true;
/*Part to fetch mails from gmail; List<MailMessage> will have all the mails fetched which can be used later to send mails.
The attachments get downloaded as the mails are read.
The MailMessage only includes the basic header information along with the number of attachments processed.
Once all emails are fetched, the client disconnects automatically*/
//Following property will not delete the email from gmail server if set to False, but deletes if it set to True
gc.SMTPHost = SecTable.Rows[0]["IncomingEmailHost"].ToString();
gc.SMTPPortNumber = Convert.ToInt32(SecTable.Rows[0]["IncomingEmailPort"].ToString());
gc.DeleteProcessedMails = Convert.ToBoolean(SecTable.Rows[0]["DeleteEmail"].ToString());
ConfigDetails = new ConfigDetails();
TempPath = ConfigDetails.GetPath(Constant.TempFolder);
//Default AttachmentPath is the path of dll directory. Howeve it can be set exclusilvely as below.
gc.AttachmentPath = TempPath + "\\";
string strUname = SecTable.Rows[0]["Username"].ToString();
string strPwd = SecTable.Rows[0]["Password"].ToString();
gc.Connect(strUname, strPwd);
gc.CopyProcessedMails = Convert.ToBoolean(SecTable.Rows[0]["CopyProcessedEmail"].ToString()); ;
gc.CopyMailTargetFolder = Convert.ToString(SecTable.Rows[0]["CopyMailTargetFolder"].ToString()); ;
Common.Synch.Factory.LogHelpFactory.log.Info("Test ");
if (gc.IsConnected)
{
Common.Synch.Factory.LogHelpFactory.log.Info("Connected");
List<MailMessage> mails = gc.GetMailList();
Common.Synch.Factory.LogHelpFactory.log.Info("Unread Mail Count:" + mails.Count.ToString()); try
{
foreach (MailMessage Mail in mails)
{
try
{
isDeleted = false;
if (null != Mail.Subject)
Common.Synch.Factory.LogHelpFactory.log.Info(Mail.Subject.ToString());
else
Common.Synch.Factory.LogHelpFactory.log.Info(Mail.FromEmail + " (no subject)");
GetMaiilboxtotable(Mail);
//if (isDeleted)
//{
//Mail.UnRead = false;
//Mail.Delete();
//}
}
catch (Exception Ex)
{
//if (Ex.Message == "Could not save attachment to a file")
//{
Common.Synch.Factory.LogHelpFactory.log.Info("Error while processing email:" + Ex.Message.ToString());
Common.Synch.Factory.LogHelpFactory.log.Info("Subject:" + Mail.Subject + ", From:" + Mail.FromName);
//Mail.UnRead = false;
//Mail.Delete();
//}
}
}
}
//if (ListofMails.Count > 0)
//{
//OutlookClient.MovFolderselection();
//}
catch (Exception Ex)
{
//if (ListofMails != null)
//{
// Marshal.ReleaseComObject(ListofMails);
//}
//ListofMails = null;
////OutlookClient.Dispose();
mails = null;
gc.Dispose();
Common.Synch.Factory.LogHelpFactory.log.Error("SearchMails(GetMailFromGmail) failed : ", Ex);
}
finally
{
if (m_MailTable.Rows.Count > 0)
{
SaveEmail();
Common.Synch.Factory.LogHelpFactory.log.Info("Save Email Complete");
}
int Sleeptime = Convert.ToInt32(ConfigDetails.GetResourceSleeptime(Constant.InboundProcess));
if (Sleeptime == 0)
{
Sleeptime = 10000;
}
ConfigDetails = null;
try
{
Thread.Sleep(Sleeptime);
}
catch (ThreadAbortException ex)
{
Common.Synch.Factory.LogHelpFactory.log.Info("Error on thread.Sleep:" + ex.Message.ToString());
}
try
{
this.DownLoadCompleteEventArgs(this, new DownLoadCompleteEventArgs("DownLoad Complete"));
}
catch (Exception ex)
{
Common.Synch.Factory.LogHelpFactory.log.Info("Error while invoking the thread:" + ex.Message.ToString());
}
Common.Synch.Factory.LogHelpFactory.log.Info("End Download Mails From Inbox");
}
}
// Log
}
}
catch (Exception ex)
{
Common.Synch.Factory.LogHelpFactory.log.Error(ex.Message.ToString());
}
}
Method to save extracted files in database:
public void GetMaiilboxtotable(MailMessage Message)
{
Common.Synch.Common.DeleteFile(TempPath);
try
{
if (Initalize())
{
if (Message.Attachments != null && Message.AttachmentsCount > 0)
{
for (int Count = 0; Count <= Message.AttachmentsCount - 1; Count++)
{
//if (Message.Attachments[Count].AttachmentAttachmentFileName.Substring(Message.Attachments[Count].AttachmentAttachmentFileName.Length - 3, 3).ToUpper() == "MSG")
//{
// Message.Attachments[Count].SaveAsFile(TempPath + "Temp.msg");
// outlookApp = new OutLook.ApplicationClass();
// MsgMail = (OutLook.MailItem)outlookApp.CreateItemFromTemplate(TempPath + "Temp.msg", Type.Missing);
// GetMaiilboxtotable(MsgMail);
// outlookApp = null;
// MsgMail = null;
//}
if (Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "ZIP" ||
Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "XML" ||
Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "XLS" ||
(Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "DAT"
&& Message.Attachments[Count].AttachmentFileName.Substring(0, 2).ToUpper() == "HJ") ||
Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "BIN")
{
if (m_MailTable.Columns.Count <= 0)
{
CreateMailTable();
}
isDeleted = true;
DataRow MailRows = m_MailTable.NewRow();
MailRows["MailID"] = Message.FromEmail;
MailRows["MsgDate"] = Message.ReceivedDate;
MailRows["MsgSubject"] = (null == Message.Subject ? string.Empty : Message.Subject);
MailRows["CreateDateTime"] = DateTime.Now;
//string GwAttachmentName = Message.Attachments[Count].AttachmentFileName;
Message.Attachments[Count].DownloadAttachment();// SaveAsFile(TempPath + Message.Attachments[Count].AttachmentFileName);
MailRows["AttachmentName"] = Message.Attachments[Count].AttachmentFileName;
ConvertBinary ConvertBinary = new ConvertBinary();
MailRows["AttachmentFile"] = ConvertBinary.ConverTOBinaryFile(TempPath + "\\" + Message.Attachments[Count].AttachmentFileName);
ConvertBinary.Dispose();
ConvertBinary = null;
//Marshal.ReleaseComObject(synchGwAttachment);
m_MailTable.Rows.Add(MailRows);
//Log
Common.Synch.Factory.LogHelpFactory.log.Info("Add Mail to MailBox Temp Table -" + Message.Attachments[Count].AttachmentFileName);
}
}
}
}
}
catch (Exception ex)
{
Message = null;
Common.Synch.Factory.LogHelpFactory.log.Info(Message.Subject + ":" + ex.ToString());
}
}
Attachment structure is:
In attachment we are sending bin files of objects and these objects further extracted and saved in database.
Problem:
Some times we are receiving large files, so while extracting service hang and stop processing in between. Could you provide me some suggestions and ideas to overcome this issue.
Please let me know if you need more information, I will try my best to provide.
Thanks in advance.
You are using DataTables.
A DataTable is an in-memory copy of relational data.
So all the data you are going to save have to fit into memory.
If you have a lot of records, big records or both this will not do.
I suggest to:
decompress the file inside a temp folder on local file system
insert into the database one file at a time using a SqlCommand
Use parameters in your INSERT command (ie insert into mytable (col1, col2) values (#col1, # col2))
I have an ASP.net web app that spawns a process (in a thread). This thread calls a '.dll' to connect to another 'subsystem'.
Problem is, when there are errors connecting to the 'subsystem', it affects my main application (main UI) and I get a 'connection refused message'. I have already put in 'try-catch' error handling routines in my thread. FYI, I would like to treat the thread as a 'Fire and forget' thread.
The thread is spawned when btnSubmit is clicked.
Please refer to trimmed-down extract of code.
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
txt_hide.Value = sStatus;
if (sStatus == "")
{
//create thread for posting
id = Guid.NewGuid();
Thread th = new Thread(() => postXMLClass.PostXML(sSeqNo));
th.Start();
sStatus = "Transaction generated..please check posting status..";
lblMessage.Text = "Transaction Generated...";
}
else
{
FormView1.DataBind(); //refresh the form
clib.Show2("Error generating transaction : " + sStatus, sender);
lblMessage.Text = "Error generating transaction : " + sStatus;
}
}
catch (SqlException ex)
{
lblMessage.Text = "Error generating transaction ...: " + ex.Message;
}
catch (Exception ex)
{
//sqc.Transaction.Rollback();
lblMessage.Text = "Error encountered...: " + ex.Message;
throw;
}
finally
{
if (dbc != null) dbc.Dispose();
if (clib != null) clib.Dispose();
}
}
public static void PostXML(string inlinkcode)
{
string sToken = "", sXMLOut = "";
Xml.Router.XMLRouter cX = new Xml.Router.XMLRouter();
try
{
cX.set_Options("com.xml.router.nameServer", appSetArray[0]);
cX.set_Options("com.xml.router.nameServerPort", appSetArray[2]);
cX.set_Options("com.xml.router.logicalServerName", appSetArray[1]);
{
sLinkcode = inlinkcode;
if (sLinkcode != null && sLinkcode != "")
{
strxml = "<?xml version=\"1.0\" encoding='UTF-8' ?>";
strxml += "<TableLinkRequest version=\"1.0\"><DocumentLinkStart><Request><StartParams>";
strxml += "<CmpCode>X</CmpCode><DocCode></DocCode></TableLinkRequest>";
sXMLOut = cX.Send(sToken, strxml);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception {0}", ex.Message);
}
finally
{
if (cX != null) cX.Logoff(sToken);
}
}
I have a RXTX project that I'm working on. I have it set ups as follows:
public void doConnect(ActionEvent event)
{
String selectedPort = (String)connectTabController.portList.getValue();
System.out.println("Connecting to: " + selectedPort);
selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);
CommPort commPort = null;
try
{
commPort = selectedPortIdentifier.open("AT QC ReponseTime", TIMEOUT);
serialPort = (SerialPort)commPort;
setConnected(true);
if (isConnected)
{
if (initIOStream() == true)
{
initListener();
System.out.println("Initializing listener");
connectTabController.gui_changeStatusLabel("Device Connected!");
}
}
}
catch (PortInUseException e)
{
System.out.println("Port In use! " + e.toString());
}
catch (Exception e)
{
System.out.println("Failed to open! " + e.toString());
}
}
public boolean initIOStream()
{
//return value for whether opening the streams is successful or not
boolean successful = false;
try {
//
input = serialPort.getInputStream();
output = serialPort.getOutputStream();
writeData(RESETTPOD);
System.out.println("Writing Reset command");
successful = true;
System.out.println("IO Stream opened successfully!");
return successful;
}
catch (IOException e) {
System.out.println("I/O Streams failed to open. (" + e.toString() + ")");
return successful;
}
}
public void initListener()
{
try
{
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}
catch (TooManyListenersException e)
{
System.out.println("Too many listeners. (" + e.toString() + ")");
}
}
That's how the connection is made, and it has a listener that's supposed to notify when data is available, which triggers the following:
#Override
public void serialEvent(SerialPortEvent evt) {
BufferedReader reader = null;
if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE)
{
try
{
reader = new BufferedReader(new InputStreamReader(input));
if (reader.ready())
{
fullLine = reader.readLine();
System.out.println(fullLine + "\n");
}
}
catch (Exception e)
{
System.out.println("#SerialEvent Failed to read data. (" + e.toString() + ")");
}
}
}
However, I keep getting "UNDERLYING INPUT STREAM RETURNED ZERO BYTES"
This makes no sense, since if there is nothing to read then the listener shouldnt be triggered int he first place. I tried running the app and I keep getting this error message around every 1/3 second, which corresponds to the burst-output of the device that's sending data. (which works fine in programs like PuttY)
If you are going to use the BufferedReader, take a look at the refence API document for javax.comm, CommPort and getInputStream. Then try using different settings for threshold and receive timeout.
eg).
serialPort.enableReceiveThreshold(3);
serialPort.enableReceiveTimeout(1);
https://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/
I have a Java-backed webscript in repo tier that creates files (with given name) in a given folder in Alfresco.
To handle the file name duplication issue I wrote this code:
NodeRef node = null;
try {
node = createNode(fullName, folderNodeRefId);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRefId);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
ContentWriter writer = serviceRegistry.getContentService().getWriter(node, ContentModel.PROP_CONTENT, true);
writer.setMimetype(getFileFormatMimetype(fileFormat));
writer.putContent(inputStream);
writer.guessEncoding();
and
private NodeRef createNode(String filename, String folderNodeRefId)
throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
NodeRef folderNodeRef = new NodeRef(folderNodeRefId);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService()
.createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,
props)
.getChildRef();
}
The codes work very fine if there is no file name duplication (a new name). But it does nothing when there is a duplication, although it executes without any errors! When I test it it doesn't throw any exceptions but no file is created either!
Any hints about the cause of that?
Thanks,
I tested this code , It's working fine
#Test
public void createNode() {
AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER_NAME);
NodeRef node = null;
String fileFormat = "txt";
String filename = "test";
NodeRef folderNodeRef = getCompanyHome();
//Create first node
node = createNode(filename, folderNodeRef);
try {
node = createNode(filename, folderNodeRef);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRef);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
}
private NodeRef getCompanyHome() {
return nodeLocatorService.getNode("companyhome", null, null);
}
private NodeRef createNode(String filename, NodeRef folderNodeRef) throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService().createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,props).getChildRef();
}
I keep getting the following error and I don't know how to fix it. Any help would be great please
Exception Details:NullReferenceException was unhandled by users code: Object reference not set to an instance of an object.
protected void LbUpload_Click(object sender, EventArgs e)
{
ERROR: if(FileUpload.PostedFile.FileName == string.Empty)
{
LabelMsg.Visible = true;
return;
}
else
{
string[] FileExt = FileUpload.FileName.Split('.');
string FileEx = FileExt[FileExt.Length - 1];
if (FileEx.ToLower() == "csv")
{
FileUpload.SaveAs(Server.MapPath("CSVLoad//" + FileUpload.FileName));
}
else
{
LabelMsg.Visible = true;
return;
}
}
CSVReader reader = new CSVReader(FileUpload.PostedFile.InputStream);
string[] headers = reader.GetCSVLine();
DataTable dt = new DataTable();
foreach (string strHeader in headers)
dt.Columns.Add(strHeader);
string[] data;
while ((data = reader.GetCSVLine()) != null)
dt.Rows.Add(data);
GridView1.DataSource = dt;
GridView1.DataBind();
if (FileUpload.HasFile)
try
{
FileUpload.SaveAs(Server.MapPath("confirm//") +
FileUpload.FileName);
LabelGrid.Text = "File name: " +
FileUpload.PostedFile.FileName + "<br>" +
FileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
FileUpload.PostedFile.ContentType + "<br><b>Uploaded Successfully";
}
catch (Exception ex)
{
LabelGrid.Text = "ERROR: " + ex.Message.ToString();
}
else
{
LabelGrid.Text = "You have not specified a file.";
}
File.Delete(Server.MapPath("confirm//" + FileUpload.FileName));
}
You are checking if the FileName is string.Empty, it sounds like you want to detect when the user clicked the button without selecting a file.
If that happens, the actual PostedFile property will be null (remember, the user didn't posted a file), you should use the FileUpload.HasFile property for that purpose:
protected void LbUpload_Click(object sender, EventArgs e)
{
if(FileUpload.HasFile)
{
LabelMsg.Visible = true;
return;
}
// ...
}
But I would recommend you also to add a RequiredFieldValidator.
More on validation:
Validating ASP.NET Server Controls
ASP.NET Validation in Depth
Are you sure that FileUpload and FileUpload.PostedFile is not null?
Either FileUpload or its PostedFile property must be null.