I have a local .rdlc report rigged to show on a button click, but for some reason the report only shows up on the 2nd button click event. I have no idea why the report doesn't show on the first button click... This is the function I call on the click event of the button.
private void ShowReport(string accountingCompanyId, string companyId, string approvalUnitId, DateTime startDate, DateTime finishDate, string supplierId,
string documentNumber, string documentType, string documentState, string costCenterId, string chargingKeyId,
string dim1Value, string dim1Description, string dim1Id, string dim2Value, string dim2Description, string dim2Id,
string dim3Value, string dim3Description, string dim3Id, bool showDetails) {
//this.ReportViewer1.Reset();
//Set report mode for local processing.
this.ReportViewer1.ProcessingMode = ProcessingMode.Local;
ISettingsReader settingsReader = SettingsReaderFactory.Instance.CreateSettingsReader();
this.ReportViewer1.LocalReport.ReportPath = settingsReader.GetSetting("ReportViewer", "FinancialReportPath" + (showDetails ? "" : "Small"), true, null);
ReportsBL reports = new ReportsBL();
// Clear out any previous datasources.
this.ReportViewer1.LocalReport.DataSources.Clear();
// Load the company dataSource.
DataTable company = reports.GetCompanyDataSet(accountingCompanyId).Tables[0];
ReportDataSource dataSourceCompany = new ReportDataSource(company.TableName, company);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceCompany);
// Load the dataSource.
DataTable report = reports.GetReportFinanceiroSmallDataSet(companyId, startDate, finishDate, chargingKeyId, costCenterId, documentNumber, documentType, dim1Value, dim2Value, dim3Value, dim1Id, dim2Id, dim3Id, supplierId, approvalUnitId, documentState, accountingCompanyId).Tables[0];
ReportDataSource dataSourceReport = new ReportDataSource(report.TableName, report);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceReport);
this.ReportViewer1.LocalReport.Refresh();
this.pnlReport.Visible = true;
}
Strangely, if I uncomment the line this.ReportViewer.Reset(); then the report will never show up regardless of the number of clicks I generate... Does anybody know if this is normal? How can work around the problem?
Thanks in advance,
I guess the problem might be that the click event is fired after the page is rendered. Try calling the method in the Page_Load event.
protected void Page_Load(object sender, EventArgs e)
{
if (IsCallback)
{
ShowReport(
// params
);
}
}
If that works, you know it has something to do with the order of execution.
I've never had to call ReportViewer.DataBind(); Below is what I typically do:
IEnumerable<ReportClass> ds = DataTranslator.GetReportData(Int64.Parse(<someId>));
report.LocalReport.ReportPath = "<some_path_to_report.rdlc>";
report.LocalReport.DataSources.Add(new ReportDataSource("DataSet", ds));
report.Visible = true;
report.LocalReport.Refresh();
After a lot of trial and error, I got it working by calling the databind() method on the the pageload event. After the pageload databinds (with no datasource set), the subsequent
button click starts working as expected.
I'm included the code in case somebody else encounters this error. (Would love to know why I need to databind in the pageload though...)
Update 2
I finally figured out the problem... Turns out the .rdlc was migrated from an old 2005 .rdl report, and that the new .rdlc contained old report parameters+sql which was somehow messing up the report loading. After I removed the unused report parameteres+sql everything started working perfectly... I've updated the code bellow to reflect what I'm now using in my project...
protected void Page_Load(object sender, System.EventArgs e) {
}
protected void btGenStats_Click(object sender, System.EventArgs e) {
...
this.ShowReport(accountingCompanyId, companyId, approvalUnitId, startDate, finishDate, supplierId, documentNumber, documentType, documentState,
costCenterId, chargingKeyId, dim1, dim1Desc, dim1Id, dim2, dim2Desc, dim2Id, dim3, dim3Desc, dim3Id, showDetails);
}
private void ShowReport(string accountingCompanyId, string companyId, string approvalUnitId, DateTime startDate, DateTime finishDate, string supplierId, string documentNumber, string documentType, string documentState, string costCenterId, string chargingKeyId, string dim1Value, string dim1Description, string dim1Id, string dim2Value, string dim2Description, string dim2Id, string dim3Value, string dim3Description, string dim3Id, bool showDetails) {
this.ReportViewer1.Reset();
//Set report mode for local processing.
this.ReportViewer1.ProcessingMode = ProcessingMode.Local;
ISettingsReader settingsReader = SettingsReaderFactory.Instance.CreateSettingsReader();
string reportPath = settingsReader.GetSetting("ReportViewer", "FinancialReportPath"+( showDetails? "" : "Small" ), true, null);
this.ReportViewer1.LocalReport.ReportPath = Server.MapPath(reportPath);
ReportsBL reports = new ReportsBL();
// Clear out any previous datasources.
this.ReportViewer1.LocalReport.DataSources.Clear();
// Load the company dataSource.
DataTable company = reports.GetCompanyDataSet(accountingCompanyId).Tables[0];
ReportDataSource dataSourceCompany = new ReportDataSource(company.TableName, company);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceCompany);
if (showDetails)
{
// Load the dataSource.
DataTable report = reports.GetReportFinanceiroDataSet(companyId, approvalUnitId, startDate, finishDate, chargingKeyId, costCenterId, documentNumber, documentType, dim1Value, dim2Value, dim3Value, dim1Id, dim2Id, dim3Id, supplierId, documentState, accountingCompanyId).Tables[0];
ReportDataSource dataSourceReport = new ReportDataSource(report.TableName, report);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceReport);
}
else
{
// Load the dataSource.
DataTable report = reports.GetReportFinanceiroSmallDataSet(companyId, approvalUnitId, startDate, finishDate, chargingKeyId, costCenterId, documentNumber, documentType, dim1Value, dim2Value, dim3Value, dim1Id, dim2Id, dim3Id, supplierId, documentState, accountingCompanyId).Tables[0];
ReportDataSource dataSourceReport = new ReportDataSource(report.TableName, report);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceReport);
}
this.pnlReport.Visible = true;
}
Try this code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string pstrType;
pstrType = Request.QueryString["Type"];
LoadReport();
}
public class CustomReportCredentials : Microsoft.Reporting.WebForms.IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord, string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public System.Net.ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName, _PassWord, _DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
// not use FormsCredentials unless you have implements a custom autentication.
authCookie = null;
user = password = authority = null;
return false;
}
}
void LoadReport()
{
string strCompanyName = objSession.SelCompanyName;
string strHeading = "";
string strBranchName = objSession.SelBranchName;
rptvwMain.ProcessingMode = ProcessingMode.Remote;
rptvwMain.ServerReport.ReportServerCredentials = new CustomReportCredentials(AppConfig.ReportServerUserName, AppConfig.ReportServerPassword, AppConfig.ReportServerDomain);
string strReportServerUrl = AppConfig.ReportServerUrl + AppConfig.ReportServerFolder;
rptvwMain.ServerReport.ReportServerUrl = new Uri(strReportServerUrl);
List<ReportParameter> parameters = new List<ReportParameter>();
if (pstrType == "OB")
{
strHeading = "Ledger Opening Balance";
rptvwMain.ServerReport.ReportPath = "/Account/OpeningBalance";
}
parameters.Add(new ReportParameter("FyId", Convert.ToInt16(objSession.FyId).ToString()));
parameters.Add(new ReportParameter("AccountGroupId", cmbAccountGroup.SelectedValue));
parameters.Add(new ReportParameter("LedgerId", cmbLedgerId.SelectedValue));
parameters.Add(new ReportParameter("BranchId", Convert.ToInt64(objSession.BranchId).ToString()));
parameters.Add(new ReportParameter("StDate", Convert.ToDateTime(RadDtpFromDate.SelectedDate).ToString()));
parameters.Add(new ReportParameter("EnDate", Convert.ToDateTime(RadDtpToDate.SelectedDate).ToString()));
parameters.Add(new ReportParameter("CompanyName", strCompanyName.ToString()));
parameters.Add(new ReportParameter("BranchName", strBranchName.ToString()));
parameters.Add(new ReportParameter("Heading",strHeading.ToString()));
rptvwMain.ServerReport.SetParameters(parameters);
rptvwMain.ServerReport.SetDataSourceCredentials(new[] { new DataSourceCredentials() { Name =AppConfig.ReportServerDataSource , UserId = AppConfig.ReportServerDSUserName, Password = AppConfig.ReportServerDSPassword } });
rptvwMain.ShowZoomControl = true;
rptvwMain.ServerReport.Refresh();
}
}
Related
This code is export event to google calendar, it is working fine in local but after upload the service in IIS server,i am getting this exception occurred.System.ServiceModel.ProtocolException: 'The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/XML; charset=utf-8).
public partial class UNGCCalendarEvent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button 1_Click(object sender, EventArgs e)
{
// WCFServiceClient client = new WCFServiceClient();
using (UNGCCalenderSoapClient uNGC = new UNGCCalenderSoapClient())
{
uNGC.Endpoint.Binding.SendTimeout = new TimeSpan(0, 2, 30);
// EntityExtractionClient nlp = new EntityExtractionClient();
uNGC.InnerChannel.OperationTimeout = new TimeSpan(0, 50, 0);
string EventSummary = TextSumary.Text.ToString();
string EventLocation = TextLocation.Text.ToString();
string EventDescription = TextDescription.Text.ToString();
string EventStartDateTime = TextStartDate.Text.ToString();
string EventEndDateTime = TextEndDate.Text.ToString();
string CustomCalenderName = TextCustomCalenderName.Text.ToString();
string StartDatetimeZone = TextStartDatetimeZone.Text.ToString();
string EndDatetimeZone = TextEndDatetimeZone.Text.ToString();
string[] attendees = Textattendees.Text.Split(',');
var a = new ArrayOfString { Textattendees.Text };
string attachmentsfileUrl = TextattachmentsfileUrl.Text.ToString();
//string s = new string(attendees);
//string a = uNGC.UNGCCalenderService(EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime));
string calendar = uNGC.ExportGoogleEvents(EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime), CustomCalenderName, StartDatetimeZone, EndDatetimeZone, attachmentsfileUrl, a);
uNGC.Close();
}
}
protected void BtnUpdate_Click(object sender, EventArgs e)
{
UNGCCalenderSoapClient uNGC = new UNGCCalenderSoapClient();
// UNGCCalender arrString = UNGCCalenderSoapClient.ArrayOfString();
string EventID = TextEventID.Text.ToString();
string EventSummary = TextSumary.Text.ToString();
string EventLocation = TextLocation.Text.ToString();
string EventDescription = TextDescription.Text.ToString();
string EventStartDateTime = TextStartDate.Text.ToString();
string EventEndDateTime = TextEndDate.Text.ToString();
string CustomCalenderName = TextCustomCalenderName.Text.ToString();
string StartDatetimeZone = TextStartDatetimeZone.Text.ToString();
string EndDatetimeZone = TextEndDatetimeZone.Text.ToString();
string[] attendees = Textattendees.Text.Split(',');
string attachmentsfileUrl = TextattachmentsfileUrl.Text.ToString();
//string s = new string(attendees);
//string a = uNGC.UNGCCalenderService(EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime));
// string calendar = uNGC.UpdateGoogleEvents(EventID,EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime), CustomCalenderName, StartDatetimeZone, EndDatetimeZone, attachmentsfileUrl, arrString.AddRange(attendees));
}
}
I have a method which adds an reminder to an event, but it fails:
FATAL EXCEPTION: main
android.database.sqlite.SQLiteException
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:184)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140)
at android.content.ContentProviderProxy.insert(ContentProviderNative.java:420)
at android.content.ContentResolver.insert(ContentResolver.java:864)
at de.appwege.droid.medwege.navigationdrawer.TerminFragment.insertReminder(TerminFragment.java:848)
The method in question:
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
What I am missing here? both eventID and minutes are defined...
Recently, I also faced same issue. Finally, I found the solution.
First of all, you have to find all logged in gmail id from the device and then select any one gmail account and find its calendar id. After that you have to pass that id to the event query like this....
values.put(Events.CALENDAR_ID, calendarId);
at last call you function
public long insertReminder(long eventID, int minutes){
ContentResolver cr = getActivity().getContentResolver();
ContentValues values = new ContentValues();
values.put(CalendarContract.Reminders.MINUTES, minutes);
values.put(CalendarContract.Reminders.EVENT_ID, eventID);
values.put(CalendarContract.Reminders.METHOD,
CalendarContract.Reminders.METHOD_ALERT);
Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
return Long.valueOf(uri.getLastPathSegment());
}
See below method for finding email id's...
public static Hashtable listCalendarId(Context context) {
try {
if (haveCalendarReadWritePermissions((Activity) context)) {
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = c.getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
if (managedCursor.moveToFirst()) {
String calName;
String calID;
int cont = 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
Hashtable<String, String> calendarIdTable = new Hashtable<>();
do {
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
calendarIdTable.put(calName, calID);
cont++;
} while (managedCursor.moveToNext());
managedCursor.close();
return calendarIdTable;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
i've an issue... I would create an app that scraping the result of a google search.. but when I try to use downloadstringasync the debug return me an error "Impossible to assign 'void' to a local variable ..."
You say how I can resolve it?
This is the code
public class SearchResult
{
public string url;
public string title;
public string content;
public FindingEngine engine;
public enum FindingEngine { google, bing, google_and_bing };
public SearchResult(string url, string title, string content, FindingEngine engine)
{
this.url = url;
this.title = title;
this.content = content;
this.engine = engine;
}
}
public static List<SearchResult> GoogleSearch(string search_expression,
Dictionary<string, object> stats_dict)
{
var url_template = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&safe=active&q={0}&start={1}";
Uri search_url;
var results_list = new List<SearchResult>();
int[] offsets = { 0, 8, 16, 24, 32, 40, 48 };
foreach (var offset in offsets)
{
var searchUrl = new Uri(string.Format(url_template, search_expression, offset));
var page = new WebClient().DownloadStringAsync(searchUrl);
var o = (JObject)JsonConvert.DeserializeObject(page);
var results_query =
from result in o["responseData"]["results"].Children()
select new SearchResult(
url: result.Value<string>("url").ToString(),
title: result.Value<string>("title").ToString(),
content: result.Value<string>("content").ToString(),
engine: SearchResult.FindingEngine.google
);
foreach (var result in results_query)
results_list.Add(result);
}
return results_list;
}
Thanks!
DownloadStringAsync doesn't return anything i.e. a void so you cannot simply assign a variable to it.
You need to add an event handler to DownloadStringCompleted which will be fired when DownloadStringAsync completes.
var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(searchUrl);
static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
// e.Result will contain the returned JSON. Move the code that parse the result to here.
}
I am working on an application in mvc4.I want the application to work in English and Russian.I got titles in russian, but error messages are still in english.
My model contains:-
[Required(ErrorMessageResourceType = typeof(ValidationStrings),
ErrorMessageResourceName = "CountryNameReq")]
public string CountryName { get; set; }
if(ModelState.IsValid) becomes false it will go to GetErrorMessage()
public string GetErrorMessage()
{
CultureInfo ci = new CultureInfo(Session["uiCulture"].ToString());
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
string errorMsg = string.Empty;
int cnt = 1;
var errorList = (from item in ModelState
where item.Value.Errors.Any()
select item.Value.Errors[0].ErrorMessage).ToList();
foreach (var item in errorList)
{
errorMsg += cnt.ToString() + ". " + item + "</br>";
cnt++;
}
return errorMsg;
}
But i always get error message in English.How can i customize the code to get current culture.
The reason for that is because you are setting the culture too late. You are setting it inside the controller action, but the validation messages were added by the model binder much earlier than your controller action even started to execute. And at that stage the current thread culture was still the default one.
To achieve that you should set the culture much earlier in the execution pipeline. For example you could do that inside the Application_BeginRequest method in your Global.asax
Just like that:
protected void Application_BeginRequest(object sender, EventArgs e)
{
CultureInfo ci = new CultureInfo(Session["uiCulture"].ToString());
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
}
i want to short my url with bitly but an exception is occur when i want to set out string to my text block
private void button1_Click(object sender, RoutedEventArgs e)
{
ShortenUrl(textBox1.Text);
}
enum Format
{
XML,
JSON,
TXT
}
enum Domain
{
BITLY,
JMP
}
void ShortenUrl(string longURL)
{
Format format = Format.XML;
Domain domain = Domain.BITLY;
string _domain;
//string output;
// Build the domain string depending on the selected domain type
if (domain == Domain.BITLY)
_domain = "bit.ly";
else
_domain = "j.mp";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
string.Format(#"http://api.bit.ly/v3/shorten?login={0}&apiKey={1}&longUrl={2}&format={3}&domain={4}",
"username", "appkey", HttpUtility.UrlEncode(longURL), format.ToString().ToLower(), _domain));
request.BeginGetResponse(new AsyncCallback(GetResponse), request);
}
void GetResponse(IAsyncResult result)
{
XDocument doc;
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string responseString = reader.ReadToEnd();
doc = XDocument.Load(reader.BaseStream);
}
//// var x = from c in doc.Root.Element("data").Elements()
// where c.Name == "url"
// select c;
//XElement n = ((IEnumerable<XElement>)x).ElementAt(0);
// textBox2.Text = ((IEnumerable<String>)x).ElementAt(0);
lista = (from Born_rich in doc.Descendants("url")
select new a()
{
shrtenurl = Born_rich.Value
}).ToList();
output = lista.ElementAt(0).shrtenurl;
textBox2.Text = output;
//
//
// textBox2.Text = s;
}
List<a> lista = new List<a>();
String output;
}
public class a
{
public String shrtenurl { set; get; }
}
The calback from HttpWebRequest occurs on a non-UI thread. If you want to change soemthing in the UI you must do it on the UI thread. Fortunatley there is an easy way to do this. You simply use the dispatcher to invoke the code in question on the UI.
Dispatcher.BeginInvoke(() => textBox2.Text = output);