object reference not to set an instance of an object - asp.net

in the detail view , i have the user control and i like fill the propeties of that with
foreach (var file in fileList.Efiles)
but i have the error "object reference not to set an instance of an object" for (fileList.Efiles)
please help what is the problem
the complete code is like below:
public partial class DocResult : System.Web.UI.Page
{
private EDMSDataContext _DataContext;
private int _TransmittalId;
private int _DocId;
protected void Page_Load(object sender, EventArgs e)
{
String tmpString1;
String tmpString2;
tmpString1 = Request.QueryString["DocId"];
if (String.IsNullOrEmpty(tmpString1))
throw new ArgumentNullException("DocId");
_DocId = Convert.ToInt32(tmpString1);
tmpString2 = Request.QueryString["TransID"];
if (String.IsNullOrEmpty(tmpString2))
throw new ArgumentNullException("TransID");
_TransmittalId = Convert.ToInt32(tmpString2);
_DataContext = new EDMSDataContext();
var query = _DataContext.spDocResult(_DocId, _TransmittalId);
DetailsView1.DataSource = query.ToList();
DetailsView1.DataBind();
spDocResultResult docresult = (spDocResultResult)DetailsView1.DataItem;
FileTemp fileList = (FileTemp)DetailsView1.FindControl("FileTemp1");
foreach (var file in fileList.Efiles)
{
file.FileName = docresult.Filename;
}
fileList.DataBind();
}
}

Try below code
if(fileList!=null)
{
foreach (var file in fileList.Efiles)
{
file.FileName = docresult.Filename;
}
fileList.DataBind();
}

Related

mail merge with dynamic file path

I had a problem generating a word template because I wanted it to be selected dynamically with ddlTemplate when selected to write in it with the merge field in the word template.
this is my code:
public partial class unTemplate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)// call the method for ONLY first time for visitor
{
{
populateDdlInstitution();
}
}
}
protected void populateDdlInstitution()
{
CRUD myCrud = new CRUD();
string mySql = #"select institutionid, institution from institution";
SqlDataReader dr = myCrud.getDrPassSql(mySql);
ddlInstitution.DataTextField = "institution";
ddlInstitution.DataValueField = "institutionid";
ddlInstitution.DataSource = dr;
ddlInstitution.DataBind();
}
protected void ddlInstitution_SelectedIndexChanged(object sender, EventArgs e)
{
// call a method to populate the template ddl
populateDdlTemplate();
}
protected void populateDdlTemplate()
{
CRUD myCrud = new CRUD();
string mySql = #"select internDocId, DocName
from internDoc
where institutionId = #institutionId";
Dictionary<string, object> myPara = new Dictionary<string, object>();
myPara.Add("#institutionId", ddlInstitution.SelectedItem.Value);
SqlDataReader dr = myCrud.getDrPassSql(mySql, myPara);
ddlTemplate.DataTextField = "DocName";
ddlTemplate.DataValueField = "internDocId";
ddlTemplate.DataSource = dr;
ddlTemplate.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
CRUD myCrud = new CRUD();
string mySql = #"select* from intern
where institutionId = #institutionId"/*+#"select internDocId,DocName from internDoc where internDocId=internDocId"*/;
Dictionary<string, object> myPara = new Dictionary<string, object>();
myPara.Add("#institutionId", ddlInstitution.SelectedItem.Value);
//myPara.AsEnumerable(#"internDocId");
SqlDataReader dr = myCrud.getDrPassSql(mySql, myPara);
gvData.DataSource = dr;
gvData.DataBind();
}
protected void btnGenerateTemplate_Click(object sender, EventArgs e)
{
wordT();
}
private static DataTable GetRecipients()
{
//Creates new DataTable instance.
DataTable table = new DataTable();
//Loads the database.
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + #"../../CustomerDetails.mdb");
//Opens the database connection.
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from intern", conn);
//Gets the data from the database.
adapter.Fill(table);
//Releases the memory occupied by database connection.
adapter.Dispose();
conn.Close();
return table;
}
public void wordT()
{
for (int i = 0; i <= gvData.Rows.Count - 1; i++)
{
String internId = gvData.Rows[i].Cells[0].Text;
String fullName = gvData.Rows[i].Cells[7].Text;
String cell = gvData.Rows[i].Cells[8].Text;
String email = gvData.Rows[i].Cells[9].Text;
Syncfusion.DocIO.DLS.WordDocument document = new Syncfusion.DocIO.DLS.WordDocument(Server.MapPath(getPath()));
//Deleting null fields
document.MailMerge.RemoveEmptyParagraphs = true;
string[] fieldNames = new string[] { "fullName", "internId", "email", "cell" };
string[] fieldValues = new string[] { fullName, internId, email, cell };
// mail merge
document.MailMerge.Execute(fieldNames, fieldValues);
//Saves
document.Save(Server.MapPath("~/myDoc/" + email + ".docx"));
document.Close();
}
// pass message to user notifying of successfull operation
lblOutput.Text = "Word Doc output generated successfully!";
}
public string getPath()
{
DirectoryInfo di = new DirectoryInfo(#"C:\projects\unSupervisorApp\Uploads\");
foreach (var d in di.EnumerateDirectories())
{
foreach (var fi in d.EnumerateFileSystemInfos())
{
if (fi.Name == (ddlTemplate.DataTextField))
{
return fi.FullName.Replace(fi.Name, "");
}
}
}
return di.FullName;
}
}//cls
the problem:
‎1-'C:/projects/unSupervisorApp/Uploads/' is a physical path but was expected to be a virtual path.‎
2- and sometime it gives me that it i can not find the file in EnumerateDirectories.
but i get the first one the most.
getFile
getPath
path of folder + ddlselectedItem.text

Passing parameters to remote SSRS report from ASP.NET MVC application

I have an ASP.NET MVC application that uses SSRS for reporting (using a web form and report viewer). I would like to pass two parameters dynamically to the remote report. My current implementation stores the parameters in session, which works fine on VS Development Server, but the variable is null on IIS, upon retrieval in the web form.
Here is the controller method that calls the view
public ActionResult ShowReport(string id)
{
var reportParameters = new Dictionary<string, string>();
reportParameters.Add("Param1", id);
reportParameters.Add("Param2", "user1");
Session["reportParameters"] = reportParameters;
return View("ReportName");
}
And here is how I attempt to retrieve the parameters from the web form
protected void Page_Load(object sender, EventArgs e)
{
var reportParameters = (Dictionary<string, string>)Session["reportParameters"];
foreach (var item in reportParameters)
{
ReportParameter rp = new ReportParameter(item.Key, item.Value);
ReportViewer1.ServerReport.SetParameters(rp);
}
}
Anyone know why Session["reportParameters"] is null?
Or is there some other way of passing these parameters?
You can do it too:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
var js = new JavaScriptSerializer();
string reportPath= Request.QueryString["LocalReport"];
string parametersTemp = Request.QueryString["ParametersReport"];
List<ReportParameter> parameters = null;
if (parametrosTemp != "")
{
parameters = JsonConvert.DeserializeObject
<List<ReportParameter>>(parametrosTemp);
}
GenerateReport(reportPath, parameters );
}
catch (Exception ex) {
statusReport.Value = ex.Message;
}
}
}
private void GenerateReport(string reportPath, List<ReportParameter> reportParameters)
{
reportCurrent.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = reportCurrent.ServerReport;
serverReport.ReportServerUrl =
new Uri(AppSettings.URLReportServer);
serverReport.ReportPath = reportPath;
serverReport.Refresh();
if (reportParameters != null)
{
reportCurrent.ServerReport.SetParameters(reportParameters);
}
}
Is the problem that Session["reportParameters"] is null or is it that you don't get any parameters added to your report? Because your code, as it stands, won't add parameters to your report even if you pass them across properly and so the report parameters will be null.
SetParameters takes IEnumerable<ReportParameter> (usually a List), not a ReportParameterobject. Your code should look more like this:
protected void Page_Load(object sender, EventArgs e)
{
var reportParameters = (Dictionary<string, string>)Session["reportParameters"];
List<ReportParameter> parameters = new List<ReportParameter>();
foreach (var item in reportParameters)
{
parameters.Add(new ReportParameter(item.Key, item.Value););
}
ReportViewer1.ServerReport.SetParameters(parameters);
}

user control properties

i have a detail view with below markup and data source of this detail view is from stored procedure "spDocResult" like below:
select DocId,TransId,FileId,Filename,ContentType,Data,DocumentNo,Title,TRANSMITTAL
from DocumentSum2
where (DocId=#Docid)AND(Transid=#Transid)
one field of this detail view should be show Efile Names so i have made 1 user control for that
public partial class FileTemp : System.Web.UI.UserControl
{
private EDMSDataContext _DataContext;
private IEnumerable<tblFile> _Efiles;
public IEnumerable<tblFile> Efiles
{
set { _Efiles = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "Download")
{
_DataContext = new EDMSDataContext();
//you can get your command argument values as follows
string FileId = e.CommandArgument.ToString();
int _FileId = Convert.ToInt32(FileId);
tblFile Efile = (from ef in _DataContext.tblFiles
where ef.FileId == _FileId
select ef).Single();
if (Efile != null)
{
download(Efile);
}}}
private void download ( tblFile Efile)
{
Byte[] bytes = (Byte[])Efile.Data.ToArray();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = Efile.ContentType.ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ Efile.FileName.ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
public override void DataBind()
{
base.DataBind();
GridViewEfile.DataSource = _Efiles;
GridViewEfile.DataBind();
}
}
now i have problem because datasource of detailview comes from a stored procedure and properties of user control is from tblFile, so when i use DetailsView1_DataBound i do not know how i have to get user control properties.when i use below code, i have error
can not implicity convert type string to system.collection.generic.iEnumerable<tblfile>
i have error for this line
fileList.Efiles = docresult.Filename;
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
spDocResultResult docresult = (spDocResultResult)DetailsView1.DataItem;
FileTemp fileList = (FileTemp)DetailsView1.FindControl("FileTemp1");
fileList.Efiles = docresult.Filename;
fileList.DataBind();
}
This might not be a data binding issue at all. It's a little hard to gather from the context, but...
FileTemp fileList = (FileTemp)DetailsView1.FindControl("FileTemp1");
fileList.Efiles = docresult.Filename;
Is fileList.Efiles a list of items that you just want to assign a file name to? If so, you might just need to foreach through them.
foreach (var file in fileList.Efiles)
{
file.FileName = docresult.Filename;
}
Also, add this line to your Efiles declaration to solve the Get accessor error.
public IEnumerable<tblFile> Efiles
{
get { return _Efiles; } // <- here
set { _Efiles = value; }
}

Object reference not set to an instance of an object

I am getting an error with an aspx Upload Control & Drop Down List on a single aspx page.
Here is the error...
Object reference not set to an instance of an object.
Here is my code for the on_submit...
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = "//DOCSD9F1/TECHDOCS/";
string uploadFolder = DropDownList1.SelectedItem.Text;
string fileName = e.UploadedFile.FileName;
string path = (uploadDirectory + uploadFolder + fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}`
here is my code for creating the drop down list...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files");
DropDownList1.DataSource = di.GetDirectories();
DropDownList1.DataBind();
foreach (DirectoryInfo i in di.GetDirectories())
{
DropDownList1.DataTextField = i.FullName;
DropDownList1.DataValueField = i.FullName;
}
}
}`
You might want to try this:
if(!Page.IsPostBack){
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files");
DirectoryInfo[] diArr = di.GetDirectories();
DropDownList1.DataSource = diArr;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Name";
DropDownList1.DataBind();
}
And get the selected value like:
string uploadFolder = DropDownList1.SelectedValue;
FYI: Make sure there are proper slashes(/) in the path you are creating while uploading the file.

ASP.NET lisbox - Selected first item, always

I have a list box which is populated using a dictioanry. When I iterate throught the selected items using the following code, it always show only the first items as selected - even if the first item is not selected.
Have you ever encountered this scenario?
Could you please help on this?
This problem occurs when I use dictionary for binding. On the other hand a generic list works fine.
private void PopulateListBox2()
{
List<string> subjectList = new List<string>();
subjectList.Add("Maths");
subjectList.Add("Science");
ListBox1.DataSource = subjectList;
ListBox1.DataBind();
}
Even it will work fine, if the values are unique. But in my scenario, the values are same; only key varies. The following works
private void PopulateListBox5()
{
Dictionary<string, string> resultDictionary = new Dictionary<string, string>();
resultDictionary.Add("Maths", "Lijo1");
resultDictionary.Add("Science", "Lijo2");
ListBox1.DataValueField = "Value";
ListBox1.DataTextField = "Key";
ListBox1.DataSource = resultDictionary;
ListBox1.DataBind();
}
^^^^^^^^^^^^^^^^^^^
The following code has the problem.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateListBox1();
ListBox1.SelectionMode = ListSelectionMode.Multiple;
}
}
private void PopulateListBox1()
{
Dictionary<string, string> resultDictionary = new Dictionary<string, string>();
resultDictionary.Add("Maths", "Lijo");
resultDictionary.Add("Science", "Lijo");
ListBox1.DataValueField = "Value";
ListBox1.DataTextField = "Key";
ListBox1.DataSource = resultDictionary;
ListBox1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
MakeList1Items();
}
private void MakeList1Items()
{
string test = null;
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected == true)
{
if(string.IsNullOrEmpty(test))
{
test=item.Text;
}
else
{
test = test +", " + item.Text;
}
}
}
Response.Write(test);
}
}
Thanks
Lijo
You have the DataValueField and DataTextField of the ListBox the wrong way around. I'm not sure why, but they must be like this:
ListBox1.DataValueField = "Key";
ListBox1.DataTextField = "Value";
So, in reality, you are best not using a Dictionary for for this kind of binding. Maybe try a List<KeyValuePair<string, string>> instead.

Resources