Why my code can't locate the data table? - c#

I have this code below to generate a report. My problem is why one of the content of my data table can't locate by my code? The ds.dt_ProposedSeminars is the table.
public JsonResult ReportProposal(int year)
{
string Userkey = "gHeOai6bFzWskyUxX2ivq4+pJ7ALwbzwF55dZvy/23BrHAfvDVj7mg ";
string PassKey = "lLAHwegN8zdS7mIZyZZj+EmzlkUXkvEYxLvgAYjuBVtU8sw6wKXy2g ";
JsonResult result = new JsonResult();
MemoryStream oStream;
PCSO_ProposedSeminars rpt = new PCSO_ProposedSeminars();
dsPCSO_TrainingProgram ds = new dsPCSO_TrainingProgram();
//-----------------------------------------------------
var seminars = db.Certificates
.Where(x => x.Year.Value.Year == year && !x.IsApproved.HasValue)
.Select(z => z).Distinct();
foreach (var train in seminars)
{
string trainingProgram = train.CertificateName;
string resourcePerson = train.ResourceSpeaker;
string target = "";
var classifications = db.CertificateTrainingClassifications.Where(a => a.CertificateId == train.CertificateId).Select(b=>b.TrainingClassification.Classification);
int x = 1;
foreach (var classification in classifications)
{
if (classifications.Count() > 1)
{
if (x == 1) target += classification;
else target += ", " + classification;
}
else target += classification;
x++;
}
if (train.TargetParticipants.HasValue)
{
target += "/" + train.TargetParticipants.Value + ((train.TargetParticipants != null) ? " pax" : "");
}
if (train.IsPerBatch.Value)
{
target += "/batch";
}
string duration = train.Duration.Value + " days";
decimal estimatedExpenses = new decimal();
estimatedExpenses = train.EstimatedExpenses.Value;
ds.dt_ProposedSeminars.Adddt_ProposedSeminarsRow(
trainingProgram,
resourcePerson,
target,
duration,
estimatedExpenses);
}
DataTable dtable = new DataTable();
dtable = ds.dt_ProposedSeminars;
rpt.SetDataSource(dtable);
rpt.Refresh();
rpt.SetParameterValue(0, year);
rpt.SetParameterValue(1, "");
rpt.SetParameterValue(2, "Head, Training Unit, Admin Department");
oStream = (MemoryStream)rpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
string filename = Convert.ToString((DateTime.Now.Month) + Convert.ToString(DateTime.Now.Day) + Convert.ToString(DateTime.Now.Year) + Convert.ToString(DateTime.Now.Hour) + Convert.ToString(DateTime.Now.Minute) + Convert.ToString(DateTime.Now.Second) + Convert.ToString(DateTime.Now.Millisecond)) + "RequestApplication";
var len = oStream.Length;
FileTransferServiceClient client2 = new FileTransferServiceClient();
RemoteFileInfo rmi = new RemoteFileInfo();
DateTime dt = DateTime.Now;
DownloadRequest dr = new DownloadRequest();
string fId = client2.UploadFileGetId("", filename, len, PassKey, Userkey, oStream);
result.Data = new
{
fileId = fId,
filename = filename
};
rpt.Close();
rpt.Dispose();
oStream.Close();
oStream.Dispose();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}
Here is the screenshot:
Here is the error.
'PIMS_Reports.TrainingProgram.dsPCSO_TrainingProgram' does not contain a definition for 'dt_ProposedSeminars' and no extension method 'dt_ProposedSeminars' accepting a first arguement of type
'PIMS_Reports.TrainingProgram.dsPCSO_TrainingProgram' could not be found (are you missing a using directive assembly reference?)

The error message states that your dsPCSO_TrainingProgram class does not contain a method or property named dt_PropsedSeminars.
What does that class look like?

Related

In web Api 2 RDLC report controller why can't i return to FILE?

what i am trying to do is to generate a PDF/Excel report in mvc web API 2 and view in a new tab in a browser.
My error says 'Non-invocable member 'File' cannot be used like a method'.
did i miss a namespace or a assembly?
any help is much appreciated.
Here is My code:
'''
public IHttpActionResult TestReport()
{
var fromDate = "01/01/2000";
var toDate = DateTime.Now.ToShortDateString();
var id = "PDF";
var result = new ApiResult();
var lr = new LocalReport();
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Reports"), "Test.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
result.Status = ApiResult.ApiStatus.Error;
result.Message = "Report Error";
return Ok(result);
}
if (fromDate == "" && toDate == "")
{
fromDate = "01/01/2000";
toDate = DateTime.Now.ToShortDateString();
}
var from = Convert.ToDateTime(fromDate);
var to = Convert.ToDateTime(toDate);
var Staffs = db.Staffs.Where(s =>
DbFunctions.TruncateTime(s.EffectiveDate) >= from.Date
&& DbFunctions.TruncateTime(s.EffectiveDate) <= to.Date && s.IsActive == true).OrderByDescending(s => s.Id)
.ToList();
var Staffs = db.Staffs.Where(s => s.empId == "10001").OrderByDescending(s => s.Id).ToList();
var Items = Staffs.Select(item => new DepViewModel
{
empId = item.empId,
Name = item.Name,
IdCard = item.IdCard,
})
.ToList();
var param0 = new ReportParameter("fromdate", from.ToShortDateString());
var param1 = new ReportParameter("todate", to.ToShortDateString());
lr.SetParameters(new ReportParameter[] { param0, param1 });
var ds = new ReportDataSource("DepDataSet1", Items.OrderByDescending(a => a.Id));
lr.DataSources.Add(ds);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>11in</PageWidth>" +
" <PageHeight>8.5in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
} '''
FileContentResult is MVC Action Result. You don't File (FileContentResult) in WebAPI.
Please modify your last return statement(return File(renderedBytes, mimeType)) as follows:
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(renderedBytes)
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType); //"application/pdf"
var input = $"inline; filename={fileNameExtension}"; //where fileNameExtension something with file name and extension for e.g., myfilename.txt
ContentDispositionHeaderValue contentDisposition;
if (ContentDispositionHeaderValue.TryParse(input, out contentDisposition))
{
result.Content.Headers.ContentDisposition = contentDisposition;
}
return this.ResponseMessage(result);

unable to read PDF controls in c#

Am tryinng to read PDf and inside PDF controls. my pdf is generated by adobe pdf library. getting null acro fields.but my form have 4 check boxes. 4 check boxed i can use to check or uncheck . i want checkbox is checked or not.
i used itextsharp to read pdf but, it is not finding controls.
private static string GetFormFieldNamesWithValues(PdfReader pdfReader)
{
return string.Join("\r\n", pdfReader.AcroFields.Fields
.Select(x => x.Key + "=" +
pdfReader.AcroFields.GetField(x.Key) + "=" + pdfReader.AcroFields.GetFieldType(x.Key)).ToArray());
}
static void Main(string[] args)
{
DataTable filedDetails;
DataRow dr;
string cName="";
string cType = "";
string cValue = "";
int txtCount = 0;
int btnCount = 0;
int chkBoxCount = 0;
int rdButtonCount = 0;
int dropDownCount = 0;
var fileName = "C:\\PreScreenings\\ViewPDF Cien.pdf";// PDFFileName.Get(context);
//var fileName = #"C:\Users\465sanv\Downloads\Read-PDF-Controls-master\ReadPDFControl\Input\David1990.pdf";
var fields = GetFormFieldNamesWithValues(new PdfReader(fileName));
string[] splitRows = fields.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
filedDetails = new DataTable("PDF Table");
filedDetails.Columns.AddRange(new[] { new DataColumn("Control Name"), new DataColumn("Control Type"), new DataColumn("Control Value") });
foreach (string row in splitRows)
{
dr = filedDetails.NewRow();
string[] str = row.Split("=".ToCharArray(), StringSplitOptions.None);
cName = str[0].ToString();
cValue = str[1].ToString();
if (str[2].ToString() == "1")
{
btnCount++;
cType = "Button" + btnCount.ToString();
}
else if (str[2].ToString() == "2")
{
chkBoxCount++;
cType = "Check Box" + chkBoxCount.ToString();
}
else if (str[2].ToString() == "3")
{
rdButtonCount++;
cType = "Radio Button" + rdButtonCount.ToString();
}
else if (str[2].ToString() == "4")
{
txtCount++;
cType = "Text Field" + txtCount.ToString();
}
else if (str[2].ToString() == "6")
{
dropDownCount++;
cType = "Drop Down" + dropDownCount.ToString();
}
dr[0] = cName;
dr[1] = cType;
dr[2] = cValue;
filedDetails.Rows.Add(dr);
}
}

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

LinQtoExcel using asp fileupload

im having problems with this function. so basically a user will upload an excel file .xls (2003 version) then once the import button is clicked it will read the excel file and import it into the sql database.
here is my code
protected void btnImport_Click(object sender, EventArgs e)
{
Business.Student student = new Business.Student();
int errorCount = 0;
int successCount = 0;
string successTotal;
int missinglastname = 0;
int missingfirstname = 0;
int missingmiddlename = 0;
if (filebiometrics.HasFile == false)
{
}
else
{
string pathToExcelFile = filebiometrics.FileName;
var excelFile = new ExcelQueryFactory(pathToExcelFile);
IEnumerable<string> worksheetnames = excelFile.GetWorksheetNames();
string worksheetName = excelFile.GetWorksheetNames().ToArray()[0];
var import = from a in excelFile.Worksheet<Business.Student.StudentList>(worksheetName) select a;
//var emptyfield = excelFile.Worksheet<Business.Employees.EmployeeImport>().Where(x => x.Surname != null).ToList();
excelFile.AddMapping<Business.Student.StudentList>(x => x.studentnumber, "Student Number");
excelFile.AddMapping<Business.Student.StudentList>(x => x.firstname, "Firstname");
excelFile.AddMapping<Business.Student.StudentList>(x => x.lastname, "Lastname");
excelFile.AddMapping<Business.Student.StudentList>(x => x.middlename, "Middlename");
string missing = "Missing!";
foreach (var a in import)
{
if (a.studentnumber == 0)
{
}
if (a.lastname == null)
{
a.lastname = missing;
missinglastname = missinglastname + 1;
}
if (a.firstname == "")
{
a.firstname = missing;
missingfirstname = missingfirstname + 1;
}
if (a.middlename == null)
{
missingmiddlename = missingmiddlename + 1;
}
else if (student.CheckExistingStudentNumber(a.studentnumber))
{
errorCount = errorCount + 1;
}
else
{
student.Create(a.studentnumber, a.firstname, a.lastname, a.middlename);
successCount = successCount + 1;
successTotal = "Total imported record: " + successCount.ToString();
}
}
txtLog.InnerText = "Total duplicate record: " + errorCount.ToString() +
Environment.NewLine +
"Total missing data on Firstname column: " + missingfirstname.ToString() +
Environment.NewLine +
"Total missing data on Lastname column: " + missinglastname.ToString() +
Environment.NewLine +
"Total missing data on middlename column: " + missingmiddlename.ToString() +
Environment.NewLine +
Environment.NewLine +
"Total imported record: " + successCount.ToString();
filebiometrics.Attributes.Clear();
}
}
im always getting this error
the error is in this line 'IEnumerable worksheetnames = excelFile.GetWorksheetNames();'
can somebody help me with this?
Your error message is self explanatory. Error is at this line:-
var excelFile = new ExcelQueryFactory(pathToExcelFile);
ExcelQueryFactory expects the full file path but you are just passing the excel file name using string pathToExcelFile = filebiometrics.FileName; and obviously it is not able to read the file.
You need to read the excel file which user is uploading and save it to the server and then read it like this:-
string filename = Path.GetFileName(filebiometrics.FileName);
filebiometrics.SaveAs(Server.MapPath("~/") + filename);
var excelFile = new ExcelQueryFactory(Server.MapPath("~/") + filename);

set multiple parameter in recursive c#

when I make 2 parameters. when the cursor on highlight ahref not getting value, as the first parameter? but always get the value of its parent.
What should I do with my code below:
please help correct the errors / shortcomings of my code.
private string LoadNavigasi(string kodeJabatan, ref int countLoop)
{
if (kodeJabatan == null)
kodeJabatan = "001";
DataSet ds = RunQuery("Select KodePosition,NamaPosition,Parent from Position where KodePosition = '" + kodeJabatan + "'");
string temp = string.Empty;
string tempP = string.Empty;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
var kode = ds.Tables[0].Rows[i][0].ToString();
var nama = ds.Tables[0].Rows[i][1].ToString();
var parent = ds.Tables[0].Rows[i][2].ToString();
if (parent == "")
parent = null;
temp = string.Format("{0}", nama);
tempP = string.Empty;
countLoop++;
if (parent != null)
{
tempP = string.Format("{0}", LoadNavigasi(parent, ref countLoop));
temp = string.Format("{1}<ul><li>{0}", temp, tempP);
}
else
{
temp = string.Format("{0}", temp);
}
return temp;
}
return temp;
}
I'm not sure if it helps but I simplify your code to what it's actually doing.
private string LoadNavigasi(string kodeJabatan)
{
if (kodeJabatan == null)
kodeJabatan = "001";
DataSet ds = RunQuery("Select KodePosition,NamaPosition,Parent from Position where KodePosition = '" + kodeJabatan + "'");
var kode = ds.Tables[0].Rows[0][0].ToString();
var nama = ds.Tables[0].Rows[0][1].ToString();
var parent = ds.Tables[0].Rows[0][2].ToString();
string temp = string.Format("<a href=?Kode={0}&Name={1}>{1}</a>", kode, nama);
if (string.IsNullOrEmpty(parent))
{
string tempP = LoadNavigasi(parent);
temp = string.Format("{1}<ul><li>{0}", temp, tempP);
}
return temp;
}
You mention something about your second parameter in the line
temp = string.Format("{0}", nama);
The second parameter is nama but I don't understand what's wrong with it.

Categories