Looping through arrays in asp.net is not working - c#

I have an array which sometimes holds values like "ABC, XYZ, TTT" and sometime only "ABC"
So while iterating through the arrays when it holds multiple it checks only for the first item and not the other item.
string[] strStateArray = new string[] { "" };
strStateArray = strOne.Split(',');
for (int i = 0; i < strStateArray.Length; i++)
{
if (dt.Rows[0]["CIRCLE"].ToString() == strStateArray[i].ToString()) // not checking for multiple items
{
}
}
updated code
for (int i = 0; i < strStateArray.Length; i++)
{
if (dt.Rows[0]["CIRCLE"].ToString() == strStateArray[i].Trim().ToString())
{
if (dt.Rows.Count > 0)
{
dt.TableName = "RecodSet";
string xml = ConvertDatatableToXML(dt);
mycon.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('File uploaded successfully.!!');", true);
// System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('File uploaded successfully.!!');", true);
}
else
{
string noData = "No data to upload.";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", noData, false);
}
}
else
{
string file_name = fluUploadBtn.FileName;
if ((System.IO.File.Exists(file_name)))
{
System.IO.File.Delete(file_name);
}
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('User is not authorised to upload data for state mentioned in excel report ');", true);
}
}

Could you just go debug the value then?
let me rewrite some code for you
String logMsg ="";
String targetKeyword = dt.Rows[0]["CIRCLE"].ToString();
for (int i = 0; i < strStateArray.Length; i++)
{
String tmp_Val_Pure = strStateArray[i] ==null? null : strStateArray[i].ToString(); //debug here see the value1
String tmp_Val = strStateArray[i] ==null? "" : strStateArray[i].ToString().Trim(); //debug here see the value2
bool isThisOk = (targetKeyword == tmp_Val ); //debug here see the val of isThisOk
if ( isThisOk )
{
logMsg += "Success Record : "+ i.ToString() + " val : " + tmp_Val ;
if (dt.Rows.Count > 0)
{ // alert case OK
} else { // alert no val dt }
}
else
{
logMsg += "Err Record : "+ i.ToString() + " val : " + tmp_Val ;
}
} //end loop
//Go check logMsg

Related

While statement for downloading URL strings

I would like to ask, How I can use the While statement for downloading URL?
Here's what I want to happen.
I want to check if the url from CheckBoxListItems is already exist from my ListView
There's a case that I'm adding another urls to my listbox and I don't want to download again.
if url is already exists in my listview it will skip and proceed to the next url(which is not yet downloaded).
Here's my current codes:
int count = 0;
int total = LB.CheckedItems.Count;
string counter = string.Empty;
using (cts = new CancellationTokenSource())
{
try
{
if (cts.IsCancellationRequested) { throw new TaskCanceledException(); }
txtOutput.Text = string.Empty;
Cursor = Cursors.WaitCursor;
Parsing = true;
Text = "Getting links information. Please wait...";
foreach (string url in LB.CheckedItems)
{
var info = await Task.Run(() => Parser.GetJsonData(url, cts.Token));
count++;
counter = "( " + count + " of " + total + " )";
lblTotalLinks.Text = counter;
Text = "Parsing in progress. Please wait... " + counter;
AddToListView(info); //ADD DOWNLOADED STRINGS TO LISTVIEW
}
Text = "Parsing done. " + counter;
}
catch (OperationCanceledException ex)
{ Text = ex.Message; }
catch (Exception ex)
{ MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
Parsing = false;
Cursor = Cursors.Default;
cts = null;
//ADD TO LISTVIEW()
private void AddToListView(MediaInfo info)
{
int count = LV.Items.Count + 1;
var results = new List<ListViewItem> { new ListViewItem(new[]
{
count.ToString(),
info.Series,
"Episode " + info.Episode,
info.Title,
info.Runtime,
info.Resolution,
info.Category,
info.URL, //here's what I want to check if already exists
info.M3u8_url,
info.FileSize,
info.Fragments
})};
ListViewItem[] array = results.ToArray();
LV.BeginUpdate();
LV.ListViewItemSorter = null;
LV.Items.AddRange(array);
LV.Focus();
LV.EndUpdate();
Countlists();
LV.Items[LV.Items.Count - 1].EnsureVisible();
}
this is the example of what I want:
string urlExists = string.Empty;
foreach (ListViewItem item in LV.Items)
{
urlExists = item.SubItems[7].Text;
foreach (string url in LB.CheckedItems)
{
while (url != urlExists)
{
}
}

How to cancel uploading?

I have 2 methods. 1 - is validation and 2 - is uploading if validation; how to cancel uploading?
1 - CheckValidationByMEAS_TYPE(lotInfo.LotDataTable, MEAS_TYPE, lotInfo);
int skipRows = 0;
foreach (DataRow item in lotTable.Rows)
{
string filename = Convert.ToString(item["Filename"]);
if (filename == string.Empty || filename == "NA")
{
continue;
}
String[] data = filename.Split('_');
string measType = Convert.ToString(data[2]);
bool rowIsNA = true;
for (int j = 1; j <= 11; j++) // From I to S in AVG WorkSheet
{
string paramValue = Convert.ToString(item[7 + j]);
if (rowIsNA == true && paramValue != "NA")
{
rowIsNA = false;
}
}
if (rowIsNA && (MEAS_TYPE.ToUpper() == measType.ToUpper() || MEAS_TYPE.ToUpper() == "ALL"))
{
skipRows++;
}
}
string message = string.Empty;
string errMsg = string.Empty;
if (skipRows > 1)
{
MessageBox.Show("Measure different rowbar or adjacent slider. " + skipRows + " sliders have no data in MATLAB", "AFM Host Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
2 - public static bool SendData(LotInfo lotInfo, List<string> submitMessage)
string message = string.Empty;
string errMsg = string.Empty;
DataTable MQDataTable;
try
{
//this is method 1 CheckValidationByMEAS_TYPE(lotInfo.LotDataTable, MEAS_TYPE, lotInfo);
}
catch (Exception exception)
{
message = "Job: " + lotInfo.SubmissionID + " FAILED to convert data for MQ submission.";
submitMessage.Add(exception.Message);
Globals.Logger.Error(exception.Message);
return false;
}
try
{
foreach (DataRow row in MQDataTable.Rows)
{
PDBAXLib.PdbClass PDB = new PDBAXLib.PdbClass();
PDB.init(AppConfig.GetString("MQConfiguration", "MQ_ADDRESS"), "1", AppConfig.GetString("MQConfiguration", "MQ_Connection_File"));
while (PDB.reupload()) ;
PDB.format("Detail");
foreach (DataColumn col in MQDataTable.Columns)
{
if (!string.IsNullOrEmpty(row[col].ToString()))
PDB.field(col.ColumnName, row[col].ToString());
else if (row[col].ToString().Equals(" "))
PDB.field(col.ColumnName, row[col].ToString());
}
PDB.formatEnd("Detail");
PDB.transmit(null);
}
MessageBox.Show("Job " + lotInfo.SubmissionID + " uploaded successfully.", "AFM SA Host", MessageBoxButtons.OK, MessageBoxIcon.Information);
message = "Job " + lotInfo.SubmissionID + " - Data uploaded successfully. " + DateTime.Now;
submitMessage.Add(message);
}
catch (Exception exception)
{
message = "Job " + lotInfo.SubmissionID + " FAILED to upload data.";
submitMessage.Add(message);
submitMessage.Add(exception.Message);
Globals.Logger.Error(exception.Message);
}
return true;
This is my problem,
if (skiprows > 1) prompt message will appear and upload the data.
I want if (skiprows > 1) prompt message and will not upload.
Thank you.
This is just one way
bool CheckValidationByMEAS_TYPE(....)
{
. . . .
if (skipRows > 1)
{
MessageBox.Show(....);
return false;
}
}
. . . . . . . .
try
{
if (!CheckValidationByMEAS_TYPE(lotInfo.LotDataTable, MEAS_TYPE, lotInfo)
return;
}
catch (Exception exception)
{
. . . . .
}

Gridvew Looping for multiple times even when selected least records in asp.net

I have a gridview in which every row contains a checkbox for selection. That selection will be used for Approve or Reject purpose.
But issue here is If I select 2 rows from the gridview it loops atleast 4-5 times and gives me multiple emails of the same row.
Below is my code. Please suggest.
protected void btnApproveCMM_Click(object sender, EventArgs e)
{
string strDate = "";
string strMailContent = "";
DataTable dtApprove = new DataTable();
CommonDB ObjDB = new CommonDB();
try
{
bool flgCMM = false;
IPColoFields ObjIPColoFields = new App_Code.IPColoFields();
List<IPColoBilling_BKP.App_Code.UMS.UMSGroupDetails> UMSGroupDetails = (List<IPColoBilling_BKP.App_Code.UMS.UMSGroupDetails>)Session["lstUMSGroupDetails"];
Session["lstUMSGroupDetails"] = UMSGroupDetails;
string strApprove = "";
if (ViewState["CheckedCheckboxes_CMM"] != null)
{
foreach (GridViewRow row in grdDisplayCMMData.Rows)
{
if (((CheckBox)row.FindControl("chkApprRejCMM")).Checked)
{
Label SAPID_CMM = (Label)row.FindControl("lblSAP_ID_CMM");
Label ID = (Label)row.FindControl("lblID_CMM");
int Id = Convert.ToInt32(ID.Text);
ObjIPColoFields.Unique_Id = Id;
ObjIPColoFields.UMS_GRP_BY_ID = intCurrentGrpId;
ObjIPColoFields.UMS_GRP_BY_NAME = strCurrentGrp;
ObjIPColoFields.UMS_GRP_TO_ID = UMSGroupDetails[1].GroupID;
ObjIPColoFields.UMS_GRP_TO_NAME = UMSGroupDetails[1].GroupName;
ObjIPColoFields.FCA_STATUS = "1";
ObjIPColoFields.LAST_UPDATED_BY = lblUserName.Text;
strDate = DateTime.Now.ToString();
strApprove = CommonDB.Approve_IPCOLO_CMMLevel(ObjIPColoFields);
if (ObjIPColoFields.Unique_Id != null || ObjIPColoFields.Unique_Id != 0)
{
strMailContent = Get_Email_Content(ObjIPColoFields.LAST_UPDATED_BY, SAPID_CMM.Text, strIPCOLO_CMM, Convert.ToString(Id), strDate, "Approved");
SendEmail(lblUserName.Text, strMailContent, strIPCOLO_CMM);
}
}
}
}
BindCMMData();
if (flgCMM == false)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Please check atleast one row'); window.location ='IpColoDefault.aspx';", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Record Approved successfully'); window.location ='IpColoDefault.aspx';", true);
}
}
catch (Exception ex)
{
string strErrorMsg = ex.Message.ToString() + " " + "StackTrace :" + ex.StackTrace.ToString();
CommonDB.WriteLog("ERROR:" + strErrorMsg, ConfigurationManager.AppSettings["IPCOLO_LOG"].ToString());
}
}
Use this code
foreach (GridViewRow row in grdDisplayCMMData.Rows)
{
if (((Checkbox)row.FindControl("chkApprRejCMM")).Checked)
{
Label SAPID_CMM = (Label)row.FindControl("lblSAP_ID_CMM");
ObjIPColoFields.Unique_Id = Id;
ObjIPColoFields.UMS_GRP_BY_ID = intCurrentGrpId;
ObjIPColoFields.UMS_GRP_BY_NAME = strCurrentGrp;
ObjIPColoFields.UMS_GRP_TO_ID = UMSGroupDetails[1].GroupID;
ObjIPColoFields.UMS_GRP_TO_NAME = UMSGroupDetails[1].GroupName;
ObjIPColoFields.FCA_STATUS = "1";
ObjIPColoFields.LAST_UPDATED_BY = lblUserName.Text;
strDate = DateTime.Now.ToString();
strApprove = CommonDB.Approve_IPCOLO_CMMLevel(ObjIPColoFields);
if (ObjIPColoFields.Unique_Id != null || ObjIPColoFields.Unique_Id != 0)
{
strMailContent = Get_Email_Content(ObjIPColoFields.LAST_UPDATED_BY, SAPID_CMM.Text, strIPCOLO_CMM, Convert.ToString(Id), strDate, "Approved");
SendEmail(lblUserName.Text, strMailContent, strIPCOLO_CMM);
}
}
}

Uploading a file to folder

With the code below I am able to save files to folder.
My problem is only two upload fields are mandatory and the remaining three are not. The code works if all the upload fields have a files selected otherswise its throws a NullReferenceException.
if (AnnualReport != null || ProjectReports != null || Publications != null || Other != null || RegistDoc != null) {
int filesize = AnnualReport.PostedFile.ContentLength;
int filesizeP = ProjectReports.PostedFile.ContentLength;
int filesizePub = Publications.PostedFile.ContentLength;
int filesizeOther = Other.PostedFile.ContentLength;
int filesizeReg = RegistDoc.PostedFile.ContentLength;
if (filesize > 2097152 && filesizeP > 2097152 && filesizePub > 1048576 && filesizeOther > 1048576 && filesizeReg > 1048576) {
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Annual/Project reports is 1.5MB and for the Publications/Other Attachemnets is 1MB');", true);
} else {
const string ReportDirectory = "REPORTS/";
//Other Document
string OtherPath = ReportDirectory + Other.FileName;
string fileNameWithoutExtensionOther = System.IO.Path.GetFileNameWithoutExtension(Other.FileName);
int iterationOther = 1;
while (System.IO.File.Exists(Server.MapPath(OtherPath))) {
OtherPath = string.Concat(ReportDirectory, fileNameWithoutExtensionOther, "-", iterationOther, ".pdf");
iterationOther++;
}
//Registration Document
string RigisDocPath = ReportDirectory + RegistDoc.FileName;
string fileNameWithoutExtensionRegis = System.IO.Path.GetFileNameWithoutExtension(RegistDoc.FileName);
int iterationRE = 1;
while (System.IO.File.Exists(Server.MapPath(RigisDocPath))) {
RigisDocPath = string.Concat(ReportDirectory, fileNameWithoutExtensionRegis, "-", iterationRE, ".pdf");
iterationRE++;
}
//Annual Reports
string ReportPath = ReportDirectory + AnnualReport.FileName;
string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(AnnualReport.FileName);
int iteration = 1;
while (System.IO.File.Exists(Server.MapPath(ReportPath))) {
ReportPath = string.Concat(ReportDirectory, fileNameWithoutExtension, "-", iteration, ".pdf");
iteration++;
}
//Project Report
string ProjecttPath = ReportDirectory + ProjectReports.FileName;
string fileNameWithoutExtensionP = System.IO.Path.GetFileNameWithoutExtension(ProjectReports.FileName);
int iterationP = 1;
while (System.IO.File.Exists(Server.MapPath(ProjecttPath))) {
ProjecttPath = string.Concat(ReportDirectory, fileNameWithoutExtensionP, "-", iterationP, ".pdf");
iterationP++;
}
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iterationPub = 1;
while (System.IO.File.Exists(Server.MapPath(publicationPath))) {
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iterationPub, ".pdf");
iterationPub++;
}
ProjectReports.SaveAs(Server.MapPath(ProjecttPath));
AnnualReport.SaveAs(Server.MapPath(ReportPath));
Publications.SaveAs(Server.MapPath(publicationPath));
RegistDoc.SaveAs(Server.MapPath(RigisDocPath));
Other.SaveAs(Server.MapPath(OtherPath));
The code you posted is very poorly formated. However, the solution to your immediate problem is to move the null checks down to each individual document.
Instead of doing a huge if line (which has questionable logic, as it only checks if ANY of the documents were uploaded)
You can just check if the required documents are present. (looking at your exising code, present means document name object is not null)
If not, throw an error.
If they are, then proceed with the rest of the code, but wrap the individual processing of optional documents in their own null check if-s.
ie.
if (AnnualReport != null) {
//the block that does stuff with the anual report object
}
I did beak down the code into diferent methods like #irreal suggested, like below;
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else
{
int filesizeP = Publications.PostedFile.ContentLength;
if (filesizeP > 2097152)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximum File size For Publication is 2.0 MB');", true);
}
else
{
const string ReportDirectory = "REPORTS/";
//publication
string publicationPath = ReportDirectory + Publications.FileName;
string fileNameWithoutExtensionPub = System.IO.Path.GetFileNameWithoutExtension(Publications.FileName);
int iteration = 1; while (System.IO.File.Exists(Server.MapPath(publicationPath)))
{
publicationPath = string.Concat(ReportDirectory, fileNameWithoutExtensionPub, "-", iteration, ".pdf");
iteration++;
}
Publications.SaveAs(Server.MapPath(publicationPath));
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='" + publicationPath + "' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
}
}
I then called it o the click event
try{
PublicationReporting();
}
catch (Exception ex)
{
pgError.Text = "Publication Exception Message: " + ex.Message;
}
finally
{
csoW_connection.Close();
}
From here it was pretty easy to figure out the problem.
I just needed to dispose the content in the upload field if no file was selected like this
public void PublicationReporting() {
//connection for the datareader
string csoWConn = ConfigurationManager.ConnectionStrings["RegisterCon"].ToString();
SqlConnection csoW_connection = new SqlConnection(csoWConn);
string database = csoW_connection.DataSource.ToString();
csoW_connection.Open();
if (Publications == null)
{
Publications.Dispose();
////
String MyString = #"UPDATE tb_Quadrennial_Report SET PublicationsPath='' WHERE Org_ID = '" + Accrediated_Orgs.SelectedValue + "'";
SqlCommand MyCmd = new SqlCommand(MyString, csoW_connection);
int LastInsertedRecordID;
LastInsertedRecordID = Convert.ToInt32(MyCmd.ExecuteScalar());
}
else{
//program continues}

How to show a message from webmethod?

Friends,I need a help regarding showing error message or any other message in web method. I tried with writing some function to show message if the return value is "0" or the return string variable's length is "0" but no result. Can you give some solution to this?
Yes, sure. Here is my code:-
[WebMethod]
public string[] GetCompletionCompany(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
if (prefixText != "")
{
strSQLQuery = "SELECT ID," +
" stallno," +
" company " +
"FROM IESS2012_IND_PartDetails " +
"WHERE company LIKE '%" + prefixText + "%' " +
"ORDER BY company";
}
DataTable dt = objDBHelper.gReturnDataSet(System.Data.CommandType.Text, strSQLQuery).Tables[0];
List<string> items = new List<string>(count);
for (int i = 0; i < dt.Rows.Count; i++)
{
string strName = dt.Rows[i][2].ToString();
items.Add(strName);
}
if (items.ToArray().Length == 0)
{
ShowMessage();
return items.ToArray();
}
else
{
return items.ToArray();
}
}
private void ShowMessage()
{
string msg= gUserMessage.NoRecords;
return msg;
}
How will I show the message that there is no record?
If you want to show the Error Message on Client Side you can just throw an appropriate Exception - SOAP will encapsulate it and you get a SOAP-Error on the client side containing the exception message.
So on the Server side:
if (items.ToArray().Length == 0)
{
throw new NoRecordsException("Your Message...");
}
and on the client side (assuming you are using C# too):
string[] result;
try
{
result = service.GetCompletionCompany(prefixText, count);
}
catch(SoapException exp)
{
string message = exp.Message; //or exp.InnerException.Message
}

Categories

Resources