set multiple parameter in recursive c# - 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.

Related

How can tell the difference between the link and the footnote using C# ITextSharp?

I have a simple PDF file that has the Link and the Footnote on a page. When I run the annotation check using iTextSharp, both of the links return the sub type as Link. Is there a way to tell the difference between those two items?
I did examine through an intellisence the structure of an annotation dictionary and notice the annotation object dictionary for the Footnote has once extra item, which is named "F", and that item has a value of 4. That item is NOT present at all in the annotation dictionary for the Link. Can I use the 'F' item/parameter as a way to tell the difference between the Link and the Footnote?
Thank you very much in advance
Here is the PDF file
Here is our code
public string AnyPDFCheckComments(string inFileName, string strUsername, string strFilename)
{
string strCommentType = string.Empty;
string strWidgetFound = string.Empty;
string strPageNumber = string.Empty;
string message = string.Empty;
string strComments = string.Empty;
string strCommentsFound = string.Empty;
int intCommentCount = 0;
PdfReader reader = new PdfReader(inFileName);
for (int i = 1; i <= reader.NumberOfPages; ++i)
{
strPageNumber = i.ToString();
PdfDictionary pagedic = reader.GetPageN(i);
PdfArray annotarray = (PdfArray)PdfReader.GetPdfObject(pagedic.Get(PdfName.ANNOTS));
if (annotarray == null || annotarray.Size == 0)
{
continue;
}
// Finding out the links
foreach (object annot in annotarray.ArrayList)
{
PdfDictionary annotationDic = null;
if (annot is PdfIndirectReference)
{
annotationDic = (PdfDictionary)PdfReader.GetPdfObject((PdfIndirectReference)annot);
}
else
{
annotationDic = (PdfDictionary) annot;
}
PdfName subType = (PdfName)annotationDic.Get(PdfName.SUBTYPE);
if ((subType.Equals(PdfName.TEXT)) && (strCommentsVariables.IndexOf("text") != -1))
{
strCommentType = "text";
//break;
}
else if ((subType.Equals(PdfName.LINK)) && (strCommentsVariables.IndexOf("Link") != -1))
{
strCommentType = "Link";
//break;
}
if ((strCommentType != ""))
{
strCommentsFound = "Yes";
intCommentCount = ++intCommentCount;
strComments = strComments + "<BR>" + "A comment type of '" + "<b>" + strCommentType + "</b>" + "' has been found on page no: " + "<b>" + strPageNumber + "</b>";
if (intCommentCount == 5)
{
break;
}
else
{
strCommentType = string.Empty;
}
}
}
}
return strComments;
}
This code worked for us
var footnoteIdentifier = annotationDic.Get(PdfName.F);
if (footnoteIdentifier != null)
{
continue;
}

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

How to do unit test on a method that has StreamReader and Database access

I have never done unit tests before. I'd like to learn how to do it. I'd like to use Visual Studio unit test and moq.
My project is transferring data from interbase to SQL Server. Firstly, I extract data from interbase into a plain text file. The layout is FieldName + some spaces up to 32 char length + field value. Then, I write a method that reads the text file line by line; once it reaches the next record, it inserts the current record into SQL Server.
So it involves in stream reader and SQL database insertion. For the stream reader, I read some post on the Internet and I pass the Stream reader as the method's parameter; but the SQL Server part, I have no idea how to simplify my method so that it can be tested.
I really need your help.
public partial class TableTransfer
{
#region declare vars
public string FirstFldName = "";
public string ErrorMsg = "";
public List<MemoBlobTrio> MemoBlobs = null;
public string SqlServerTableName = "";
#endregion
public bool DoTransfer(System.IO.StreamReader sr, Func<TransferShare, string, string, bool> TransferTable)
{
#region declare var
bool DoInsert = true;
TransferShare transferShare = null;
string line = string.Empty;
string blobLines = string.Empty;
string fldName = string.Empty;
string value = string.Empty;
bool Is1stLine = true;
bool isMemoFld = false;
MemoBlobTrio memoBlobTrio = null;
int idx = 0;
#endregion
try
{
using(sr)
{
transferShare = new TransferShare();
ConnectSQLServer(transferShare);
transferShare.StartInsert(SqlServerTableName);
bool readNext = true;
do
{
try
{
if (readNext)
line = sr.ReadLine();
if ((line != null) && (line.Trim() != ""))
{
fldName = line.Length > 30 ? line.Substring(0, 31).TrimEnd() : "";
Is1stLine = fldName == FirstFldName;
if (Is1stLine)
{
if (DoInsert)
EndInsert(transferShare, line);
else
transferShare.ClearSQL();
DoInsert = true;
}
idx = 0;
isMemoFld = false;
while (idx < MemoBlobs.Count)
{
if (fldName == (MemoBlobs[idx] as MemoBlobTrio).fbFldName)
{
memoBlobTrio = MemoBlobs[idx] as MemoBlobTrio;
line = InsertMemoBlob(transferShare, sr, memoBlobTrio.ssFldName, fldName, memoBlobTrio.fbNextFldName);
readNext = false;
isMemoFld = true;
}
idx++;
}
if (!isMemoFld)
{
if (line.Length > 31)
value = line.Remove(0, 31);
else
value = "";
if (!TransferTable(transferShare, fldName, value))
DoInsert = false;
readNext = true;
}
}
}
catch (Exception err)
{
HandleError(err, line);
}
} while (line != null);
if (DoInsert)
EndInsert(transferShare, line);
}
}
finally
{
transferShare.SQLConn.Dispose();
}
return true;
}
private static void ConnectSQLServer(TransferShare transferShare)
{
TransferShare.SQLServerConnStr = "Data Source=" + Environment.MachineName + "\\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True";
transferShare.SQLConn.ConnectionString = TransferShare.SQLServerConnStr;
transferShare.SQLConn.Open();
}
}
public class TransferShare
{
public void StartInsert(string TableName)
{
tableName = TableName;
}
public void EndInsert(TransferShare transferShare, string line)
{
SqlCommand Cmd = null;
try
{
sqlInsFld = sqlInsFld.Remove(sqlInsFld.Length - 1);
sqlInsValue = sqlInsValue.Remove(sqlInsValue.Length - 1);
sqlInsFld = "Insert into " + tableName + " (" + sqlInsFld + ")";
sqlInsValue = " Values (" + sqlInsValue + ")";
Cmd = new SqlCommand(sqlInsFld + sqlInsValue, SQLConn);
Cmd.ExecuteNonQuery();
}
catch (Exception err)
{
throw (new Exception(err.Message));
}
finally
{
sqlInsFld = "";
sqlInsValue = "";
}
}
}

Why my code can't locate the data table?

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?

I need to rebind in Grid-view after every record completed in for loop process?

I try to import the records from csv and binding into grid.Then every records process for other details. In this case I need to update the UI after every record completed.
WebscrapeSettings objweb = new WebscrapeSettings();
var dtcontact = GetDataTableFromCsv(#"D:\\(1-5) DEN.csv", true);
if (dtcontact.Rows.Count > 0)
{
string starttime = DateTime.Now.ToString();
for (int ic = 0; ic < dtcontact.Rows.Count; ic++)
{
objweb.SearchType = "Company Linked In";
objweb.ContactName = dtcontact.Rows[ic]["Contact"].ToString();
objweb.Location = dtcontact.Rows[ic]["LinkedInLocation"].ToString();
objweb.Title = dtcontact.Rows[ic]["Title"].ToString();
objweb.SearchString = "";
objweb.EmailDomain = "";
objweb.Company = dtcontact.Rows[ic]["Company"].ToString();
string result = "";
var t = WebScrape(objweb);
if (t.Count > 0)
{
foreach (var pair in t)
{
divnormal.InnerHtml = ic + "-" + Thread.CurrentThread.ManagedThreadId + "-" + "<br/> <br/> <br/>" + divnormal.InnerHtml;// +"<br/> <br/> <br/>" + pair.Value;
}
}
//I want to rebind the Grid Here
BindImportfileDetails();
BindImportrecordsdetails(ImportFileID);
}
string endtime = DateTime.Now.ToString();

Categories