Alert message not popping up though the dynamic textbox is empty - asp.net

Below is the code how I am creating the dynamic textboxes. I want to validate if any of the dynamic textboxes created are empty and if yes, should throw an error message or alert to user prompting to fill up the textboxes on Additem button click. I get the alert message entered into the function, after which I don't receive any message alerting the user to fill in the textbox "xxxx".
Please help me to fix the code
if (ControlType == "TextBox")
{
int textBoxLength;
TextBox MynewTextBox = new TextBox();
MynewTextBox.ID = "txt" + Fldname;
MynewTextBox.Width = 100;
MynewTextBox.BorderStyle = BorderStyle.Solid;
MynewTextBox.Attributes.Add("Type", "T");
MynewTextBox.Attributes.Add("IsKeyField", "Y");
MynewTextBox.Attributes.Add("IsMandatory", "Y");
}
protected void Page_Load(object sender, EventArgs e)
{
btnAddItem.Attributes.Add("onClick", "if(!ValidateMandatoryFields()) return false;");
}
<script language="javascript" type="text/javascript">
function ValidateMandatoryFields() {
alert("entered into the function");
var inputControls = document.getElementsByTagName("input");
alert(inputControls.length);
for (var i = 0; i < inputControls.length; i++) {
if (inputControls[i].getAttribute("IsKeyField") == "Y") {
if (inputControls[i].getAttribute("Type") == "T" || (inputControls[i].getAttribute("Type") == "C")) {
if (inputControls[i].getAttribute("IsMandatory") == "Y") {
if (inputControls[i].value == "") {
alert(inputControls[i].getAttribute("KeyField_Name") + "is required.");
errorMsg += "\n" + inputControls[i].getAttribute("KeyField_Name") + " is required.";
isValidated = false;
}
}
}
}
}
}
}
</script>
enter link description here
i followed the link above
It still did not help me
function ValidateMandatoryFields() {
alert("entered into the function");
var inputControls = document.getElementsByTagName("input");
alert(inputControls.length);
for (var i = 0; i < inputControls.length; i++) {
if (inputControls[i].getAttribute("IsKeyField") == "Y") {
alert(inputControls[i]);
}
else {
alert("first if statemenet");
}
if (inputControls[i].getAttribute("Type") == "T" || (inputControls[i].getAttribute("Type") == "C")) {
alert(inputControls[i]);
}
else {
alert("second if statement");
}
if (inputControls[i].getAttribute("IsMandatory") == "Y") {
alert(inputControls[i]);
}
else {
alert("third if statement");
}
if (inputControls[i].value == "") {
alert(inputControls[i].getAttribute("KeyField_Name") + "is required.");--error here
errorMsg += "\n" + inputControls[i].getAttribute("KeyField_Name") + " is required.";
isValidated = false;
}
else {
alert("name: " + inputControls[i].id);
alert("length: " + inputControls[i].value.length());
alert("value: " + inputControls[i].value);
}
}
}
It pop ups of all else statements appear and finally i get a error stating Microsoft JScript runtime error: Object expected. Which means that none of my if condition is true...How do I get it to work...please help me with the correct logic

Try adding an else clause to see what the values are:
if (inputControls[i].value == "") {
... your code
} else
{
alert("name: " + inputControls[i].id);
alert("length: " + inputControls[i].value.length());
alert("value: " + inputControls[i].value);
}
It's possible they are set to null or spaces instead of just an empty string.

I was able to fix my code as shown below:
function validateInput() {
var arrTextBox = document.getElementsByTagName("input");
var retValue = 1;
var returnValue = 1;
for (i = 0; i < arrTextBox.length; i++) {
if (arrTextBox[i].type =="text" && arrTextBox[i].getAttribute("IsMandatory")=="Y" && arrTextBox[i].value == "") {
retValue = 0;
}
}
if (retValue == 0) {
alert("Validation Failed");
return false;
}
else {
alert("Validation Success");
return true;
}
on the ascx.cs file
btnAddItem.Attributes.Add("onclick", "{return validateInput()};");

Related

How to download and extract large files from email using window service

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

Retrieving images from Database into ArrayList and Displaying it one by one from ArrayList in ASP.NET

using following code i store images into ArrayList.
public ArrayList getImagesToArray(string qry)
{
ArrayList arr;
if (myConn.State == System.Data.ConnectionState.Closed)
myConn.Open();
if (myDR != null)
myDR.Close();
myComm = new SqlCommand(qry, myConn);
using (myComm)
{
arr = new ArrayList();
myDR = myComm.ExecuteReader();
while (myDR.Read())
{
arr.Add((byte[])myDR[0]);
}
return arr;
}
}
Now i retreive images to an ArrayList using Following Code
ArrayList arrImgs_Main = Q.getImagesToArray("Select FieldImg from InfoTagQA I INNER JOIN PensionScannedDocs P on p.ScanImageID=i.ScanImageID Where P.PersonalNumber='" + hid_PersonalNo.Value + "'");
Now I display image one by one from arrayList to ImageUrl by clicking Next and Previous button
protected void lnk_BackImage_Click(object sender, EventArgs e)
{
try
{
if (arrImgs_Main.Count > 0)
{
if (i > 0)
{
i--;
img_mainImage.ImageUrl = "data:image;base64," + Convert.ToBase64String((byte[])arrImgs_Main[i]);
lab_TotalRecords.Text = "(" + (i + 1) + "/" + arrImgs_Main.Count + ")";
if (i == 0)
{
lnk_ForwardImage.Visible = true;
lnk_BackImage.Visible = false;
}
}
}
}
catch(Exception ee)
{
ShowErrorMsg(ee.Message);
}
}
**All above code works fine and quick on my local machine, but after deployment on server , it take much time in displaying image one by one from array.
Am i doing doing right in above code or going on wrong way. Please guide me **

DataTable Retrieves another DataTable Information?

I Have an Exception in my Live Application..DataTable Retrives another DataTable information..
if (HttpContext.Current.User != null)
{
if (Session["username"] != null)
{
string pageName = Page.Page.AppRelativeVirtualPath.Substring(Page.Page.AppRelativeVirtualPath.LastIndexOf('/') + 1);
DataTable dtFeatures2 = new DataTable();
dtFeatures2.Clear();
objMatermenuPL.usertype = Session["UserType"].ToString();
dtFeatures2 = objMastermenuBAL.GetMastermenu(objMatermenuPL);
DataView dt = new DataView(dtFeatures2);
dt.Sort = "fld_feature ASC";
if (dtFeatures2 != null)
{
foreach (Control control in leftpanel.Controls)
{
Type ty = control.GetType();
if (ty.Name.ToUpper() == "HTMLANCHOR")
{
int i = dt.Find(control.ID.Substring(3));
if (i < 0 && control.ID.Contains("lnk"))
control.Visible = false;
if (control.ID.Contains("lnk") && control.ID.Substring(3) + ".aspx" == pageName)
{
HtmlAnchor a = (HtmlAnchor)control;
a.Attributes.Add("class", "active");
}
}
}
}
}
}
else
{
Response.Redirect("~/Login.aspx");
}
This code we use All most all master pages...If an exception Raise,then it comes directly
this line..
dtFeatures2 = objMastermenuBAL.GetMastermenu(objMatermenuPL);
Message like : Cannot find column fld_feature.
"dtFeatures2" is Filled With Before Opened Page DataTable Information...
This exception gone after some..It's Working Fine 100%....Some times only shows these exception...What happend Here........

GridView sorting: SortDirection

I have a problem with ASP gridview sorting. I have a mistake, but I can't find it...grid always sort one direction.
string _ordering_fieldname
{
get { return ViewState["column"] == null ? "adr" : (string)ViewState["column"]; }
set { ViewState["column"] = value; }
}
string _ordering_direction
{
get { return ViewState["direction"] == null ? "asc" : (string)ViewState["direction"]; }
set { ViewState["direction"] = value; }
}
protected void Spisok_Sorting(object sender, GridViewSortEventArgs e)
{
_OrderingField ordering = new _OrderingField(e.SortExpression);
switch (e.SortDirection)
{
case SortDirection.Ascending: ordering.orderingDirection = OrderingDirection.Ascending; _ordering_direction = "asc"; break;
case SortDirection.Descending: ordering.orderingDirection = OrderingDirection.Descending; _ordering_direction = "desc"; break;
default: ordering.orderingDirection = OrderingDirection.Ascending; _ordering_direction = "asc"; break;
}
_ordering_fieldname = ordering.fieldName;
//here I call refreshing my grid with sorting
}
of course you need to use your _ordering_fieldname & _ordering_direction values
//here I call refreshing my grid with sorting
var dt = GetFromDatabaseFunction();
var dv = dt.DefaultView();
dv.Sort = _ordering_fieldname + " " + _ordering_direction;
GridView1.DataSource = dv.ToTable();
GridView1.DataBind();

asp.net button click event not working with firefox

Following is the code that i am using. It work in IE but the button click event is not generated properly in firefox:
function trapEnter(btn,hdn, event) {
var key;
var isIE = true;
debugger;
if (window.event) {
key = window.event.keyCode; //IE
isIE = true;
}
else {
key = event.which; //firefox
isIE = false;
}
if (key == 13) {
var btn = document.getElementById(btn);
if (btn != null) { //If we find the button click it
document.getElementById(hdn).value = '1'
btn.click();
key = 0;
}
}
}
I think your function has the wrong parameters. Try this:
function trapEnter(e) {
e = e || window.event || event;
var code = e.charCode || e.keyCode || e.which;
if (code == 13) {
var btn = document.getElementById('<%= YourButtonID.ClientID %>');
if (btn != null) { //If we find the button click it
document.getElementById(hdn).value = '1';
btn.click();
key = 0;
}
}
}

Resources