I have a WCF web service, which I have hosted in IIS on my PC. This I have added as Service Reference in a Visual Studio Project and I am able to invoke it successfully in a web service in this VS Project.
Now I am trying to deploy this web services on a remote PC, which doesn't have Visual Studio installed. For this purpose I copied the .svc and web.config files and bin folder of this web services to a folder on the remote PC. Then I hosted the services on IIS pointing to the respective folder. Now when I browse the web service using the .svc link I am able to access the web service from my PC. I added this web service as a service reference in my Visual Studio project and everything looks OK, I am able to see the separate methods and their parameters in the Object browser. The problem appears when I try to invoke methods from this web services.
I am able to invoke one method and then when I invoke the second one I get the following error (The absolutely same web service and all its methods work perfectly if hosted in IIS on my PC.):
Object reference not set to an instance of an object.
Here is a part of the method where I invoke the web service (the web service name is TFSWS):
public void ImportRequirements(string username, string password)
{
TFSWS.TFSWSClient obj = new TFSWS.TFSWSClient();
string projects = obj.GetTFSProjects(username, password, TFS_URI);
string list = obj.GetAllWorkItems(ProjectName2, username, password, TFS_URI, WItypes);
Here is the code of the first method which I am able to invoke successfully from TFSWS:
public string GetTFSProjects(string userName, string password, string Uri)
{
StringWriter MyStringWriter = new StringWriter();
NetworkCredential cred = new NetworkCredential(userName, password);
TfsTeamProjectCollection _tfs = new TfsTeamProjectCollection(new Uri(Uri), cred);
_tfs.Authenticate();
ICommonStructureService tfsProjectService = (ICommonStructureService)_tfs.GetService(typeof(ICommonStructureService));
ProjectInfo[] projects = tfsProjectService.ListAllProjects();
string[] proj = new string[projects.Length];
for (int i = 0; i < projects.Length; i++)
{
proj[i] = projects[i].ToString();
}
DataTable ProjectsDT = GetDataTableFromArray(proj);
...
}
Here is the code of the second method that I invoke from TFSWS and that throws the error message (When I debug I can see that all parameters are assigned correctly):
public string GetAllWorkItems(string projectName, string username, string password, string URI, string[] WItypes)
{
StringWriter MyStringWriter = new StringWriter();
NetworkCredential cred = new NetworkCredential(username, password);
TfsTeamProjectCollection _tfs = new TfsTeamProjectCollection(new Uri(URI), cred);
_tfs.Authenticate();
WorkItemStore _witStore =(WorkItemStore)_tfs.GetService(typeof(WorkItemStore));
DataTable myData = new DataTable();
string project = projectName;
string[] m_columns;
Hashtable context = new Hashtable();
Project proj = _witStore.Projects[project];
}
string myQuery = "SELECT [System.Id], [System.Title], [System.WorkItemType], [System.State] FROM WorkItems WHERE ...";
WorkItemCollection result = _witStore.Query(myQuery, context);
DisplayFieldList fieldList = result.Query.DisplayFieldList;
...
}
You can debug remotely to figure out the issue the code is experiencing on the target machine, without installing all of Visual Studio on it. You just need to deploy debug instead of release mode assemblies, and have the remote debugger service running on it.
Remote Debugging Setup
Related
I need access to files that are in a files server in my LAN from my Angular app.
I assume that I need to publish my Angular app in the same network, that is, in my IIS Server inside the same LAN
Now on my local machine, I try to access my shared folder \192.168.100.7\OfertasHistoric" but I donĀ“t know how to do it.
When I try this
[HttpGet("directorio")]
public async Task<ActionResult<string[]>> GetDirectoryContents()
{
string[] files = Directory.GetFiles(#"\\192.168.100.7\ofertashistorico");
return files;
}
I get this error
System.IO.DirectoryNotFoundException: Could not find a part of the path '/Users/kintela/Repos/Intranet-WebAPI/Intranet.API/\192.168.100.7\ofertashistorico'
It seems that the path that you give to the GetFiles method only searches from the current directory where the project is located downwards and I don't know how to indicate a different one.
I also do not know how to manage the issue of the credentials necessary to access said resource
Any idea, please?
Thanks
I am using below code and it works for me. Please check it.
Steps:
Navigate to the path like : \\192.168.2.50\ftp
Delete \ftp, the address in folder explorer should be \\192.168.2.50, find the folder you want, right click and map network drive.
You can try it with this address ftp:\\192.168.2.50, it will pop up a window. Input you usename and password, then you can check the files.
Test Result
Sample code
[HttpGet("directorio")]
public IActionResult GetDirectoryContents()
{
string networkPath = #"ftp:\\192.168.2.50";
string userName = #"Administrator";
string password = "Yy16";
#region FtpWebRequest
var networkCredential = new NetworkCredential(userName, password);
var uri = new Uri(networkPath);
var request = (FtpWebRequest)WebRequest.Create(uri);
request.Credentials = networkCredential;
request.Method = WebRequestMethods.Ftp.ListDirectory;
try
{
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
catch (WebException ex)
{
Console.WriteLine("Access to the path '" + networkPath + "' is denied. Error message: " + ex.Message);
}
#endregion
return Ok();
}
I have the following code below.
When I run Debug in Visual Studio with this code in an ASP.NET Core App (so running as IIS Express) this works
When I run Debug in Visual Studio with this code in a ASP.NET hosted process in a Windows Service this return nothing, but also no error messages
I connect from my home laptop via RDP to another laptop where VPN is running, so I think that is probably it. I tried running visual studio as admin, running the compiled exe as admin, /runas with the domain specified, etc but the commandline app will show nothing while the asp.net core app shows the list. So it must be the user it runs under.
But when i run WindowsIdentity.GetCurrent().Name in both cases it gives the same domain and name (me). In task manager the devenv and iis process is me.
public List<AdSecurityGroupDTO> GetAllDomainSecurityGroups(string domain)
{
List<AdSecurityGroupDTO> result = new List<AdSecurityGroupDTO>();
using (var ctx = new PrincipalContext(ContextType.Domain, domain))
{
GroupPrincipal findAllGroups = new GroupPrincipal(ctx, " * ");
PrincipalSearcher ps = new PrincipalSearcher(findAllGroups);
foreach (Principal group in ps.FindAll())
{
AdSecurityGroupDTO adSecurityGroupDTO = new();
adSecurityGroupDTO.Name = group.Name;
adSecurityGroupDTO.Description = group.Description;
adSecurityGroupDTO.DisplayName = group.DisplayName;
adSecurityGroupDTO.DistinguishedName = group.DistinguishedName;
adSecurityGroupDTO.SamAccountName = group.SamAccountName;
result.Add(adSecurityGroupDTO);
}
return result;
}
}
Your help will be highly appreciated, I have registered a Plug-in on phone call create in CRM Dynamics 2015, When I debug the plugin using the profiler, the plugin Registration tool stops working as soon as I make a call to the WCF service client method exposed. I have tried with both an ASXM service and a WCF service,i have deployed the service in IIS on the same server CRM is hosted,I tested the service against a console and SOAP UI, everything works fine, the minute I use it kin a Plugin context it crashed the registration tool on service call. There is no error logged in the plugin Registration tool log files, here is my plugin code below
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context == null)
{
throw new ArgumentNullException("localContext");
}
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity phoneCallEntity = (Entity)context.InputParameters["Target"];
if (phoneCallEntity.LogicalName != "phonecall")
return;
//ensure that the Plugin fires on a create operaton
if (context.MessageName == "Create")
{
try
{
BasicHttpBinding myBinding = new BasicHttpBinding();
myBinding.Name = "BasicHttpBinding_IService1";
myBinding.Security.Mode = BasicHttpSecurityMode.None;
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
EndpointAddress endPointAddress = new EndpointAddress("http://154.66.196.127/Webservice/ZoiperCallHistory.asmx");
ZoiperCallHistorySoapClient client = new ZoiperCallHistorySoapClient(myBinding,endPointAddress);
client.Open();
CallHistory callHistory = client.GetZoiperCallHistory();
client.GetZoiperCallHistory();
The code fails on this line : CallHistory callHistory = client.GetZoiperCallHistory();
Thanks in advance.
In my experience the plugin registration tool doesn't go well with debugging web service calls. Try instead using the tracing service to identify errors or to analyze the web service response.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
I have a .NET 4 project made of a EXE project and a class library. The class library contains a reference to a webservice (using WCF).
Everything works ok only if I have deployed the app.config file (that contains the info about the binding) along with my exe. How can I have everything configured by code without the need to deploy an app.config file (I don't want my users to change those settings).
Thank you.
Andrea
You can use the ChannelFactory class to generate proxies to your services.
Everything you configure through the configuration file can also be done using code.
You just need to instantiate an instance of the correct binding and configure its properties according to the service requirements on the other side.
For example:
private IDisposableService GetClient()
{
var netBinding = new BasicHttpBinding();
netBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
netBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
var factory = new ChannelFactory<IDisposableService>(netBinding, new EndpointAddress(new Uri(ServerUrl)));
factory.Credentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
factory.Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
var channel = factory.CreateChannel();
return channel;
}
interface IDisposableService : IYourService, IDisposable
{
}
Then you can simply use:
using (var proxy = GetClient())
{
// call proxy here
}
This is how I did it:
MyServiceResponseClient embEvalServiceClient = new MyServiceResponseClient (new BasicHttpBinding(),
new EndpointAddress(new Uri(url)));
if (embEvalServiceClient != null)
{
embEvalServiceClient.GetPendingEvalsCompleted += getPendingEvalsCompletedHandler;
embEvalServiceClient.GetPendingEvalsAsync(attemptId);
}
I have a selfhosted WCF service application which I want to deploy by a msi installer package. The endpoint uses http port 8888. In order to startup the project under windows 2008 after installation I have to either run the program as administrator or have to edit the http settings with netsh:
"netsh http add urlacl url=http://+:8888/ user=\Everyone"
I want to edit the http settings from my installer class. Therefore I call the following method from the Install() method:
public void ModifyHttpSettings()
{
string parameter = #"http add urlacl url=http://+:8888/ user=\Everyone";
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo("netsh", parameter);
psi.Verb = "runas";
psi.RedirectStandardOutput = false;
psi.CreateNoWindow = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process.Start(psi);
}
This method will work for english versions of windows, but not for localized versions (The group Everyone has different names in localized versions). I have also tried to use Environment.UserName to allow access at least for the current logged on user. But this does also not work, because the installer class is run by the msi service which runs under the user SYSTEM. Hence Enviroment.UserName returns SYSTEM and that is not what I want. Is there a way to grant access to all (or at least for the current logged on) user to my selfhosted WCF service from a msi installer class?
My aproach to a solution:
public void ModifyHttpSettings()
{
string everyone = new System.Security.Principal.SecurityIdentifier(
"S-1-1-0").Translate(typeof(System.Security.Principal.NTAccount)).ToString();
string parameter = #"http add urlacl url=http://+:8888/ user=\" + everyone;
ProcessStartInfo psi = new ProcessStartInfo("netsh", parameter);
psi.Verb = "runas";
psi.RedirectStandardOutput = false;
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
Process.Start(psi);
}
The SID "S-1-1-0" is a wellknown SID and stands for the "Everyone" account. The SID is the same for all localizations of windows. The method Translate of SecurityIdentifier class returns the localized name of the Everyone account.