How to download and extract large files from email using window service - asp.net

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))

Related

Fixing a Zip Path Traversal Vulnerability in Android app in Google Play Store

The question has been asked (and answered) but I have not been able to get it to work in my code.
This is the support document:
https://support.google.com/faqs/answer/9294009
I have tried to use the answer from here:
Fixing a Zip Path Traversal Vulnerability In Android
My original code:
public void copyFiles() {
try {
String roms_dir = mm.getMainHelper().getInstallationDIR();
File fm = new File(roms_dir + File.separator + "saves/"
+ "dont-delete-" + getVersion() + ".bin");
if (fm.exists())
return;
fm.mkdirs();
fm.createNewFile();
// Create a ZipInputStream to read the zip file
BufferedOutputStream dest = null;
InputStream fis = mm.getResources().openRawResource(R.raw.files);
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(fis));
// Loop over all of the entries in the zip file
int count;
byte data[] = new byte[BUFFER_SIZE];
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (!entry.isDirectory()) {
String destination = roms_dir;
String destFN = destination + File.separator
+ entry.getName();
// Write the file to the file system
FileOutputStream fos = new FileOutputStream(destFN);
dest = new BufferedOutputStream(fos, BUFFER_SIZE);
while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} else {
File f = new File(roms_dir + File.separator
+ entry.getName());
f.mkdirs();
}
}
zis.close();
String dir = this.getInstallationDIR();
if(!dir.endsWith("/"))dir+="/";
String rompath = mm.getPrefsHelper().getROMsDIR() != null && mm.getPrefsHelper().getROMsDIR()!="" ? mm
.getPrefsHelper().getROMsDIR() : dir + "roms";
mm.getDialogHelper()
.setInfoMsg(
"Created or updated: '"
+ dir
+ "' to store save states, cfg files and MAME assets.\n\nBeware, copy or move your zipped ROMs under '"
+ rompath
+ "' directory!\n\nMAME4droid 0.139 uses only 0.139 MAME romset.");
mm.showDialog(DialogHelper.DIALOG_INFO);
} catch (Exception e) {
e.printStackTrace();
}
}
I have tried this:
public void copyFiles() {
try {
String roms_dir = mm.getMainHelper().getInstallationDIR();
File fm = new File(roms_dir + File.separator + "saves/"
+ "dont-delete-" + getVersion() + ".bin");
if (fm.exists())
return;
fm.mkdirs();
fm.createNewFile();
// Create a ZipInputStream to read the zip file
BufferedOutputStream dest = null;
InputStream fis = mm.getResources().openRawResource(R.raw.files);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
// Loop over all of the entries in the zip file
int count;
byte data[] = new byte[BUFFER_SIZE];
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
// Create an outputFile object and check that the path is safe with ensureZipPathSafety
//*
String outputDir = "";
File outputFile = new File(outputDir, entry.getName());
String outputFileName = outputFile.getCanonicalPath();
System.out.println(outputFileName);
try {
ensureZipPathSafety(outputFile, outputDir);
} catch (Exception e) {
e.printStackTrace();
return;
}
//*/
if (!entry.isDirectory()) {
System.out.println("We get past !entry.isDirectory check");
String destination = roms_dir;
String destFN = destination + File.separator
+ entry.getName();
// Write the file to the file system
FileOutputStream fos = new FileOutputStream(destFN);
dest = new BufferedOutputStream(fos, BUFFER_SIZE);
while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} else {
File f = new File(roms_dir + File.separator
+ entry.getName());
f.mkdirs();
}
}
zis.close();
String dir = this.getInstallationDIR();
if(!dir.endsWith("/"))dir+="/";
String rompath = mm.getPrefsHelper().getROMsDIR() != null && mm.getPrefsHelper().getROMsDIR()!="" ? mm
.getPrefsHelper().getROMsDIR() : dir + "roms";
mm.getDialogHelper()
.setInfoMsg(
"Created or updated: '"
+ dir
+ "' to store save states, cfg files and MAME assets.\n\nBeware, copy or move your zipped ROMs under '"
+ rompath
+ "' directory!\n\nMAME4droid 0.139 uses only 0.139 MAME romset.");
mm.showDialog(DialogHelper.DIALOG_INFO);
} catch (Exception e) {
e.printStackTrace();
}
}
private void ensureZipPathSafety(final File outputFile, final String destDirectory) throws Exception {
String destDirCanonicalPath = (new File(destDirectory)).getCanonicalPath();
String outputFilecanonicalPath = outputFile.getCanonicalPath();
String outputFileCanonicalPath = "";
if (!outputFileCanonicalPath.startsWith(destDirCanonicalPath)) {
Object canonicalPath = null;
throw new Exception(String.format("Found Zip Path Traversal Vulnerability with %s", canonicalPath));
}
}

How can i append a pdf into another? Alfresco

How can i append a pdf into another?
I tried using this code, but I am getting java.lang.NullPointerException when i try to getContentInputStream.
what am I doing wrong? How can I attach one pdf to another?
PDDocument pdfTarget = null;
InputStream is = null;
InputStream tis = null;
for (ChildAssociationRef file: quotationsFiles) {
try {
NodeRef toAppend = file.getChildRef(); //workspace://SpacesStore/11bce382-45bf-4c67-95bc-a65361b323ef
ContentReader append = getReader(toAppend);
is = append.getContentInputStream(); // Here iam getting java.lang.NullPointerException
NodeRef targetNodeRef = reportFile.getNodeRef();
ContentReader targetReader = getReader(targetNodeRef);
tis = targetReader.getContentInputStream();
String fileName = String.valueOf(serviceRegistry.getNodeService().getProperty(targetNodeRef, ContentModel.PROP_NAME));
// stream the document in
pdf = PDDocument.load(is);
pdfTarget = PDDocument.load(tis);
// Append the PDFs
PDFMergerUtility merger = new PDFMergerUtility();
merger.appendDocument(pdfTarget, pdf);
merger.setDestinationFileName(fileName);
merger.mergeDocuments();
} catch (Exception e) {
//throw new AlfrescoRuntimeException("IOException", e);
ColorLogUtil.debug(LOGGER, "IOException Error caused by :" + e);
}
}
private ContentReader getReader(NodeRef nodeRef) {
if (serviceRegistry.getNodeService().exists(nodeRef) == false) {
throw new AlfrescoRuntimeException("NodeRef: " + nodeRef + " does not exist");
}
QName typeQName = serviceRegistry.getNodeService().getType(nodeRef);
if (serviceRegistry.getDictionaryService().isSubClass(typeQName, ContentModel.TYPE_CONTENT) == false) {
throw new AlfrescoRuntimeException("The selected node is not a content node");
}
ContentReader contentReader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
if (contentReader == null) {
throw new AlfrescoRuntimeException("The content reader for NodeRef: " + nodeRef + "is null");
}
return contentReader;
}
See if this code works for you:
public NodeRef mergePdfs(List<NodeRef> nodeRefList, String fileName,NodeRef destinationNode)
throws FileNotFoundException,FileExistsException,Exception {
InputStream originalInputStream = null;
ContentReader reader = null;
NodeRef newDocNoderef = null;
PDFMergerUtility PDFmerger = new PDFMergerUtility();
ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
try {
LOGGER.debug("Merging of Doc Started");
for (NodeRef node : nodeRefList) {
reader = contentService.getReader(node, ContentModel.PROP_CONTENT);
originalInputStream = reader.getContentInputStream();
PDFmerger.addSource(originalInputStream);
}
PDFmerger.setDestinationStream(outputstream);
PDFmerger.mergeDocuments();
if(originalInputStream!=null) {
originalInputStream.close();
}
newDocNoderef = writeContentToAlfresco(outputstream, nodeRefList, fileName,destinationNode);
LOGGER.debug("Documents are merged and new pdf is created at "+newDocNoderef);
} finally {
if(outputstream!=null)
outputstream.close();
}
return newDocNoderef;
}
public NodeRef writeContentToAlfresco(ByteArrayOutputStream outputstream, List<NodeRef> childRefList,
String fileName,NodeRef destinationNode) throws FileExistsException,IOException,Exception {
NodeRef pdf = null;
Map<QName, Serializable> props = new HashMap<>();
Map<Date, NodeRef> dateMap = new HashMap<Date, NodeRef>();
NodeRef parentNodeRef=null;
try {
LOGGER.debug("Upload to Alfresco Started");
for(NodeRef noderef : childRefList) {
Date date = (Date) nodeService.getProperty(noderef, ContentModel.PROP_MODIFIED);
dateMap.put(date, noderef);
}
Map<Date, NodeRef> m1 = new TreeMap<Date, NodeRef>(dateMap);
Map.Entry<Date, NodeRef> entry = m1.entrySet().iterator().next();
NodeRef finalnodeRef = entry.getValue();
if(destinationNode!=null) {
parentNodeRef = destinationNode;
}else {
parentNodeRef = nodeService.getPrimaryParent(finalnodeRef).getParentRef();
}
QName[] myModelProps = CommonConstants.myModelProps;
for (QName myModelProp : myModelProps) {
Serializable object = nodeService.getProperty(finalnodeRef, myModelProp);
props.put(myModelProp, object);
}
FileInfo pdfInfo = fileFolderService.create(parentNodeRef, fileName + ".pdf",
MyModel.TYPE_CUSTOM_MYMODEL_TYPE);
pdf = pdfInfo.getNodeRef();
nodeService.setProperties(pdf,props);
nodeService.setProperty(pdf, ContentModel.PROP_TITLE,
nodeService.getProperty(finalnodeRef, ContentModel.PROP_TITLE));
nodeService.setProperty(pdf, ContentModel.PROP_DESCRIPTION,
nodeService.getProperty(finalnodeRef, ContentModel.PROP_DESCRIPTION));
nodeService.setProperty(pdf,ContentModel.PROP_NAME,fileName + ".pdf");
ContentWriter writer = contentService.getWriter(pdf, ContentModel.PROP_CONTENT, true);
writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
writer.setEncoding("UTF-8");
writer.putContent(new ByteArrayInputStream(outputstream.toByteArray()));
LOGGER.debug("Upload to Alfresco Ended");
} catch(FileExistsException fee) {
ExceptionUtils.printRootCauseStackTrace(fee);
throw new FileExistsException(parentNodeRef, fileName);
}
catch (Exception e) {
ExceptionUtils.printRootCauseStackTrace(e);
throw new Exception(e);
} finally {
if (outputstream != null)
outputstream.close();
}
return pdf;
}
This actually seems like one of the features we support in alfresco-pdf-toolkit out of the box. You could either use that addon, or get some inspiration from the code backing it.

Stored procedure executing even with the error message

I'm working with two stored procedures in an ASP.NET button function. While I get an error message based on the results that the invoice number is already dispatched from the other stored procedure, it still moves to the other stored procedure and executes it.
If the user gets this error message:
This invoice num was already dispatched!
then it shouldn't move on to this aspect of the function
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
//CheckBox chk = (CheckBox)GridView2.Rows[i].Cells[0].FindControl("CheckBox3");
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
myReader.Close();
}
}
else if (invoice1=="1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
**int a = cmd.ExecuteNonQuery();**
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
//Button2.Visible = false;
//showData();
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
You have a very, very simple logic error, but it is incredibly hard to see because your code is such a mess. Therefore, my answer is:
REFACTOR REFACTOR REFACTOR
It is important to get into the habit of writing short functions and controlling their inputs and outputs. If you don't do this, even a fairly trivial operation like this one gets very confusing and error-prone.
Here is an example of how to organize things. We remove most of the code from the click handler:
protected void DeleteButton_Click(object sender, EventArgs e)
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
if (IsChecked(row))
{
var result = ProcessRow(row, i);
DisplayResult(i, result);
}
}
}
Firstly, notice it has a meaningful name. These become very important as your application grows. Also, look how short it is! Where did all the code go? Well, it went into two separate methods, which are now short enough for us to view on one page-- a common requirement that IT organizations impose on their programmers, to avoid spaghetti code.
protected TransactionResult ProcessRow(GridViewRow row, int index)
{
var SID = GridView2.Rows[index].Cells[3].Text.Trim();
var custPONum = GridView2.Rows[index].Cells[4].Text.Trim();
var loadSheetNum = txtDispatchNum.Text;
var removeUser = lblUsername.Text.Replace("Welcome", "");
return ExecuteInvoiceTransaction(SID, custPONum, loadSheetNum, removeUser);
}
And
public void DisplayResult(int rowIndex, TransactionResult result)
{
switch result
{
case TransactionResult.Success:
dt.Rows.RemoveAt(rowIndex);
DisplayTotals(rowIndex);
DisplaySuccess("Selected record(s) successfully updated");
break;
case TransactionResult.AlreadyDispatched;
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
break;
case TransactionResult.RecordNotRecorded;
DisplayError("Record has not yet been recorded");
break;
case TransactionResult.AlreadyRemoved:
DisplayError("This invoice number was remove from dispatch sheet before!!");
break;
}
}
These methods in turn call a variety of helper methods, each of which does one thing and one thing only. This could be referred to as separation of concerns, which is really important for structured code.
Here's the rest of the methods:
enum TransactionResult
{
Success,
AlreadyDispatched,
RecordNotRecorded,
AlreadyRemoved
}
private bool ExecuteSelectStatus(SqlConnection connection, SqlTransaction transaction, string invoiceNum, string custPONum)
{
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", invoiceNum);
command.Parameters.AddWithValue("#custPONum", custPONum);
using (var myReader = command.ExecuteReader())
{
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
return false;
}
}
}
return true;
}
}
private int ExecuteRemoveInvoice(SqlConnection objConnection, SqlTransaction transaction, string loadSheetNum, string invoiceNum, string removeUser)
{
try
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", loadSheetNum);
cmd.Parameters.AddWithValue("#invoiceNum", invoiceNum);
cmd.Parameters.AddWithValue("#removeUser", removeUser);
return cmd.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
if (ex.Number == 2627) //Primary key violation
{
return -1;
}
}
}
protected TransactionResult ExecuteInvoiceTransaction(string invoiceNum, string custPONum, string loadSheetNum, string removeUser)
{
var strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
var ok = ExecuteSelectStatus(objConnection, transaction, invoiceNum, custPONum);
if (!ok) return TransactionResult.AlreadyDispatched;
var a = ExecuteRemoveInvoice(objConnection, transaction, loadSheetNum, invoiceNum, removeUser);
switch a
{
case -1:
return TransactionResult.AlreadyRemoved;
case 0:
return TransactionResult.RecordNotRecorded;
default:
transaction.Commit();
return TransactionResult.Success;
}
}
}
}
public void DisplayTotals(int i)
{
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text;
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
}
public void DisplaySuccess(string message)
{
lblError.ForeColor = Color.Green;
lblError.Text = message;
}
public void DisplayError(string message)
{
lblError.ForeColor = Color.Red;
lblError.Text = message;
}
A few things to note:
You don't need to call Dispose() if you are using using.
You should always catch the most specific exception possible, per Microsoft's guidance. My example does this.
The exception handling for the primary key error is isolated into the method that calls the stored procedure. The overall business logic shouldn't have to know details about the SQL implementation. I've shown how you can identify the specific error based on this post.
Because there are four possible outcomes, I added an enumeration called TransactionResult so we could return the status to the caller easily.
Some of these methods are short-- just two lines-- and that is OK. The main reason to separate them out is to give them a meaningful name and make the code shorter and easier to read.
This code is much more structured but it could still be improved! In many implementations, the code that accesses the database is actually moved to a completely different layer or project.
See if this works. Moved your if/else together:
protected void Button2_Click(object sender, EventArgs e)
{
try
{
for (int i = GridView2.Rows.Count - 1; i >= 0; i--)
{
var row = GridView2.Rows[i];
CheckBox chk = row.FindControl("chkInvoice") as CheckBox;
if (chk != null && chk.Checked)
{
string strSQLconstring = System.Configuration.ConfigurationManager.ConnectionStrings["TWCL_OPERATIONSConnectionString"].ToString();
using (SqlConnection objConnection = new SqlConnection(strSQLconstring))
{
objConnection.Open();
using (SqlTransaction transaction = objConnection.BeginTransaction())
{
string SID = GridView2.Rows[i].Cells[3].Text.Trim();
SqlDataReader myReader = null;
using (SqlCommand command = new SqlCommand("PP_SelectStatus", objConnection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#invoiceNum", SID);
command.Parameters.AddWithValue("#custPONum", GridView2.Rows[i].Cells[4].Text.Trim());
myReader = command.ExecuteReader();
if (myReader.Read())
{
string invoice1 = (myReader["status"].ToString());
if (invoice1 == "0")
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('This invoice num was already dispatched!')", true);
}
else if (invoice1 == "1")
{
using (SqlCommand cmd = new SqlCommand("PP_RemoveInvoice", objConnection, transaction))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#loadSheetNum", txtDispatchNum.Text);
cmd.Parameters.AddWithValue("#invoiceNum", SID);
cmd.Parameters.AddWithValue("#removeUser", lblUsername.Text.Replace("Welcome", ""));
int a = cmd.ExecuteNonQuery();
cmd.Dispose();
if (a > 0)
{
dt.Rows.RemoveAt(i);
////Read invoice qty from grid view 2
string invoice = GridView2.Rows[i].Cells[5].Text.ToString();
decimal invoiceTotal = Convert.ToDecimal(txtInvoiceTotal.Text) - Convert.ToDecimal(invoice);
txtInvoiceTotal.Text = invoiceTotal.ToString();
////Read invoice weight from grid view 2
string weight = GridView2.Rows[i].Cells[6].Text.ToString();
decimal invoiceWeight = Convert.ToDecimal(txtQtyWeight.Text) - Convert.ToDecimal(weight);
txtQtyWeight.Text = invoiceWeight.ToString();
lblError.ForeColor = Color.Green;
lblError.Text = "Selected record(s) successfully updated";
}
else
{
lblError.ForeColor = Color.Red;
lblError.Text = " Record has not yet been recorded";
}
}
//objConnection.Close();
transaction.Commit();
}
}
}
GridView2.DataSource = dt;
GridView2.DataBind();
txtInvoiceCount.Text = dt.Rows.Count.ToString();
}
}
}
}
}
catch (Exception ex)
{
if (ex.Message.StartsWith("Violation of PRIMARY KEY constraint"))
{
lblError.ForeColor = Color.Red;
lblError.Text = " This invoice number was remove from dispatch sheet before!!";
}
else
{
// re-throw the error if you haven't handled it
lblError.Text = ex.Message;
throw;
}
}
}
}

asp.net upload control is not working in ipad

The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?

blackberry HttpConnection.GET

URL: http://monSite/GET.asp
we must authenticate before getting the result.
I want to send the login and password with HttpConn.setRequestMethod (HttpConnection.POST) and retrieve the XML file with HttpConn.setRequestMethod (HttpConnection.GET) with the same HTTP Client.
conn = (HttpConnection) new ConnectionFactory().getConnection(_url).getConnection();
URLEncodedPostData postData = null;
postData = new URLEncodedPostData("UTF-8", false);
postData.append("userName",_username);
postData.append("passWord", _password);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LANGUAGE, "en-US");
conn.setRequestProperty(HttpProtocolConstants.HEADER_CACHE_CONTROL,"no-cache, no-store, no-transform");
// Specify the content type.
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, postData.getContentType());
byte [] postBytes = postData.getBytes();
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, Integer.toString(postBytes.length));
os = conn.openOutputStream();
os.write(postBytes);
os.flush();
os.close();
//GET XML file
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
int total = 0;
int size = 1024;
char[] buffer = new char[size];
int len;
InputStreamReader isr = new InputStreamReader(conn.openInputStream(), "UTF-8");
while ((len = isr.read(buffer, 0, size)) > 0)
{
buff.append(buffer, 0, len);
total += len;
}
result = buff.toString();
} else {
result = "Error in connection" + conn.getResponseCode();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
the HttpConnection.POST works very well but GET no (login failed: the authentication parameter does not saved)
In HttpConnection.GET request you need to append attribute in your url like:
String url="http://www.xyz?userName="+_username+"&password="+_password+"";
and then get the InputStream
below link may be helpful for you
http://supportforums.blackberry.com/t5/Java-Development/Make-an-HTTP-Connection-to-get-a-Content-of-URL/td-p/95075

Resources