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;
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()
My code look like below.
protected void btnApprove_Click(object sender, EventArgs e)
{
if (id == "Button2")
{
string sql = #"update AdjTranSeqDetails set Approver1Status = 'Rejected',finalStatus='Rejected' ,updatedtime = GETDATE(),Approver1Comment ='{1}',modifieduser = '{2}' where TranSeq ={0}";
sql = String.Format(sql, tbxTranSeq.Text, TextBox2.Text, Master.CurrentUser);
string sql2 = #"INSERT INTO AdjTranSeqDetailsHistory SELECT * FROM AdjTranSeqDetails WHERE tranSeq={0}";
sql2 = String.Format(sql2, tbxTranSeq.Text);
string sql3 = #"delete from AdjTranSeqDetails where tranSeq={0}";
sql3 = String.Format(sql3, tbxTranSeq.Text);
if (dba.SqlUpdate(sql, ref ex, ref rowCt) || dba.SqlInsert(sql2, ref ex, ref rowCt) ||dba.SqlDelete(sql3, ref ex, ref rowCt))
{
string sscript = "<script language=\"Jscript\" > ";
if (Master.PageMode == "View")
{
sscript += "if (window.opener && !window.opener.closed) ";
sscript += "{window.opener.DoSearch();}";
}
sscript += "window.opener='x';self.close();";
sscript += "</Script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "SelfClose", sscript);
}
}
updateapp();
GetBillTranInfo();
}
Like Button2, like have 10 button. If one if condition function done I need to close the window and need to reload the page. Can I do like this?
I have tried like above but that is not working for me.
In my user controls, after updating data I do:
Response.Redirect(Request.RawUrl);
That ensures that the page is reloaded, and it works fine from a user control. You use RawURL and not Request.Url.AbsoluteUri to preserve any GET parameters that may be included in the request.
You probably don't want to use: __doPostBack, since many aspx pages behave differently when doing a postback.
I am creating a macro for Excel (2007/2010) which gathers information about the process and displays it within specified cells. So far I cannot get the GDI/User objects, but I can get the handle etc.
I use this to get the process:
Set oServ = GetObject("winmgmts:")
Set cProc = oServ.ExecQuery("Select * from Win32_Process")
I then find the process i am looking for and grab Peak Working Set memory, Handles, etc. I have tried using GetGuiResources to grab GDI/User Objects but I cannot get it to work for a specified process (returns 0). I read a post where it said to use OpenProcess, but that doesn't work either.
Range(CStr(Cell_Holder)).Value = GetGuiResources(jProc.Handle, 0) 'jProc is the process wanted
Range(CStr(Cell_Holder)).Value = GetGuiResources(GetCurrentProcess, 0)' this works...
Since the WMI-Query returns a Win32_Process object but the GetGuiResources requires a hWND (window handle), you have to get the handle from the Win32_Process. Unfortunately this is not the Handle member of the Win32_Process.
You could use the System.Diagnostics.Process class to get the required window handle. In C#, you would do the following:
using System.Diagnostics;
using System.Management;
const int GR_GDIOBJECTS = 0;
// ...
String wmiQuery = "select * from Win32_Process";
ManagementObjectSearcher search = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection processList = search.Get();
foreach (ManagementObject obj in processList)
{
int pid = (int)(uint)obj["ProcessId"];
Process p = Process.GetProcessById((int)pid);
String name = p.ProcessName;
try
{
int handleCount = GetGuiResources(p.Handle, GR_GDIOBJECTS);
Console.WriteLine(name + ": " + handleCount);
}
catch
{
Console.WriteLine(name + ": Access denied");
}
}
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
I have a filter in grails to capture all controller requests and insert a row into the database with the controllerName, actionName, userId, date, and guid. This works fine, but I would like to find a way to increase the performance. Right now it takes ~100 milliseconds to do all this with 70-80ms of that time creating a statement. I've used both a domain object insert, groovy Sql, and raw java connection/statement. Is there any faster way to improve the performance of inserting a single record within a filter? Alternatively, is there a different pattern that can be used for the inserts? Code (using groovy SQL) Below:
class StatsFilters {
def grailsApplication
def dataSource
def filters =
{
logStats(controller:'*', action:'*')
{
before = {
if(controllerName == null || actionName == null)
{
return true
}
def logValue = grailsApplication.config.statsLogging
if(logValue.equalsIgnoreCase("on") && session?.user?.uid != null & session?.user?.uid != "")
{
try{
def start = System.currentTimeMillis()
Sql sql = new Sql(dataSource)
def userId = session.user.uid
final String uuid = "I" + UUID.randomUUID().toString().replaceAll("-","");
String insert = "insert into STATS(ID, CONTROLLER, ACTION, MODIFIED_DATE, USER_ID) values ('${uuid}','${controllerName}','${actionName}',SYSDATE,'${userId}')"
sql.execute(insert)
sql.close()
def end = System.currentTimeMillis()
def total = end - start
println("total " + total)
}
catch(e)
{
log.error("Stats failed to save with exception " + e.getStackTrace())
return true
}
}
return true
}
}
}
}
And my current data source
dataSource {
pooled = true
dialect="org.hibernate.dialect.OracleDialect"
properties {
maxActive = 50
maxIdle = 10
initialSize = 10
minEvictableIdleTimeMillis = 1800000
timeBetweenEvictionRunsMillis = 1800000
maxWait = 10000
validationQuery = "select * from resource_check"
testWhileIdle = true
numTestsPerEvictionRun = 3
testOnBorrow = true
testOnReturn = true
}
//loggingSql = true
}
----------------------Solution-------------------------
The solution was to simply spawn a thread and do the stats save. This way user response time isn't impacted, but the save is done in near real time. The number of users in this application (corporate internal, limited user group) doesn't merit anything more robust.
void saveStatData(def controllerName, def actionName, def userId)
{
Thread.start{
Sql sql = new Sql(dataSource)
final String uuid = "I" + UUID.randomUUID().toString().replaceAll("-","");
String insert = "insert into STATS(ID, CONTROLLER, ACTION, MODIFIED_DATE, USER_ID) values ('${uuid}','${controllerName}','${actionName}',SYSDATE,'${userId}')"
sql.execute(insert)
sql.close()
}
}
Better pattern is not to insert the row in the filter instead just add a record to some list and flush the list into database regularly by asynchronous job (using Quartz plugin for example).
You could loose some data if application crashes, but if you schedule the job to run often (like every x minutes), it should not be an issue.