asp.net C# webform show report without reportviewer - asp.net

currently i want to generate the report without showing in reportviewer. I search for the solution online but i only can find the MVC approach. I cant convert it to normal webform behavior.
public ActionResult Report(string id)
{
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View("Index");
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
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>1in</MarginLeft>" +
" <MarginRight>1in</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);
}
enter code here
Here is the sample of code that can allow user to generate the report in different format such as PDF, excel, image. ( http://www.dotnetawesome.com/2013/09/microsoft-report-in-mvc-4.html ).
Anyone can help or provide me a website which have a simple tutorial of that by using the SQL select statement instead of LINQ ?

As far as returning the report from a WebForms page, what you have above is actually pretty close. You want to return the renderedBytes array through the Response object of your current Page context like:
protected void ReportPrint_Click(object sender, EventArgs e)
{
string id = "PDF"; // get this from another control on your page
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
// handle error condition
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
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>1in</MarginLeft>" +
" <MarginRight>1in</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);
Response.Clear(); // we're going to override the default page response
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=report." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
This will replace the normal page response with your report content.
As far as SQL vs Linq, the DataSource object that ReportViewer uses is the old-style System.Data.DataTable so just look for information on populating a DataTable from SQL.

Related

SMS application is not sending special characters asp.net mvc

I have an ASP.NET MVC application that sends SMS from the web, problem is it doesn't send some special characters such as ~!##$&, when I send something like &&&&, it doesn't send SMS, if I send something like dan&dan it will send the first dan and remove remaining character and word.
Hare is my code:
public ActionResult SendSms(SendBatch member)
{
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "mypassword";
string user = "username";
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" + "username=" + user + "&" + "password=" + pass + "&" + "message=" + mess + "&" + "msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
Hope someone can assist.
Because you use Get method to call SMS web service, illegal characters automatically removed from your SMS. You need to use HttpUtility.UrlEncode to encode characters before sending.
Thanks so much for the light, i manage to find a solution using HttpUtility.UrlEncode:
public ActionResult SendSms(SendBatch member)
{
StreamReader objReader;
WebClient client = new WebClient();
string mess = member.Message;
string cell = member.Cell;
string pass = "mypassword";
string user = "username";
string message = HttpUtility.UrlEncode(mess, System.Text.Encoding.GetEncoding("ISO-8859-1"));
string baseurl = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" + "username=" + user + "&" + "password=" + pass + "&" + "message=" + message + "&" + "msisdn=" + cell;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}

checkout.fi payment gateway implement (convert php code to asp.net with C#)

I am implementing checkout.fi payment gateway. I got the source code in php and java.I don't have any idea about php. That's why I want to convert Php source code to Asp.net code. Any Help Please
Below link given the sample code of PHP
https://checkoutfinland.github.io/#testing
and other sample java code link on github
https://github.com/AgiSol/checkout-java/
i have made code in asp.net but it is not working. For reference i have taking a Test Data. Below my code. This code run on button click event.
Code here
<pre><code>
protected void Button2_Click(object sender, EventArgs e){
string ver = "0001";
string stamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string amount = "1000";
string refer = "2432324";
string message = "hi";
string language = "FI";
string returnurl = "domain.com/return.aspx";
string cancelurl = "domain.com/cancel.aspx";
string reject = "2";
string delaye = "";
string country = "FIN";
string currency = "EUR";
string device = "10"; // 10 = XML
string content = "1";
string type = "0";
string algorithms = "3";
string delivery_date = "20171207";
string firstname = "Tarun";
string family = "Parmar";
string address = "Ääkköstie 5b3\nKulmaravintolan yläkerta";
string postcode = "33100";
string postoffice = "Tampere";
string MERCHANT="375917";
string SECRET_KEY= "SAIPPUAKAUPPIAS";
string macnew = encryptionMD5(ver, stamp, amount, refer, message, language,MERCHANT ,returnurl, cancelurl, reject,delaye, country,currency, device, content, type,algorithms, delivery_date, firstname,family, address, postcode,postoffice, SECRET_KEY).ToUpper();
string email = "support#checkout.fi";
string phone = "0800552010";
string status = "1";
string generatedMac = GetHashSha256(ver,stamp, refer, amount, status, algorithms, SECRET_KEY);
NameValueCollection collections = new NameValueCollection();
collections.Add("VERSION", ver);
collections.Add("STAMP", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
collections.Add("AMOUNT", amount);
collections.Add("REFERENCE", refer);
collections.Add("MESSAGE", message);
collections.Add("LANGUAGE", language);
collections.Add("RETURN", "domain.com/return.aspx");
collections.Add("CANCEL", "domain.com/cancel.aspx");
collections.Add("REJECT", reject);
collections.Add("DELAYED", delaye);
collections.Add("COUNTRY", country);
collections.Add("CURRENCY", currency);
collections.Add("DEVICE", device);
collections.Add("CONTENT", content);
collections.Add("TYPE", type);
collections.Add("ALGORITHM", algorithms);
collections.Add("DELIVERY_DATE", delivery_date);
collections.Add("FIRSTNAME", firstname);
collections.Add("FAMILYNAME", family);
collections.Add("ADDRESS",address);
collections.Add("POSTCODE", postcode);
collections.Add("POSTOFFIC", postoffice);
collections.Add("MAC", macnew);
collections.Add("EMAIL", email);
collections.Add("PHONE", phone);
collections.Add("MERCHANT",MERCHANT);
collections.Add("SECRET_KEY", SECRET_KEY);
string remoteUrl = "https://payment.checkout.fi";
string html = "<html><head>";
html += "</head><body onload='document.forms[0].submit()'>";
html += string.Format("<form name='PostForm' method='POST' action='{0}'>", remoteUrl);
foreach (string key in collections.Keys)
{
html += string.Format("<input name='{0}' type='text' value='{1}'>", key, collections[key]);
}
html += "</form></body></html>";
Response.Clear();
Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
Response.HeaderEncoding = Encoding.GetEncoding("ISO-8859-1");
Response.Charset = "ISO-8859-1";
Response.Write(html);
Response.End();
}
Function For encryptionMD5
public string encryptionMD5(String VERSION, String STAMP, String AMOUNT, String REFERENCEs, String MESSAGE, String LANGUAGE, String merchantId, String RETURN, String CANCEL, String REJECT, String DELAYED, String COUNTRY, String CURRENCY, String DEVICE, String CONTENT, String TYPE, String ALGORITHM, String DELIVERY_DATE, String FIRSTNAME, String FAMILYNAME, String ADDRESS, String POSTCODE, String POSTOFFICE, String PasswordID)
{
string passwords = VERSION + STAMP + AMOUNT + REFERENCEs + MESSAGE + LANGUAGE + merchantId + RETURN + CANCEL + REJECT + DELAYED + COUNTRY + CURRENCY + DEVICE + CONTENT + TYPE + ALGORITHM + DELIVERY_DATE + FIRSTNAME + FAMILYNAME + ADDRESS + POSTCODE + POSTOFFICE + PasswordID;
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] encrypt;
UTF8Encoding encode = new UTF8Encoding();
encrypt = md5.ComputeHash(encode.GetBytes(passwords));
StringBuilder encryptdata = new StringBuilder();
for (int i= 0; i<encrypt.Length; i++) {
encryptdata.Append(encrypt[i].ToString());
}
return encryptdata.ToString();
}
Function For GetHashSha256
<pre><code>
public string GetHashSha256(string VERSION,string STAMP, string REFERENCE,string PAYMENT, string STATUS, string ALGORITHM, string password)
{
string text = VERSION + STAMP + REFERENCE + PAYMENT + STATUS + ALGORITHM + password;
byte[] bytes = Encoding.ASCII.GetBytes(text);
SHA256Managed hashstring = new SHA256Managed();
byte[] hash = hashstring.ComputeHash(bytes);
string hashString = string.Empty;
foreach (byte x in hash)
{
hashString += String.Format("{0:x2}", x);
}
return hashString;
}
This above code give below error
Creating a Payment Transaction failed (-24).
Error in field: MAC
Thanks in Advance if anybody help in solving this problem.
Well, the Finland checkout payment gateway means that your MAC is not hashed correctly. I downloaded the java version from their github and it works perfectly. You are not generating the correct MD5 hash.
Quite a few problems in your code. First of all you must append + sign with each of the strings because they do same in Java. Second, you are assigning algorithms = "3". You should use algorithms = "2" for MD5. Third your encryptionMD5 doesn't returns correct hash.
Below is the correct implementation that I have done for you:
string ver = "0001";
string stamp = "kpjkq1510841290161";
string amount = "1490";
string refer = "12345";
string message = "My custom message";
string language = "FI";
string returnurl = "http://localhost/success";
string cancelurl = "http://localhost/cancel";
string reject = "http://localhost/rejected";
string delaye = "http://localhost/delayed";
string country = "FIN";
string currency = "EUR";
string device = "10"; // 10 = XML
string content = "1";
string type = "0";
string algorithms = "2";
string delivery_date = "20171123";
string firstname = "Tero";
string family = "Testaaja";
string address = "Mystreet 1";
string postcode = "12345";
string postoffice = "Tampere";
string MERCHANT = "375917";
string SECRET_KEY = "SAIPPUAKAUPPIAS";
using (MD5 md5Hash = MD5.Create())
{
string fromValue = String.Join("+", new string[] { ver, stamp, amount, refer, message, language, MERCHANT, returnurl, cancelurl, reject, delaye, country, currency, device, content, type, algorithms, delivery_date, firstname, family, address, postcode, postoffice, SECRET_KEY });
string macnew = GetMd5Hash(md5Hash, fromValue);
}
public string GetMd5Hash(MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
Output is c84e068fcab5c4dad93a29dd4c567b7f
Verified from finland checkout java github project.
And one tip is that you should use StringBuilder for appending text instead of concatenating with + sign for improved performance.

rdlc Report works in local but not on server

I have a report with some datasets, working perfectly in local, but on the server i get the error :
One or more parameters required to run the report have not been specified.
I don't have any parameters on this report, so i don't understand this error... I have this code in controller :
public ActionResult RunReport(int PremiseId)
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath("~/Views/Report/PremisePricing.rdlc");
Premise premise = _db.GetPremise(PremiseId);
ICollection<PremisePricing> premisePricings;
if (premise.PremiseMeters.Count() > 0)
{
premisePricings = premiseMeterPricingToPremisePricing(_db.FindAllPremiseMeteredPricing(premise).ToList());
}
else
{
premisePricings = _db.FindAllPremisePricing(PremiseId).ToList();
}
// Add your data source
List<ReportDataSource> listDS = new List<ReportDataSource>();
ICollection<Premise> premises = new List<Premise>();
premises.Add(premise);
ReportDataSource premiseDS = new ReportDataSource("Premise", premises);
listDS.Add(premiseDS);
ReportDataSource premisePricingDS = new ReportDataSource("PremisePricing", premisePricings);
listDS.Add(premisePricingDS);
ICollection<CompanyProvider> companyProviders = new List<CompanyProvider>();
CompanyProvider companyProvider = _db.GetCompanyProvider();
companyProviders.Add(companyProvider);
ReportDataSource companyProviderDS = new ReportDataSource("CompPro", companyProviders);
listDS.Add(companyProviderDS);
ICollection<CompanyProviderContactManager> companyProviderContactManager = new List<CompanyProviderContactManager>();
if (companyProvider.CompanyProviderContactManager != null)
{
companyProviderContactManager.Add(companyProvider.CompanyProviderContactManager);
}
ReportDataSource companyProviderContactManagerDS = new ReportDataSource("CompProContactManager", companyProviderContactManager);
listDS.Add(companyProviderContactManagerDS);
ICollection<Customer> customer = new List<Customer>();
if (_db.GetPremiseProviderByPremiseId(PremiseId) != null)
{
Customer cust = _db.GetPremiseProviderByPremiseId(PremiseId).Customer;
customer.Add(cust);
}
ReportDataSource customerDS = new ReportDataSource("Customer", customer);
listDS.Add(customerDS);
RenderReport(localReport, listDS, companyProvider.logo);
return View();
}
private void RenderReport(LocalReport localReport, List<ReportDataSource> listDS, byte[] logo)
{
foreach (ReportDataSource ds in listDS)
{
localReport.DataSources.Add(ds);
}
HttpContextBase imageDirectoryPath = HttpContext;
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</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;
//Render
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Write to the outputstream
//Set content-disposition to "attachment" so that user is prompted to take an action
//on the file (open or save)
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=Pricing." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
Any suggestion?

Insert SQL (Access) not working using webmethods Asp.net

I am trying to insert some fields into the local ms access database using webmethod(services) and website. I have tried looking up but cannot seem to spot where I've gone wrong. Can anyone tell me if I am doing it right. The code below does not add new data into the database nor does it direct me back to the page requested.
Services Webmethod:
[WebMethod]
public void AddNewPosts(string postUserName, string postTitle, DateTime postMessagepostDateTime, int subTopicId, string postMessage)
{
//Connection string for the datbase
string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/Forum.accdb;Persist Security Info=True";
OleDbConnection myConn = new OleDbConnection(database);
//Execute the query
string queryStr = "Insert into Posts (TopicId, PostTitle, PostUserName, PostDateTime) VALUES (" + subTopicId + ",'" + postTitle + "','" + postUserName + "'," + postMessagepostDateTime + ")";
// Create a command object
OleDbCommand myCommand = new OleDbCommand(queryStr, myConn);
// Open the connection
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
Calling the above method from my website:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//string postUserName = Page.User.Identity.Name;
string postUserName = "tom123";
string postTitle = txtTitle.Text;
string postMessage = txtMessage.Text;
DateTime postDateTime = DateTime.Now;
int subTopicId = int.Parse(Request.QueryString["id"]);
Service fs = new Service();
fs.AddNewPosts(postUserName, postTitle, postDateTime, subTopicId, postMessage);
//Redirect back to the SubTopic page
Response.Redirect("SubTopic.aspx?id=" + subTopicId.ToString());
}
Can you try with quotes around the date time
string queryStr = "Insert into Posts (TopicId, PostTitle, PostUserName, PostDateTime) VALUES (" + subTopicId + ",'" + postTitle + "','" + postUserName + "','" + postMessagepostDateTime + "')";

how to export a local report to a pdf and excel file?

I have two web pages, page1.aspx and page2.aspx. In page1, there is a button; in page2, there is a local report (rdlc). When I click the button, it will bring up page2, and exporting the report to a pdf and excel file. If the report is Crystal Report, in the page_load of page2, I can call the function ExportToDisk(ExportFormatType, FileName) to export the report to pdf/excel. But now I am using local report (rdlc), I wonder how do I export it to a pdf/excel.
http://weblogs.asp.net/rajbk/archive/2006/03/02/How-to-render-client-report-definition-files-_28002E00_rdlc_2900_-directly-to-the-Response-stream-without-preview.aspx
/// <summary>
/// References:
/// </summary>
private void RenderReport() {
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath("~/Report.rdlc");
//A method that returns a collection for our report
//Note: A report can have multiple data sources
List<Employee> employeeCollection = GetData();
//Give the collection a name (EmployeeCollection) so that we can reference it in our report designer
ReportDataSource reportDataSource = new ReportDataSource("EmployeeCollection", employeeCollection);
localReport.DataSources.Add(reportDataSource);
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
//http://msdn2.microsoft.com/en-us/library/ms155397.aspx
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render the report
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Clear the response stream and write the bytes to the outputstream
//Set content-disposition to "attachment" so that user is prompted to take an action
//on the file (open or save)
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=foo." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}

Resources