Int does not contain a constructor that takes one argument - asp.net

In my .NET application, I recently had to make some changes in the database structure and upon changing code I have run into this error message.
The line used to say _categoryID = new Guid(Request.QueryString["CategoryID"].ToString()); which worked fine to retrieve a list of products based on the categoryid, but now I had to add a top level category called Market, and I used int instead of Guid in the database, because to me using Guid is a pain.
But now when I change the line I mentioned to _marketID = new Int32(Request.QueryString["MarketID"].ToString()); I get the error.
Here is the chunk of code :
#region Variables
Int32 _marketID;
#endregion
if ( Request.QueryString [ "MarketID" ] != null )
{
_marketID = new Int32(Request.QueryString["MarketID"].ToString());
ViewState["MarketID"] = _marketID;
BindDataToUI ( );
CreateFilterInSession ( );
}

Try this instead :
_marketID = Convert.ToInt32(Request.QueryString["MarketID"]);
note : no need to use ToString() for querystring values, they're all natively strings anyway.

Related

Panel using stored procedure - Code not reacting as expected

I have hit a small issue and hoping someone might be able to assist. I am using a panel - On the page load, it should list all the products as no category has been selected as per stored procedure (this works perfectly).
When a user clicks on a specific category, it should only show the products that have the specific CategoryID. When I run the code in SQL, it works a dream for this part too, so assume the stored procedure is ok.
At
CategoryID = CategoryID
in GetProducts, I get
Warning: Assignment made to same variable; did you mean to assign something else?
However I am following a tutorial video and this works fine. Is there another silly error that is preventing it from working?
I think I have included all the required code - sorry if its a bit overkill!!
Thanks as ever in advance - Jack
Code behind pnlCategories:
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart();
{
CategoryID = CategoryID;
};
Error identified - additional ";" added at following line:
ShoppingCart k = new ShoppingCart();
Code now reads
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
and functions as expected!
that looks like a c# error and not a SQL Server error.
The problem is here in your GetProducts method. CategoryID = CategoryID;
C# is case sensitive. If you check your tutorial carefully, one of these will probably be lower case. Make sure you type that carefully.
try code change below and see where the compiler complains.
CategoryID = categoryID;
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart();
{
CategoryID = CategoryID;
};
dlProducts.DataSource = null;
dlProducts.DataSource = k.GetProdcuts();
dlProducts.DataBind();
}

$date not picking up current date - Sitecore

I am having an issue while setting default value for datetime field in sitecore standard values.
I know that $date takes the current date. If I specify $date in standard values for a date time field , it always takes the date as "1/1/0001".
How do I fix this ?
It is possible to enter tokens in the fields on the standard values, and then these will be replaced with other values, but only when a new item which use that template is created. It will not set date for the existing items which use this template.
$date is one of the token and it's replates with the system date (yyyyMMdd).
There is a blog post written by John West which explains how to Expand Standard Values Tokens in Existing Items with the Sitecore ASP.NET CMS.
EDIT:
Here is the code which is a part of MasterVariablesReplacer class which is used to replace $date token:
text = this.ReplaceWithDefault(text, "$date", (Func<string>) (() => DateUtil.IsoNowDate), context);
It is called from the ReplaceVariables processor, which is a part of expandInitialFieldValue pipeline (see /sitecore/admin/showconfig.aspx for all the expandInitialFieldValue processors).
You can try to add your own processor to this pipeline and see why the $date is not replaced properly:
public class ReplaceVariables : ExpandInitialFieldValueProcessor
{
public override void Process(ExpandInitialFieldValueArgs args)
{
Assert.ArgumentNotNull((object) args, "args");
MasterVariablesReplacer variablesReplacer = Factory.GetMasterVariablesReplacer();
string text = args.SourceField.Value;
if (variablesReplacer == null)
args.Result = text;
else
args.Result = variablesReplacer.Replace(text, args.TargetItem);
}
}

Cannot implicitly convert type 'System.Linq.IQueryable to System.Data.Entity.DbSet<>

I receive the following error when I try to run my code. I haven't managed to solve it yet, please Help:
edit: Marked with * where it fails.
>
public IQueryable<Video> GetVideos([QueryString("id")] int? categorieId)
{
var _db = new TeleviziuneAcademicaAspSilverlight.Models.VideoContext();
IQueryable<Video> query = *_db.Videos;*
if (categorieId.HasValue && categorieId > 0)
{
query = query.Where(v => v.CategorieID == categorieId);
}
return query;
Change
IQueryable<Video> query =
to
IQueryable<Appname.Models.Video> query =
The reason for your error is that you have the type Video defined twice and because of using a short type name you accidentally reference not the one Video you should.
Also change it in the method's return value
public IQueryable<Appname.Models.Video> GetVideos( ... )
You seem to have two classes called Video. If you need both, you'll need to project from one to the other before your return statement:
return query.Select(dbVideo => new Appname.Video()
{
Prop1 = dbVideo.Prop1,
Prop2 = dbVideo.Prop2,
// etc.
});
Though you'll probably need to change the return type to an IEnumerable<> if you do that.
If you can just work with Appname.Models.Video, change IQueryable<Video> to IQueryable<Appname.Models.Video> in the method signature and the method body.

Returning a column from a linked table in LINQ to SQL

My problem is that I am trying to return a simple query that contains an object Story. The Story object has a UserId in the table which links to aspnet_users' UserId column. I have created a partial class for Story that adds the UserName property since it does not exist in the table itself.
The following query gets all stories; however, a pagination helper takes the query and returns only what's necessary once this is passed back to the controller.
public IQueryable<Story> FindAllStories(){
var stories = (from s in db.Stories
orderby s.DateEntered descending
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
}
);
return stories;
}
When the helper does a .count() on the source it bombs with the following exception:
"Explicit construction of entity type 'MyWebsite.Models.Story' in query is not allowed."
Any ideas? It's not a problem with the helper because I had this working when I simply had the UserName inside the Story table. And on a side note - any book recommendations for getting up to speed on LINQ to SQL? It's really kicking my butt. Thanks.
The problem is precisely what it tells you: you're not allowed to use new Story as the result of your query. Use an anonymous type instead (by omitting Story after new). If you still want Story, you can remap it later in LINQ to Objects:
var stories = from s in db.Stories
orderby s.DateEntered descending
select new
{
Title = s.Title,
StoryContent = s.StoryContent,
DateEntered = s.DateEntered,
DateUpdated = s.DateUpdated,
UserName = s.aspnet_User.UserName
};
stories = from s in stories.AsEnumerable() // L2O
select new Story
{
Title = s.Title,
StoryContent = s.StoryContent,
...
};
If you really need to return an IQueryable from your method and still need the Username of the user you can use DataContext.LoadOptions to eagerload your aspnet_user objects.
See this example.

Accessing the object/row being edited in Dynamic Data

I'm modifying the "Edit.aspx" default page template used by ASP.NET Dynamic Data and adding some additional controls. I know that I can find the type of object being edited by looking at DetailsDataSource.GetTable().EntityType, but how can I see the actual object itself? Also, can I change the properties of the object and tell the data context to submit those changes?
Maybe you have found a solution already, however I'd like to share my expresience on this.
It turned out to be a great pita, but I've managed to obtain the editing row. I had to extract the DetailsDataSource WhereParameters and then create a query in runtime.
The code below works for tables with a single primary key. If you have compound keys, I guess, it will require modifications:
Parameter param = null;
foreach(object item in (DetailsDataSource.WhereParameters[0] as DynamicQueryStringParameter).GetWhereParameters(DetailsDataSource)) {
param = (Parameter)item;
break;
}
IQueryable query = DetailsDataSource.GetTable().GetQuery();
ParameterExpression lambdaArgument = Expression.Parameter(query.ElementType, "");
object paramValue = Convert.ChangeType(param.DefaultValue, param.Type);
Expression compareExpr = Expression.Equal(
Expression.Property(lambdaArgument, param.Name),
Expression.Constant(paramValue)
);
Expression lambda = Expression.Lambda(compareExpr, lambdaArgument);
Expression filteredQuery = Expression.Call(typeof(Queryable), "Where", new Type[] { query.ElementType }, query.Expression, lambda);
var WANTED = query.Provider.CreateQuery(filteredQuery).Cast<object>().FirstOrDefault<object>();
If it's a DD object you may be able to use FieldTemplateUserControl.FindFieldTemplate(controlId). Then if you need to you can cast it as an ITextControl to manipulate data.
Otherwise, try using this extension method to find the child control:
public static T FindControl<T>(this Control startingControl, string id) where T : Control
{
T found = startingControl.FindControl(id) as T;
if (found == null)
{
found = FindChildControl<T>(startingControl, id);
}
return found;
}
I found another solution, the other ones did not work.
In my case, I've copied Edit.aspx in /CustomPages/Devices/
Where Devices is the name of the table for which I want this custom behaviour.
Add this in Edit.aspx -> Page_Init()
DetailsDataSource.Selected += entityDataSource_Selected;
Add this in Edit.aspx :
protected void entityDataSource_Selected(object sender, EntityDataSourceSelectedEventArgs e)
{
Device device = e.Results.Cast<Device>().First();
// you have the object/row being edited !
}
Just change Device to your own table name.

Resources