Resolve connection issue when calling a WCF service through windows 8 app - c#

I am trying to call a WCF service via a windows 8.1 app that I have created. But when I call it I get the exception:
One or more errors occurred
Unable to connect to the remote server
There was no endpoint listening at http://theRequestedService.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
An attempt was made to access a socket in a way forbidden by its access permissions [theIPAddress:thePortNumber]
I have reviewed the settings of the service and they seem to be okay and have checked to see if I can access it the following ways:
access via browser (successful)
access via console application (successful)
run Fiddler4 and my windows 8 app (successful)
access directly from the app (falied)
NB: I ran fiddler4 to try and get an error message that would lead me to the solution
I thought I may have altered a setting in my project, so created a fresh test project, but I get the same issue.
The exception messages seem self explanatory so why am I able to successfully connect via the other methods but not through the app? and what steps need to be taken to resolve this issue?
MY CONNECTION CODE (if this helps with solving the problem)
class ConnectionManager
{
public static ConnectionStatus IsConnected()
{
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
ConnectionStatus result = (connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess) ? ConnectionStatus.NotSet : ConnectionStatus.NoInternet;
if (result == ConnectionStatus.NotSet)
{
CommonFunctionsClient client = new CommonFunctionsClient();
try
{
client.ChannelFactory.Endpoint.Binding.SendTimeout = TimeSpan.FromMilliseconds(3000);
if (client.PingAsync().Result)
result = ConnectionStatus.Connected;
else
result = ConnectionStatus.NoWCF;
}
catch (Exception ex)
{
throw ex;
//result = ConnectionStatus.NoWCF;
}
}
return result;
}
}
public enum ConnectionStatus
{
Connected,
NoWCF,
NoInternet,
NotSet
}

For me to resolve this issue I downloaded HtmlAgilityPack
HtmlAgilityPack found here from nuGet
I guess the error was due to an issue with x-paths.
I admit this is far from a complete answer but it may help someone resolve their issue if they come across the same thing.
Hopefully someone could provide a reason this solution worked, or a better solution to this issue.

Related

Blazor Webassembly, DatabaseCRUD: Internal Server Error 500 with published version

Problem Details
I have a Blazor project with a simple Database-CRUD (create, read, update, delete) example. It works properly when I run it within Visual Studio but if I publish it the program runs into an error.
Project Details
IDE is Visual Studio 2019. Project is Blazor Webassembly. I tried .NET CORE 3.1 and .NET 5.0. Database is SQL Server 2019. IIS for publishing.
Code Details
Database access is working with mapping (Scaffold-DbContext). I use the nuggets “Microsoft.EntityFrameworkCore.Tools” and “Microsoft.EntityFrameworkCore.SqlServer”.
This is the read command:
using var httpResponse = await Http.GetAsync("/api/DataLrs/Index");
This is the read command-snippet I use for more error details:
using var httpResponse = await Http.GetAsync("/api/DataLrs/Index");
if (!httpResponse.IsSuccessStatusCode)
{
// set error message for display, log to console and return
errorMessage = httpResponse.ReasonPhrase;
Console.WriteLine($"There was an error! {errorMessage}");
return;
}
// convert http response data to UsersResponse object
dataLrsList = await httpResponse.Content.ReadFromJsonAsync<DataLrs[]>();
Error Details
When I publish the project with IIS and try to execute the same commands I get the following error in the browser:
Internal Server Error
System.Net.Http.HttpRequestException: net_http_message_not_success_statuscode, 500
Solution Attempts Details
As already mentioned, when I run it in Visual Studio it works without any problems. I already googled and tried several stuff but nothing really works.
How can I get a better error description?
Is anybody familiar with this problem?
I realized many people have the same/similar problem, but I couldn’t find a clear solution
Thanks!
Yes, you are right, I am using EF Core. Sorry! Forgot to mention that important detail.
Database Details
To make it not too complicated I am using a database on my pc and I am also publishing (IIS) on my pc. If all works, I would proceed with a server.
I retrieved my connection string via Visual Studio’s SQLServerObjectExplorer. I use for both modes (debug, publish) the same connection string which is stored in appsettings.json.
This is the connection string:
Data Source=CND823509T\SQLEXPRESS;Initial Catalog=DataComposerWebDBTest;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
Method Details
Here are some of my method details, I will just copy the important lines (hope that is enough). I got the structure from a general example I googled. As already mentioned, locally it works.
RazorePage.razor
dataLrsList = await Http.GetFromJsonAsync<DataLrs[]>("/api/DataLrs/Index")
DataLrsAccessLayer.cs
public IEnumerable<DataLrs> GetData()
{
try
{
return _context.DataLrs.ToList();
}
catch (Exception ex)
{
throw;
}
}
DataLrsController.cs
[HttpGet]
[Route("api/DataLrs/Index")]
public IEnumerable<DataLrs> Index()
{
return _dataLrs.GetData();
}
Questions Details
Do you need more details?
What do you mean with localDB stuff?
Thanks!

Can not connect to Sql database in C# asp mvc application with Entity Framework BUT the same code works with Winform application

First of all, please excuse me if it sounds too rooky. I consider myself novice in MVC applications.
I have ran into a strange problem and there does not seem to be any way out of this, at least so far..I have looked everywhere and left no stone unturned to get it worked. Finally I turned to this forum.
This is my first post, so any mistakes please overlook and guide me.
The problem is multifaceted...
The High Level Details...
I have created a C# ASP MVC Web Application waiting to be uploaded on a Remote Server (Client Machine)
The application uses Entity Framework - Code First approach
Connects to the database with Windows Authentication system
Scene1: Where the application worked
I have tested the application on my machine and it worked flawlessly.
I have Express edition of Sql Server Management Studio installed on my system.
Scene2: Where the application failed. The Problem - Big Picture
It works great on my system but while testing it on the Remote Server it crashes
The application fails to connect to the Remote Server Sql Database. As soon as it tries to connect to the database, it crashes with an error message "Login failed for user '<UserName>."
I have checked everything in the connection string - like -
Data source name is correct
Initial Catlog also points at the correct database name
Integrated Security = true
There is no UserID or password mentioned
Connection string worked great on my system. But it does work on the Client Machine and shows the error above.
Connection string is:
connectionString="Data Source=RemoteComputerName;Initial Catalog=DatabaseName;Integrated Security=True; MultipleActiveResultSets=true"
I am not able to figure out exactly what is causing the error - Is it my code or Is it the Sql Server database settings - permissions.
Since the connection worked on my local machine, which means the code is correct
In order to check whether sql server permissions are working..I have created partial 'test connection application' in WINFORM and uploaded on the Server, this time the code works and read all the table data.
but when I try to connect in MVC project it shows the error..."Login failed for user...".
I'm totally confused what works in WINFORM fails in MVC.
Database permissions must be right because when tried to access it using WINFORM it worked.
please let me know if I have missed to provide any details in this post.
Any help is highly appreciated!!!
Thank You.
Please show your connection string. (you can block out any real passwords, actual server names, actual db names).
Since you mention "Integrated Security = true"..........then you have to be aware of which Identity is running the process (the website or the winforms.exe)
When running as winforms app, you are running as "you" (most likely). As in, the logged in user to the windows o/s.
When running under IIS, you are running under the Identity associated with the App Pool you are using..which most likely is NOT you, but rather a service account.
Your service-account does not have access to the sql-server.
You can read in depth here: https://support.microsoft.com/en-us/help/4466942/understanding-identities-in-iis#:~:text=ApplicationPoolIdentity%3A%20When%20a%20new%20application,also%20a%20least%2Dprivileged%20account.
You can show this......by catching an exception, and then something like this:
You can replace ArithmeticException with whatever, I'm just showing "adding info" to a caught exception and rethrowing.
try
{
// some sql server access code
}
catch(Exception ex)
{
throw new ArithmeticException("What is the real IIdentity: " + this.FindIIdentity(), ex);
}
private string FindIIdentity()
{
try
{
//'Dim user As WindowsPrincipal = CType(System.Threading.Thread.CurrentPrincipal, WindowsPrincipal)
//'Dim ident As IIdentity = user.Identity
string returnValue = string.Empty;
WindowsIdentity ident = WindowsIdentity.GetCurrent();
returnValue = ident.Name;
try
{
returnValue += " on " + System.Environment.MachineName;
} catch (Exception ex)
{}
return returnValue;
} catch (Exception ex)
{
return "Error Finding Identity";
}
}
IIS screenshots

InternetExplorer COMException: System.Runtime.InteropServices.COMexception: The RPC server is unavailable

I'm very new to C# so please excuse me if it's a silly question.
I created a console application that uses the "InternetExplorer" from SHDocVw. This application goes to a website and performs some operations. It works just fine on my computer, but when I try to publish it I just can't to get it to work on my colleagues computers. These other computers don't have dotnet core installed.
So if I publish the app as framework-dependant I get a hostfxr.dll missing library error and it obviously doesn't work at all.
I thought I could fix this by publishing the app as self-dependant. This didn't help either. I always need to paste the "Interop.MSHTML.dll" and "Interop.SHDocVw.dll" manually. When I do, the app at least starts. Internet explorer shows up, the "Navigate" command works. But as soon as I try to hide the window, or try to work with elements in the page, it just crashes.
There are two types of errors I get:
Unhandled Exception: System.Runtime.InteropServices.COMexception: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
at SHDocVw.IWebBrowser2.set_Visible(Boolean pBool)
at MyWebApp.IEDriver.Visibility(Boolean isVisible)
at MyWebApp.Program.Main(String[] args)
Other times I get a very similar error, but it's even mentions my own user files, even when running on a different machine. Is that normal?
Unhandled exception. System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (0x800706BA)
at SHDocVw.InternetExplorerClass.get_ReadyState()
at IEAutomation.IEDriver.WaitForComplete() in C:\Users\St3ve\source\repos\MyWebApp\MyWebApp\IEDriver.cs:line 552
at TestWeb.Program.Main(String[] args) in C:\Users\St3ve\source\repos\MyWebApp\MyWebApp\Program.cs:line 82
I tried to to google the errors, but can't get it work, I would be really grateful for any hints or help.
The crux of this approach is to make sure we are accessing the right InternetExplorer object that is associated with our process
private InternetExplorer _IE;
public Process m_Proc = Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "-nomerge www.google.com");
public IEDriver()
{
Thread.Sleep(5000);
_IE = null;
ShellWindows m_IEFoundBrowsers = new ShellWindows();
foreach (InternetExplorer Browser in m_IEFoundBrowsers)
{
if (Browser.HWND == (int)m_Proc.MainWindowHandle)
{
_IE = Browser;
break;
}
}
Then in your methods like WaitForCompleteNew(), Navigate(), etc where ever you attempt to access InternetExplorer's proprties or methods, you can use object _IE.
_IE.Visible = false;
document = ((HTMLDocument)_IE.Document)

Can't access ServiceController (InvalidOperationException) when trying to read on remote/another computer

I have a local service running on my computer and trying to get other computers to be able to read the status of my service (whether it's running, stopped, etc.) However, I am unable to as I get an InvalidOperationException error, saying that I am unable to open Service Control Manager. Locally, I am able to, but on another remote computer I am unable to. The ServiceController (cs) object just returns an object with properties that all have the InvalidOperationException error.
I've tried closing down all the firewalls on the other computers, tried running Visual Studio on Administrator privileges, but nothing seems to be working. I've noticed that others suggested hard coding your admin credentials and using WindowsIdentity and Impersonation but that wouldn't work for my project (as it wouldn't be a viable solution at my workplace - wouldn't make sense with the business logic as don't want to give clients any in-house credentials).
Here's my snippet of code:
public bool CheckServiceStatus()
{
try
{
string machineName = pubSubConfig.MachineName;
string serviceName = pubSubConfig.ServiceName;
System.ServiceProcess.ServiceController cs = new System.ServiceProcess.ServiceController(serviceName, machineName);
if (cs != null && cs.ServiceName == serviceName && cs.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
return true;
}
}
catch(Exception ex)
{
Trace.TraceError("Unable to check service status: /r/n {0}", ex.Message);
}
return false;
}
The error is this:
System.InvalidOperationException: Cannot open Service Control Manager on computer '___'.
This operation might require other privileges. ---> System.ComponentModel.Win32Exception: Access is denied
Does anyone know any workarounds as to how I can get other computers running my C# program to be able to read the ServiceController object?
Thanks!
So as I said in the comments, I was not able to get around the SCM (Service Control Manager) due to admin privileges when accessing another remote computer (makes sense if you think about security). However, I did find another solution that was more or less a workaround. I'll post the solution here in case anyone finds it helpful.
So to check the status of the Windows Service (like if it's running or not), I added an additional WCF service that is hosted in the Windows Service. So now the service can expose a method that literally just returns true.
Essentially the thought-process around it was that if the WCF service is accessible then that means the Window Service is running, and thus will always return true. If the Windows service is down, the WCF service will also be down and thus making that method not available. You wouldn't get anything to return, so you would know that the service is down and not running.
Hope that helps someone! I know it's not really a direct solution to the problem I had originally asked, but it was a workaround, indirect solution.

How to consume java REST webservice in windows phone 8?

I am trying to consume Java REST Webservice in windows phone 8.But it is always giving 404 (page not found) exception (system.net.http.httpexception).That means not able to connect to webservice.
Following is the client code which i used for consuming webservice.
try
{
HttpClient http = new HttpClient();
String result = await http.GetStringAsync("http://192.168.0.56:8078/sample/page/name");
MessageBox.Show(result);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
Please help.Thanks in advance.
Issue solved.Emulator was not able to connect to internet,which was the problem.I tried in windows phone and its working fine.Thanks #akshay2000.
Check your Network Adapters and Verify that there are Hyper-V in their names or 'v' prefixes on the Adapter names, if there are you should check if they are enabled, and enable them if disabled.
If you have nothing like that you should repair the sdk, and that will fix the issue.

Categories