System Web HttpException - c#

i downloaded a bootstrap and i want to use it in my asp.net MVC project, i added the css files to content folder and the js files to scripts folder , then the code in the index file from this download to my layout , after running the program , i am getting this error: System.Web.HttpException: The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "featured".
can you please help me, thanks!

The reason you are not seeing the change in the database are because the below code will only run when the Model (Genre or Albums) is changed e.g. you added a new field, not when you amend the data.
public class SampleData : DropCreateDatabaseIfModelChanges<MusicStoreEntities>
{
protected override void Seed(MusicStoreEntities context)
{
var genres = new List<Genre>
{
new Genre { Name = "Rock" },
new Genre { Name = "Jazz" },
new Genre { Name = "Metal" },
new Genre { Name = "Alternative" },
new Genre { Name = "Disco" },
new Genre { Name = "Blues" },
new Genre { Name = "Latin" },
new Genre { Name = "Reggae" },
new Genre { Name = "Pop" },
new Genre { Name = "Classical" },
};
There are other Database Initialisation strategies, CreateDatabaseIfNotExists, DropCreateDatabaseAlways, you can find more details on these here
To resolve your issue you can either change the Database Initialisation strategy as #Fabiano has suggested to DropCreateDatabaseAlways. Be warned this will drop and create the database everytime you run your application.
Or if you have access to your database and have the relevant permissions you can edit the Genre table and then amend the Seed code so that if will be correct if you change your model.
Or you can continue with the tutorials here and this will show you how to edit, create and delete Genres.

Related

Auto-Delete Certain type of Document in Mongodb in collection

I have a collection called PeopleDocument. This collection contains three different types of files: IDCardCopy, taxCopy, PermitCopy. Users can upload any of these files. I want to autodelete IDCardCopy one year after it was uploaded. I am looking at MongoDB TTL, however I have some questions:
db.PeopleDocument.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 31622400} )
If I create an index like the one above, I think it will delete all files in PeopleDocument after 1 year, is it possible to only delete IDCardCopy?
More detail:
This is a C# code I use to insert Document:
var collInternDocuments = _database.GetCollection<BsonDocument>("PPLDocuments");
var doc = new BsonDocument{
{"Documentid", strDocumentID},
{ "FileType", typeOfDocument},
{ "FileContent", file.ContentType},
{ "FileName", file.FileName},
{ "UploadTime", DateTime.Now},
{ "UploadedBy", uploadedBy},
{ "GridFSFileID", strGridFSFileID}
};
collInternDocuments.UpdateOne( Builders<BsonDocument>.Filter.Eq("_id", internUserID), Builders<BsonDocument>.Update.AddToSet("Documents", doc));
This is how I created Index:
db.PeopleDocument.createIndex( {UploadTime:1},
{
expireAfterSeconds:900,
partialFilterExpression:{
FileType:{$eq:"IDCardCopy"}
}
})
This is the results for db.PeopleDocument.getIndexes():
{
"v":2,
"key":{
"_id":1
},
"name" :"_id_",
"ns" : "people.PeopleDocument"
},
{
"v":2,
"key":{
"UploadTime":1
},
"name" :"UploadTime_1",
"ns" : "people.PeopleDocument",
"expireAfterSeconds":900,
"partialFilterExpression":{
"FileType": { "$eq":"IDCardCopy"
}
}
}
This didn't delete the file after 900 sec, could this be a date issue?
this works for me. after 10secods (not exactly due to the deletion thread running every 60seconds), the IDCardCopy document is gone.
db.PeopleDocument.createIndex(
{ "uploadTime": 1 },
{
expireAfterSeconds: 10,
partialFilterExpression: { "FileType": { $eq: "IDCardCopy" } }
}
)
db.PeopleDocument.insertMany(
[
{
uploadTime: new ISODate(),
FileType: "IDCardCopy"
},
{
uploadTime: new ISODate(),
FileType: "taxCopy"
},
]
)
make sure you're setting the uploadTime field to the correct UTC now time in your application.
I think you should add in PeopleDocument the column expiresAt and fill this field on creating concrete record depended on your file type. And then simply create index like that:
db.PeopleDocument.createIndex( { "expiresAt": 1 }, { expireAfterSeconds: 0} )
I solved this by creating a C# console app that will delete documents created one year ago, I created a Task Scheduler that will run everyday to run this app.

Trouble Exporting WPF ListView Data to CSV with Filehelpers

Have hit a wall with this so hopefully SO can be of help and I've not overlooked an obvious question previously answered. I'm trying export data from a ListView (actually SQLite data that's populating it via a list) to a new CSV file - no fancy filepicker as yet, just need to save the file locally (it's a Metro 8.1 App but being deployed to Surface 3, not RT). I've created a method based on examples I've found but it doesn't seem to be writing the file (have searched local machine after attempting export but nothing found). It's compiling fine and I'm not hitting any exceptions when debugging, also I'm using Filehelpers 2.0 as I couldn't get the current version to install (VS 2015 Community). 'Candidate' is the class for the datasource (DB/listview).
Class:
using SQLite;
using FileHelpers;
namespace SolutionName.Model
{
[Table("Candidates")]
[DelimitedRecord(",")]
[IgnoreEmptyLines()]
[IgnoreFirst()]
public class Candidate
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string AreasInterest { get; set; }
} // end class Candidate
} // end namespace
Method (called by a button):
private void WriteCSVFile(List<Candidate> dataSource)
{
//filehelper object
FileHelperEngine engine = new FileHelperEngine(typeof(Candidate));
List<Candidate> csv = new List<Candidate>();
//convert any datasource to csv based object
foreach (var item in dataSource)
{
Candidate temp = new Candidate();
temp.Title = item.Title;
temp.FirstName = item.FirstName;
temp.LastName = item.LastName;
temp.Email = item.Email;
temp.Phone = item.Phone;
temp.AreasInterest = item.AreasInterest;
csv.Add(temp);
} // end foreach
//give file a name and header text
engine.HeaderText = "Title,FirstName,LastName,Email,Phone,AreaInterest";
//save file locally
engine.WriteFile("export.csv", csv);
} // end method WriteCSVFile
Any pointers would be appreciated.
Testing: Passed
Version 3.2: No issues
Version 2.2: No issues
Using either version of FileHelpers this works as expected. I threw the following code into a test console and it ran through perfectly so my only suggestion now is that you are either not passing it data, or attempting to write to either a read-only or invalid location.
Do you see any exceptions in the Output tab of Visual Studio?
Have you confirmed you have data going into the dataSource parameter?
Have you confirmed the full path that you are writing the export.csv to?
Do you have the csv file open in Excel?
Note: that having the CSV open in Excel causes a full lock on the CSV file so you must exit Excel or close the file to be able to write to it
Code:
static void TestMain2(string[] args)
{
List<Candidate> source = new List<Candidate>()
{
new Candidate() { Id = 1, Email = "test1#test.com", Title = "Mr", FirstName = "Fred", LastName = "Flintstone", AreasInterest = "Area1", Phone = "+44 1234 123123" },
new Candidate() { Id = 3, Email = "test2#test.com", Title = "Mr", FirstName = "Barney", LastName = "Rubble", AreasInterest = "Area2", Phone = "+44 1234 231231" },
new Candidate() { Id = 2, Email = "test3#test.com", Title = "Mrs", FirstName = "Wilma", LastName = "Flintstone", AreasInterest = "Area3", Phone = "+44 1234 312312" }
};
WriteCSVFile(source);
}
private static void WriteCSVFile(List<Candidate> dataSource)
{
//filehelper object
FileHelperEngine engine = new FileHelperEngine(typeof(Candidate));
List<Candidate> csv = new List<Candidate>();
//convert any datasource to csv based object
foreach (var item in dataSource)
{
Candidate temp = new Candidate();
temp.Title = item.Title;
temp.FirstName = item.FirstName;
temp.LastName = item.LastName;
temp.Email = item.Email;
temp.Phone = item.Phone;
temp.AreasInterest = item.AreasInterest;
csv.Add(temp);
} // end foreach
//give file a name and header text
engine.HeaderText = "Title,FirstName,LastName,Email,Phone,AreaInterest";
//save file locally
engine.WriteFile("export.csv", csv);
} // end method WriteCSVFile
CSV File
Title,FirstName,LastName,Email,Phone,AreaInterest
0,Mr,Fred,Flintstone,test1#test.com,+44 1234 123123,Area1
0,Mr,Barney,Rubble,test2#test.com,+44 1234 231231,Area2
0,Mrs,Wilma,Flintstone,test3#test.com,+44 1234 312312,Area3
Notes:
The ID column wasn't copied over so this was always zero, but that may just have been because of your sample code.
I believe it's recommended to be using the generic FileHelperEngine rather than typeof() parameter on the base class since this initialises various methods/properties to utilise T rather than just a generic object.
You can try downloading the source to FileHelpers and linking your project directly to the library to debug what's going on internally.
You did previously mention that you have a System.*.dll referencing problem, check that you are using the Full Framework and not a Client one as that may cause that issue. I am not sure whether a W8 universal app allows that though.

How to autoformat code on array initialization?

Every time I have array initialization and try to format the code by pressing CTRL+K and CTRL+D, the code indent doesn't get formatted automatically.
Sample code.
var users = new[]
{
new User(),
new User ( ),
new User { Id = 1 },
new User { Id = 1 } ,
new User { Id = 1 } ,
new User { Id = 1 },
};
Expected result.
var users = new[]
{
new User(),
new User(),
new User { Id = 1 },
new User { Id = 1 },
new User { Id = 1 },
new User { Id = 1 },
};
My indenting setting.
Already tried installing Code Maid and pressing shortcut in the following menu (Format Document, Format Selection).
Select your block of code and use CTRL+E , \ which deletes horizontal white space. Then tabify the code as desired.
You can also find this under EDIT --> ADVANCED --> Delete horizontal white space from your Visual Studio menu.
Check out this CodeMaid -Extension for Visual studio.
Highlight that section of the text and try to press CTRL+K+F or CTRL+K, CTRL+F

RavenDB throws a JSON deserialisation error when retrieving document

I've just completed a round of refactoring of my application, which has resulted in my removing a project that was no longer required and moving its classes into a different project. A side effect of this is that my User class, which is stored in RavenDB, has a collection property of a type moved to the new assembly. As soon as I attempt to query the session for the User class I get a Json deserialisation error. The issue is touched upon here but the answers don't address my issue. Here's the offending property:
{
"OAuthAccounts": {
"$type": "System.Collections.ObjectModel.Collection`1[
[Friendorsement.Contracts.Membership.IOAuthAccount,
Friendorsement.Contracts]], mscorlib",
"$values": []
},
}
OAuthAccounts is a collection property of User that used to map here:
System.Collections.ObjectModel.Collection`1[[Friendorsement.Contracts.Membership.IOAuthAccount, Friendorsement.Contracts]]
It now maps here:
System.Collections.ObjectModel.Collection`1[[Friendorsement.Domain.Membership.IOAuthAccount, Friendorsement.Domain]]
Friendorsement.Contracts no longer exists. All of its types are now in Friendorsement.Domain
I've tried using store.DatabaseCommands.StartsWith("User", "", 0, 128) but that didn't return anything.
I've tried looking at UpdateByIndex but not got very far with it:
store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName",
new IndexQuery {Query = "Tag:Users"},
new[]
{
new PatchRequest { // unsure what to set here }
});
I'm using Raven 2.0
Below is a simple sample application that shows you the patching Metadata. While your example is a little different this should be a good starting point
namespace SO19941925
{
internal class Program
{
private static void Main(string[] args)
{
IDocumentStore store = new DocumentStore
{
Url = "http://localhost:8080",
DefaultDatabase = "SO19941925"
}.Initialize();
using (IDocumentSession session = store.OpenSession())
{
for (int i = 0; i < 10; i++)
{
session.Store(new User {Name = "User" + i});
}
session.SaveChanges();
}
using (IDocumentSession session = store.OpenSession())
{
List<User> users = session.Query<User>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).ToList();
Console.WriteLine("{0} SO19941925.Users", users.Count);
}
Operation s = store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName",
new IndexQuery {Query = "Tag:Users"},
new ScriptedPatchRequest
{
Script = #"this['#metadata']['Raven-Clr-Type'] = 'SO19941925.Models.User, SO19941925';"
}, true
);
s.WaitForCompletion();
using (IDocumentSession session = store.OpenSession())
{
List<Models.User> users =
session.Query<Models.User>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).ToList();
Console.WriteLine("{0} SO19941925.Models.Users", users.Count);
}
Console.ReadLine();
}
}
internal class User
{
public string Name { get; set; }
}
}
namespace SO19941925.Models
{
internal class User
{
public string Name { get; set; }
}
}
UPDATE: Based on the initial answer above, here is the code that actually solves the OP question:
store.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName",
new IndexQuery {Query = "Tag:Users"},
new ScriptedPatchRequest
{
Script = #"this['OAuthAccounts']['$type'] =
'System.Collections.ObjectModel.Collection`1[
[Friendorsement.Domain.Membership.IFlexOAuthAccount,
Friendorsement.Domain]], mscorlib';",
}, true
);
Here are two possible solutions:
Option 1: Depending on what state your project is in, for example if you are still in development, you could easily just delete that collection out of RavenDB from the Raven Studio and recreate all those User documents. All the new User documents should then have the correct class name and assembly and should then deserialize correctly. Obviously, if you are already in production, this probably won't be a good option.
Option 2: Depending on how many User documents you have, you should be able to manually edit each one to specify the correct C# class name and assembly, so that they will be deserialized correctly. Again, if you have too many objects to manually modify, this may not be a good option; however, if there are just a few, it shouldn't be too bad to open each one up go to the metadata tab and paste the correct value for "Raven-Entity-Name" and "Raven-Clr-Type".
I ended up doing this:
Advanced.DatabaseCommands.UpdateByIndex(
"Raven/DocumentsByEntityName",
new IndexQuery {Query = "Tag:Album"},
new []{ new PatchRequest() {
Type = PatchCommandType.Modify,
Name = "#metadata",
Nested= new []{
new PatchRequest{
Name= "Raven-Clr-Type",
Type = PatchCommandType.Set,
Value = "Core.Model.Album, Core" }}}},
false);

jQuery Treeview - Where do I start?

I want a treeview of dates with year, month and days. I will be using $.ajax to retrieve webservice json data. That bit is easy, but not sure how the json data should be constructed for the jquery treeview to work.
I am using http://jquery.bassistance.de/treeview/demo/ (not used before) in creating my treeview.
I've not used bassistance but have used jstree which has good documentation and examples
This link may also be helpful: http://www.jstree.com/documentation/json_data
An example of the type of json sent down might be
new object[]{
new {
attr = new {id = "node1"},
state = "closed",
data = new {
title = "Title1",
icon = "ico-database"
}
},
new {
attr = new {id = "node2"},
state = "closed",
data = new {
title = "Title2",
icon = "ico-database"
}
}
};

Categories