ASP.NET MVC IFrame webform CrystalReportViewer - c#

This issue has been bugging me for a few hours. I have an MVC View(Report.cshtml) with an iframe in it. I set the src of the iframe dynamically by passing in the model.
I have a webform(ReportViewer.aspx) which has a crystalreportviewer in it. I pass in the the reportname and parameters as part of query string to this webform.
ControllerCode:
[HttpPost]
[Authorize]
public ActionResult ViewReport(ReportInfoViewModel _model)
{
string _parameterList = "";
ReportViewerViewModel _rptObj = new ReportViewerViewModel();
string[] _selected = {"0021", "2000", "0387"};
string subParam = "plazaparam=";
subParam += String.Join(",", _selected);
_parameterList = string.Concat(_parameterList, "#usrplazaparam=", String.Join(",", _selected));
string _reportSubPath = _model.report_path.Replace("\\", "/");
string _reportPath = string.Concat("~/Content/Reports", _reportSubPath.Trim());
string content = Url.Content(string.Format("~/CrystalReports/ReportViewer/ReportViewerForm.aspx?ReportName={0}&Parameters={1}", _reportPath, _parameterList));
_rptObj.ReportViewerPath = content;
return View("Report", _rptObj);
}
Report.cshtml:
#{
ViewBag.Title = "Report";
Layout = "~/Views/Shared/_rootLayout.cshtml";
}
#model CSC.ViewModels.ReportViewerViewModel
<iframe src="#Model.ReportViewerPath" style="width:100%; height:100%; border:none;"></iframe>
ReportViewer.aspx:
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Views/Shared/ReportSite.Master" CodeBehind="ReportViewerForm.aspx.cs" Inherits="CSC.CrystalReports.ReportViewer.ReportViewerForm" %>
<%# Register Assembly="CrystalDecisions.Web, Version=13.0.3500.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" Namespace="CrystalDecisions.Web" TagPrefix="CR" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" HasCrystalLogo="False" AutoDataBind ="false" Height="100%" EnableParameterPrompt="false" EnableDatabaseLogonPrompt="false" ToolPanelWidth="200px"
Width="100%" ToolPanelView="None"/>
</asp:Content>
ReportViewer.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ReportDocument"] != null)
{
//ClientScript.RegisterStartupScript(this.GetType(), "IF", "alert('" + "Session Varialbe != null" + "');", true);
ReportDocument doc = (ReportDocument)Session["ReportDocument"];
CrystalReportViewer1.ReportSource = null;
CrystalReportViewer1.ReportSource = doc;
}
else
{
string reportPath = Request.QueryString["ReportName"];
string parameters = Request.QueryString["Parameters"];
this.objReport = null;
Session.Remove("ReportDocument");
this.objReport = new ReportDocument();
//ClientScript.RegisterStartupScript(this.GetType(), "Parameters", "alert('" + parameters + "');", true);
LoadReport(reportPath, parameters);
}
}
On Index.cshtml's page submit to ReportsController's ViewReport action, I pass in a dynamically constructed query string "ReportViewer.aspx?ReportName={reportName}&Parameters={parameterString}" to the iframe's src. This code should dynamically load the report specified in the query string dynamically(crystalreportviewer) and show the page. What is happening is that the same report is being loaded and displayed in the new page. I am not sure what I am doing wrong.
I would appreciate if somebody could point me in the right direction.
Thank you for your help
NH

Related

Add Dynamic control directly on aspx page not from backend code

I want the checkbox control to be added dynamically with different id's in different th tags generating in a loop
<table border="1">
<thead>
<%string j = " Check"; %>
<%for (int i = 0; i < 10;i++ )
{%>
<th style="padding:2px; width:500px;">Table Head<br /><br />
<%
CheckBox chk = new CheckBox();
chk.ID = i + j;
chk.Text = "I am " + i + j;
%>
//I want this checkbox to be added dynamically here with different id's in different th tags generating in a loop
<asp:CheckBox runat="server" ID="<%=i+j%>"/>
</th>
<%} %>
</thead>
</table>
the way to do this is to create yourself a server-control with all the parameters you need, creating the controls in the OnInit, and rendering html in the RenderControl, and accessing the controls from public props like this:
public class DynamicCbs : Control
{
public int CtrlsCount { get; set; }
public List<CheckBox> lstCheckBoxs;
/// decleration of controls must be in the OnInit since the next stage of the page life cycle is to connect whatever came back from the client to the server
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
lstCheckBoxs = new List<CheckBox>();
for (int i = 0; i < CtrlsCount; i++)
{
string id = "DynamicCbs" + i;
CheckBox cbx = new CheckBox()
{
ID = id,
Text = "i am " + id
};
lstCheckBoxs.Add(cbx);
//add controls to control tree
this.Controls.Add(cbx);
}
}
/// here you must build ur html
public override void RenderControl(HtmlTextWriter writer)
{
writer.RenderBeginTag(HtmlTextWriterTag.Table);
writer.RenderBeginTag(HtmlTextWriterTag.Thead);
foreach (var cbx in lstCheckBoxs)
{
writer.RenderBeginTag(HtmlTextWriterTag.Th);
cbx.RenderControl(writer);
writer.RenderEndTag();
}
writer.RenderEndTag();//thead
writer.RenderEndTag();//table
}
}
full example
ok I found the solution. I have use asp:Table control to solve this problem
My aspx page code is :
<asp:Table ID="ObjectwiseTable2" runat="server"
CssClass="AccessTable" BorderColor="Black" width="100%">
</asp:Table>
My .cs page code to Add content and dynamic content in the table is :
TableHeaderRow thead = new TableHeaderRow();
TableHeaderCell th = new TableHeaderCell();
th.Controls.Add(new LiteralControl("Object Wise Detail(s)"));
th.RowSpan = 2;
thead.Cells.Add(th);
int totalUsers = accesswiseDt.Rows.Count;
for (int User = 0; User < totalUsers; User++)
{
TableHeaderCell th2 = new TableHeaderCell();
th2.Controls.Add(new LiteralControl(accesswiseDt.Rows[User]["users"].ToString()));
IsReviewPending = view_access.IsWaitingForViewAccess(ApplicationTree.SelectedNode.Value, Session["empCode"].ToString(), accesswiseDt.Rows[User]["empcode"].ToString());
if (IsReviewPending)
{
th2.Controls.Add(new LiteralControl("<br />"));
CanReviewAccess = true;
//Code for Adding Dynamic control in specific cell of the table
CheckBox chk = new CheckBox();
chk.ID = ApplicationTree.SelectedNode.Value + "_" + accesswiseDt.Rows[User]["empcode"].ToString();
chk.Text = "Access Reviewed";
th2.Controls.Add(chk);
}
thead.Cells.Add(th2);
}

Upload, rename and display the image with Ajax asyncfileupload - ASP.NET

I want to upload the image to web server file and get the path and save it to database.
HTML and Javascript
<img id="imgDisplay" alt="" src="" style="display: none" class="img-thumbnail" />
<ajaxToolkit:AsyncFileUpload OnClientUploadComplete="uploadComplete" runat="server"
ID="AsyncFileUpload1" UploaderStyle="Traditional" CompleteBackColor="White" UploadingBackColor="#CCFFFF"
ThrobberID="imgLoader" OnUploadedComplete="FileUploadComplete" OnClientUploadStarted="uploadStarted" />
<asp:Image ID="imgLoader" runat="server" ImageUrl="~/Images/loader2.gif"
Height="21px" Width="23px" />
<script type="text/javascript">
function uploadStarted() {
$get("imgDisplay").style.display = "none";
}
function uploadComplete(sender, args) {
var imgDisplay = $get("imgDisplay");
imgDisplay.src = "images/loader.gif";
imgDisplay.style.cssText = "";
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:240px;width:240px";
imgDisplay.src = img.src;
};
img.src = "<%=ResolveUrl(UploadFolderPath) %>" + args.get_fileName();
}
</script>
C# code behind, event file upload complete
protected string UploadFolderPath = "~/Images/";
protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + filename);
}
With code above, I success to do it... But the problem become when I want to rename the file with GUID, the image not appear after upload.
C# code behind
protected string UploadFolderPath = "~/Images/";
protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string fileext = System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
string file_id = Guid.NewGuid().ToString();
AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + file_id + fileext);
}
I realize in the javascript, it will refer to agrs from file upload control. So that means it cannot refer the new file name.
Javascript
img.src = "<%=ResolveUrl(UploadFolderPath) %>" + args.get_fileName();
So I google to find how to paste a value from code behind to javascript. And I found it. Then modified my behind code something like this
protected string UploadFolderPath = "~/Images/";
protected string image = "";
protected void FileUploadComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string fileext = System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
string file_id = Guid.NewGuid().ToString();
AsyncFileUpload1.SaveAs(Server.MapPath(this.UploadFolderPath) + file_id + fileext);
image = this.ResolveUrl(this.UploadFolderPath) + file_id + filename;
}
And the javascript
<script type="text/javascript">
function uploadStarted() {
$get("imgDisplay").style.display = "none";
}
function uploadComplete(sender, args) {
var imgDisplay = $get("imgDisplay");
imgDisplay.src = "images/loader.gif";
imgDisplay.style.cssText = "";
var img = new Image();
img.onload = function () {
imgDisplay.style.cssText = "height:240px;width:240px";
imgDisplay.src = img.src;
};
img.src = "<%=ResolveUrl(image) %>";
}
</script>
Still not appear because the image variable not have a value inside it. How to solved this?
Sorry for my bad english
Nothing issue with your codes, the only problem i see is that since you edited the path you must revert it back to the original values if you retrieve it unless no image will show.
aspx code for fileupload
<ajax:asyncfileupload id="Asyncfileupload1" onclientuploadcomplete="uploadComplete1"
width="350px" runat="server" uploaderstyle="Traditional"
throbberid="Image6" onuploadedcomplete="Asyncfileupload1_UploadedComplete" />
javascript function
function uploadComplete1()
{
window.location = window.location.href;
}
aspx.cs code
protected void Asyncfileupload1_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
string name = Asyncfileupload1.FileName;
string[] spi = name.Split('.');
int len = spi.Length;
string type = spi[len - 1];
if (type == "apk" || type == "ipa")
{
if (Asyncfileupload1.PostedFile.ContentLength > 10)
{
string filename = System.IO.Path.GetFileName(Asyncfileupload1.FileName);
string ext = Path.GetExtension(filename);
string newfilename = Path.GetRandomFileName();
newfilename += ext;
Asyncfileupload1.SaveAs(Server.MapPath("~/product_application/") + newfilename);
MobileStoreEntities mse = new MobileStoreEntities();
ProductMast um = new ProductMast();
int loginid = Utility.login_id();
um = mse.ProductMasts.Where(i => i.ProductID == proid).FirstOrDefault();
um.ApplicationFile = "~/product_application/" + newfilename;
int check1 = mse.SaveChanges();
lblDoc.Text = "Old file is available. Want to change? Then Upload";
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "TestAlert", "alert('" + "Size problem." + "');", true);
}
//Response.Redirect("ProductFileUpload.aspx?proid="+HttpUtility.UrlEncode(enc));
//Response.Redirect("ProductFileUpload.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "TestAlert", "alert('" + "Must upload doc, docx or pdf file." + "');", true);
}
}

Crystal report viewer not display after publish

i have a problem with crystal report when i publish my website crystal report viewer not show
report, Show blank page how to fix it..?
Please help me..
on button click code
protected void btnShowReport_Click(object sender, EventArgs e)
{
try
{
clsFunctions objFunc = new clsFunctions();
CrystalReportViewer1.Visible = true;
report.FileName = Server.MapPath(#"~/reports/NoteBalanceSheetRepot.rpt");
string server = WebConfigurationManager.AppSettings["ReportServer"];
string user = WebConfigurationManager.AppSettings["ReportUserID"];
string password = WebConfigurationManager.AppSettings["ReportUserPwd"];
string database = WebConfigurationManager.AppSettings["ReportDatabase"];
report.SetDatabaseLogon(user, password, server, database);
string strSelection = "1=1 ";
string strTitle = WebConfigurationManager.AppSettings["CompanyName"].ToString();
string strTitle1 = WebConfigurationManager.AppSettings["AppName"].ToString();
string SelectedDate = ClosingYear.Text.Replace("-","/");
string ClosingDate = SelectedDate.Insert(3, "0");
string NextYear = DateTime.ParseExact(ClosingDate.ToString(), "mm/dd/yyyy", null).ToString("dd/mm/yyyy");
string previousYear = DateTime.ParseExact(ClosingDate.ToString(), "mm/dd/yyyy", null).ToString("dd/mm/yyyy");
string[] getsp = previousYear.Split('/');
string dd= getsp[0].ToString().Replace(getsp[0],"07");
string mm = getsp[1].ToString().Replace(getsp[1], "01");
int yyyy = Convert.ToInt32(getsp[2]) - 1;
string Final = mm + "/" + dd + "/" + yyyy;
report.SetParameterValue("CompanyName", strTitle);
report.SetParameterValue("AppName", strTitle1);
report.SetParameterValue("NYear", getsp[2]);
report.SetParameterValue("PYear", yyyy);
report.SetParameterValue("nextYear",NextYear );
report.SetParameterValue("previousYear", Final);
objECls.FileName = "~/reports/NoteBalanceSheetRepot.rpt";
objECls.SelectionFormula = strSelection;
clsFunctions.SaveEntity(ViewState, objECls);
CrystalReportViewer1.ReportSource = report;
}
catch (BusinessLogic.CustomException ex1)
{
(new clsFunctions()).SetMessage(ex1.Message, Master);
}
catch (Exception ex)
{
}
}
.aspx code
<td>
<asp:Button ID="btnShowReport" runat="server" Text="Preview" OnClick="btnShowReport_Click"/>
</td></tr>
<tr>
<td colspan="4">
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
AutoDataBind="true" Visible="false"
ReportSourceID="CrystalReportSource1" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server" >
<Report FileName="reports\NoteBalanceSheetRepot.rpt">
</Report>
</CR:CrystalReportSource>

Why code behind C# button_clicked function doesn't call Javascript function?

I want to test the C# code side when user click the button, the method in C# function should be able to call the JavaScript function to show alert C# public variable results. Somehow it doesn't call anything at all. At the bottom of ButtonRequest_Click function, I wrote Page.ClientScript.RegisterStartupScript(this.GetType(), "CreateIsm();", "CreateIsm();", true); to call CreateIsm(); function in JavaScript. Maybe this doesn't work?
Here is C# codes,
public Collection<PSObject> output = new Collection<PSObject>();
public string deviceName = "";
public string ipAddresses = "";
public string YourScript = "";
protected void ButtonRequest_Click(object sender, EventArgs e)
{
deviceName = string.Empty;
ipAddresses = string.Empty;
HiddenName.Visible = false;
string str = "";
string ipAddress = "";
string name = "";
var tbids = (List<string>)Session["tbids"];
//create a powershell
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
RunspaceInvoke invoke = new RunspaceInvoke();
Pipeline pipeline = runSpace.CreatePipeline();
Command invokeScript = new Command("Invoke-Command");
//Add powershell script file and arguments into scriptblock
ScriptBlock sb = invoke.Invoke(#"{D:\Scripts\Get-FreeAddress.ps1 '" + DropDownListContainer.SelectedValue + "' " + DropDownListIP.SelectedValue + "}")[0].BaseObject as ScriptBlock;
invokeScript.Parameters.Add("scriptBlock", sb);
invokeScript.Parameters.Add("computername", TextBoxServer.Text);
pipeline.Commands.Add(invokeScript);
Collection<PSObject> output = pipeline.Invoke();
runSpace.Close();
Runspace runSpace2 = RunspaceFactory.CreateRunspace();
runSpace2.Open();
foreach(PSObject psObject in output)
{
ipAddress = "" + psObject;
ipAddresses += "" + psObject;
foreach(var id in tbids)
try
{
name = Request[id];
deviceName += Request[id] + "\r\n";
Pipeline pipeline2 = runSpace2.CreatePipeline();
Command invokeScript2 = new Command("Invoke-Command");
//Add powershell script file and arguments into scriptblock
ScriptBlock sb2 = invoke.Invoke(#"{D:\Scripts\Set-IPAddress.ps1 " + ipAddress + " " + name + "}")[0].BaseObject as ScriptBlock;
invokeScript2.Parameters.Add("scriptBlock", sb2);
invokeScript2.Parameters.Add("computername", TextBoxServer.Text);
pipeline2.Commands.Add(invokeScript2);
tbids.RemoveAt(0);
Collection<PSObject> output2 = pipeline2.Invoke();
foreach(PSObject psObject2 in output2)
{
str = str + psObject2;
}
break;
}
catch
{
}
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "CreateIsm();", "CreateIsm();", true);
}
Javascript on aspx side in html,
<%# Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" CodeBehind="~/Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js" type="text/javascript"></script>
<script>
CreateIsm = function (funct) {
alert('<%=ipAddresses%>');
alert('<%=deviceName%>');
};
</script>
</head>
<body>
<form id="form1" runat="server">
//the are html codes here but I cut it off except ButtonRequest
<asp:Button ID="ButtonRequest" runat="server" Text="Request" Visible="False"
onclick="ButtonRequest_Click" />
</form>
</body>
</html>
Read this: http://msdn.microsoft.com/en-us/library/3hc29e2a(v=vs.100).ASPX
You can use OnClientClick like this:
<asp:button id="Button1" runat="server" OnClientClick="return confirm('Ok to post?')" onclick="Button1_Click" Text="Click!" />

Web User Control Postback Issue with Treeview

I am trying to build a website that has a custom File Explorer. Eventually I hope to build it out further and allow uploads, but I'm facing an issue calling it from the code behind.
My user control contains a Treeview, and if call it like this:
<fe:FileExplorer filePath="/Resources/" runat="server"></fe:FileExplorer>
everything works fine, but when I call it from the code behind like this:
FileExplorer uc = (FileExplorer)LoadControl("~/Controls/FileExplorer.ascx");
uc.filePath = "/Uploads/Newsletter/";
PAGECONTROLS.Controls.Add(uc);
I have an issue with the Post back.
The issue appears to be when I'm getting the selected node. It grabs the selected node when I use the .Net inline, but when I use the code behind it seems to loose the post back:
TreeNode nd = FolderTree.SelectedNode; <-- Always Null when called in code behind.
Below is the Code Behind:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Troop_101.Controls
{
public partial class FileExplorer : System.Web.UI.UserControl
{
public string FilePath;
public string filePath{
set { FilePath = value; }
get { return FilePath; }
}
protected void Page_Load(object sender, EventArgs e)
{
string RootFilePath = Server.MapPath(FilePath);
if (!IsPostBack)
{
DirectoryInfo rootDir = new DirectoryInfo(RootFilePath);
TreeNode rootNode = new TreeNode(rootDir.Name, rootDir.FullName);
FolderTree.Nodes.Add(rootNode);
TraverseTree(rootDir, rootNode);
FolderTree.CollapseAll();
}
string ReturnStr = "";
TreeNode nd = FolderTree.SelectedNode;
if (nd != null)
{
ReturnStr = getFolderContent(nd.Value);
}
else
{
ReturnStr = getFolderContent(RootFilePath);
}
RESOURCE_FolderContent.InnerHtml = ReturnStr;
foreach (TreeNode tn in FolderTree.Nodes)
{
tn.Expand();
}
}
private void TraverseTree(DirectoryInfo currentDir, TreeNode currentNode)
{
foreach (DirectoryInfo dir in currentDir.GetDirectories())
{
TreeNode node = new TreeNode(dir.Name, dir.FullName);
currentNode.ChildNodes.Add(node);
TraverseTree(dir, node);
}
}
private string getFolderContent(string filePath)
{
string ReplacePath = Server.MapPath(FilePath);
var info = new DirectoryInfo(filePath);
var fileInfo = info.GetFiles();
string LinkTemplate = "<table><tr><td><img src=\"{1}\" height=\"25px\"></td><td style=\"vertical-align:center;\">{2}</td></tr></table>";
string ReturnFiles = "";
if (fileInfo.Length <= 0)
{
ReturnFiles = "No Files In Folder<br />";
}
foreach (FileInfo file in fileInfo)
{
string FileExt = file.Extension.ToLower().Replace(".", "");
if (!File.Exists(HttpContext.Current.Server.MapPath("/images/ExtensionIcons/" + FileExt + ".png")))
FileExt = "_blank";
string fir = filePath.Replace(ReplacePath, "");
ReturnFiles += String.Format(LinkTemplate, FilePath + fir + "/" + file.Name, "/images/ExtensionIcons/" + FileExt + ".png", file.Name);
}
return ReturnFiles;
}
}
}
And here is the .NET
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="FileExplorer.ascx.cs" Inherits="Troop_101.Controls.FileExplorer" %>
<div style="width:90%; border:thick solid #656565;margin:0 auto; background-color:#ffffff; padding:5px;" class="tableroundcorners">
<style type="text/css">
.node_left {
padding:5px;
}
</style>
<table style="width:100%;height:350px;">
<tr>
<td id="RESOURCE_FileTree" runat="server" style="width:150px;border-right:solid #757575 thin;overflow:auto;">
<asp:TreeView ID="FolderTree" runat="server" NodeIndent="15" ShowLines="True" LineImagesFolder="~/Controls/FileExplorerTree">
<HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
<NodeStyle Font-Names="Tahoma" Font-Size="8pt" Width="100%" CssClass="node_left" ForeColor="Black" HorizontalPadding="0px" NodeSpacing="0px" VerticalPadding="2px" />
<ParentNodeStyle Font-Bold="False" />
<SelectedNodeStyle Font-Underline="true" HorizontalPadding="0px" VerticalPadding="0px" BackColor="#cccccc" />
</asp:TreeView>
</td>
<td id="RESOURCE_FolderContent" runat="server" style="text-align:left;overflow:auto;">
</td>
</tr>
</table>
</div>
In the code behind make sure that your are adding the control in the OnInit method to ensure that the control exists prior to processing the post back data (before the page load event)
http://i.msdn.microsoft.com/dynimg/IC386473.png (ASP.NET LifeCycle)

Categories