Report Output Export File Name Issue in CRM 4.0 - reporting-services

We have recently upgraded our CRM system from 3.0 to 4.0. Since then we are
having troubles with our reports.
Whenever we export the report to excel format, the file which is created in
CRM 4.0 has name as some "GUID".xls. Not just the name of the file, the sheet
contianing the output also has GUID as the name. This applies to other
formats also (output file name contains GUID).
I can save the rename the file as something else. But we have subscriptions
over most of our reports which sends out excel output of the report to a set
of ppl.
Instead of uploading the RDL from CRM 4.0, if i can upload the report to
some other SSRS folder and give a link, it will work. But we dont want to do
it.
Can anyone help me with this?
Thanks

Not sure, but it's possible to try create custom render extention for Excel. Change the Render method from article as it was proposed by this comment with the only difference - use excel format:
public bool Render(Report report,
NameValueCollection reportServerParameters,
NameValueCollection deviceInfo, NameValueCollection clientCapabilities,
EvaluateHeaderFooterExpressions evaluateHeaderFooterExpressions,
CreateAndRegisterStream createAndRegisterStream)
{
string strUri = string.Empty;
strUri +=
"http://localhost/Reports/Reserved.ReportViewerWebControl.axd";
strUri += "?ReportSession=" + reportServerParameters["SessionID"];
// Here you can check the name of report provided to viewer for export.
// If it's incorrect, you may extend method to set the right name.
strUri += "&FileName=" + report.Name;
strUri += "&ControlId=" + Guid.Empty;
strUri += "&Culture=" +
CultureInfo.CurrentCulture.LCID.ToString(
CultureInfo.InvariantCulture);
strUri += "&UICulture=" +
CultureInfo.CurrentUICulture.LCID.ToString(
CultureInfo.InvariantCulture);
strUri += "&ReportStack=1";
strUri += "&OpType=Export";
strUri += "&ContentDisposition=OnlyHtmlInline";
strUri += "&Format=MHTML";
Stream outputStream = null;
StreamWriter streamWriter = null;
try
{
//Output to Excel
outputStream = createAndRegisterStream(report.Name, "xls",
System.Text.Encoding.UTF8,
"application/vnd.ms-excel", true, StreamOper.CreateAndRegister);
streamWriter = new StreamWriter(outputStream);
//Input
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUri);
//Credentials
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
//Output
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Input
Stream inputStream = response.GetResponseStream();
StreamReader streamReader =
new StreamReader(response.GetResponseStream());
//Read/Write
streamWriter.Write(streamReader.ReadToEnd());
}
finally
{
if (streamWriter != null)
{
streamWriter.Flush();
}
}
return false;
}
You may add this renderer as a new custom extention (you will have to change subscription format then) or replace existing excel extention - see Specifying Rendering Extension Parameters in Configuration Files

Related

Uploading File using Windows.Web.Http.HttpClient - WinRT 8.1 PCL

I have a requirement of uploadng the file to Server in Win8.1 PCL project.
Windows.Web.Http.HttpClient.
I tried in Advanced Rest Client and it works fine
PFA # http://i.stack.imgur.com/N8cv5.png
I have the Code like this.
Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri);
HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());
streamContent.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
streamContent.Headers.Add("Content-Length", stream.Length.ToString());
streamContent.Headers.Add("Content-Disposition", "form-data; name=\"" + flKey + "\"; filename=\"" + fleNm + "\"");
request.Content = streamContent;
var httpClient = new Windows.Web.Http.HttpClient();
var cts = new CancellationTokenSource();
Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token);
String resp = response.Content.ToString();
This is not working. Pls le me know whats wrong with the Code, why this code is not able to write the file to the server.
Thanks in Advance

Change Report Name On PDF when exporting from report viewer

I have a working report, but I'd like to change the report name. By default it uses the RDL filename. I'd like to set different name for the downloaded files.
Is there a way to generate the file name for reports downloaded from SSRS dynamically?
Please try using DisplayName Property of ReportViewer
ReportViewer.ServerReport.DisplayName = <Your Parameter Value>;
ReportViewer.LocalReport.DisplayName = <Your Parameter Value>;
If you're using a data driven subscription you can set the report name dynamically with SQL.
Otherwise there is no way to do this within SSRS. You could always use an external script to rename the PDF for you after export but it isn't completely automatic.
You can also do this using a Javascript hook. There's a tutorial here which got me started but didn't fully work for me.
What I ended up doing was adding some javascript to ReportViewer.aspx in <sql server folder>\ReportServer\Pages\, in a script tag at the end of the <body>. The checks against the URL ensure that it only affects reports it is supposed to change the name on.
This works fine with spaces and other special characters (as long as they're allowed in a file name).
function modifyExportFileName() {
/* Change the name of file exports */
var filename = false;
if (window.location.href.indexOf('Folder/Report') !== -1) { //it's the report we want
filename = getParameter('parameter'); // returns false if not set
// should also have access to report DOM here, also Date(), etc.
} // could add more here as needed in else if blocks
if (filename) { // we have a filename set.
console.log('changing filename of exported reports to ' + filename);
changeFilename(filename);
}
}
function getParameter(param) {
//case sensitive parameter extractor.
var l = window.location.href;
if (l.indexOf(param + '=' > -1)) {
var param_location = l.indexOf(param + '=') + (param + '=').length;
return l.substring(param_location, l.indexOf('&', param_location + 1));
}
return false;
}
function changeFilename(filename) {
var r = null,
url = null;
try {
r = this.$find('ReportViewerControl')._getInternalViewer();
} catch(e) {
setTimeout(function () {changeFilename(filename)}, 1000); //maybe we're not done loading.
console.log("trying again");
return false;
}
url = r.ExportUrlBase;
if (url) {
var i = url.indexOf('FileName='),
j = url.indexOf('&', i+1);
r.ExportUrlBase = url.substring(0, i) + 'FileName=' + filename + url.substring(j);
console.log('reset filename to ' + filename);
}
}
modifyExportFileName();
Edit: I noticed that this code didn't run in IE on the corporate network. The reason is the console.logs. Comment them out if your site is running in IE Compatibility mode, as IE5 didn't have a console.

asp.net/HTML file upload control not uploading mutiple files as expected

I am using asp.net file control. I am uploading multiple files. The problem is when I select two or multiple files, it's only upload one file multiple times. I mean if I select two different images, It will upload the first image two times. And if I select three images, then it will upload first image three times.
My file upload control is following,
<asp:FileUpload runat="server" ID="file" multiple />
And I server side code is following
protected void click(object sender, EventArgs e) {
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = file.ContentLength;
string fileName = Request.Headers["X-File-Name"];
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
// IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory
string savedFileName = Path.Combine(#"D:\Temp\", Guid.NewGuid().ToString() + ".jpg");
file.SaveAs(savedFileName);
}
}
I have no idea why this is behaving this way. When I debug the server side code, it's giving me different names of files from "Request.Headers["X-File-Name"]" but somehow it's uploading same content (the first image from the multiple images that I try to upload)
You can get posted files from file upload control if you are using ASP.NET > 4.0 like this
foreach (HttpPostedFile f in file.PostedFiles)
{
//HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = f.ContentLength;
string fileName = f.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
// IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory
string savedFileName = Path.Combine(#"D:\Temp\", Guid.NewGuid().ToString() + ".jpg");
f.SaveAs(savedFileName);
}
With ASP.NET 4.0 or less aslo available in 4.0 and above
HttpFileCollection fc = Request.Files;
for (int i = 0; i < fc.Count; i++)
{
HttpPostedFile f = fc[i];
int fileSizeInBytes = f.ContentLength;
string fileName = f.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
// IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory
string savedFileName = Path.Combine(#"D:\Temp\", Guid.NewGuid().ToString() + ".jpg");
f.SaveAs(savedFileName);
}

PDFTron Convert from HTML to PDF on WinRT

I'm writing a Windows 8 Store App using WinJS. My app needs to generate PDFs with text and graphs. I was under the impression that PDFtron could convert HTML to PDF, but that does not seem to be the case for an App Store application. Is this true?
The front end uses WinJS/HTML and Telerik Radcharts to render graphs in SVG. I then pipe the DOM down to disk as an HTML file. It shows the graph and numbers nicely. I want to convert the HTML to a PDF to preserve the styling as well as the content.
The WinRT version does not come with the HTML2PDF assembly or the .Convert() method. Is it somewhere else? I've searched the docs, samples, and the web.
PDFTron's PDFNet SDK on WinRT does not support HTML to PDF conversion (as at version 6.2).
Here is the response I received from PDFTron support on this question:
While the PDFNet SDK on WinRT cannot itself convert from HTML
to PDF, the PDFNet SDK on Windows desktop can do so. You can find
sample code for for HTML to PDF conversion at
http://www.pdftron.com/pdfnet/samplecode.html#HTML2PDF.
Some of our clients send HTML to a server of theirs, where
PDFNet can convert the HTML to PDF. Note that on Windows
desktop there are many conversion options, including converting Office
to PDF and converting any printable document format to PDF.
EVO has implemented the following solution to convert HTML to PDF in WinRT and Windows Store Applications. You can find a compelte code sample in that page.
The copy of the code sample is:
private async void buttonConvertUrlToPdf_Click(object sender, RoutedEventArgs e)
{
// If another conversion is in progress then ignore current request
bool ignoreRequest = false;
lock(pendingConversionSync)
{
if (pendingConversion)
ignoreRequest = true;
else
{
msgUrlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Visible;
pendingConversion = true;
}
}
if (ignoreRequest)
return;
try
{
String serverIP = textBoxServerIP.Text;
uint port = uint.Parse(textBoxServerPort.Text);
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, port);
// set service password if necessary
if (textBoxServicePassword.Text.Length > 0)
htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text;
// set HTML viewer width
htmlToPdfConverter.HtmlViewerWidth = int.Parse(textBoxHtmlViewerWidth.Text);
// set HTML viewer height if necessary
if (textBoxHtmlViewerHeight.Text.Length > 0)
htmlToPdfConverter.HtmlViewerHeight = int.Parse(textBoxHtmlViewerHeight.Text);
// set navigation timeout
htmlToPdfConverter.NavigationTimeout = int.Parse(textBoxHtmlViewerWidth.Text);
// set conversion delay if necessary
if (textBoxConversionDelay.Text.Length > 0)
htmlToPdfConverter.ConversionDelay = int.Parse(textBoxConversionDelay.Text);
// set PDF page size
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize();
// set PDF page orientation
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation();
// set margins
htmlToPdfConverter.PdfDocumentOptions.LeftMargin = int.Parse(textBoxLeftMargin.Text);
htmlToPdfConverter.PdfDocumentOptions.RightMargin = int.Parse(textBoxRightMargin.Text);
htmlToPdfConverter.PdfDocumentOptions.TopMargin = int.Parse(textBoxTopMargin.Text);
htmlToPdfConverter.PdfDocumentOptions.BottomMargin = int.Parse(textBoxBottomMargin.Text);
// add header
if (checkBoxAddHeader.IsChecked != null && (bool)checkBoxAddHeader.IsChecked)
{
htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true;
DrawHeader(htmlToPdfConverter, true);
}
// add footer
if (checkBoxAddFooter.IsChecked != null && (bool)checkBoxAddFooter.IsChecked)
{
htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true;
DrawFooter(htmlToPdfConverter, true, true);
}
string urlToConvert = textBoxUrl.Text;
string errorMessage = null;
// Convert the HTML page from give URL to PDF in a buffer
byte[] pdfBytes = await Task.Run<byte[]>(() =>
{
byte[] resultBytes = null;
try
{
resultBytes = htmlToPdfConverter.ConvertUrl(urlToConvert);
}
catch (Exception ex)
{
errorMessage = String.Format("Conversion failed. {0}", ex.Message);
return null;
}
return resultBytes;
});
if (pdfBytes == null)
{
MessageDialog errorMessageDialog = new MessageDialog(errorMessage, "Conversion failed");
await errorMessageDialog.ShowAsync();
return;
}
// Save the PDF in a file
Windows.Storage.StorageFolder installedLocation = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile outStorageFile = installedLocation.CreateFileAsync("EvoHtmlToPdf.pdf", CreationCollisionOption.ReplaceExisting).AsTask().Result;
FileIO.WriteBytesAsync(outStorageFile, pdfBytes).AsTask().Wait();
// Open the file in a PDF viewer
await Windows.System.Launcher.LaunchFileAsync(outStorageFile);
}
finally
{
lock (pendingConversionSync)
{
msgUrlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
pendingConversion = false;
}
}
}

Get a uri from a LocalStorage in Windows Phone

I write the following code to save some images from internet:
public static async Task SaveImage(string name, string uri)
{
var localfolder = ApplicationData.Current.LocalFolder;
var client = new HttpClient();
var imageStream = await client.GetStreamAsync(uri); //Secuencia de bytes
var storageFile = await localfolder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await imageStream.CopyToAsync(outputStream);
}
}
My problem is when I try to set these images store in the Local Storage to a CycleTile because this class needs the Uri's, and I don't know how to provide the uri here. This is what I have:
CycleTileData cycleicon = new CycleTileData();
cycleicon.Title = "Fotopantalla";
cycleicon.Count = 0;
cycleicon.SmallBackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileSmall.png", UriKind.RelativeOrAbsolute);
List<Uri> images = new List<Uri>();
for (int i = 0; i < 9; i++)
{
/// tries...
string path1 = "ms-appdata:///local/image" + i + ".jpg";
string path2 = "isostore:/Shared/ShellContent/image" + i + ".jpg";
string path3 = "ms-appdata:///Local/Shared/ShellContent/image" + i + ".jpg";
///
Uri uri = new Uri(path2, UriKind.RelativeOrAbsolute);
images.Add(uri);
}
cycleicon.CycleImages = images;
What am I wrong or what am I missing?
For any ShellTileData related data structures you have to use path2:
"isostore:/Shared/ShellContent/*" if the images are not in the (read only) InstalledLocation folder.
For more details see: http://blogs.msdn.com/b/andy_wigley/archive/2013/04/10/live-apps-creating-custom-tile-and-lock-screen-images.aspx
I have something similar in my code:
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (!store.DirectoryExists("Shared/ShellContent"))
{
store.CreateDirectory("Shared/ShellContent");
}
StorageFolder shellContent = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("Shared", CreationCollisionOption.OpenIfExists);
shellContent = await shellContent.CreateFolderAsync("ShellContent", CreationCollisionOption.OpenIfExists);
Stream imgin = picture.GetImage();
//Picture read stream from Media Library or other input stream
StorageFile new_img = await shellContent.CreateFileAsync(newPictureName);
Stream imgout = await new_img.OpenStreamForWriteAsync();
imgin.CopyTo(imgout);
imgout.Close(); // <- necessary in your code or not?
imgin.Close(); // <-
I'm not sure, whether you really need the Isostore thing at the beginning, but it works, if I haven't done some stupid mistake while shortening the code. ;-)
Also have a look at "StandardTileData.BackgroundImage Property", "Data for Windows Phone" and "How to use the Isolated Storage Explorer tool for Windows Phone" from Microsoft's Dev Center. (The last one is about how to have a look at the saved image file on your device.)