Telerik JustMock doesn't call expected arranged method - silverlight

I have a simple silverlight unit test which doesn't work as expected:
DataContext context = Mock.Create<DataContext>(Constructor.Mocked);
List<Resource> resources = new List<Resource>();
Resource resource = new Resource
{
ContentType = "string",
Data = Encoding.UTF8.GetBytes("Test")
};
Mock.Arrange(() => context.Resources.Add(resource)).DoInstead(() => resources.Add(resource));
Mock.Arrange(() => context.Resources.SingleOrDefault()).Returns(resources.SingleOrDefault());
context.Resources.Add(resource);
var loaded = context.Resources.SingleOrDefault();
The resource property is added correctly to the local resources (context.Resources.Add(resource)) list, however when I'm trying to read it back (context.Resources.SingleOrDefault()) nothing gets returned.

In order to return the updated value of resources.SingleOrDefault(), you will need to use lambda expression in the arrangement, like this:
Mock.Arrange(() => context.Resources.SingleOrDefault())
.Returns(() => resources.SingleOrDefault());
Otherwise, when the context.Resources.SingleOrDefault() method is called, the mock will return null, which is the value of the resources.SingleOrDefault() call at the time of the arrangement.

I don;t think you should do stubbing on the .SingleOrDefault. It is .NET FW System.Lynq extension and it is well tested. Why I meant well tested means that there is no real point in stubbing this method. You ALWAYS assume it ALWAYS gives the SingleOrDefault instance.
With your Unit Test you can stub the collection List that return by the Resources. Then simply access the SingleOrDefault. The below test passes
[TestMethod]
public void YourReadableTestMethod()
{
var context = Mock.Create<DataContext>(Constructor.Mocked);
context.Resources = new List<Resource>();
var resources = new List<Resource>();
var resource = new Resource {
ContentType = "string",
Data = Encoding.UTF8.GetBytes("Test")
};
resources.Add(resource);
Mock.Arrange(() => context.Resources).ReturnsCollection(resources);
context.Resources.Add(resource);
var loaded = context.Resources.SingleOrDefault();
Assert.IsNotNull(loaded);
}

Related

Why would the ASP.NET MVC HttpFileCollection return an array of strings rather than a Collection of HttpPostedFile?

I have an AngularJS + ASP.NET MVC 5 application where I am attempting to implement single file uploading.
On the client side I have the following code:
api.uploadFileV2 = function (alias, file, fnSuccess, fnError) {
var formData = new FormData();
formData.append(file.name, file);
$http.post('/api/V2/Upload/' + alias, formData, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(function (data) {
if (fnSuccess)
fnSuccess(data);
}).error(function (data) {
if (fnError)
fnError(data);
});
}
The file parameter is passed in from a function invoked by a button click and when executing in Chrome and in Edge I can see that the file parameter is in fact a file object.
Back on the server side I have a route to a controller defined as follows:
config.Routes.MapHttpRoute(
name: "V2UploadApi",
routeTemplate: "api/V2/Upload/{alias}/{id}",
defaults: new { controller = "Upload", id = RouteParameter.Optional }
);
Back on the server side I have my UploadController in which I have the following method defined:
public JArray Upload(string Alias)
{
JArray results = new JArray();
try
{
HttpRequest r = HttpContext.Current.Request;
HttpFileCollection c = r.Files;
foreach (var item in r.Files)
{
string theType = item.GetType().Name;
}
}
...
}
NOTE: The reason for the odd method signature with the Alias parameter is that ultimately the uploaded file will be managed by a Powershell script the selection and security level of which depends on the alias value.
Upon execution of the UploadController.Upload method I see the Alias value I'm expecting.
I do not see my file object. So var item does not resolve to the type HttpPostedFile as I expect but instead it resolves to a string type and so the variable "theType" contains "string" and not "HttpPostedFile". The HttpFileCollection doesn't actually contain a collection of HttpPostedFile objects and attempting cast the items in the collection results to the type HttpPostedFile results in an exception being thrown.
What could be causing this bizarre behavior on the server side and what can I do o correct it?
Something as basic as uploading a file should not be this difficult so I must be missing something obvious - trouble is I'm not seeing it.
So after another debugging session I altered the code to:
HttpRequest r = HttpContext.Current.Request;
HttpFileCollection c = r.Files;
foreach (string key in r.Files.Keys)
{
var item = r.Files[key];
string theType = item.GetType().Name;
}
This code not only works but also appeals to my old fashioned coding style of NOT lazily leaving absolutely everything up to the compiler using var. I wrongly assumed the enumerator of the HttpFileCollection to return (string)Key/(HttpPostedFile)Value pairs but I was wrong.

'504 - Gateway Timeout' when Indexing the items in Episerver Find

When Indexing the items, it fails sometimes and it gives,
The remote server returned an error: (504) Gateway Timeout. [The remote server returned an error: (504) Gateway Timeout.]
The Indexing logic is here as below,
var client = EPiServer.Find.Framework.SearchClient.Instance;
List<ItemModel> items = getItems(); // Get more than 1000 items
List<ItemModel> tempItems = new List<ItemModel>();
//Index 50 items at a time
foreach(var item in items)
{
tempItems.Add(item);
if (tempItems.Count == 50)
{
client.Index(tempItems);
tempItems.Clear();
}
}
What causes this to happen ?
Note: The above mentioned ItemModel is a custom model which is not implemented interfaces (such as IContent). And the items is a list of ItemModel objects.
Additional info:
EPiServer.Find.Framework version 13.0.1
EPiServer.CMS.Core version 11.9.2
I always figured the SearchClient to be a bit sketchy when manipulating data in Find, as far as I figured (but I have to check this) the SearchClient obey under the request limitation of Episerver Find and when doing bigger operations in loops it tends to time out.
Instead, use the ContentIndexer, i.e.
// Use this or injected parameter
var loader = ServiceLocator.Current.GetInstance<IContentLoader>();
// Remove all children or not
var cascade = true;
ContentReference entryPoint = ...where you want to start
// Get all indexable languages from Find
Languages languages = SearchClient.Instance.Settings.Languages;
// Remove all current instances of all languages below the selected content node
//languages.ForEach(x => ContentIndexer.Instance.RemoveFromIndex(entryPoint, cascade.Checked, x.FieldSuffix));
foreach (var lang in languages)
{
if (cascade)
{
var descendents = loader.GetDescendents(entryPoint);
foreach (ContentReference descendent in descendents)
{
ContentIndexer.Instance.RemoveFromIndex(descendent, false, lang.FieldSuffix);
}
}
// Try delete the entrypoint
var entryTest = loader.Get<IContent>(entryPoint, new CultureInfo(lang.FieldSuffix));
if (entryTest != null)
{
var delRes = ContentIndexer.Instance.Delete(entryTest);
}
}
This is the most bulletproof way to delete stuff from the index as far as I figured.

Unable to cast object of type [TweetSharp.TwitterUser]' to type 'TweetSharp.TwitterCursorList`1[TweetSharp.TwitterUser]'

hi i want to get follower list via tweetsharp but i have a exception this = Unable to cast object of type 'System.Collections.Generic.List1[TweetSharp.TwitterUser]' to type 'TweetSharp.TwitterCursorList1[TweetSharp.TwitterUser]'.
help me please HOW CAN I GET FOLLOWERLIST?
my code like this
string aranan = "anilsarii";
var AramaAyari = new SearchForUserOptions { Q = aranan, Count = 25 };
var users = ts.SearchForUser(AramaAyari); //Get list of users by query
//...
//var asd=ts.FollowList(new FollowListOptions{ OwnerId= 2603023494});
var followers = ts.ListFollowers(new ListFollowersOptions { Cursor = -1 });
while (followers.NextCursor != null)
{
followers = ts.ListFollowers(new ListFollowersOptions { followers.NextCursor });
}
You may just need to change this line;
followers = ts.ListFollowers(new ListFollowersOptions { followers.NextCursor });
to
followers = ts.ListFollowers(new ListFollowersOptions { Cursor = followers.NextCursor });
If that doesn't work, it's likely a problem in TweetSharp itself. TweetSharp has been abandoned by the original authors and is no longer maintained. As a result, there are a number of problems using it with the current Twitter API, due to changes on Twitter's end in the last few years. However there are several forks of TweetSharp that are current.
I tried your code with the one line modified above using TweetMoaSharp (a fork, available on Nuget, or on github here; https://github.com/Yortw/tweetmoasharp) and it worked fine.
Full disclosure: TweetMoaSharp is a fork primarily maintained by me. If you search Nuget for 'TweetSharp' you should find several others.

Circular references and stack overflow exceptions

I have this many to many association between KundeInfo and HovedKategori, which I have mapped in my MS SQL database like this:
I have implemented the methods KundeInfo.HovedKategoris:
public IEnumerable<KundeInfo> KundeInfos
{
get
{
using (var dc = new DataClassesBSMAKSDataContext())
{
dc.DeferredLoadingEnabled = false;
var kundeInfoHovedKategoris = dc.KundeInfoHovedKategoris.Where(x => x.HovedKategori_Id == Id);
var kundeInfos = dc.KundeInfos.Where(x => kundeInfoHovedKategoris.Any(y => y.KundeInfo_Id == x.Id));
return kundeInfos.ToList();
}
}
}
... and HovedKategori.KundeInfos:
public IEnumerable<HovedKategori> HovedKategoris
{
get
{
using (var dc = new DataClassesBSMAKSDataContext())
{
var kundeInfoHovedKategoris = dc.KundeInfoHovedKategoris.Where(x => x.KundeInfo_Id == Id);
var hovedKategoris = dc.HovedKategoris.Where(x => kundeInfoHovedKategoris.Any(y => y.HovedKategori_Id == x.Id));
return hovedKategoris.ToList();
}
}
}
This retrieves the associated KundeInfos from a specific HovedKategori and opposite. The problemhowever lies in the serialization. When I call ToList(), or serialize these objects to JSON, linq will try to first follow all references returned by HovedKategori.KundeInfos, if it were that method I were to call first, and then it would for each returned object, try to follow all references returned by KundeInfo.HovedKategoris and so on, until it would cast a stack overflow exception.
If I could somehow prevent linq from following certain properties with an [Ignore] attribute or something, it would work, but I haven't been able to find anything like that.
What can I do in this situation?
This is in part a design issue. What you should really ask yourself is if you need navigation properties in every possible direction. For example if you just add a Kategori ID instead of a navigation property you could still query your context (by using the ID) but do you really need to always get all the Kategori's with all underlying data?
also if you make your properties virtual you have lazy loading and will only get the information if you .Include it or explicitly reference it.
Ok - So I solved this problem by just making it into methods on the respective classes, which it should be in the first place, since it retrieved these entities from the database. So yes, partially design issue.
Virtual did not work, I considered using projection and an abstract class, but it would be such a haystack of inheritance, and class casts, that it would not even be worth considering.
public IEnumerable<KundeInfo> KundeInfos()
{
using (var dc = new DataClassesBSMAKSDataContext())
{
var kundeInfoHovedKategoris = dc.KundeInfoHovedKategoris.Where(x => x.HovedKategori_Id == Id);
var kundeInfos = dc.KundeInfos.Where(x => kundeInfoHovedKategoris.Any(y => y.KundeInfo_Id == x.Id));
return kundeInfos.ToList();
}
}

RIA-Services - how to WhereOr or use an IN style construct

I am using SL 4, WCF RIA Services against Entity Framework 4.0. I have an Entity, Visit, that has a string Status field. I have a search screen where I need to display results that have StatusA or StatusB. I am struggling to find a way to specify a client-side query that specifies a collection of statuses that should be matched. If I was to write what I want in SQL it would look something like:
select * from Visit where Status in ('StatusA', 'StatusB');
Client side, it appears to be straightforward to chain Where methods for a WhereAnd effect:
var query = this.PqContext.GetVisitsQuery();
if (!string.IsNullOrEmpty(this.PracticeName))
{
query = query.Where(v => v.PracticeName.ToUpper().Contains(this.PracticeName.ToUpper()));
}
if (this.VisitDateAfter.HasValue)
{
query = query.Where(v => v.VisitDate > this.VisitDateAfter);
}
if (this.VisitDateBefore.HasValue)
{
query = query.Where(v => v.VisitDate < this.VisitDateBefore);
}
However, I can't seem to find a straightforward way to do a WhereOr style operation. I have tried this:
var statuses = new List<string>();
if (this.ShowStatusA)
{
statuses.Add("StatusA");
}
if (this.ShowStatusB)
{
statuses.Add("StatusB");
}
if (statuses.Any())
{
query = query.Where(BuildContainsExpression<Visit, string>(e => e.Status, statuses));
}
Where BuildContainsExpression looks like:
private static Expression<Func<TElement, bool>> BuildContainsExpression<TElement, TValue>(Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
{
if (null == valueSelector)
{
throw new ArgumentNullException("valueSelector");
}
if (null == values)
{
throw new ArgumentNullException("values");
}
ParameterExpression p = valueSelector.Parameters.Single();
if (!values.Any())
{
return e => false;
}
var equals =
values.Select(
value =>
(Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));
var body = equals.Aggregate<Expression>(Expression.Or);
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
But this throws a "Bitwise operators are not supported in queries." exception. Any clues? Is there an alternative way to build an expression tree that works here or do I need to pass all the parameters over to the server and use the BuildContainsExpression there?
Your time and your guidance are much appreciated.
You can create a query method such as the following in your domain service:
GetVisitsByStatus(string[] statusList) {
// create the LINQ where clause here
}
And then from the client, call context.GetVistsByStatusQuery(string[]).
Not all of LINQ is (or even can) be exposed over the URL, so there are always cases where you need to use simple parameters, and have the middle tier construct the LINQ expressions that eventually define the query that goes to the back-end data store.
Hope that helps.

Resources