I am writing a mobile service scheduler in my mobile service .net backend source .
When I debug my app, when program calls Controller's getAll() method, get an exception. The message is
"Object reference not set to an instance of an object."
I have a Model named Source, and also have a Controller name SourceController.
SourceController sourceController = new SourceController();
List<Source> sources = new List<Source>();
sources = sourceController.GetAllSource().ToList();
At the line 3, I get this Error :
"Object reference not set to an instance of an object."
I ain't did any changes in Sources controller class. This means in Visual Studio I clicked and add Controller to Source. Also ain't did any changes in DataContext.
Can anybody help?
Unless you are doing unit testing you won't instantiate the controller directly -- it is initialized when a request comes in for an action within the controller.
If you are writing a test then note that your "sources" list isn't assigned to anything so it looks like SourceController.GetAllSource() gets a null source and hence ToList() will fail with the null exception that you see.
Hope this helps,
Henrik
Related
I'm using Sentry for logging errors etc. It works fine when creating a SentryEvent with a supplied Exception object. I'm trying to create ones that do not come from an exception, just a condition that needs to be flagged up on the system.
To this extent I've set the exception to null and everything works fine, except that the issue has '' as its title. I can't find anywhere in the SentryEvent object that I can set as a title to avoid this.
How do I label an event manually?
The "title" or "label" provided in the web interface is the "message" property of the event.
If you are using the official Sentry client "SharpRaven", then use CaptureMessage method instead of CaptureException.
RavenClient.CaptureMessage("Whoops!")
If you're working on your own client, or simply use HTTP requests, then set the "Message" of the event in the JSON blob:
{
"message": "Whoops!"
}
I've two WCF services connected to my client. I want to use a User-object, retrieved from service #1, and use this as paramter for service #2. Here is my MVC-Controller TournamentController.cs code:
private readonly GCTournamentServiceClient _tournamentClient = new GCTournamentServiceClient();
public ActionResult Join(int id)
{
GCUserServiceClient userClient = new GCUserServiceClient();
// Get current user
var currentUser = userClient.GetUser(0);
if (currentUser != null)
{
// Get selected tournament
var selectedTournament = _tournamentClient.GetTournament(id);
// Check if there are available seats in the tournament
if (selectedTournament.Seats > selectedTournament.RegistredUsers.Count)
{
// Check if user exist amoung registred users
if (!selectedTournament.RegistredUsers.Contains(currentUser))
{
selectedTournament?.RegistredUsers.Add(currentUser);
}
}
}
}
The error Visual Studio prompt me with:
Argument 1: cannot convert from 'GConnect.Clients.WebClient.GCUserService.User' to 'GConnect.Clients.WebClient.GCTournamentService.User'
So the problem is currentUser, which has the type GCUserService.User. I'm unable to use this as parameter for RegistredUsers
The error itself makes perfect sense, however, I'm not quite sure how I'm suppose to convert this type (properly). Some articles states, that a "shared"-service has to be created, which holds the User-type. I just can't believe, that a solution like that, should be necessary.
I might have misunderstood some basic stuff here (working with WCF and MVC), but please enlighten me, if that's the case.
So the problem is currentUser, which has the type GCUserService.User.
I'm unable to use this as parameter for RegistredUsers
There are 2 approaches to solve this problem:
1)
Create a class library project (Visual Studio) and add the User class in that project, compile it and add its assembly's (.dll) reference to both services and the client (your MVC application). Next retrieve that user object as you are already doing it
var currentUser = userClient.GetUser(0);
GetUser will return the type of User that is defined in a separate assembly which is added as reference as suggested above. The TournamentService will also reference the same assembly and the RegistredUsers.Add(User userToadd) method will take the same User object and WCF runtime should be able to serialise/desterilise it.
2)
In your MVC client application, new up the User object that is acceptable by the TournamentService.RegistredUsers.Add method. Populate its properties from the currentUser and pass in that object as parameter to RegistredUsers.Add method.
Best Practice
Ideally, I would recommend the first approach which is more work but a better practice and that your User class is maintained centrally and code is reused.
Hope this helps!
I am bit curious about one thing which has happen while trying to understand the concept of Service References and Web Service References.
What I did is?
In my project I have added a web service as a Service Reference and trying to get my script run through the use of client.
But while getting result it is throwing an exception as in the following image:
I have tried to trace out the cause but not able to get the proper answer for that.
I have following code for the resultant object.
[
ComVisible(false),
Serializable,
SoapTypeAttribute("RecordList", "http://www.someadd.com/dev/ns/SOF/2.0"),
XmlType(TypeName="RecordList", Namespace="http://www.someadd.com/dev/ns/SOF/2.0")
]
public class MyRecordListWrapper
{
private IxRecordList recordList = null;
private const string XMLW3CSchema = "http://www.w3.org/2001/XMLSchema";
[SoapElement("Headers")]
public Header[] Headers = null;
[SoapElement("Records")]
public Record[] Records = null;
// some methods to work on intialization
public SmRecordListWrapper(ref IxRecordList p_RecordList)
{
recordList = p_RecordList;// record list initialization
Headers = CreateWrapperHeaders(); // will return header class object
Records = CreateWrapperRecords(); // will return record object
}
}
Can anyone tell me why this error is showing for me?
While adding reference as a Web Service Reference
when I add the same reference as a web reference that time the program is not showing any error and runs successfully?
So can anyone tell me what is the difference in working with the same code using service reference and web service reference?
and Which is a correct way to ass references?
Hope I will get some more described answers to make the things easy to understand.
Thanks in advance.
Adding a web reference, visual studio uses xsd.exe to generate the classes from the service metadata. This uses XmlSerializer under the hood.
Adding a service reference, visual studio uses svcutil.exe to generate the classes from the metadata. This uses DataContractSerializer under the hood.
Two separate tools, two outcomes. For general information, DataContractSerializer is a lot less forgiving when it comes to generating classes from metadata.
I have this weird problem when trying to mock an interface with MockedClass.Setup(x => x.Method()).
This is the interface I'm mocking.
public interface IClassFactory
{
object GetValueFromFormData(string key, MultipartFormDataStreamProvider provider);
}
This is my test.
[TestMethod]
[ExpectedException(typeof(NullReferenceException))]
public async Task ClassApiController_ImportClassList_ThrowsNullReferenceExceptionWhenNoClassId()
{
// Arrange
_classFactory = new Mock<IClassFactory>();
// THIS IS THE LINE THAT GIVES AN EXCEPTION
_classFactory.Setup(x => x.GetValueFromFormData("classIdNull", null)).Returns(string.Empty);
ClassApiController controller = new ClassApiController(_classRepository.Object, _surveyRepository.Object, _classFactory.Object);
// Act
string result = await controller.ImportClassList();
}
If you look at my comment "THIS IS THE LINE THAT GIVES AN EXCEPTION" you see I send null, but it doesn't matter if I send the MultipartFormDataStreamProvider as an instansiated class instead, I still get the same exception.
Exception message: System.ArgumentException: Expression of type 'System.Net.Http.MultipartFormDataStreamProvider' cannot be used for parameter of type 'System.Net.Http.MultipartFormDataStreamProvider' of method 'System.Object GetValueFromFormData(System.String, System.Net.Http.MultipartFormDataStreamProvider)'
If you know why I can't mock the method just because it has this object as parameter, please help me, I'm clueless.
Thanks!
EDIT:
See solution in my answer
you should try
_classFactory = Mock.Of<IClassFactory>();
Mock.Get(_classFactory).Setup(x => x.GetValueFromFormData("classIdNull", It.IsAny<MultipartStreamProvider>()))
.Returns(string.Empty);
With the help of #Vignesh.N I finally solved it. The simple answer in this case was that my solution is divided into several projects. Web, Test, Data and so on. In the web project I had referenced the web api .dll:s via Nuget and in the test project I had referenced them directly via Add references -> Assemblies -> Framework. Thereby the .dll:s had identical Versions but not File versions. After making Nuget take care of all the projects web api .dll files it worked instantly.
So all in all, stupid mistake and hard to spot.
I have a rather outdated assembly that I'm using to communicate via SOAP with software my company writes. As it stands right now, getting the assembly updated is not an option, so please don't suggest it.
In previous iterations the normal method of communication was done utilizing the MS Soap Toolkit 3.0 (MSSOAPLIB30). You would call the login() method of the assembly and it would return an instance derived from IHeaderHandler that you would then assign to the instance of the soap client. Please refer here for more information on how this worked.
Well, I would like to use a more updated approach for communication with this web service. Thus far I have been able to successfully reference the web service with wcf, however I'm running into issues figuring out how to bridge the IHeaderHandler instance to something that the wcf proxy can comprehend. In other words, I'm trying to bridge two generations of technologies together. I've verified that using the method mentioned in the link above does actually work. Now it's just a matter of figuring out how to make this instance of IHeaderHandler useful.
Here is some example code for the old approach:
string strBasicWsdlUrl = "http://" + _strDeviceName + "/MetasysIII/WS/TimeManagement/TimeService.asmx";
object[] Parameters1 = new object[] { strBasicWsdlUrl, "", "", "" };
bool[] Parameters2 = new bool[] { true, true, true, true };
TSClient = Activator.CreateInstance(Type.GetTypeFromProgID("MSSOAP.SoapClient30"));
NewLateBinding.LateGet(TSClient, null, "MSSoapInit", Parameters1, null, null, Parameters2);
Parameters1 = new object[] { NewLateBinding.LateGet(JCISecurity, null, "HeaderHandler", new object[0], null, null, null) };
NewLateBinding.LateSet(TSClient, null, "HeaderHandler", Parameters1, null, null);
As you can see, a new instance of the soap client is initialized with the wsdl file and then the HeaderHandler attribute from the JCISecurity instance (which is the aforementioned assembly I'm using to authenticate with the software) which is derived from IHeaderHandler is passed to the HeaderHandler of the soap client. This process then ensures that all future requests from the soap client have this header attached.
It's also important to note that the proxy class generated from WCF for my web service has two interesting parameters attached to all web methods: EncryptedCertificate and LoginResult. I'm assuming these values will exist in the IHeaderHandler instance as the original documentation of the service does not reference these two parameters. However, I cannot verify this is the case because I've yet to be able to figure out how to access the content embedded in the IHeaderHandler instance.
As it stands, I see two possible solutions at this point: Figure out a way to make the WCF proxy class directly use the IHeaderHandler instance being generated with the assembly or figure out a way to extract the necessary information from the IHeaderHandler instance and use Message Inspectors to manually attach the details to the headers.
WCF is very extensible. One of those extension points is Message Inspectors:
A message inspector is an extensibility object that can be used in the service model's client runtime and dispatch runtime programmatically or through configuration and that can inspect and alter messages after they are received or before they are sent.
See also WCF Extensibility Samples and Extending WCF.