API calls not happening on opening of Cefsharp application in Testcomplete - cefsharp

I have a Cefsharp application which has Html pages with Javascript. Js makes API calls which happens fine if I open cef application in windows but most of API calls are not happening when I am opening same cef application through testcompelete.
On debugging application I am getting CORS warning.
I am using CefCustomScheme which has root folder path, schemeName and host name specified. And provided same shemeName and host name in Address in wpf: chromiumwebrowse tag. If I hard-code root folder path in Address Source binding, its working fine even in testcomplete.
private static CefCustomScheme GetAlmanacScheme(IAppSettings appSettings)
{
try
{
var almanacFolder = appSettings.Settings["ALMANAC_WIDGET_PATH"];
if (string.IsNullOrWhiteSpace(almanacFolder))
{
almanacFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Thermo", "InstConnectAgent", "AlmanacWidget");
}
var factory = new FolderSchemeHandlerFactory(almanacFolder, "thermo", "almanac");
return new CefCustomScheme() { SchemeName = "thermo", SchemeHandlerFactory = factory, IsCorsEnabled = true };
}
catch
{
return null;
}
}
and Source is
private const string WidgetUrl = "thermo://almanac";
public string Source
{
get
{
return WidgetUrl;
}
}

Related

HttpClient and WebClient requests / responses don't work for intranet with DefaultCredentials

Problem: I am unable to get content from an company internal webpage through using HttpClient or WebClient. I am able to get the content by accessing the URL directly, however.
Details: .NET Core 3.1 Razor Pages, IIS 10, Windows Authentication.
I have a website http://myintranet/Editor/Bib/4343 where a user can press a button to generate a static page. Behind the scenes, it attempts to read a stream from http://myintranet/Editor/NewBib/4343/true and create a static HTML page from it.
When clicking the button, the response is always IIS 10.0 Detailed Error - 401.1 - Unauthorized etc.
However when I access the webpage directly in the browser, it opens up just fine (note that if it is the first time accessing the website, I am prompted by the browser to enter my username and password. After that, the browser remembers these credentials).
Also note that when running it from localhost through Visual Studio, all works fine, the static page downloads properly too.
Here is my code:
Version 1:
public IActionResult OnPostGenerateStaticPage()
{
try
{
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true, PreAuthenticate = true });
HttpResponseMessage response = client.GetAsync(Url.PageLink().Replace("Bib", "NewBib") + "/true").Result;
var indexPageContents = response.Content.ReadAsStreamAsync().Result;
var cd = new System.Net.Mime.ContentDisposition
{
FileName = BibNumber + ".htm",
Inline = false,
};
Response.Headers.Add("Content-Disposition", cd.ToString());
return File(indexPageContents, "text/html");
}
catch (IOException)
{
return RedirectToPage("./Bib");
}
}
Version 2:
public IActionResult OnPostGenerateStaticPage()
{
try
{
WebClient client = new WebClient { UseDefaultCredentials = true };
string desiredUrl = Url.PageLink().Replace("Bib", "NewBib") + "/true";
var indexPageContents = client.OpenRead("desiredUrl");
var cd = new System.Net.Mime.ContentDisposition
{
FileName = BibNumber + ".htm",
Inline = false,
};
Response.Headers.Add("Content-Disposition", cd.ToString());
return File(indexPageContents, "text/html");
}
catch (IOException)
{
return RedirectToPage("./Bib");
}
}
Another thing, I have asked the web server admin to check that NTLM is above Negotiate for the authentication providers for this website and it is. Also, Anonymous and Basic Authentication are disabled and Windows Authentication is enabled.
Not sure where to go from here...

Assembly.UnsafeLoadFrom causes web app crash

I am trying to load a DLL from internet, more specifically it is Azure storage (Blob), so I used "Assembly.UnsafeLoadFrom" like this:
Assembly.UnsafeLoadFrom(#"https://accountname.blob.core.windows.net/test/calculator.dll");
But becuaset this specific call, my web app (published) returns:
"The specified CGI application encountered an error and the server
terminated the process."
The weird part is if I am using my local build, it is fine. there is no crash and the return result is correct.
I am using Visual Studio 2015 and .net 5.
Please let me know how to resolve this issue or how to debug it.
Thanks
For a simple way, you could achieve your purpose by the following code:
calculator.dll
public class Calculator
{
public string HelloWorld(string userName)
{
return string.Format("Hello world, {0}!", userName);
}
}
HomeController.cs
public async Task<ActionResult> Index()
{
string url = "https://brucechen.blob.core.windows.net/dll/calculator.dll";
HttpClient client = new HttpClient();
var bytes = await client.GetByteArrayAsync(url);
//load assembly from bytes
Assembly assembly = Assembly.Load(bytes);
var calc = assembly.CreateInstance("calculator.Calculator");
//invoke the method and get result
var result = calc.GetType().InvokeMember("HelloWorld", BindingFlags.InvokeMethod, null, calc, new[] { "Bruce" });
ViewData["result"] = result;
return View();
}
Result

signalr self-host and static file server (e.g. owin.selfhost)

I have been "too" succesfully with my stand-alone Singular web service. We would like to now remove the IIS server, which does little other than serve about 10 JS/HTML/CSS files. Node.JS has a static-files plugin,
I looked and I saw that Katana, OWIN.SelfHost also has such a feature.
http://odetocode.com/blogs/scott/archive/2014/02/10/building-a-simple-file-server-with-owin-and-katana.aspx
Update
It was suggested to use the OWIN.Self-Host which has a feature, but I am unsure of where to put it in my existing code, and if it would effect the existing SIGNALR code (all Hubs share the same HTTP request calls, so I am also squeezing in Self-host on the same port, I wonder if that works). As well as it would be nice to use Scott Allen's (above referenced) example which also allows File Browsing.
Here is the code I current use to start up SIGNALR (V2.2) , which is run at the directly from the Main.cs file:
class Comm
{
public string url = "http://localhost:7700";
// string url = "http://*:7700"; // Requires admin privileges
public void start()
{
Task t = Task.Run(() =>
{
WebApp.Start<Startup>(url);
this.Clients = GlobalHost.ConnectionManager.GetHubContext<GatewayHub>().Clients;
Console.WriteLine("Server running on {0}", url);
Thread.Sleep(Timeout.Infinite);
});
}
public void send()
{
Clients.All.display("broadcast sent...");
}
private IHubConnectionContext<dynamic> Clients
{
get;
set;
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableDetailedErrors = (Tools.LogLevel >= 12);
hubConfiguration.EnableJavaScriptProxies = true;
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR("/signalr", hubConfiguration);
}
}
This answer is really from #Tracther, and I wish he would write it up so that I can credit him. But thanks to his input, here is what works for me. I did not need the commented lines. All I needed was to set the paths for /signlar and for the static FileSystem
}
class Startup
{
public void Configuration(IAppBuilder app)
{
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableDetailedErrors = (Tools.DebugLevel > 12);
hubConfiguration.EnableJavaScriptProxies = true;
app.UseCors(CorsOptions.AllowAll);
//app.UseStaticFiles();
app.UseFileServer(new FileServerOptions()
{
//RequestPath = new PathString("/Scopes"),
EnableDirectoryBrowsing = true,
FileSystem = new PhysicalFileSystem(#".\Scopes"),
});
app.MapSignalR("/signalr", hubConfiguration);
}
}

Uploading a file from .NET application to a Web API POST endpoint

I'd like to use Web API to build some endpoints for applications to consume. The first job I'd like it to do is allow the client to upload a file to the server.
The client will run a .NET app of some kind, maybe a console app or maybe something else. It won't be a webpage using a form element or file input.
I think the Web API would look something like this:
public class FileController : ApiController
{
public bool Post(File newFile)
{
return true;
}
}
Using this as a model class:
public class File
{
public string name { get; set; }
public Stream uploadStream { get; set; }
}
I'm sure that's horribly wrong but it's my first Web API.
I'm trying to test this in a console application:
namespace TestFileUpload
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting the test...");
using (FileStream readstream = new FileStream(#"C:\\Test\Test2.txt", FileMode.Open, FileAccess.Read))
{
WebAPI.Classes.File newFile = new WebAPI.Classes.File()
{
name = "Test.txt",
uploadStream = readstream
};
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:50326");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
response = client.PostAsJsonAsync("http://localhost:50326/api/file", newFile).Result;
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
};
Console.ReadLine();
}
}
}
Now I'm getting a timeout error when I try to get the response:
"Error getting value from 'ReadTimeout' on 'System.IO.FileStream'."
Help?
There are many ways for a client to consume a Web API service, but the most straight forward would be to use the web api client library. Perhaps you should consider building a simple get method that returns an object before jumping into file uploads.
Web API from .NET Client
You can not add a service reference as Web API does not expose a wsdl.

AppHarbor NopCommerce running issue

I uploaded nopcommerce solution to appharbor (using this method Can't build notcommerce project under appharbor) and solution succesfully builded, but I receiving 403 error - Forbidden: Access is denied when trying to open page(Allow write-access to file system is set to true).
Thanks and hope for your help
The problem is that the standard NopCommerce solution contains two Web Projects. AppHarbor only deploys one web project per application, and in this case, we happen to deploy Nop.Admin which is not what you want.
To resolve this, you should take advantage of the AppHarbor solution file convention and create an AppHarbor.sln solution file that only references the Nop.Web project.
We use a wrapper in our base controller to ensure that all of our code is oblivious to appharbor port changing.
First, fix in Webhelper.cs:75
public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl)
{
string url = string.Empty;
if (_httpContext == null)
return url;
if (includeQueryString)
{
string storeHost = GetStoreHost(useSsl);
if (storeHost.EndsWith("/"))
storeHost = storeHost.Substring(0, storeHost.Length - 1);
url = storeHost + _httpContext.Request.RawUrl;
}
else
{
#if DEBUG
var uri = _httpContext.Request.Url;
#else
//Since appharbor changes port number due to multiple servers, we need to ensure port = 80 as in AppHarborRequesWrapper.cs
var uri = new UriBuilder
{
Scheme = _httpContext.Request.Url.Scheme,
Host = _httpContext.Request.Url.Host,
Port = 80,
Path = _httpContext.Request.Url.AbsolutePath,
Fragment = _httpContext.Request.Url.Fragment,
Query = _httpContext.Request.Url.Query.Replace("?", "")
}.Uri;
#endif
url = uri.GetLeftPart(UriPartial.Path);
}
url = url.ToLowerInvariant();
return url;
}
So what we did is simply add files from https://gist.github.com/1158264 into Nop.Core\AppHarbor
and modified base controllers:
nopcommerce\Presentation\Nop.Web\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(RequestContext requestContext)
{
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current),
requestContext.RouteData));
}
//Same file from here downwards...
}
nopcommerce\Presentation\Nop.Web.Admin\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
//set work context to admin mode
EngineContext.Current.Resolve<IWorkContext>().IsAdmin = true;
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current), requestContext.RouteData));
//base.Initialize(requestContext);
}
//Same file from here downwards...
}
Enable the Directory Browsing feature in IIS Express
Note This method is for the web developers who experience the issue when they use IIS Express.
To do this, follow these steps:
Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt:
C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:directoryBrowse /enabled:true
refrence :https://support.microsoft.com/en-us/kb/942062

Resources