Trying to add unit test for the below controller.
public HttpResponseMessage pldindexingSummary()
{
try
{
Logger.log.Info("Begin GET api/capturestats/pldindexingsummary request from " + HttpContext.Current.User.Identity.Name);
using (Utilities.CreateTransactionScope())
{
if (!PLDGlobals.isPopulated) _repository.PopulatePLDGlobals();
return Request.CreateResponse(HttpStatusCode.OK, _repository.GetIndexingSummary());
}
}
catch (EntityException enEx)
{
Logger.log.Error("Entity Error in GET api/capturestats/pldindexingsummary", enEx);
Utilities.SendEmail("GET api/capturestats/pldindexingsummary", Utilities.EntityError + enEx.Message, enEx.StackTrace.ToString(), string.Empty);
HttpError error = new HttpError(Utilities.EntityError + enEx.Message);
return Request.CreateResponse(HttpStatusCode.InternalServerError, error);
}
catch (Exception ex)
{
Logger.log.Error("General Error in GET api/capturestats/pldindexingsummary", ex);
Utilities.SendEmail("GET api/capturestats/pldindexingsummary", Utilities.ExceptionError + ex.Message, ex.StackTrace.ToString(), string.Empty);
HttpError error = new HttpError(Utilities.ExceptionError + ex.Message);
return Request.CreateResponse(HttpStatusCode.InternalServerError, error);
}
}
public static TransactionScope CreateTransactionScope()
{
var transactionOptions = new TransactionOptions();
transactionOptions.IsolationLevel = IsolationLevel.ReadUncommitted;
transactionOptions.Timeout = TransactionManager.MaximumTimeout;
return new TransactionScope(TransactionScopeOption.Required, transactionOptions);
}
This is what i have done so far.
[TestMethod]
public void GetAllIndexingSummary()
{
// Arrange
var mockRepository = new Mock<IPLDRepository>();
mockRepository.Setup(x => x.GetIndexingSummary())
.Returns(new List<IndexingSummaryResponseDTO>
{
new IndexingSummaryResponseDTO {DocumentQueueId =1, DocumentQueueName = "Sales Upload", DepartmentName = "PLD_SalesUpload", DocumentCount= 10, OldestDocumentDate = "09/01/2016 09:25:50", UserLocation = "Dover" , IsChecked = false, Usernames = "Gupta_A_N0182727, Ansara_E_N0000391, Aronson_D_N0175509" },
new IndexingSummaryResponseDTO {DocumentQueueId =2, DocumentQueueName = "Inbound Fax Manual", DepartmentName = "PLD_InboundFaxManual", DocumentCount= 20, OldestDocumentDate = "09/02/2016 12:55:04", UserLocation = "Dover" , IsChecked = false, Usernames = "Bent_E_N0156485, Herron_E_N0175690" },
new IndexingSummaryResponseDTO {DocumentQueueId =3, DocumentQueueName = "Rating Scan", DepartmentName = "PLD_RatingScan", DocumentCount= 30, OldestDocumentDate = "09/03/2016 04:45:08", UserLocation = "Dover" , IsChecked = false, Usernames = "Gupta_A_N0182727, Jinkens_M_N0178324" },
new IndexingSummaryResponseDTO {DocumentQueueId =4, DocumentQueueName = "Indexing/Loading Error", DepartmentName = "PLD_IndexingLoadingError", DocumentCount= 50, OldestDocumentDate = "09/04/2016 05:10:28", UserLocation = "Dover" , IsChecked = false, Usernames = "Gupta_A_N0182727, Keshavarz_M_N0070514" },
new IndexingSummaryResponseDTO {DocumentQueueId =5, DocumentQueueName = "Prod Center Scan", DepartmentName = "PLD_ProdCenterScan", DocumentCount= 60, OldestDocumentDate = "09/05/2016 16:12:12", UserLocation = "Dover" , IsChecked = false, Usernames = "Libby_S_N0145549, Long_S_N0236534, Miller_K_N0177119" },
new IndexingSummaryResponseDTO {DocumentQueueId =6, DocumentQueueName = "Prod Center Inbound Fax", DepartmentName = "PLD_ProdCenterInboundFax", DocumentCount= 70, OldestDocumentDate = "09/06/2016 15:25:03", UserLocation = "Dover" , IsChecked = false, Usernames = "Parmer_N_N0290328, Porter_S_N0074020" },
new IndexingSummaryResponseDTO {DocumentQueueId =7, DocumentQueueName = "Research Dover", DepartmentName = "PLD_ResearchDover", DocumentCount= 0, OldestDocumentDate = "N/A", UserLocation = "Dover" , IsChecked = false, Usernames = "Porter_S_N0074020" },
new IndexingSummaryResponseDTO {DocumentQueueId =8, DocumentQueueName = "Orlando Fax/Scan", DepartmentName = "PLD_OrlandoFaxScan", DocumentCount= 80, OldestDocumentDate = "09/08/2016 21:25:03", UserLocation = "Orlando" , IsChecked = false, Usernames = "Putnam_S_N0199165" },
new IndexingSummaryResponseDTO {DocumentQueueId =9, DocumentQueueName = "Research Orlando Fax/Scan", DepartmentName = "PLD_ResearchOrlandoFaxScan ", DocumentCount= 10, OldestDocumentDate = "09/09/2016 18:25:03", UserLocation = "Orlando" , IsChecked = false, Usernames = "Seefeld_J_N0030634" },
});
var controller = new CaptureStatsController(mockRepository.Object);
controller.Request = new HttpRequestMessage();
controller.Configuration = new HttpConfiguration();
//Act
var result = controller.pldindexingSummary();
Assert.IsNotNull(result, "Result is null");
IList<IndexingSummaryResponseDTO> product;
Assert.IsTrue(result.TryGetContentValue<IList<IndexingSummaryResponseDTO>>(out product));
Assert.AreEqual(10, product.Count);
}
I am getting NullReference Exception : Object reference not set to an instance of object.
This is my first Unit test.I am not sure where it is going wrong. I have followed the Microsoft article. reference link :
https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api
Related
So basically I wanted to do:
json code,
statement,
when statement is true,some other json text
continuation of previous json code
This is currently my code and I'm looking a way to shorten it, any solutions?
if (textBox1.Text != "Enter Address")
{
if (textBox2.Text != "Enter Address")
{
//1+2+3 OK
if (textBox3.Text != "Enter Address")
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic {
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "easy",
name = textBox15.Text,
difficulty = Convert.ToInt32(numericUpDown1.Value),
path = textBox1.Text
},
new ItemChart
{
type = "hard",
name = textBox16.Text,
difficulty = Convert.ToInt32(numericUpDown2.Value),
path = textBox2.Text
},
new ItemChart
{
type = "extreme",
name = textBox17.Text,
difficulty = Convert.ToInt32(numericUpDown3.Value),
path = textBox3.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
//1+2 (3) OK
else
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "easy",
name = textBox15.Text,
difficulty = Convert.ToInt32(numericUpDown1.Value),
path = textBox1.Text
},
new ItemChart
{
type = "hard",
name = textBox16.Text,
difficulty = Convert.ToInt32(numericUpDown2.Value),
path = textBox2.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
}
else
{
//1+3 (2) OK
if (textBox3.Text != "Enter Address")
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "easy",
name = textBox15.Text,
difficulty = Convert.ToInt32(numericUpDown1.Value),
path = textBox1.Text
},
new ItemChart
{
type = "extreme",
name = textBox17.Text,
difficulty = Convert.ToInt32(numericUpDown3.Value),
path = textBox3.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
//1 (2)(3) OK
else
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "easy",
name = textBox15.Text,
difficulty = Convert.ToInt32(numericUpDown1.Value),
path = textBox1.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
}
}
else
if (textBox2.Text != "Enter Address")
{
//2+3 (1) OK
if (textBox3.Text != "Enter Address")
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "hard",
name = textBox16.Text,
difficulty = Convert.ToInt32(numericUpDown2.Value),
path = textBox2.Text
},
new ItemChart
{
type = "extreme",
name = textBox17.Text,
difficulty = Convert.ToInt32(numericUpDown3.Value),
path = textBox3.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
//2 (1)(3)
else
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "hard",
name = textBox16.Text,
difficulty = Convert.ToInt32(numericUpDown2.Value),
path = textBox2.Text
}
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
}
else
{
var item = new Item
{
version = 1,
schema_version = 2,
id = textBox14.Text,
title = textBox7.Text,
title_localized = textBox18.Text,
artist = textBox6.Text,
artist_localized = textBox8.Text,
artist_source = textBox9.Text,
illustrator = textBox10.Text,
illustrator_source = textBox11.Text,
charter = textBox13.Text,
music = new ItemMusic
{
path = textBox4.Text
},
music_preview = new ItemMusicPreview
{
path = textBox5.Text
},
background = new ItemBackground
{
path = open3.SafeFileName
},
charts = new List<ItemChart>
{
new ItemChart
{
type = "extreme",
name = textBox17.Text,
difficulty = Convert.ToInt32(numericUpDown3.Value),
path = textBox3.Text
},
}
};
var settings = new JsonSerializerSettings()
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new SnakeCaseNamingStrategy()
}
};
var json = JsonConvert.SerializeObject(item, settings);
if (File.Exists(#"C:\Users\Public\Desktop\level files\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory(#"C:\Users\Public\Desktop\level files\");
}
if (File.Exists($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\") == false)
{
// Make a path
System.IO.Directory.CreateDirectory($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\");
}
File.WriteAllText($#"C:\Users\Public\Desktop\level files\{textBox14.Text}\level.json", json, new UTF8Encoding(false));
}
I was going to add "storyboard = open9.FileName" to "new ItemChart"s but not add the storyboard line when the file address is not imported.
List<StoreDetailDto> items = new List<StoreDetailDto>();
items.Add(new StoreDetailDto { StoreNumber = 2, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1"});
items.Add(new StoreDetailDto { StoreNumber = 3, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1"});
items.Add(new StoreDetailDto { StoreNumber = 6, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1"});
items.Add(new StoreDetailDto { StoreNumber = 7, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1"});
items.Add(new StoreDetailDto { StoreNumber = 9, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1"});
items.Add(new StoreDetailDto { StoreNumber = 6, WarehouseNumber = 4202, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1"});
items.Add(new StoreDetailDto { StoreNumber = 7, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1"});
items.Add(new StoreDetailDto { StoreNumber = 9, WarehouseNumber = 4203, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1"});
items.Add(new StoreDetailDto { StoreNumber = 9, WarehouseNumber = 4207, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1"});
I have collection above where there is a overlapping between store 6, 9 but store 7 is not overlap it's a duplicate. I am finding overlaps as such that same store with different warehouse.
in order to acheive that I am doing below:
var overlapDupStores = items.GroupBy(
u => u.StoreNumber,
u => { return u; },
(key, g) => g.ToList())
.ToList()
.Where(cnt => cnt.Count() > 1);
foreach (var dpovl in overlapDupStores)
{
var stores = dpovl.Where(g => g.IsResolved != true).GroupBy(u => new { u.StoreNumber, u.WarehouseNumber }).ToList();
if (stores.Count() > 1)
{
response.OverlappingStores.AddRange(stores.SelectMany(gr => gr).ToList());
}
}
I am first finding stores which are duplicates , it will have object inside object with duplicates of stores with count = 2 and then grouping by storenumber and warehouse number for different store and warehouse count will still be 2 but for same store and warehouse which is duplicate it will be count = 1 so i am finding count > 1 so i can find duplicates and check Isresolved not to pull same store again once it is resolved.
Below is the fiddle:
https://dotnetfiddle.net/TknnkJ
Try this one, using LINQ's GroupBy().Select().Where() to group and filter the list of objects based on the criteria that I assume you require, given the output you showed.
A description:
GroupBy() => Groups the objects using the StoreNumber
property.
Select() => Selects the objects where the
IsResolved property is false
Where() => Filters the
objects that have more than 1 elements with different
WarehouseNumber
SelectMany()=> Flattens the Grouping, to have
all the matching objects in a sequential view
OrderBy() could be added, if required, to order the list on StoreNumber ThenBy() WarehouseNumber.
The Duplicates filter may not be correct, depending on the use case. It might be necessary to adapt it.
var Duplicates =
items.GroupBy(store => store.StoreNumber)
.Select(grp => grp.Where(store => store.IsResolved == false))
.Where(stores => stores.Count() > 1 && stores.Select(w => w.WarehouseNumber).Distinct().Count() == 1)
.SelectMany(stores => stores)
.ToList();
var Overlapping =
items.GroupBy(store => store.StoreNumber)
.Select(grp => grp.Where(store => store.IsResolved == false))
.Where(store => store.Count() > 1 && store.Select(w => w.WarehouseNumber).Distinct().Count() > 1)
.SelectMany(stores => stores)
.ToList();
Overlapping.ForEach(ovr =>
Console.WriteLine($"{ovr.StoreNumber} " +
$"{ovr.WarehouseNumber} " +
$"{ovr.IsResolved} " +
$"{ovr.StoreName} " +
$"{ovr.WarehouseName}"));
This Overlapping List prints:
6 4201 False StoreEx WarehouseEx1
6 4202 False StoreEx WarehouseEx1
9 4201 False StoreEx WarehouseEx1
9 4203 False StoreEx WarehouseEx1
9 4207 False StoreEx WarehouseEx1
This Duplicates List prints:
7 4201 False StoreEx WarehouseEx1
7 4201 False StoreEx WarehouseEx1
I think these queries do the job:
var overlaps =
items
.GroupBy(x => new { x.StoreNumber, x.WarehouseNumber })
.GroupBy(x => x.Key.StoreNumber)
.Where(x => x.Skip(1).Any())
.Where(x => !x.Any(y => y.Any(z => z.IsResolved)))
.SelectMany(x => x.SelectMany(y => y))
.ToList();
var duplicates =
items
.GroupBy(x => new { x.StoreNumber, x.WarehouseNumber })
.GroupBy(x => x.Key.StoreNumber)
.Where(x => !x.Skip(1).Any())
.Where(x => x.First().Skip(1).Any())
.Where(x => !x.Any(y => y.Any(z => z.IsResolved)))
.SelectMany(x => x.SelectMany(y => y))
.ToList();
I used this source data:
var items = new List<StoreDetailDto>()
{
new StoreDetailDto { StoreNumber = 2, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1" },
new StoreDetailDto { StoreNumber = 3, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1" },
new StoreDetailDto { StoreNumber = 6, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1" },
new StoreDetailDto { StoreNumber = 7, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1" },
new StoreDetailDto { StoreNumber = 9, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1" },
new StoreDetailDto { StoreNumber = 6, WarehouseNumber = 4202, IsResolved = true, StoreName = "StoreEx", WarehouseName = "WarehouseEx1" },
new StoreDetailDto { StoreNumber = 7, WarehouseNumber = 4201, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1" },
new StoreDetailDto { StoreNumber = 9, WarehouseNumber = 4203, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1" },
new StoreDetailDto { StoreNumber = 9, WarehouseNumber = 4207, IsResolved = false, StoreName = "StoreEx", WarehouseName = "WarehouseEx1" },
};
It's worth noting that if 7 were to have a third record with a new WarehouseNumber that it would appear in the overlaps result and would include the duplicate there.
If I understand you correctly. The following will give you want you want.
var warehouseCountsByStore =
from item in items
group item by new { item.StoreNumber, item.WarehouseNumber } into store
where store.Count() != 0
select new
{
store.Key.StoreNumber,
store.Key.WarehouseNumber,
Count = store.Count()
};
var storesWithDuplicateWarehouses =
from warehouse in warehouseCountsByStore
where warehouse.Count != 1
select new { warehouse.StoreNumber };
var storesWithMultipleWarehouse =
from item in items
group item by new { item.StoreNumber } into store
where store.Count() > 1
&& storesWithDuplicateWarehouses.Any(x => x.StoreNumber != store.Key.StoreNumber)
select new
{
store.Key.StoreNumber
};
Console.WriteLine("Duplicates");
foreach (var store in storesWithDuplicateWarehouses)
Console.WriteLine(store.StoreNumber);
Console.WriteLine("Overlap");
foreach (var store in storesWithMultipleWarehouse)
Console.WriteLine(store.StoreNumber);
I have these lists:
List<Author> MyAuthorList = new List<Author>();
List<string> BookListNo1 = new List<string>() { "The Girl with the Dragon Tattoo", "The Name of the Rose", "The Alienist", "In Cold Blood", "The Firm" };
List<string> BookListNo2 = new List<string>() { "And Then There Were None", "Mystic River", "The Shadow of the Wind", "Angels & Demons" , "The Big Sleep", "The Pelican Brief" };
List<string> BookListNo3 = new List<string>() { "One for the Money", "The Maltese Falcon", "In the Woods", "Presumed Innocent", "The Thirteenth Tale", "A is for Alibi", "Postmortem" };
List<string> BookListNo4 = new List<string>() { "Midnight in the Garden of Good and Evil", "The Strange Case of Dr. Jekyll and Mr. Hyde", "A Time to Kill", "The Historian" };
MyAuthorList.Add(new Author() { FirstName = "John", LastName = "Smith", Address = "Germany", Age = 13, NumberOfBooks = 5, EMBG = 123123, Books = BookListNo1, BankAccount = 1111, BankName = "Stupid Bank Name", BankAddress = "No One Knows" });
MyAuthorList.Add(new Author() { FirstName = "Max", LastName = "Warren", Address = "France", Age = 32, NumberOfBooks = 6, EMBG = 321321, Books = BookListNo2, BankAccount = 2222, BankName = "Stupid Bank Name", BankAddress = "Near The Bakery" });
MyAuthorList.Add(new Author() { FirstName = "Quinn", LastName = "Swanson", Address = "Russia", Age = 11, NumberOfBooks = 7, EMBG = 456456, Books = BookListNo3, BankAccount = 3333, BankName = "Stupid Bank Name", BankAddress = "On Some Desert Island" });
MyAuthorList.Add(new Author() { FirstName = "Ben", LastName = "Chaplin", Address = "Indonesia", Age = 34, NumberOfBooks = 4, EMBG = 654654, Books = BookListNo4, BankAccount = 4444, BankName = "Stupid Bank Name", BankAddress = "Moskovska 45" });
MyAuthorList.Add(new Author() { FirstName = "Jack", LastName = "Smirnoff", Address = "Germany", Age = 35, NumberOfBooks = 6, EMBG = 789789, Books = BookListNo2, BankAccount = 5555, BankName = "Stupid Bank Name 2", BankAddress = "Moskovska 452" });
Now I need to find all Authors from Germany with books that have the words "Girl" and "Blood" in them.
This is what I have tried so far:
I get all the authors from Germany like this:
var germanAuthors = MyAuthorList.Where(x => x.Address.Contains("Germany"));
..and all the books that have the words "Blood" and "Girl" in them like this:
var BooksOfAuthorsFromGermany = MyAuthorList.Where(x => x.Address.Contains("Germany")).SelectMany(y => y.Books);
List<string> words = new List<string> { "Blood", "Girl"};
var searchedListOfBooks = BooksOfAuthorsFromGermany.Where(s => words.Any(w => s.Contains(w)));
However, I can't combine these two together.
Do I need to do this in a completely different way?
Try this
var BooksOfAuthorsFromGermany = MyAuthorList
.Where(x => x.Address.Contains("Germany")
&& x.Books.Where(a => a.Contains("Girl")
|| a.Contains("Blood")).Count() > 0)
.ToList();
You can combine two query as follows ,
List<string> words = new List<string> { "Blood", "Girl"};
var AuthorList = MyAuthorList.Where(x => x.Address.Contains("Germany") && x.Books.Any(a => words.Any(w=> a.Contains(w)))).ToList();
According to your requirement you can use this
var germanAuthors = MyAuthorList.Where(x => x.Address.Contains("Germany") && x.Books.Any(y => y.Contains("Blood") && y.Contains("Girl"))).Select(Z => Z.FirstName);
var germanAuthorsWithBloodOrGirl = MyAuthorList.Where(x => x.Address.Contains("Germany") && x.Books.Any(y => y.Contains("Blood") || y.Contains("Girl"))).Select(Z => Z.FirstName);
I have a seed method which fills up my database with some seed data. It works for the most part but my directors are being duplicated. Of course this is not what I want. Here's the code:
protected override void Seed(MovieModel.MovieContext context)
{
var genres = new List<Genre>
{
new Genre{Description = "Action", Movies = new List<Movie>()
{
new Movie{Title = "The Expandables", Duration = 120, Director = new Director
{
FirstName = "Silvester", LastName = "Stallone"
}},
new Movie{Title = "The Expandables II", Duration = 96, Director = new Director
{
FirstName = "Silvester", LastName = "Stallone"
}},
new Movie{Title = "The Expandables III", Duration = 86, Director = new Director
{
FirstName = "Silvester", LastName = "Stallone"
}}
}},
new Genre{Description = "Thriller", Movies = new List<Movie>()
{
new Movie{Title = "Pulp Fiction", Duration = 110, Director = new Director
{
FirstName = "Quentin", LastName = "Tarrantino"
}},
new Movie{Title = "Inglorious Bastards", Duration = 142, Director = new Director
{
FirstName = "Quentin", LastName = "Tarrantino"
}}
}},
new Genre{Description = "Fantasy", Movies = new List<Movie>()
{
new Movie{Title = "The Fellowship of the Ring", Duration = 220, Director = new Director
{
FirstName = "Peter", LastName = "Jackson"
}},
new Movie{Title = "The Two Towers", Duration = 210, Director = new Director
{
FirstName = "Peter", LastName = "Jackson"
}},
new Movie{Title = "The Return of the King", Duration = 230, Director = new Director
{
FirstName = "Peter", LastName = "Jackson"
}}
}},
new Genre{Description = "Horror", Movies = new List<Movie>()
{
new Movie{Title = "Texas Chainsaw Massacre", Duration = 86, Director = new Director
{
FirstName = "Wayne", LastName = "Rooney"
}},
new Movie{Title = "Annabelle", Duration = 90, Director = new Director
{
FirstName = "Cristiano", LastName = "Ronaldo"
}}
}},
new Genre{Description = "Science Fiction", Movies = new List<Movie>()
{
new Movie{Title = "Interstellar", Duration = 245, Director = new Director
{
FirstName = "Gareth", LastName = "Bale"
}},
new Movie{Title = "Pandorum", Duration = 90, Director = new Director
{
FirstName = "David", LastName = "Beckham"
}}
}}
};
genres.ForEach(g => context.Genres.AddOrUpdate(u => u.Description, g));
context.SaveChanges();
}
The Director, Movie and Genre class have simple get and set properties and navigation properties. As it currently is the genres and movies are inserted without duplicate data. However Silvester Stallone is inserted 3 times as a director. How do I solve this?
This is because you are creating multiple instances Director - EF has no way to know that if it sees two instances of Director with the same first & last name it should only create a single row, so it creates two rows.
At a guess what you want to do is something like this:
protected override void Seed(MovieModel.MovieContext context)
{
var stallone = new Director { FirstName = "Silvester", LastName = "Stallone" };
var tarrantino = new Director { FirstName = "Quentin", LastName = "Tarrantino" };
var jackson = new Director { FirstName = "Peter", LastName = "Jackson" };
var rooney = new Director { FirstName = "Wayne", LastName = "Rooney" };
var ronaldo = new Director { FirstName = "Cristiano", LastName = "Ronaldo" };
var bale = new Director { FirstName = "Gareth", LastName = "Bale" };
var beckham = new Director { FirstName = "David", LastName = "Beckham" };
var genres = new List<Genre>
{
new Genre{Description = "Action", Movies = new List<Movie>()
{
new Movie{Title = "The Expandables", Duration = 120, Director = },
new Movie{Title = "The Expandables II", Duration = 96, Director = stallone},
new Movie{Title = "The Expandables III", Duration = 86, Director = stallone}
}},
new Genre{Description = "Thriller", Movies = new List<Movie>()
{
new Movie{Title = "Pulp Fiction", Duration = 110, Director = tarrantino},
new Movie{Title = "Inglorious Bastards", Duration = 142, Director = tarrantino}
}},
new Genre{Description = "Fantasy", Movies = new List<Movie>()
{
new Movie{Title = "The Fellowship of the Ring", Duration = 220, Director = jackson},
new Movie{Title = "The Two Towers", Duration = 210, Director = jackson},
new Movie{Title = "The Return of the King", Duration = 230, Director = jackson}
}},
new Genre{Description = "Horror", Movies = new List<Movie>()
{
new Movie{Title = "Texas Chainsaw Massacre", Duration = 86, Director = rooney},
new Movie{Title = "Annabelle", Duration = 90, Director = ronaldo}
}},
new Genre{Description = "Science Fiction", Movies = new List<Movie>()
{
new Movie{Title = "Interstellar", Duration = 245, Director = bale},
new Movie{Title = "Pandorum", Duration = 90, Director = beckham}
}}
};
genres.ForEach(g => context.Genres.AddOrUpdate(u => u.Description, g));
context.SaveChanges();
}
I.e. only create a single instance of Director for each row you want in your database.
(You would end up having the same problem if you had the same film in multiple Genres)
This is My Type:
public class MyObj {
public long Number { get; set; }
public string Name { get; set; }
public string Message { get; set; }
public DateTime RegisterDate { get; set; }
}
So I have a list of Myobj And I need to split the list to some lists where the objects of Name and Number of objects are equal, some thing like grouped by Name and Number:
assume this Sample:
List<MyObj> MyObjects = new List<MyObj>{
new MyObj() { Number = 1, Name = "BMW", Message = "msg1", RegisterDate = DateTime.Now },
new MyObj() { Number = 1, Name = "BMW", Message = "msg2", RegisterDate = DateTime.Now },
new MyObj() { Number = 1, Name = "BMW", Message = "msg3", RegisterDate = DateTime.Now },
new MyObj() { Number = 1, Name = "Honda", Message = "msg11", RegisterDate = DateTime.Now },
new MyObj() { Number = 1, Name = "Honda", Message = "msg12", RegisterDate = DateTime.Now },
new MyObj() { Number = 2, Name = "BMW", Message = "msg22", RegisterDate = DateTime.Now },
new MyObj() { Number = 2, Name = "BMW", Message = "msg23", RegisterDate = DateTime.Now },
new MyObj() { Number = 2, Name = "BMW", Message = "msg24", RegisterDate = DateTime.Now },
new MyObj() { Number = 2, Name = "Honda", Message = "msg30", RegisterDate = DateTime.Now },
new MyObj() { Number = 3, Name = "BMW", Message = "msg41", RegisterDate = DateTime.Now },
new MyObj() { Number = 3, Name = "BMW", Message = "msg42", RegisterDate = DateTime.Now },
new MyObj() { Number = 3, Name = "Ford", Message = "msg51", RegisterDate = DateTime.Now },
new MyObj() { Number = 3, Name = "Ford", Message = "msg52", RegisterDate = DateTime.Now },
new MyObj() { Number = 3, Name = "Ford", Message = "msg53", RegisterDate = DateTime.Now }
};
So I need a List<List<MyObj>> :
List<MyObj> MyObjectwith1AndBMW = new List<MyObj> {
new MyObj() { Number = 1, Name = "BMW", Message = "msg1", RegisterDate = DateTime.Now },
new MyObj() { Number = 1, Name = "BMW", Message = "msg2", RegisterDate = DateTime.Now },
new MyObj() { Number = 1, Name = "BMW", Message = "msg3", RegisterDate = DateTime.Now }
};
List<MyObj> MyObjectWith1AndHonda = new List<MyObj> {
new MyObj() { Number = 1, Name = "Honda", Message = "msg11", RegisterDate = DateTime.Now },
new MyObj() { Number = 1, Name = "Honda", Message = "msg12", RegisterDate = DateTime.Now }
};
List<MyObj> MyObjectWith2AndBMW = new List<MyObj> {
new MyObj() { Number = 2, Name = "BMW", Message = "msg22", RegisterDate = DateTime.Now },
new MyObj() { Number = 2, Name = "BMW", Message = "msg23", RegisterDate = DateTime.Now },
new MyObj() { Number = 2, Name = "BMW", Message = "msg24", RegisterDate = DateTime.Now }
};
List<MyObj> MyObjectWith2AndHonda = new List<MyObj> {
new MyObj() { Number = 2, Name = "Honda", Message = "msg30", RegisterDate = DateTime.Now }
};
List<MyObj> MyObjectwith3AndBMW = new List<MyObj> {
new MyObj() { Number = 3, Name = "BMW", Message = "msg41", RegisterDate = DateTime.Now },
new MyObj() { Number = 3, Name = "BMW", Message = "msg42", RegisterDate = DateTime.Now }
};
List<MyObj> MyObjectWith3AndFord = new List<MyObj> {
new MyObj() { Number = 3, Name = "Ford", Message = "msg51", RegisterDate = DateTime.Now },
new MyObj() { Number = 3, Name = "Ford", Message = "msg52", RegisterDate = DateTime.Now },
new MyObj() { Number = 3, Name = "Ford", Message = "msg53", RegisterDate = DateTime.Now }
};
the result is :
List<List<MyObj>> result = new List<List<MyObj>> {
MyObjectwith1AndBMW,
MyObjectWith1AndHonda,
MyObjectWith2AndBMW,
MyObjectWith2AndHonda,
MyObjectwith3AndBMW,
MyObjectWith3AndFord
};
SO what is your suggestion? How can I find list of MyObj with same the equal names and equal numbers?
List<List<MyObj>> result = MyObjects.GroupBy(m => new { m.Name, m.Number })
.Select(g => g.ToList())
.ToList();
var groups = (from row in MyObjects
group row by new { row.Number, row.Name } into grp
select grp.ToList()).ToList();
which is a List<List<MyObj>> grouped by .Number and .Name (together).