HttpFileCollectionBase: Mocking Count-Property - asp.net-mvc

I try to mock the Count-Property of an instance of HttpFileCollectionBase - but somehow it doesn't work.
var fakedRequest = new Mock<HttpRequestBase>();
var fakedFile = new Mock<HttpPostedFileBase>();
fakedFile.SetupGet(x => x.InputStream).Returns(inputStream);
var fakedFileCollection = new Mock<HttpFileCollectionBase>();
fakedFileCollection.SetupGet(x => x.Count).Returns(1);
fakedRequest.SetupGet(x => x.Files).Returns(fakedFileCollection.Object);
fakedRequest.SetupGet(x => x.Files[0]).Returns(fakedFile.Object);
var sut = new TestableExploreController(null, fakedTemporaryStorageRepository.Object)
{
HttpRequest = fakedRequest.Object
};
As you see, I create a mocked HttpRequest, which I inject to the system under test. The Count-Property is defined to return 1 - but it always returns 0. I'm using Moq.
What am I doing wrong?

Scott Hanselman blogged about this. The problem is the following line:
fakedRequest.SetupGet(x => x.Files[0]).Returns(fakedFile.Object);
Try like this and it should work:
var fakedRequest = new Mock<HttpRequestBase>();
var fakedFile = new Mock<HttpPostedFileBase>();
fakedFile.SetupGet(x => x.InputStream).Returns(inputStream);
var fakedFileCollection = new Mock<HttpFileCollectionBase>();
fakedFileCollection.SetupGet(x => x.Count).Returns(1);
fakedFileCollection.SetupGet(x => x[0]).Returns(fakedFile.Object);
fakedRequest.SetupGet(x => x.Files).Returns(fakedFileCollection.Object);

Here's a deeper example using NSubstitute that allows you to foreach over the file collection
var request = Substitute.For<HttpRequestBase>();
var firstFile = Substitute.For<HttpPostedFileBase>();
firstFile.ContentLength.Returns(1);
firstFile.FileName.Returns("firstFile.txt");
firstFile.ContentType.Returns("text");
firstFile.InputStream.Returns(new MemoryStream());
var secondFile = Substitute.For<HttpPostedFileBase>();
secondFile.ContentLength.Returns(1);
secondFile.FileName.Returns("secondFile.txt");
secondFile.ContentType.Returns("text");
secondFile.InputStream.Returns(new MemoryStream());
var fileKeys = new[] { "1", "2" };
var files = Substitute.For<HttpFileCollectionBase>();
files.GetEnumerator().Returns(fileKeys.GetEnumerator());
files[fileKeys[0]].Returns(firstFile);
files[fileKeys[1]].Returns(secondFile);
request.Files.Returns(files);
Example caller usage https://stackoverflow.com/a/1760523/37055

Related

NMI Create Subscription Giving Authentication Failed Error

In my project i am configuring NMI Payment gateway in which i create a plan and then customer and now creating subscription against that plan but client giving response of Authentication Failed below is the response of client
response=3&responsetext=Authentication Failed&authcode=&transactionid=0&avsresponse=&cvvresponse=&orderid=&type=&response_code=300
Below is my service code
var addsubscription = "add_subscription";
var date = DateTime.UtcNow;
var year = date.Year.ToString();
var month = date.Month.ToString();
var padedmonth = month.PadLeft(2, '0');
var day = date.Day.ToString();
var padedday = day.PadLeft(2, '0');
var startdate = year + padedmonth + padedday;
string option = $"plan_id={model.Data.StripePlanId}&recurring={addsubscription}&payment_token={model.Data.StripePaymentToken}&ccnumber={model.Data.CCNumber}&ccexp={model.Data.CCExpiry}&start_date={startdate}";
var requester = new NMIGatewayRequester();
var relativeUrl = "https://secure.networkmerchants.com/api/transact.php";
var response = requester.Request(relativeUrl, RestSharp.Method.POST, option);
var customerResponseObj = GetPaymentApiResponseValues(response.Split('&').Select(x => x.Split('=')).ToDictionary(x => x[0], x => x[1]));
public class NMIGatewayRequester
{
private RestClient client;
public string Request(string relativeUrl, RestSharp.Method verb, string option)
{
client = new RestSharp.RestClient($"{relativeUrl}") { Timeout = -1 };
var request = new RestRequest(verb);
request.AddParameter("application/x-www-form-urlencoded", option, ParameterType.RequestBody);
var subResponse = client.Execute(request);
if (!subResponse.IsSuccessful)
{
throw new Exception("Unable to Process Request");
}
return subResponse.Content;
}
}
You need to include a security key in your options:
string option = $"security_key=[...]&plan_id={model.Data.StripePlanId}&[...]";
See documentation here.

ask for version control server (client) from VssConnection

Dears
Please help me to work with VssConnection from Microsoft.VisualStudio.Services.Client.15.134.0-preview package
I need to get pending changes for workspace, query it for conflict and commit
This is how i do it with TfsTeamProjectCollection and
var vssCred = new VssClientCredentials();
using (TfsTeamProjectCollection collection = new TfsTeamProjectCollection(uri, vssCred))
{
collection.Authenticate();
var scs = collection.GetService<VersionControlServer>();
var scsProject = scs.GetTeamProject(teamProjectName);
var workspace = scsProject.VersionControlServer.GetWorkspace(localPath);
var pending = scs.QueryPendingSets(new string[] { "$/" }, RecursionType.Full, workspace.Name, loginName);
if (pending.Any())
{
var pendingChanges = new[] { pending.First().PendingChanges.First() };
var validation = workspace.EvaluateCheckin2(CheckinEvaluationOptions.Conflicts, pendingChanges, "", null, null);
var conflicts = validation.Conflicts;
if (conflicts != null && conflicts.Any())
{
var message = string.Join("\r\n", conflicts.Select(_ => string.Format("{0} {1}", _.Message, _.ServerItem)));
throw new ArgumentException(string.Format("conflict was found\r\n{0}", message));
}
var res = workspace.CheckIn(pendingChanges, "test checkin");
TestContext.WriteLine("checked in {0}", res);
}
}
However there are vsts integration samples that uses VssConnection object
How can I get the same VersionControlServer from VssConnection instance?
I've tried to find Microsoft.TeamFoundation.VersionControl.Client.WebAPi (like Microsoft.TeamFoundation.WorkItemTracking.WebApi) but failed.
var vssCred = new VssClientCredentials();
using (VssConnection connection = new VssConnection(uri, vssCred))
{
var prj = connection.GetClient<ProjectHttpClient>();
var p = prj.GetProject(teamProjectName).Result;
//i'd like to get prj.VersionControl here
//or something like var scs = connection.GetService<VersionControlServer>();
}
Is it possible to get versionControlServer from VssConnection? Should I continue to use TfsTeamProjectCollection to do this task?
You could use TfsTeamProjectCollection as before, as there is no workspace method in VssConnection:
TfvcHttpClient tfvcClient = connection.GetClient<TfvcHttpClient>();
List <TfvcItem> tfvcItems = tfvcClient.GetItemsAsync("$/", VersionControlRecursionType.OneLevel).Result;
More examples, you can refer to the link below:
https://learn.microsoft.com/en-us/vsts/integrate/get-started/client-libraries/samples?view=vsts

OpenUI5: Where is the data gone, loaded by sap.ui.model.odata.v2.ODataModel()?

I have been googling and testing around for quite a few days with no success. If someone could give me a hint to point me into the right direction, then I would greatly appreciate that.
What is my target: to get some data from an OData service and show it in an UI5 oTable. Later on, I will have to do the CRUD-operations, but for now the aim is just to show the data successfully.
What I have got so far: I have an MVC project. I have created an OpenUI5Controller.cs, whose purpose is to represent an ODataService:
public class OpenUI5Controller : Controller
{
private MyEntities myEntities = new MyEntities();
public JsonResult GetAllContragents()
{
try
{
IQueryable<Contragent> contragents = myEntities.Contragent.OrderBy(x => x.Code);
// for now, take the first 100 only
contragents = contragents.Take(100);
var jsonData = new
{
rows = contragents.ToList()
//rows = "123"
};
var res = Json(jsonData, JsonRequestBehavior.AllowGet);
return res;
}
catch (Exception e)
{
LoggingService.WriteLog("Error in OpenUI5Controller.GetAllContragents()", e);
return null;
}
}
}
After that, I try to consume the data like this:
var oModel = new sap.ui.model.odata.v2.ODataModel('/OpenUI5/GetAllContragents', {
//maxDataServiceVersion: '2.0',
json: true,
skipMetadataAnnotationParsing: true,
// none of those callbacks is ever triggered, even the requestFailed...!?
requestSent: function (a, b, c) {
debugger;
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
},
requestFailed: function (a, b, c) {
debugger;
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
},
requestCompleted: function (a, b, c) {
debugger;
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
},
batchRequestCompleted: function (a, b, c) {
debugger;
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
},
useBatch : false
});
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
var vfewgvfewgv4 = oModel.getProperty('contragents');
var vfewgvfewgv5 = oModel.getProperty('/contragents');
var vfewgvfewgv6 = oModel.getProperty('Contragents');
var vfewgvfewgv7 = oModel.getProperty('/Contragents');
debugger;
When stopping at this breakpoint, I see this in the Chrome Developer Tools:
Moving further, I came accross this and tried to read() those contragents:
oModel.read('/Contragents', {
success: function (event) {
debugger;
// event.root I guess should be the received data as jsonString
// As I guess, I will have to get it and give it to oModel.oData manually, or am I wrong? I guess this would cause update(), delete()... calls to fail later on. Anyways...
sap.ui.getCore().setModel(oModel); // https://archive.sap.com/discussions/thread/3746588 - seems not to work like this
if (withJsonModel !== true) { https://help.sap.com/saphelp_uiaddon20/helpdata/en/12/32241b99d7437ba3614698d53dfa4b/content.htm
oTable.setModel(oModel);
oTable.bindRows("/");
//oTable.bindRows("/rows");
oTable.placeAt('tblContragents', "only");
}
},
error: function (event) {
debugger;
}
});
Here, neither success, nor error callback gets ever triggered.
After this read() attempt, I have again:
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
var vfewgvfewgv4 = oModel.getProperty('contragents');
var vfewgvfewgv5 = oModel.getProperty('/contragents');
var vfewgvfewgv6 = oModel.getProperty('Contragents');
var vfewgvfewgv7 = oModel.getProperty('/Contragents');
and I see this:
After that, I have oTable = new sap.ui.table.Table(...);
Finally, I try this:
sap.ui.getCore().setModel(oModel);
//oTable.setModel(oModel); // or maybe should be this one directly?
oTable.bindRows("/Contragents");
oTable.placeAt('tblContragents', "only");
As a result, I get an empty table.
I suppose I should tell you what I see in Fiddler as well: I see this request: 1 200 HTTP localhost:55714 /OpenUI5/GetAllContragents/$metadata
As a result in the TextView of the response section, I see the data as json, that I need to show in the table.
How to make it work and show the data in the table?
edit from 02.02.2017: I have 1% of progress. After some more and more testing and googling, I decided to try it like this.
First of all, some time ago (can't really remember when), after seeing a good example for OdataServices, I decided to create a dedicated controller like this:
public class ContragentsController : ODataController
{
private MyEntities db = new MyEntities();
//public System.Web.Mvc.JsonResult GetContragents()
public string GetContragents()
{
try
{
IQueryable<Contragent> contragents = db.Contragent.OrderBy(x => x.Code);
// for now, give me first 100
contragents = contragents.Take(100);
var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var rows = jsSerializer.Serialize(contragents.ToList());
//var jsonData = new
//{
// rows = model
//};
//var res = new System.Web.Mvc.JsonResult();
//res.Data = jsonData;
//res.JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet;
return rows;
}
catch (Exception e)
{
//...some errorLogging
return null;
}
}
After that, I changed the call to ODataModel() like this:
var oModel = new sap.ui.model.odata.v2.ODataModel(BASE_HREF + 'odata/', {
//maxDataServiceVersion: '2.0',
json: true,
skipMetadataAnnotationParsing: true,
// those callbacks still do not get called at all
requestSent: function (a, b, c) {
debugger;
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
},
requestFailed: function (a, b, c) {
debugger;
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
},
requestCompleted: function (a, b, c) {
debugger;
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
},
batchRequestCompleted: function (a, b, c) {
debugger;
var trgrwg = oModel.getData();
var vfewgvfewgv = oModel.getProperty('/');
var vfewgvfewgv2 = oModel.getProperty('/rows');
var vfewgvfewgv3 = oModel.getProperty('rows');
},
useBatch : false
});
The whole drama is that SapUI5 runs a request for $metadata, before making the actual request to odata/Contragents and so on. As expected in this case, I see in Fiddler, that the server 404-s to that request: http://localhost:55714/odata/Contragents/$metadata and it doesn't reach the moment to make the request to Contragents. I know, that I will have to change the source of the library somewhere in order to prevent this $metadata request from running, which I don't want to do. So in Fiddler's Composer, I tried the following: localhost:55714/odata/$metadata and it returned some xml with the desired metadata (maybe indeed it is important, but I haven't understood yet why). Next step was to modify the call to sap.ui.model.odata.v2.ODataModel(); as shown above. The great thing after all that is the fact, that oModel.read('/Contragents', {...}); showed signs of life! Now, the success callback gets called and in event.root I get those contragents as json string. And then what? I tried oModel.setData(JSON.parse(event.root)); but it gave me this error:
Also, if I manage to get it working this way, I don't quite understand, will the CRUD methods of oModel work? oModel.setData()-ing is something familliar to me from the time when I was playing around with JSONModel():
oModel = new sap.ui.model.json.JSONModel();
oModel.setData(dataForGrid); // this works like a charm
But using JSONModel() means, that I cannot use the insert(), update()... methods of sap.ui.model.odata.v2.ODataModel(), because JSONModel(); does not provide us with them, which is normal, as long as I get dataForGrid via a standard $.ajax() call.
edit2: While debugging, I noticed, that the method ContragentsController.GetContragents(); gets called twice and in the console, I see this error message:
edit3: Following the good example for ODataService, I added a "selection" method to the controller like this:
// GET: odata/Contragents(5)
[EnableQuery]
public SingleResult<Contragent> GetContragents([FromODataUri] string key)
{
return SingleResult.Create(db.Contragent.Where(contragent => contragent.Code == key));
}
In Fiddler, it 404-s and does not get called at all no matter if i Compose it like this: http://localhost:55714/Contragents(2) or like this: http://localhost:55714/odata/Contragents(2)
Couple of minutes later, I've got couple of % progress. I looked even closer in the tutorial and I noticed something, which made me change the "selection" method to this:
// GET: odata/Contragents(5)
[EnableQuery]
public SingleResult<Contragent> Get([FromODataUri] string key)
{
return SingleResult.Create(db.Contragent.Where(contragent => contragent.Code == key));
}
Now, when I Compose this request: http://localhost:55714/odata/Contragents(2), it now does not 404, but does 406 Not Acceptable. I came across this error code some time ago and I didn't understand well what is the reason for it and how is it related to ODataServices.
I just reminded myself what does 406 mean and it turns out, that every method on the controller must return a json result as string. Because, SapUI5 sets Accept-Type to "application/json".

templateService.Parse not able to parese Tuple used in view(MVC)

I am trying to parse a .cshtml with tuple and tuple used for acces two models in the view same time, but it is not working throwing error, but if I am using only one model than same this is wotking.
Here is my code:
Controller:
var deviceModel = new DevicesInformationDataViewModel { };
var eventModel = new EventsInformationDataViewModel{ };
var templateFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Views\\EmailTemplates");
var emailTemplatePath = Path.Combine(templateFolderPath, "EmailTemplates.cshtml");
var templateService = new TemplateService();
var emailHtmlBody = "";
string email = data[1];
ViewBag.info = data[0];
if (data[0] == "DeviceInfo")
{
deviceModel.Address = data[2];
deviceModel.Description = data[3];
deviceModel.eDescription = data[4];
deviceModel.Fault = data[5];
deviceModel.Type = data[6];
deviceModel.TypeCode = Int32.Parse(data[7]);
deviceModel.DriftCompensation = Int32.Parse(data[8]);
deviceModel.AlarmSensitivity = data[9];
deviceModel.Status = data[10];
emailHtmlBody = templateService.Parse(System.IO.File.ReadAllText(emailTemplatePath), deviceModel, ViewBag.info, null);
}
View:
If using like this, not working:
#model Tuple<DevicesInformationDataViewModel,EventsInformationDataViewModel>
but if using like this, it is working:
#model DevicesInformationDataViewModel
Can any body tell me what I am doing wrong and please tell me how can I resolve
this issue?

TestManagementHttpClient Create Test Run

I am trying below C# code to create TFS test run. But every time I am getting below error. Though I have given test plan details. I couldnt even find documentations on this.
Error
An exception of type 'Microsoft.TeamFoundation.TestManagement.WebApi.TestObjectNotFoundException' occurred in mscorlib.dll but was not handled in user code
Additional information: Test plan {0} not found.
Code
public async Task CreateTestRun()
{
TestManagementHttpClient witClient = connection.GetClient<TestManagementHttpClient>();
TestCaseResultUpdateModel TestCaseResultUpdateModel = new TestCaseResultUpdateModel();
ShallowReference testPlanReference = new ShallowReference();
testPlanReference.Id = "{TestPlanId}";
testPlanReference.Name = "{TestPlanName}";
testPlanReference.Url = "http://{TFSInstance}/{Project}/_apis/test/plans/{TestPlanID}";
RunCreateModel RunCreateModel = new RunCreateModel("SWAT-Run","",new int[] {2304187},testPlanReference,
null,0,"",false,"Error Message","","","","","comment","","", "",
null, null, null, null,null,"","","","",new TimeSpan(0,0,10,0,0),"",null);
TestRun testRun = await witClient.CreateTestRunAsync(this.Project, RunCreateModel, null);
}
I have done it succssful with below code, hope it can be helpful to you.
var tfsRun = _testPoint.Plan.CreateTestRun(false);
tfsRun.DateStarted = DateTime.Now;
tfsRun.AddTestPoint(_testPoint, _currentIdentity);
tfsRun.DateCompleted = DateTime.Now;
tfsRun.Save(); // so results object is created
var result = tfsRun.QueryResults()[0];
result.Owner = _currentIdentity;
result.RunBy = _currentIdentity;
result.State = TestResultState.Completed;
result.DateStarted = DateTime.Now;
result.Duration = new TimeSpan(0L);
result.DateCompleted = DateTime.Now.AddMinutes(0.0);
var iteration = result.CreateIteration(1);
iteration.DateStarted = DateTime.Now;
iteration.DateCompleted = DateTime.Now;
iteration.Duration = new TimeSpan(0L);
iteration.Comment = "Run from TFS Test Steps Editor by " + _currentIdentity.DisplayName;
for (int actionIndex = 0; actionIndex < _testEditInfo.TestCase.Actions.Count; actionIndex++)
{
var testAction = _testEditInfo.TestCase.Actions[actionIndex];
if (testAction is ISharedStepReference)
continue;
var userStep = _testEditInfo.SimpleSteps[actionIndex];
var stepResult = iteration.CreateStepResult(testAction.Id);
stepResult.ErrorMessage = String.Empty;
stepResult.Outcome = userStep.Outcome;
foreach (var attachmentPath in userStep.AttachmentPaths)
{
var attachment = stepResult.CreateAttachment(attachmentPath);
stepResult.Attachments.Add(attachment);
}
iteration.Actions.Add(stepResult);
}
var overallOutcome = _testEditInfo.SimpleSteps.Any(s => s.Outcome != TestOutcome.Passed)
? TestOutcome.Failed
: TestOutcome.Passed;
iteration.Outcome = overallOutcome;
result.Iterations.Add(iteration);
result.Outcome = overallOutcome;
result.Save(false);

Resources