Subsonic:SimpleRepository Parent Child relationship - subsonic3

I am trying to use the SimpleRepository feature in Subsonic3 - first of all, I must say a big thanks to RobC - Subsonic really rocks, and I can't wait to see additional updates to the SimpleRepository. I am a big fan of the migration approach (developer/class driven rather than starting with the DB).
I have had a look at the post here:
Parent and Child object in SimpleRepository
but I am still a bit confused.
If I have got these classes defined:
public class Permit {
public int PermitID {get; set;}
public string Number { get; set; }
public DateTime? DateIssued { get; set; }
public Product product { get; set; }
}
public class Product
{
public int ProductID { get; set; }
public string Value { get; set; }
}
and then I want to save the data for a Permit, what should I be doing? Should I have defined a ProductID in the Permit class, and then programatically link them up? Or should the below code work?
var repo = new SimpleRepository("ECPermit", SimpleRepositoryOptions.RunMigrations);
var permit = new Permit();
var product = new Product();
permit.Number = "apermit";
permit.DateAdded = DateTime.Now;
product.Value = "this is a product";
repo.Add(permit);
permit.product = product;
repo.Add(product);
This is creating the Permit and Product table, but no links between them. What am I doing wrong?
Thanks

What you need to be aware of here is that the relationships are created by populating foreign keyvalues. So what you're doing in your example is creating a permit and saving it then setting the ProductID of the permit (but not saving this information), then saving the product. If you reorder your code as follows the ProductID will be set correctly:
var repo = new SimpleRepository("ECPermit", SimpleRepositoryOptions.RunMigrations);
var permit = new Permit();
var product = new Product();
product.Value = "this is a product";
repo.Add(product);
permit.Number = "apermit";
permit.DateAdded = DateTime.Now;
permit.ProductId = product.Id;
repo.Add(permit);

Related

How to get distinct values from 2 different columns in the same list

So as you can see from the code bellow i have a list object named Matches, from which i would like to get a single list of the distinct teams, both from HomeTeam and AwayTeam. I'm trying to use LINQ and i can get a list of distinct teams if i only use HomeTeam parameter or AwayTeam parameter but not both together.
Thank you.
public class Match
{
public int ID { get; set; }
public string Country { get; set; }
public string Championship { get; set; }
public string Seasson { get; set; }
public DateTime MatchDate { get; set; }
public string HomeTeam { get; set; }
public int HomeScore { get; set; }
public int AwayScore { get; set; }
public string AwayTeam { get; set; }
}
private List<Match> Matches;
Matches = dataAccess.GetAllMatches();
I'm Trying to do something like that:
result = Matches.Select(HomeTeam, AwayTeam).Distinct().ToList();
At the risk that this smells like homework, a hint rather than code. Get your Home teams, Union your Away teams and apply a Distinct to the result.
So i finally come up with this solution.
Notice that now i need also to get not only the team but the country which the team belongs to.
public class Team
{
public string Name { get; set; }
public string Country { get; set; }
}
So Union really do the job here but since now i need to get it as an anonymous type... here is the code:
List<Team> teams = new List<Team>();
var result = Matches.Select(x => new { Name = x.HomeTeam, Country = x.Country }).Union(Matches.Select(x => new { Name = x.AwayTeam, Country = x.Country })).ToList();
foreach (var record in result)
{
teams.Add(new Team { Name = record.Name, Country = record.Country });
}
return teams;
I would prefer this way:
List<Team> teamsResult = Matches.Select(x => new Team { Name = x.HomeTeam, Country = x.Country }).Union(Matches.Select(x => new Team { Name = x.AwayTeam, Country = x.Country })).ToList();
But this way get duplicates so i will stick with the first example for now.
Do you think it is the more elegant way to go?
Thank you.
You can take advantage of GroupBy, like this:
IEnumerable<Team> teams = Matches.GroupBy(m => new { m.AwayTeam, m.HomeTeam, m.Country })
.Select(
g =>
new[]
{
new Team {Country = g.Key.Country, Name = g.Key.AwayTeam},
new Team {Country = g.Key.Country, Name = g.Key.HomeTeam}
})
.SelectMany(x => x)
.GroupBy(t => new { t.Name, t.Country })
.Select(g => new Team { Name = g.Key.Name, Country = g.Key.Country });

How to convert a dynamic list into list<Class>?

I'm trying to convert a dynamic list into a list of class-model(Products). This is how my method looks like:
public List<Products> ConvertToProducts(List<dynamic> data)
{
var sendModel = new List<Products>();
//Mapping List<dynamic> to List<Products>
sendModel = data.Select(x =>
new Products
{
Name = data.GetType().GetProperty("Name").ToString(),
Price = data.GetType().GetProperty("Price").GetValue(data, null).ToString()
}).ToList();
}
I have tried these both ways to get the property values, but it gives me null errors saying these properties doesn't exist or they are null.
Name = data.GetType().GetProperty("Name").ToString(),
Price = data.GetType().GetProperty("Price").GetValue(data,
null).ToString()
This is how my Model-class looks like:
public class Products
{
public string ID { get; set; }
public string Name { get; set; }
public string Price { get; set; }
}
Can someone please let me know what I'm missing? thanks in advance.
You're currently trying to get properties from data, which is your list - and you're ignoring x, which is the item in the list. I suspect you want:
var sendModel = data
.Select(x => new Products { Name = x.Name, Price = x.Price })
.ToList();
You may want to call ToString() on the results of the properties, but it's not clear what's in the original data.

Why Glass Mapper Returning Null Values?

I'm using Glass V4. I have a set up of MVC Web Area Project.
I have installed the Glass Mapper in the Main Project (WebProject).
I'm trying to do the Glass Casting in my Area Project.
public class ContactController : SitecoreController
{
private readonly ISitecoreContext _context;
private IGlassHtml _glassHtml;
public ContactController()
: this(new SitecoreContext())
{
}
public ContactController(ISitecoreContext context)
{
_context = context;
_glassHtml = new GlassHtml(context);
}
// GET: Contact
public ActionResult ContactUs()
{
var db = Sitecore.Context.Database;
var datasource = db.GetItem(RenderingContext.Current.Rendering.DataSource);
var ViewModel = new Models.ContactUs();
ViewModel.Headerstring = datasource.Fields["Headerstring"].Value;
ViewModel.Substring = datasource.Fields["Substring"].Value;
ViewModel.Description = ((MultilistField)datasource.Fields["Description"]).GetItems().Select(s => s.Fields["Line"].Value).ToList<string>();
return View(ViewModel);
}
public ActionResult ContactUsGlass()
{
var model = _context.GetCurrentItem<ContactUsGlassModel>();
return View(model);
}
}
I'm able to get the value with the First Action Method but not with the second.
Model:
public class ContactUs
{
public string Headerstring { get; set; }
public string Substring { get; set; }
public List<string> Description { get; set; }
}
Glass Model:
public class ContactUsGlassModel
{
public virtual string Headerstring { get; set; }
public virtual string Substring { get; set; }
}
I understand I don't need to register my Namespace in Glass V4.
You should not use _context.GetCurrentItem method. Use _context.GetItem instead:
public ActionResult ContactUsGlass()
{
var model = context.GetItem<ContactUsGlassModel>(RenderingContext.Current.Rendering.DataSource);
return View(model);
}
You don't want to get model from your Sitecore.Context.Item (which is used in GetCurrentItem method. You want to get your model from the DataSource of the current rendering.
What #Marek has answered is the right way of pulling the rendering item into model. GetCurrentItem by default gives the page item being served by Sitecore. If the fields that your model needs are fields of your page item then GetCurrentItem can also fill your model. If Datasource nesting is enabled, then if the datasource is not set on the rendering, Sitecore returns the page item again.
You can inherit from GlassController and then use GetLayoutItem() to get the datasorced item. If it's null then you need to publish the template in sitecore and make sure you mappings are correct if you are not using TDS :)

Extract mail list addresses from MailGun

I want to extract the addresses OUT OF MailGun, into a CSV and delete the MailGun altogether.
The MailGun database is the only copy of the 951 addresses I have absolutely no access to the database in any form other than looking at the list in MailGun.
http://documentation.mailgun.com/api-mailinglists.html#mailing-lists
This is my solution to this problem in C# ,and it can get all members of a list(not only 100 limited).In addition, i use Newtonsoft.Json. Update: I found the 'total_count' has a maximum value 10000, so if the members in your mailing list is more than 10000, the request will return the maximum value 10000! In that case, this is not a great solution!
public void ExportMailList(string listName)
{
RestClient client = new RestClient();
List<MemberDetail> totalMember = new List<MemberDetail>();
client.BaseUrl = new Uri("https://api.mailgun.net/v3");
client.Authenticator =
new HttpBasicAuthenticator("api",
"key-yourKey");
RestRequest reqForTotal = new RestRequest();
reqForTotal.Resource = "lists/{list}/members";
reqForTotal.AddParameter("list", listName, ParameterType.UrlSegment);
int resultTotal= JsonConvert.DeserializeObject<Member>(client.Execute(reqForTotal).Content).total_count;
int skipTimes = resultTotal / 100;
for (int i = 0; i <= skipTimes; i++)
{
RestRequest request = new RestRequest();
request.Resource = "lists/{list}/members";
request.AddParameter("list", listName, ParameterType.UrlSegment);
request.AddParameter("skip",100*i);
totalMember.AddRange(JsonConvert.DeserializeObject<Member>(client.Execute(request).Content).items);
}
//CreateCSVFromGenericList(...);
}
public class Member
{
public List<MemberDetail> items { get; set; }
public int total_count { get; set; }
}
public class MemberDetail
{
public string address { get; set; }
public string name { get; set; }
public bool subscribed { get; set; }
public object vars { get; set; }
}
In the method CreateCSVFromGenericList(..), you can refer to this blog, and export the data to .csv file in any format you want.
Using curl,php or any other programming language you can achieve this, then simply delete the mailing list through the control panel:
curl -s --user 'api:YOURAPIKEY' -G \
https://api.mailgun.net/v2/lists/Your#MailingListName.com/members
Apikey and mailing list name are available from the control panel!
In python :
def get_members():
return requests.get(
"https://api.mailgun.net/v3/lists/LIST_NAME/members",
auth=("api", "key-YOUR_KEY"),
data={'limit': 100, 'skip': 1380})
Note that limit and skip are useful to paginate through your member list.

How to update the content inside a list in c#

I have a class as follow:
public class student
{
public string studentID { get; set; }
public string studentName { get; set; }
public string studentGender { get; set; }
public string studentCGP { get; set; }
}
List<student> students = new List<student>();
..... I had added some data into the students List mention above, except for the data to the studentCGP.
After my other calculation for the studentCGP data, how do I put the data back to respectively? I'll have the studentID and studentCGP in hand.
using Linq...
var student = students.Find( x => x.studentID == idValue );
student.studentCGP = cgpValue;
Seems pretty trivial... am I missing something in the question?
students.Single(o => o.studentID == idValue).studentCGP = cgpValue;
There is a number of functions that you can use, just choose the one that suits you the best. For example you can use also First, Last etc.