ASPxGridview undefined - devexpress

I have a basic 1 table grid. I have a field called Branch type. The branch type can only be Corporate or Franchise. When i click on the edit button on the ASPxgridview row , i would like to display and hide fields on the edit form, depending on what Branch Type it is. So if it is Corporate i would like to Display the Manager field and Hide the Owner field. When the branch type is Franchise then I would like the Owner field to be displayed and the Manager field to be hidden on the edit form. all details can show on the grid view but on the edit form i would like to force the user to only fill in applicable fields.
If you look below:
this is basically what i want to achieve on loading the edit form :
protected void ASPxGridViewStores_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
{
if (!ASPxGridViewStores.IsEditing || e.Column.FieldName != "StoreOwnershipID") return;
if(e.KeyValue == DBNull.Value || e.KeyValue == null) return;
object val = ASPxGridViewStores.GetRowValuesByKeyValue(e.KeyValue, "S_ID");
if(val == DBNull.Value) return;
int StoreOwnershipID = (Int32)val;
if (StoreOwnershipID == 4)
{ ASPxComboBox ManagerID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ManagerID");
ManagerID.Enabled = true;
ASPxComboBox ContactID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ContactID");
ManagerID.Enabled = true;
}
else
{ ASPxComboBox ManagerID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ManagerID");
ManagerID.Enabled = false;
ASPxComboBox ContactID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ContactID");
ManagerID.Enabled = false;
}
}
and then depending on selecting Corporate or Franchise in the "StoreOwnershipID" field i will use the client side script to enable or disable the additional fields.
I have done some research as well, and i came up with the following code:
SelectedIndexChanged="function(s, e) {
var value = s.GetValue();
if(value == 4)
GridViewStores.GetEditor("OwnerName").SetVisible(true);
else
GridViewStores.GetEditor("OwnerName").SetVisible(false);
}"
but when this is called i get the following error:
Microsoft JScript runtime error: 'GridViewStores' is undefined
I have added the HTTPhandler in the web.config:
<httpModules>
<add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v10.2, Version=10.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
</httpModules>
and
<system.webServer>
<modules>
<add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v10.2, Version=10.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
</modules>
as you can see below i have inserted the ClientInstanceName,
i have changed the ClientIDMode from AutoID to Inherit to Static to Predictable and each scenario does not work and still renderes : Microsoft JScript runtime error: 'ASPxGridview' is undefined.
below my gridview tag
<dx:ASPxGridView ID="ASPxGridView" runat="server" AutoGenerateColumns="False"
ClientIDMode="Predictable" DataSourceID="SqlDataSource1" KeyFieldName="S_ID"
ClientInstanceName="ASPxGridView">
i have now even tried creating a new page with just a sqldatasource and gridview with the storetype field as acombobox and including the javascript as mentioned in my previous posts.. and no luck at all. i have given you my web.config settings where i declared the httphandler, so what else do you suggest i do to get this working?
here is my webconfig:
section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<httpModules>
<add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v10.2, Version=10.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
</httpModules>
<httpHandlers>
<add type="DevExpress.Web.ASPxClasses.ASPxHttpHandlerModule, DevExpress.Web.v10.2, Version=10.2.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET" path="DX.ashx" validate="false" />
</httpHandlers>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
sorry for the looong question. by the way this is using DevExpress Gridview. The guys from devexpress cant help me and tak 1 day to answer a question, so its been going on for almost a week now...
Thank you
Werner

The Java Script is a case sensitive language. So, if the ClientInstanceName is set to ASPxGridView, your code should be:
ASPxGridView.GetEditor("OwnerName").SetVisible(true);
I see that the error message contains the 'ASPxGridview;' identifier. It means that your code contains the ASPxGridview identifier but you should use the ASPxGridView (based on your mark up). Also, I believe that this code is wrong:
if (StoreOwnershipID == 4)
{ ASPxComboBox ManagerID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ManagerID");
ManagerID.Enabled = true;
ASPxComboBox ContactID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ContactID");
ManagerID.Enabled = true;
}
else
{ ASPxComboBox ManagerID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ManagerID");
ManagerID.Enabled = false;
ASPxComboBox ContactID = (ASPxComboBox)ASPxGridViewStores.FindEditFormTemplateControl("ContactID");
ManagerID.Enabled = false;
}
You set the Enabled property of the ManagerID object twice to the same value. Please check it. I have nothing to add. if this does not help, please let me know the support center ticket ID and if possible attach the source code of the page (cs and aspx) and web.config there. We will try to help you.
Update: I have found your question in the support center and answered it. Hope, this helps.

Related

How to read App Setting key in Web config Connection string?

It is possible to use app keys for all the connection string inputs and read those on connection string like bellow
<add name="DefaultConnection" connectionString="Data Source=$(Server);Initial Catalog=$(Catalog);User ID=$(User);Password=$(Password)" providerName="System.Data.SqlClient" />
<add key="$(Server)" value="xxxx" />
<add key="$(Catalog)" value="xxxx" />
<add key="$(User)" value="xxxx" />
<add key="$(Password)" value="xxxx" />
As #Ertürk Öztürk already say - it's not possible.
If you searching for more or less clean way to do it i suggest you to use SqlConnectionStringBuilder or DbConnectionStringBuilder if you using not MSSQL data base.
In your code it will be like this with SqlConnectionStringBuilder:
//create connection string builder
System.Data.SqlClient.SqlConnectionStringBuilder connectionStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
//set all properties from your WebConfig
connectionStringBuilder.DataSource = ConfigurationManager.AppSettings["Server"];
connectionStringBuilder.InitialCatalog = ConfigurationManager.AppSettings["Catalog"];
connectionStringBuilder.UserID = ConfigurationManager.AppSettings["User"];
connectionStringBuilder.Password = ConfigurationManager.AppSettings["Password"];
//not you can get rigth formatted connection string
var connectionString = connectionStringBuilder.ConnectionString;
It's not possible. Actually you don't need to do this, that's why it's not possible. Because you can change the other parts of web.config same like AppSettings.
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString =
String.Format("Data Source={0};Initial Catalog={1};UserID={2};Password={3}",
"server", "db", "ID", "Pass");

Membership Profile Property retrieval

I am using Membership in .net web application.
I have the following web.config configuration...
<profile ...>
.....
<properties>
<add name="FirstName"/>
<add name="LastName"/>
<add name="DateOfBirth" type="DateTime"/>
.....
</properties>
</profile>
I inserted data using the following code segment, which affected the aspnet_profile database table.
dynamic profile = ProfileBase.Create("Username");
profile.Initialize("Username", true);
profile.FirstName = "someFirstName";
profile.LastName = "someLastName";
profile.Save();
Now please anyone suggest me how to retrieve this data.
Now please anyone suggest me how to retrieve this data.
You can use System.Web.Profile.ProfileManager and then its API like FindProfilesByUserName(), GetAllProfiles() etc.
Here is already a solved thread.
This is what i did to retrieve profile property value...
string Firstname = ProfileBase.Create("UserName").GetPropertyValue("FirstName").toString();

SqlException when creating a new item in Asp.Net MVC 3 app

In my "web store" mvc app I want to add items to database. Items table has CreatedBy field and it is a foreign key from User table UserId field. Everything was working before I put the database into the App_Data folder. Now I get the SqlException when trying to create a new Item:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Item_contains_User". The conflict occurred in database "C:\USERS\ALEKSEY\REPOS\2\WEBSTORE\WEBSTORE\APP_DATA\WEBSTORE.MDF", table "dbo.Users", column 'UserId'.
Here is the Create method of ItemRepository class:
public Item CreateItem(int productId, Guid userId)
{
var item = new Item
{
ProductId = productId,
CreatedBy = userId,
};
_dataContext.Items.InsertOnSubmit(item);
_dataContext.SubmitChanges(); // in this line the exception occures !
return item;
}
Here is the controller method Create:
[HttpGet]
public ViewResult Create()
{
var p = _productRepository.CreateProduct("", "", 0, "", "", "");
var userId = (Guid)Membership.GetUser().ProviderUserKey;
var item = _itemsRepository.CreateItem(p.ProductId, userId);
// some code
return View(model);
}
Besides, I use Linq to Sql model drag an' drop approach.
Here is the changed web.config connection string part:
<connectionStrings>
<add name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
As I said everything was working before I moved the database to App_Data file. I also tried to remove the dependency between Items and Users tables - the exact same exception.
Any help would be appropriate. Thanks in advance!
Edits:
Ok, now I really broke the dependency between Items and Users tables and no exception occures. But! I have to somehow know who has created each product, so breaking the dependency is not an option. I also tried to remove all code that initializes the CreatedBy field.
Any ideas??
Edits (part 2):
The second comment below gives a great advise! I found that all users that are created are stored now in the aspnet.sdf database!!!
But if I remove the connection string "DeafaultConnection":
<add name="DefaultConnection" connectionString="Data Source=|DataDirectory|\aspnet.sdf"
providerName="System.Data.SqlServerCe.4.0" />
I will get ConfigurationErrorsException:
"The connection name 'DefaultConnection' was not found in the applications
configuration or the connection string is empty."
in the folowing line:
var userId = (Guid)Membership.GetUser().ProviderUserKey;
Ok, as I guessed the issue was in the configuration. Each provider (for some reason) in the connection string had "DefaultConnection". I changed it to "WebStoreConnectionString". And now everything works!
p.s. thanks #w0lf, he pushed the thoughts in the right direction)

How to set FedAuth cookie SessionToken.IsPersistent conditionally when SessionSecurityTokenCreated

I am using WIF with WS Federation so that my ASP.NET application can authenticate against an STS (Thinktecture IdentityServer). In my RP I would like to pragmatically set the cookie persistence based off of the claims of the user.
Watching the traffic in Fiddler I can see the WIF FedAuth cookie is first set when the STS token is posted to the RP. Before the cookie is set I would like to intercept some event and either set the cookie to be persistent (or not) depending on the current claims.
I understand that I can set the cookie persistence in the web.config, however this behavior needs to be conditional based off of the user.
<wsFederation ... persistentCookiesOnPassiveRedirects="true" />
My first approach was to try handling the various SessionSecurityTokenCreated events but these events never seemed to be fired. Am I adding the handlers incorrectly? Or is there a better way of doing this?
protected void Application_Start()
{
...
FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenCreated +=
new EventHandler<SessionSecurityTokenCreatedEventArgs>(SessionAuthenticationModule_SessionSecurityTokenCreated);
FederatedAuthentication.WSFederationAuthenticationModule.SessionSecurityTokenCreated +=
new EventHandler<SessionSecurityTokenCreatedEventArgs>(WSFederationAuthenticationModule_SessionSecurityTokenCreated);
}
//This never seems to fire...
void SessionAuthenticationModule_SessionSecurityTokenCreated(object sender,
SessionSecurityTokenCreatedEventArgs e)
{
if (e.SessionToken.ClaimsPrincipal.HasClaim("someClaim", "someValue"))
e.SessionToken.IsPersistent = true;
else
e.SessionToken.IsPersistent = false;
}
//This never seems to fire either...
void WSFederationAuthenticationModule_SessionSecurityTokenCreated(object sender,
SessionSecurityTokenCreatedEventArgs e)
{
if (e.SessionToken.ClaimsPrincipal.HasClaim("someClaim", "someValue"))
e.SessionToken.IsPersistent = true;
else
e.SessionToken.IsPersistent = false;
}
Interesting to note: if I add a handler for SessionAuthenticationModule_SessionSecurityTokenReceived this event seems to fire. Here I can re-issue the cookie and set IsPersistent = true but this doesn't get fired until after the cookie is first set and I would prefer to do this when the cookie is first issued.
After testing a bit: If I Reissue the cookie in SessionAuthenticationModule_SessionSecurityTokenReceived then SessionAuthenticationModule_SessionSecurityTokenCreated will be fired. I just can't seem to find out why this is not fired on the initial creation of the cookie when the token is first POSTed to the RP.
The source of my problem was:
a) I was using a custom WSFederationAuthenticationModule.
b) I wasn't wiring up the events in the Global.asax using the name of the custom module.
Assuming my web.config has this in it:
<system.webServer>
// ...
<add name="MyCustomWSFederationAuthenticationModule"
type="MyLib.MyCustomWSFederationAuthenticationModule, Thinktecture.IdentityModel, Version=1.0.0.0, Culture=neutral"
preCondition="managedHandler" />
<add name="SessionAuthenticationModule"
type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
preCondition="managedHandler" />
// ...
</system.webServer>
And assuming "MyCustomWSFederationAuthenticationModule" is the name of the custom fed-auth module. Then I just had to fix the name of the method handler (with nothing in app start).
protected void Application_Start()
{
//Nothing here.
}
//This never seems to fire either...
void MyCustomWSFederationAuthenticationModule_SessionSecurityTokenCreated(object sender,
SessionSecurityTokenCreatedEventArgs e)
{
if (e.SessionToken.ClaimsPrincipal.HasClaim("someClaim", "someValue"))
e.SessionToken.IsPersistent = true;
else
e.SessionToken.IsPersistent = false;
}

How to render Active Reports WebViewer in ASP.NET MVC

I asked this question in the DataDynamics forum earlier today. I thought that maybe I'd get some sort of response here at SO.
I am trying to get the WebViewer up and running in my ASP.NET MVC application.
I am attempting to render the webviewer in the controller (webViewer.RenderControl(htmlTextWriter) and then put the results into ViewData and display the report in my view. I dont' even know if this is the correct way to go about this. Any help would be greatly appreciated.
Controller code:
public ActionResult Display()
{
CurrentReport = new DetailedReport { ReportData = new DetailedData() { Repository = _repository } };
var webViewer = new WebViewer();
CurrentReport.Run();
webViewer.ID = "WebViewer1";
webViewer.Visible = true;
webViewer.ViewerType = ViewerType.HtmlViewer;
webViewer.Width = Unit.Percentage(100);
webViewer.Report = CurrentReport;
var stringWriter = new StringWriter();
var htmlTextWriter = new HtmlTextWriter(stringWriter);
webViewer.RenderBeginTag(htmlTextWriter);
webViewer.RenderControl(htmlTextWriter);
webViewer.RenderEndTag(htmlTextWriter);
ViewData["WebViewer"] = stringWriter.ToString();
return View();
}
Display.aspx code:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Admin.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%# Register assembly="ActiveReports.Web, Version=5.2.1013.2, Culture=neutral, PublicKeyToken=cc4967777c49a3ff" namespace="DataDynamics.ActiveReports.Web" tagprefix="ActiveReportsWeb" %>
<%# Import Namespace="xxxx.Core"%>
<asp:Content ID="Content1" ContentPlaceHolderID="ClientAdminContent" runat="server">
<%=ViewData["WebViewer"] %>
</asp:Content>
Error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 60: var htmlTextWriter = new HtmlTextWriter(stringWriter);
Line 61: webViewer.RenderBeginTag(htmlTextWriter);
Line 62: webViewer.RenderControl(htmlTextWriter);
Line 63: webViewer.RenderEndTag(htmlTextWriter);
Line 64:
Source File: C:\Projects\xxxx\xxxx\app\xxxx.Web.Controllers\ReportsController.cs Line: 62
****Update:****
Based on the answer by scott (thank you) my controller now looks like this:
public ActionResult Display()
{
ViewData["Report"] = new DetailedReport { ReportData = new DetailedReport { ReportData = new DetailedData() { Repository = _repository } };
return View();
}
And my view looks like this: (I have no code behind files for my views).
<%
var report = (ActiveReport3) ViewData["Report"];
report.Run();
WebViewer1.Report = report;
%>
<ActiveReportsWeb:WebViewer ID="WebViewer1" runat="server" Height="100%" Width="100%" ViewerType="AcrobatReader" />
I watch it go through debugger, and it seems to correctly step through the Details section, putting values into my fields. But after all is done, I get the message "No Report Specified." I'm hoping that I really don't have to use a codebehind file on my view because I'm not using them anywhere else. I have also debugged to verify that report.Document.Pages.Count > 0. I have put the code block both above and below the WebViewer control (don't think that really matters). Any additional thoughts?
****Update #2:****
I ended up using the answer found here: Alternative to using the OnLoad event in an ASP.Net MVC View? in combination with scott's excellent answer below. It was a timing thing with generating and binding the report to the control. So my View looks like this in the end... (where Model.Report is an ActiveReport3)
<script runat="server">
private void Page_Load(object sender, EventArgs e)
{
var report = Model.Report;
report.Run();
WebViewer1.Report = report;
}
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="ClientAdminContent" runat="server">
<ActiveReportsWeb:WebViewer ID="WebViewer1" runat="server" Height="100%" Width="100%" ViewerType="AcrobatReader" />
</asp:Content>
Thanks for everyone's help!
We have investigated this internally and found the following solution. You can add the WebViewer to a View normally. There is no need for the complicated low-level interaction code in your example. Instead, just add the WebViewer to your aspx view normally. In our sample the WebViewer was added as follows:
<ActiveReportsWeb:WebViewer ID="WebViewer1" runat="server" Height="100%" Width="100%" ViewerType="AcrobatReader" />
That is enough to get the WebViewer working on the view.
In the controller we specified an ActiveReport as follows:
ViewData["Report"] = new SampleReport();
In the codebehind of the View we hook the report to the view:
WebViewer1.Report = ViewData["Report"] as ActiveReport3;
Then the tricky part begins. There are some IHttpHandlers used by ActiveReports when running under ASP.NET for some of the viewer types such as AcrobatReader / PDF. To ensure our handlers are working you must get ASP.NET MVC routing to allow them to process as normal. Luckily it is easy to do so. Just add the following line of code to the Global.asax.cs file:
routes.IgnoreRoute("{*allarcachitems}", new { allarcachitems = #".*\.ArCacheItem(/.*)?" });
That will ignore the route. Note that according to my reading there may be problems since ASP.NET routing seems to allow only a single "catch all" route like this. Therefore, if you have multiple of these IgnoreRoute commands and or you have any problems with a .axd file, you'll need to modify the constraints dictionary argument to accomidate the .axd as well as .ArCacheItem.
For more information see the following article: http://haacked.com/archive/2008/07/14/make-routing-ignore-requests-for-a-file-extension.aspx
You can download the full sample from our forums at http://www.datadynamics.com/forums/ShowPost.aspx?PostID=121907#121907
Scott Willeke
Data Dynamics / GrapeCity
For anyone else having this issue and using IIS7 Make sure you add the Active reports handlers under the <handlers> section not <httpHandlers>.
<add name="RPX" verb="*" path="*.rpx" type="DataDynamics.ActiveReports.Web.Handlers.RpxHandler, ActiveReports.Web, Version=6.1.2814.0, Culture=neutral, PublicKeyToken=cc4967777c49a3ff"/>
<add name="ActiveReport" verb="*" path="*.ActiveReport" type="DataDynamics.ActiveReports.Web.Handlers.CompiledReportHandler, ActiveReports.Web, Version=6.1.2814.0, Culture=neutral, PublicKeyToken=cc4967777c49a3ff"/>
<add name="ArCacheItem" verb="*" path="*.ArCacheItem" type="DataDynamics.ActiveReports.Web.Handlers.WebCacheAccessHandler, ActiveReports.Web, Version=6.1.2814.0, Culture=neutral, PublicKeyToken=cc4967777c49a3ff"/>
I thought i had the IgnoreRoute setup improperly because I was getting 404 errors. However I was following the tutorial given by ActiveReports which has them in the IIS6 section instead of IIS7.

Resources