I am new to MVC4 with Entity Framework. Now i am doing RDLC report, here i am passing the parameters to the Report to Filter the data. It's working on local. When i am publishing on server it's not working. It's showing exception like ( An error occurred while processing your request). I am not able to find the exact error. Please help me to resolve this problem. Thanks in advance.
This is my Controller code:
var name = Convert.ToString(form["name"]);
var date = Convert.ToString(form["cdate"]);
var dateList = Convert.ToDateTime(form["cdate"]);
string id = Convert.ToString(form["value"]);
//id = "PDF";
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("../Reports"), "DailyReport.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View("Index");
}
//Assigning the parameters to the list
List<ReportParameter> lst = new List<ReportParameter>();
ReportParameter rptName = new ReportParameter("rptname", name);
ReportParameter rptDate = new ReportParameter("rptdate", date);
lst.Add(rptName);
lst.Add(rptDate);
lr.SetParameters(lst);
var rptData =
from d in db.Tbl_DailyReport
where (d.CreatedOn == dateList)
join u in db.Tbl_Users on d.CreatedBy equals u.UserID
where (u.UserName == name)
join c in db.Tbl_Mst_City on u.UserCity equals c.CityId
join ds in db.Tbl_Mst_Designation on u.UserDesignation equals ds.DesignationID
select new
{
u.UserName,
c.CityName,
ds.Designation,
d.DailyReport,
d.Achivement,
d.ReportTime,
d.Comment,
d.CreatedOn
};
//Passing the parameters to the report
ReportDataSource rd = new ReportDataSource("DataSet_dr", rptData);
lr.DataSources.Add(rd);
lr.Refresh();
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</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);
Not sure what you want but try setting properties of RDLC report as following while publishing your website.
Build action = Content,
Copy to output Directory = Copy if newer.
and publish your website.
You can read more about publishing RDLC Here
Related
Although this has been asked before, none of the answers provided solve my issue. I AM passing in all of the required report parameters and all have HasValidValue set in the State property of the parameter array of ExecutionInfo. I am using ReportExecution2005.asmx in my ASP.NET web application. There is no GetParameters() call method to ReportExecution2005.ReportExecutionService object.
My report is calling a subreport so the input parameters are identical to the main report and the subreport. There are 4 single value inputs (two integer, two text) and then one Multivalue text input parameter which I supply multiple values for. I have double and tripled checked that the values I'm setting in the Multivalue input parameter match exactly one of the default parameters.
Here is the code that setups up the reports and renders/writes it out to a PDF file:
protected void btnPrintReq_Tests_Click(object sender, EventArgs e)
{
string query = string.Format("SELECT PatientFName, PatientLName, Address1 + ' ' + Address2 AS Address, City, Region AS State, PostalCode, Email, Phone, Gender, DOB, CONVERT(VARCHAR, ClinicID) AS ClinicID FROM Tbl_ShippingDropShip WHERE RequestID = {0}", giRequestID.ToString());
string sClinicID = string.Empty;
try
{
//get the drop ship test order details
SqlDataReader reader = default(SqlDataReader);
reader = o_cSQL.RunSQLReturnDataReader(query);
REService.ReportExecutionService rs_ext = new REService.ReportExecutionService();
rs_ext.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs_ext.Url = ConfigurationManager.AppSettings["ReportExecutionServer"];
List<string> ordereditems = new List<string> { };
ordereditems = GetOrderedItems(); //panels and profiles
int numordereditems = ordereditems.Count;
List<String> comments = new List<String>();
if (cbIce.Checked)
comments.Add("Ice");
if (cbKit.Checked)
comments.Add("Kit");
if (cbSwabs.Checked)
comments.Add("Swabs");
if (cbGoldTop.Checked)
comments.Add("Gold Top");
if (cbNeedlePack.Checked)
comments.Add("Needle Pack");
if (cbButterflyPack.Checked)
comments.Add("Butterfly Pack");
if (comments.Count == 0)
comments.Add("");
byte[] result = null;
string historyID = null;
string devInfo = null;
string encoding;
string mimeType;
string extension;
REService.Warning[] warnings = null;
string[] streamIDs = null;
//define the size of the parameter array to pass into the REService
REService.ParameterValue[] rValues = new REService.ParameterValue[4 + numordereditems];
while (reader.Read())
{
sClinicID = reader["ClinicID"].ToString();
rValues[0] = new REService.ParameterValue();
rValues[0].Name = "ClinicID";
rValues[0].Value = sClinicID;
rValues[1] = new REService.ParameterValue();
rValues[1].Name = "ReqFormID";
rValues[1].Value = giRequestID.ToString();
rValues[2] = new REService.ParameterValue();
rValues[2].Name = "DropShipID";
rValues[2].Value = giDropShipID.ToString();
rValues[3] = new REService.ParameterValue();
rValues[3].Name = "Comments";
rValues[3].Value = string.Join(",",comments.ToArray());
int j = 0;
for (int i = 4; i < rValues.Length; i++)
{
rValues[i] = new REService.ParameterValue();
rValues[i].Name = "PanelsNProfiles";
rValues[i].Label = "Panels and Profiles :";
rValues[i].Value = ordereditems[j++];
}
}
REService.ExecutionInfo res_info = new REService.ExecutionInfo();
res_info = rs_ext.LoadReport("/zReportSandbox/RequisitionDS", historyID);
res_info = rs_ext.SetExecutionParameters(rValues, "en-us");
res_info = rs_ext.GetExecutionInfo();
result = rs_ext.Render("PDF", devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
string pdfFile = "Requisition_" + giRequestID.ToString() + "_"+ txtPatientName_Edit.Text + ".pdf";
string sPDFSavePath = ConfigurationManager.AppSettings["Shipping_Requisitions"] + sClinicID;
//add the date pathing
sPDFSavePath = ReportHelper.CreateDateDirectories(sPDFSavePath);
//make sure the file doesn't already exist and if it does, delete it so we create a new one
ReportHelper.checkPDFfilesNDirectory(sPDFSavePath +#"\", pdfFile);
FileStream stream = File.Create(sPDFSavePath + #"\" + pdfFile, result.Length);
stream.Write(result, 0, result.Length);
stream.Close();
}
catch(Exception ex)
{
Common.CommonUtilities.FatalError(sPageName, "btnPrintReq_Tests_Click", query, ex.Message.ToString(), ex.ToString());
}
}
I have noticed that the ExecutionInfo item shows me all parameters in the array of the report, meaning the required INPUT parameters AND the INTERNAL parameters, but also noticed that for the INTERNAL parameters, the default value that was set in the report is satisfied and ExecutionInfo shows them with the State of HasValidValue.
The following list is what I know
the report works on its own, so the Main report that calls the Subreport has no issues creating the PDF
there report when run in SSRS does prompt for the 4 input parameters
I have tried the removal of the report in SSRS and redeployed it because there were many that suggested this somehow fixes issues like this.
I have tried the Insert a table, delete the columns and put subreport in one cell of table trick and still the same error.
It would be nice if the error would state what parameter it sees as not being satisfied, even if there are more than one, then simply listing the first one before erroring out would help a developer work through the issues.
The attached picture shows the values I'm passing in for the multivalue parameters (PanelsNProfiles). I'm also attaching my RDL files for the main report and the Subreport, but had to add a (.txt) file extension to them to be able to upload them.
Here is the error in the SSRS execution log:
library!ReportServer_0-57!5250!03/23/2022-09:06:27:: i INFO: RenderForNewSession('/zReportSandbox/RequisitionDS')
processing!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: , Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: One or more parameters required to run the report have not been specified.;
reportrendering!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.RenderingObjectModelException: , Microsoft.ReportingServices.ReportProcessing.RenderingObjectModelException: One or more parameters were not specified for the subreport, 'RequisitionTopDS', located at: /zReportSandbox/RequisitionTopDS.;
processing!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: An error has occurred while processing a sub-report. Details: One or more parameters were not specified for the subreport, 'RequisitionTopDS', located at: /zReportSandbox/RequisitionTopDS. Stack trace:
at Microsoft.ReportingServices.OnDemandReportRendering.SubReport.FinalizeErrorMessageAndThrow()
at Microsoft.ReportingServices.OnDemandReportRendering.SubReport.RetrieveSubreport()
Not sure if anyone has come across this, but currently porting a K13 MVC project over to K13 .Net core (5.0) - both using the same CMS just different Kentico libraries packages but of same hotfix version.
standard Search API functionality being used in both with exact same parameters for a search query but finding that .net core instance will return a TreeNode in its searchResults.Items Data object where the MVC would return its stronglyTyped object
Function
protected ItemsAndCount<News> GetItemsAndCount(string nodeAliasPath, int pageSize = 12, string searchText = "", int currentPage = 0, int category = 0, int year = 0)
{
var culture = LocalizationContext.CurrentCulture.CultureCode;
var defaultCulture = CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName);
var combineWithDefaultCulture = SiteInfoProvider.CombineWithDefaultCulture(SiteContext.CurrentSiteName);
var documentTypes = News.CLASS_NAME;
var docCondition = new DocumentSearchCondition(documentTypes, culture, defaultCulture, combineWithDefaultCulture);
var condition = new SearchCondition(GetExtraConditions(category, year), SearchModeEnum.ExactPhrase, SearchOptionsEnum.NoneSearch, docCondition, false);
var query = ValidationHelper.GetString(searchText, string.Empty);
var path = nodeAliasPath + "/";
var parameters = new SearchParameters
{
Path = path,
SearchFor = SearchSyntaxHelper.CombineSearchCondition(query, condition),
SearchSort = OrderBy,
CurrentCulture = LocalizationContext.CurrentCulture.CultureCode,
DefaultCulture = CultureHelper.GetDefaultCultureCode(SiteContext.CurrentSiteName),
CombineWithDefaultCulture = SiteInfoProvider.CombineWithDefaultCulture(SiteContext.CurrentSiteName),
User = MembershipContext.AuthenticatedUser,
SearchIndexes = SearchIndexHelper.SEARCHINDEX_NEWS,
DisplayResults = pageSize,
StartingPosition = currentPage == 0 ? 0 : (currentPage - 1) * pageSize,
NumberOfProcessedResults = 10000
};
var searchResult = SearchHelper.Search(parameters);
//TotalNoOfRecords = searchResult.TotalNumberOfResults;
return new ItemsAndCount<News>
{
Items = GetItems(searchResult.Items).ToList(),
Count = searchResult.TotalNumberOfResults
};
}
So according to the API docs for SearchHelper, this does look like intended behavior. But you don't actually have to use SearchHelper. You could call the Azure Search client directly and work with the SearchDocument object it returns. An example of this is in the LearningKit for 13.
So this turned out to be an issue due to having all generated code files in a separate library
https://docs.xperience.io/custom-development/adding-custom-assemblies#Addingcustomassemblies-Enablingclassdiscovery
what was throwing me is that all the rest of the site was actually running as expected without this, only searchitems & customtableitems where not returning as strongly typed.
I am trying to create a simple tool that creates a model from metadata. I am successful in creating tables and columns, but unable to create relationships under model. While trying to add FromTable and ToTable properties to relationship object i was getting an error saying those properties are read-only and cannot be changed.
Below is the sample code that i am using to create relationships.
public void AddRelationshipsToModel()
{
OleDbDataReader reader = null;
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = metadataConnInfo.ConnectionString;
connection.Open();
OleDbCommand command = connection.CreateCommand();
command.CommandText = "select source_parent_table_name,source_parent_column_name, source_child_table_name,source_child_column_name from HX_VIEWS_RMS.BI_TABULAR_RELATIONSHIPS where MODEL_NAME='"+database.Model.Name +"'";
reader = command.ExecuteReader();
while(reader.Read())
{
string _toTable = srcAndTabularTableMap[reader.GetValue(0).ToString().Trim()];
string _toColumn = srcTableAndTabularColMap[reader.GetValue(0).ToString().Trim()][ reader.GetValue(1).ToString().Trim()];
string _fromTable = srcAndTabularTableMap[reader.GetValue(2).ToString().Trim()];
string _fromColumn = srcTableAndTabularColMap[reader.GetValue(2).ToString().Trim()][reader.GetValue(3).ToString().Trim()];
Table fromTable = Database.Model.Tables[_fromTable];
DataColumn fromColumn = (DataColumn)fromTable.Columns[_fromColumn];
Table toTable = Database.Model.Tables[_toTable];
DataColumn toColumn = (DataColumn)fromTable.Columns[_toColumn];
SingleColumnRelationship relationship = new SingleColumnRelationship();
relationship.FromTable = fromTable;
relationship.FromColumn = fromColumn;
relationship.ToTable = toTable;
relationship.ToColumn = toColumn;
//database.Model.Relationships.Add(new SingleColumnRelationship() { FromColumn = fromColumn ,ToColumn =toColumn});
}
connection.Close();
}
catch(Exception ex)
{
logger.Error(ex.Message);
}
}
This blog post is a good walk through.
Try just setting the FromColumn and ToColumn properties not the FromTable and ToTable settings. Optionally you can set them as part of the constructor:
SingleColumnRelationship relationship = new SingleColumnRelationship()
{
FromColumn = fromColumn,
ToColumn = toColumn
};
Tabular object model API has quite a few readonly fields / properties. Basically they are trying to tell you that you are not suppose to edit these fields directly but rather let API fill them for you.
Typical relationship look like this
Server = new Microsoft.AnalysisServices.Tabular.Server();
[...]
Server.Databases["MyDatabaseName"].Model.Relationships.Add(new SingleColumnRelationship
{
Name = "Relationship name",
FromColumn = Server.Databases["MyDatabaseName"].Model.Tables["FromTableName"].Columns["FromColumnName"],
FromCardinality = RelationshipEndCardinality.Many,
ToColumn = Server.Databases["MyDatabaseName"].Model.Tables["ToTableName"].Columns["ToColumnName"],
ToCardinality = RelationshipEndCardinality.One,
CrossFilteringBehavior = CrossFilteringBehavior.BothDirections,
IsActive = false
});
Try to handle with this class - Microsoft.AnalysisServices.Tabular.SingleColumnRelationship
I have a document library called Documents in production. I wrote a timer job for sending emails based on the columns in the library.
Everything was fine in the dev environment but the timer job in prod is giving me exceptions. Any ideas?
Entering monitored scope (Timer Job Corporate Policies - Reminder Emails)
The Execute method of job definition CorporatePolicyReminders.DailySchedule (ID 3586f4d2-1bc1-4770-b5b8-4c2c578ee8d5) threw an exception. More information is included below. Object reference not set to an instance of an object.
Exception stack trace:
at CorporatePolicyReminders.CorporatePolicyReminders.SendCorporateReminder(SPWeb web)
at CorporatePolicyReminders.DailySchedule.Execute(Guid contentDbId)
at Microsoft.SharePoint.Administration.SPTimerJobInvokeInternal.Invoke(SPJobDefinition jd, Guid targetInstanceId, Boolean isTimerService, Int32& result)
Leaving Monitored Scope (Timer Job Corporate Policies - Reminder Emails). Execution Time=364.288198639771
SendCorporateReminers Method
public void SendCorporateReminder(SPWeb web)
{
SPList lstComplaint = Helper.GetList(web, "Documents", Helper.ListType.Library);
if (lstComplaint != null)
{
string query = "<Where><Eq><FieldRef Name='DocFormat' /><Value Type='Choice'>Policy</Value></Eq></Where>";
SPListItemCollection colRecords = Helper.ExecuteQueryRecursive(lstComplaint, query, null, 2000);
if (colRecords != null && colRecords.Count > 0)
{
foreach (SPListItem item in colRecords)
{
DateTime Expires = Helper.GetSPFieldDateTimeValue(item, "Expires");
String Title = Helper.GetSPFieldTextValue(item, "Title");
SPFieldUserValueCollection userResp = Helper.GetUsers(item, "Contact");
TimeSpan totaldays = DateTime.Now.Date - Expires.Date;
Int32 days = totaldays.Days;
String emailtemplatekeyA = "AEmail" + days.ToString();
String emailtemplatekeyB = "BEmail" + days.ToString();
String respToEmail = String.Empty;
if (userResp != null && userResp.Count > 0)
{
foreach (SPFieldUserValue user in userResp)
{
if (!string.IsNullOrEmpty(respToEmail))
respToEmail += ",";
respToEmail += user.User.Email;
}
}
HandleEmails handleEmail = new HandleEmails();
handleEmail.AddValueToPlaceholder(HandleEmails.EmailPlaceHolders.SendingTypeValue.EmailRecipient, PlaceHolder.USERRESP.ToString(), respToEmail);
handleEmail.AddValueToPlaceholder(HandleEmails.EmailPlaceHolders.SendingTypeValue.OTHER, PlaceHolder.TITLE.ToString(), Title);
handleEmail.AddValueToPlaceholder(HandleEmails.EmailPlaceHolders.SendingTypeValue.OTHER, PlaceHolder.EXPDT.ToString(), Expires.ToShortDateString());
handleEmail.AddValueToPlaceholder(HandleEmails.EmailPlaceHolders.SendingTypeValue.OTHER, PlaceHolder.ID.ToString(), item.ID.ToString());
handleEmail.SendMail(web, emailtemplatekeyA);
handleEmail = new HandleEmails();
handleEmail.AddValueToPlaceholder(HandleEmails.EmailPlaceHolders.SendingTypeValue.EmailRecipient, PlaceHolder.USERRESP.ToString(), respToEmail);
handleEmail.AddValueToPlaceholder(HandleEmails.EmailPlaceHolders.SendingTypeValue.OTHER, PlaceHolder.TITLE.ToString(), Title);
handleEmail.AddValueToPlaceholder(HandleEmails.EmailPlaceHolders.SendingTypeValue.OTHER, PlaceHolder.EXPDT.ToString(), Expires.ToShortDateString());
handleEmail.AddValueToPlaceholder(HandleEmails.EmailPlaceHolders.SendingTypeValue.OTHER, PlaceHolder.ID.ToString(), item.ID.ToString());
handleEmail.SendMail(web, emailtemplatekeyB);
}
}
}
}`
I found the issue and resolved it.Person whose userid is no longer valid is Contact the person of document (he is in contact column for the library i am creating timer job). So timer job is throwing exception (Object reference not set to an instance of an object.) whenever it is trying to read Contact column of the document. i figured it out by modifying my code as below and i removed that person from that column.
Helper.WriteUlsInformation("Item processing:" + i.ToString(), TraceSeverity.Verbose);
DateTime Expires = Helper.GetSPFieldDateTimeValue(item, "Expires");
Helper.WriteUlsInformation("Expires:" + Expires.ToString(), TraceSeverity.Verbose);
String Title = Helper.GetSPFieldTextValue(item, "Title");
Helper.WriteUlsInformation("Title:" + Title, TraceSeverity.Verbose);
SPFieldUserValueCollection userResp = Helper.GetUsers(item, "Contact");
Helper.WriteUlsInformation("UserResp read" , TraceSeverity.Verbose);
TimeSpan totaldays = DateTime.Now.Date - Expires.Date;
Int32 days = totaldays.Days;
Helper.WriteUlsInformation("Days:"+ days.ToString(), TraceSeverity.Verbose);
String emailtemplatekeyA = "AEmail" + days.ToString();
String emailtemplatekeyB = "BEmail" + days.ToString();
String respToEmail = String.Empty;
I am developing a view page.
Here is my code:
int idses = Convert.ToInt32(Session["ID"].ToString());
// address
DataTable adrDT = new DataTable();
adrDT = ClassView.GetRows(idses);
houseN.Text = adrDT.Rows[0]["houseN"].ToString();
streetAD.Text = adrDT.Rows[0]["stAddress"].ToString();
townAD.Text = adrDT.Rows[0]["town"].ToString();
cityAD.Text = adrDT.Rows[0]["city"].ToString();
stateAD.Text = adrDT.Rows[0]["state"].ToString();
zipC.Text = adrDT.Rows[0]["zipCOde"].ToString();
ddlC.SelectedValue = adrDT.Rows[0]["countryID"].ToString();
teleNumb.Text = adrDT.Rows[0]["telephoneN"].ToString();
faxNumb.Text = adrDT.Rows[0]["faxN"].ToString();
this the code in my datalayer:
string rowSQL = "SELECT Merchant_Master.id, Merchant_Master.CompanyName, Merchant_Master.Url, Merchant_Master.AddressID, Industry.IndustryName, "
+ "Merchant_Master.IsActive, Merchant_Master.IsDeleted, Merchant_Master.DateCreated "
+ "FROM Merchant_Master JOIN Industry on Merchant_Master.IndustryID = Industry.id where Merchant_Master.id = #id";
//string rowSQL = "SELECT CompanyName, Url, DateCreated FROM Merchant_Master";
string[] param = {"#id"};
object[] paramVal = {};
return ClassDBQuery.ExecDataReader(rowSQL, param, paramVal);
My question is: How will I call the #id in the code behind?
adrDT = ClassView.GetRows(idses); -> in this line...when I put idses, I get the error "No overload for method 'GetRows()' takes one argument"... What should I do?
This means that, on your ClassView class, you dont have a GetRows method expecting any parameter. Look your ClassView again.
EDIT:
If the type of idses is int, you should do:
public static DataTable GetRows(int ideses) {...}