Type Conversion Error for casting UI.Usercontrol to custom conrol in Class Library - user-controls

I've 3 of .NET Projects.
One of these project is an ASP.Net Web Form Application named Index. And the other projects are listed below
Index.Database Project is Database Layer
Index.Platform Project is Bussiness layer.
In bussiness layer im loading UserControls. There is information bout these UserControls in db. (Path, ascx file, name, Title, Content, Positions etc )
In bussiness layer i created a class drived from UserControl named ModuleControl.
Index.Platform referenced by System.Web.dll also uses Using System.Web.UI.WebControls.
I'm planning to use this ModuleControl fields in my loaded UserControls. There is another class named IndexSite instanced on Default.aspx's Load_Page event.
namespace Index.Platform.Modules
{
public class ModuleControl : System.Web.UI.UserControl
{
public string Title { get; set; }
public bool ShowTitle { get; set; }
public string Content { get; set; }
public ModuleControl()
{
}
}
}
//Index.Platform.IndexSite
private void InitializeModules(System.Web.UI.Page page)
{
string mPath = null;
try
{
ModuleDictionaryList = DBFactory.LoadModules();
PositionList = DBFactory.PositionList;
ModuleList = DBFactory.ModuleList;
foreach (KeyValuePair<string, List<module>> pair in ModuleDictionaryList)
{
foreach (var item in pair.Value)
{
mPath = "/Modules/" + item.Name + "/" + item.Name + ".ascx";
iControl = (ModuleControl)page.LoadControl(mPath);
ShowTitle = Convert.ToBoolean(item.ShowTitle);
iControl.ShowTitle = ShowTitle;
iControl.Title = item.Title;
iControl.Content = item.Content;
panel = (PlaceHolder)page.Master.FindControl(item.Position);
panel.Controls.Add(iControl);
//HttpContext.Current.Response.Write(item.Position + "<br>");
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
this class takes an argument from Default.aspx. Page sends its self.
protected void Page_Load(object sender, EventArgs e)
{
IndexSite site = IndexSite.Instance.Create(this);
}
Yes, In Bussines layer I use LoadControl method to load USerControl also im adding these controls to a panel control which is in MasterPage (PlaceHolder).
My problem is in this line: iControl = (ModuleControl)page.LoadControl(mPath);
I cant cast UserControl to ModuleControl. Remember this ModuleControl drived from UserControl and all of my ascx file drived from ModuleControl class.
Throws this error: "Unable to cast object of type 'ASP.modules_mod_login_mod_login_ascx' to type 'Index.Platform.Modules.ModuleControl'."
If i do these proccess in Main application there is no error for casting ModuleControl.
When id seperate my application to 3. I stuck here.

Related

Orchard CMS: Create Content Items from External Data Source

In Orchard CMS I have a service that pulls data from an external data source, and loads the data into an Orchard Content Part. The Part has a migration that welds it with a title part, and I have a route so that my controller is being hit via a URL:
I am using a controller to access the item via a URL, much like the Blog Part controller. However I can't render my part...
The Blog Controller does similar to the following:
var asset = _assetService.Get(1234);
if (asset == null) return HttpNotFound();
var model = _services.ContentManager.BuildDisplay(asset);
return new ShapeResult(this, model);
But if I do this, the 'BuildDisplay' method looks for asset.ContentItem but this is null, despite deriving my part from 'ContentPart'.
What do I need to do to get my data to display?
If I understand correctly, you are trying to display only one part, and not a whole content item.
To display a single shape, you can do the following:
private readonly IAssetService _assetService;
public MyController(IShapeFactory shapeFactory, IAssetService assetService) {
_assetService = assetService;
Shape = shapeFactory;
}
public dynamic Shape { get; set; }
public ActionResult MyAction(int assetId) {
var asset = _assetService.Get(1234);
if (asset == null) return HttpNotFound();
// the shape factory can call any shape (.cshtml) that is defined
// this method assumes you have a view called SomeShapeName.cshtml
var model = Shape.SomeShapeName(asset);
return new ShapeResult(this, model);
}
!!Note:
This does not kick of the (display)driver of the part, it only returns the .cshtml with the given model
By having my part deriving from ContentPart, I can use the following Controller method:
private readonly IAssetService _assetService;
private readonly IOrchardServices _services;
public MyController(IShapeFactory shapeFactory, IAssetService assetService, IOrchardServices services) {
_assetService = assetService;
_services = services;
Shape = shapeFactory;
}
public dynamic Shape { get; set; }
public ActionResult MyAction(int assetId) {
var asset = _assetService.Get(1234);
if (asset == null) return HttpNotFound();
// this method assumes you have a view called Parts.Asset.cshtml (see the AssetPartDriver)
var model = _services.ContentManager.New("Asset");
var item = contentItem.As<AssetPart>();
item.Populate(asset) // Method that just populates the service loaded object into the ContentPart
return new ShapeResult(this, _services.ContentManager.BuildDisplay(item));
}
This will use the 'AssetPartDriver':
public class AssetPartDriver : ContentPartDriver<AssetPart>
{
protected override DriverResult Display(AssetPart part, string displayType, dynamic shapeHelper)
{
return ContentShape("Parts_Asset", () => shapeHelper.Parts_Asset()); // Uses Parts.Asset.cshtml
}
}
And in conjunction with the 'Placement.info' file renders on the screen:
<Placement>
<Match ContentType="Asset">
<Match DisplayType="Detail">
<Place Parts_Asset="Content"/>
</Match>
</Match>
</Placement>
The migration file combines my web service part with other Orchard parts:
public class Migrations : DataMigrationImpl
{
public int Create()
{
ContentDefinitionManager.AlterTypeDefinition("Asset", cfg => cfg
.WithPart("AssetPart")
.WithPart("AutoroutePart", builder => builder
.WithSetting("AutorouteSettings.AllowCustomPattern", "True"))
.Listable()
.Securable()
.Creatable(false));
ContentDefinitionManager.AlterPartDefinition("AssetPart", part => part
.WithDescription("A part that contains details of an individual Web Service loaded asset."));
return 1;
}
}
These additional parts are not yet used, but can be populated during creation and displayed individually using the placement file.
This is the first step of what I was trying to achieve!!

VaryByParam fails if a param is a list

I've got this action in MVC
[OutputCache(Duration = 1200, VaryByParam = "*")]
public ActionResult FilterArea( string listType, List<int> designersID, int currPage = 1 )
{
// Code removed
}
that fails to present the correct HTML with url like
http://example.com/en-US/women/clothing?designersID=158
http://example.com/en-US/women/clothing?designersID=158&designersID=13
Is this a know bug of OutputCache in .NET cause cannot recognize VaryByParam with a list param or am I missing something?
I too had the same issue in MVC3 and I believe it's still the same case in MVC5.
Here is the setup I had.
Request
POST, Content-Type:application/json, passing in an array of string as the parameter
{ "options": ["option1", "option2"] }
Controller Method
[OutputCache(Duration = 3600, Location = OutputCacheLocation.Any, VaryByParam = "options")]
public ActionResult GetOptionValues(List<string> options)
I tried every option possible with OutputCache and it just wasn't caching for me. Binding worked fine for the actual method to work. My biggest suspicion was that OutputCache wasn't creating unique cache keys so I even pulled its code out of System.Web.MVC.OutputCache to verify. I've verified that it properly builds unique keys even when a List<string> is passed in. Something else is buggy in there but wasn't worth spending more effort.
OutputCacheAttribute.GetUniqueIdFromActionParameters(filterContext,
OutputCacheAttribute.SplitVaryByParam(this.VaryByParam);
Workaround
I ended up creating my own OutputCache attribute following another SO post. Much easier to use and I can go enjoy the rest of the day.
Controller Method
[MyOutputCache(Duration=3600)]
public ActionResult GetOptionValues(Options options)
Custom Request class
I've inherited from List<string> so I can call the overriden .ToString() method in MyOutputcache class to give me a unique cache key string. This approach alone has resolved similar issues for others but not for me.
[DataContract(Name = "Options", Namespace = "")]
public class Options: List<string>
{
public override string ToString()
{
var optionsString= new StringBuilder();
foreach (var option in this)
{
optionsString.Append(option);
}
return optionsString.ToString();
}
}
Custom OutputCache class
public class MyOutputCache : ActionFilterAttribute
{
private string _cachedKey;
public int Duration { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.Url != null)
{
var path = filterContext.HttpContext.Request.Url.PathAndQuery;
var attributeNames = filterContext.ActionParameters["Options"] as AttributeNames;
if (attributeNames != null) _cachedKey = "MYOUTPUTCACHE:" + path + attributeNames;
}
if (filterContext.HttpContext.Cache[_cachedKey] != null)
{
filterContext.Result = (ActionResult) filterContext.HttpContext.Cache[_cachedKey];
}
else
{
base.OnActionExecuting(filterContext);
}
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.HttpContext.Cache.Add(_cachedKey, filterContext.Result, null,
DateTime.Now.AddSeconds(Duration), System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Default, null);
base.OnActionExecuted(filterContext);
}
}

Unable to Serialize into XML

I am trying to Serialize the content of some text into an XML file (performed when a user saves their selections), and then will later deserialize it (when the user chooses to display their saved selection).
I have been following the following tutorial on serialization.
I have also tried to do this via LINQ to XML but was either getting namespace errors, or the tool returned no errors, but did not work (with the same problem as described below).
The problem I am having is that my code is not returning any errors, but the function is not working (I have a label control that allows me to see that the 'catch' is being returned). I am building the tool in Expression Blend, using C#.
Here is my SaveSelection.cs Class
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Serialization;
using System.Xml;
namespace DYH
{
public class SaveSelections
{
[XmlAttribute("Title")]
public string Title
{ get; set; }
[XmlElement("Roof")]
public string RoofSelection
{ get; set; }
[XmlElement("Cladding")]
public string CladdingSelection
{ get; set; }
[XmlElement("MixedCladding")]
public string MixedCladdingSelection
{ get; set; }
[XmlElement("FAJ")]
public string FAJSelection
{ get; set; }
[XmlElement("GarageDoor")]
public string GarageDoorSelection
{ get; set; }
[XmlElement("FrontDoor")]
public string FrontDoorSelection
{ get; set; }
}
}
Here is my C# code
// Save Selection Button
private void Button_SaveSelection_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
try
{
// Save selections into the SavedSelections.xml doc
SaveSelections userselection = new SaveSelections();
userselection.Title = TextBox_SaveSelection.Text;
userselection.RoofSelection = Button_Roof_Select.Text;
userselection.CladdingSelection = Button_Cladding_Select.Text;
userselection.MixedCladdingSelection = Button_MixedCladding_Select.Text;
userselection.FAJSelection = Button_FAJ_Select.Text;
userselection.GarageDoorSelection = Button_GarageDoor_Select.Text;
userselection.FrontDoorSelection = Button_FrontDoor_Select.Text;
SerializeToXML(userselection);
// XDocument xmlSaveSelections = XDocument.Load("../SavedSelections.xml");
//
// XElement newSelection = new XElement("Selection", //xmlSaveSelections.Element("Selections").Add(
// //new XElement("Selection",
// new XElement("Title", TextBox_SaveSelection.Text),
// new XElement("RoofSelection", Button_Roof_Select.Text),
// new XElement("CladdingSelection", Button_Cladding_Select.Text),
// new XElement("MixedCladdingSelection", Button_MixedCladding_Select.Text),
// new XElement("FAJSelection", Button_FAJ_Select.Text),
// new XElement("GarageDoorSelection", Button_GarageDoor_Select.Text),
// new XElement("FrontDoorSelection", Button_FrontDoor_Select.Text));
//
//// xmlSaveSelections.Add(newSelection);
//// xmlSaveSelections.Save("../SavedSelections.xml");
SelectionLabel.Text = "Your selection has been saved as " + "'" + TextBox_SaveSelection.Text + "'. We suggest you write down the name of your selection.";
}
catch(Exception ex)
{
throw ex;
SelectionLabel.Text = "There was a problem saving your selection. Please try again shortly.";
}
}
// Saves SaveSelection.cs to XML file SavedSelections.xml
static public void SerializeToXML(SaveSelections selection)
{
XmlSerializer serializer = new XmlSerializer(typeof(SaveSelections));
TextWriter textWriter = new StreamWriter(#"/SavedSelections.xml");
serializer.Serialize(textWriter, selection);
textWriter.Close();
}
I have left evidence of one of my previous attempts commented out so you can see a previous format I tried.
My issue is that when I try to use the tool, the SelectionLabel.Text returns "There was a problem saving your selection. Please try again shortly." so I know that the code is returning the catch and not executing the 'try'.
Any help??
Edit 18/6/2012: The below code was the code that worked as per correct answer to question.
public void Button_SaveSelection_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
string roofSelection = TextBox_SaveSelection.Text + "_RoofSelection";
string claddingSelection = TextBox_SaveSelection.Text + "_CladdingSelection";
string mixedCladdingSelection = TextBox_SaveSelection.Text + "_MixedCladdingSelection";
string fajSelection = TextBox_SaveSelection.Text + "_FAJSelection";
string garageDoorSelection = TextBox_SaveSelection.Text + "_GarageDoorSelection";
string frontDoorSelection = TextBox_SaveSelection.Text + "_FrontDoorSelection";
try
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
// Gives us 6Mb of storage space in IsoStore
Int64 isoSpaceNeeded = 1048576 * 6;
Int64 currentIsoSpace = store.AvailableFreeSpace;
// If space needed is greater than (>) space available, increase space
if (isoSpaceNeeded > currentIsoSpace)
{
// If user accepts space increase
if (store.IncreaseQuotaTo(currentIsoSpace + isoSpaceNeeded))
{
IsolatedStorageFileStream file = store.CreateFile("SavedSelections.txt");
file.Close();
// Stream writer to populate information in
using (StreamWriter sw = new StreamWriter(store.OpenFile("SavedSelections.txt", FileMode.Open, FileAccess.Write)))
{
appSettings.Add(roofSelection, Button_Roof_Select.Text);
sw.WriteLine(roofSelection);
appSettings.Add(claddingSelection, Button_Cladding_Select.Text);
sw.WriteLine(claddingSelection);
appSettings.Add(mixedCladdingSelection, Button_MixedCladding_Select.Text);
sw.WriteLine(mixedCladdingSelection);
appSettings.Add(fajSelection, Button_FAJ_Select.Text);
sw.WriteLine(fajSelection);
appSettings.Add(garageDoorSelection, Button_GarageDoor_Select.Text);
sw.WriteLine(garageDoorSelection);
appSettings.Add(frontDoorSelection, Button_FrontDoor_Select.Text);
sw.WriteLine(frontDoorSelection);
}
SelectionLabel.Text = "Your selection has been saved as " + "'" + TextBox_SaveSelection.Text + "'. We suggest you write down the name of your selection.";
}
}
}
SelectionLabel.Text = "Your selection has been saved as " + "'" + TextBox_SaveSelection.Text + "'. We suggest you write down the name of your selection.";
}
catch //(Exception ex)
{
//throw ex;
SelectionLabel.Text = "There was a problem saving your selection. Please try again shortly.";
}
}
It looks like your issue is because you're trying to a file, but that file did not come from a FileSaveDialog initiated by a user action. You're running into a security feature of Silverlight where you're not allowed access to the local file system. Instead, try writing to IsolatedStorage. However, be aware that end users can completely (as well as selectively) disable application storage so you'll need to handle those exceptions as well.
Here's a quick article on how to use IsolatedStorage.

Retrieving values of ReadOnly fields from DynamicData DetailsView in Edit Mode on Updating using LinqDataSource

I have several tables in my database that have read-only fields that get set on Inserting and Updating, namely: AddDate (DateTime), AddUserName (string), LastModDate (DateTime), LastModUserName (string).
All of the tables that have these values have been set to inherit from the following interface:
public interface IUserTrackTable
{
string AddUserName { get; set; }
DateTime AddDate { get; set; }
string LastModUserName { get; set; }
DateTime LastModDate { get; set; }
}
As such, I have the following method on the Edit.aspx page:
protected void DetailsDataSource_Updating(object sender, LinqDataSourceUpdateEventArgs e)
{
IUserTrackTable newObject = e.NewObject as IUserTrackTable;
if (newObject != null)
{
newObject.LastModUserName = User.Identity.Name;
newObject.LastModDate = DateTime.Now;
}
}
However, by the time it hits this method, the e.OriginalObject has already lost the values for all four fields, so a ChangeConflictException gets thrown during the actual Update. I have tried adding the four column names to the DetailsView1.DataKeyNames array in the Init event handler:
protected void Page_Init(object sender, EventArgs e)
{
// other things happen before this
var readOnlyColumns = table.Columns.Where(c => c.Attributes.SingleOrDefaultOfType<ReadOnlyAttribute>(ReadOnlyAttribute.Default).IsReadOnly).Select(c => c.Name);
DetailsView1.DataKeyNames = DetailsView1.DataKeyNames.Union<string>(readOnlyColumns).ToArray<string>();
DetailsView1.RowsGenerator = new CustomFieldGenerator(table, PageTemplates.Edit, false);
// other things happen after this
}
I've tried making that code only happen on PostBack, and still nothing. I'm at a lose for how to get the values for all of the columns to make the round-trip.
The only thing the CustomFieldGenerator is handling the ReadOnlyAttribute, following the details on C# Bits.
UPDATE: After further investigation, the values make the round trip to the DetailsView_ItemUpdating event. All of the values are present in the e.OldValues dictionary. However, they are lost by the time it gets to the LinqDataSource_Updating event.
Obviously, there are the "solutions" of making those columns not participate in Concurrency Checks or other ways that involve hard-coding, but the ideal solution would dynamically add the appropriate information where needed so that this stays as a Dynamic solution.
i Drovani, I assume you want data auditing (see Steve Sheldon's A Method to Handle Audit Fields in LINQ to SQL), I would do this in the model in EF4 you can do it like this:
partial void OnContextCreated()
{
// Register the handler for the SavingChanges event.
this.SavingChanges += new EventHandler(context_SavingChanges);
}
private static void context_SavingChanges(object sender, EventArgs e)
{
// handle auditing
AuditingHelperUtility.ProcessAuditFields(objects.GetObjectStateEntries(EntityState.Added));
AuditingHelperUtility.ProcessAuditFields(objects.GetObjectStateEntries(EntityState.Modified), InsertMode: false);
}
internal static class AuditingHelperUtility
{
internal static void ProcessAuditFields(IEnumerable<Object> list, bool InsertMode = true)
{
foreach (var item in list)
{
IAuditable entity = item as IAuditable;
if (entity != null)
{
if (InsertMode)
{
entity.InsertedBy = GetUserId();
entity.InsertedOn = DateTime.Now;
}
entity.UpdatedBy = GetUserId();
entity.UpdatedOn = DateTime.Now;
}
}
}
}
Sadly this is not possible with EF v1

Web Parts custom property not showing up

I'm trying to create a custom property for my web part, but can't get it to show up in Sharepoint. Here's my current code :
[Serializable]
[XmlRoot(Namespace = "MyWebPart")]
[DefaultProperty("Text")]
public class MyWebPart : WebPart
{
...
[Category("My Web Parts Properties")]
[DefaultValue(defaultPropertyValue)]
[WebPartStorage(Storage.Shared)]
[FriendlyNameAttribute("Property name")]
[Description("Longer desc for my property")]
[Browsable(true)]
[XmlElement(ElementName = "SomeProperty")]
public string SomeProperty
{
get { return someProperty; }
set { someProperty = value; }
}
Is there something else required to get custom properties working?
I think you're using the wrong properties
SO - Sharepoint custom web part property does not show up in the toolbox

Resources