Windows 10 Universal App - Package doesn't work normally as debug mode - networking

public async Task<List<Tip>> GetTips()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://APIURL ");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse res = await request.GetResponseAsync();
StreamReader sr = new StreamReader(res.GetResponseStream());
string result = sr.ReadToEnd();
List<Tip> tips = JsonConvert.DeserializeObject<List<Tip>>(result);
return tips;
}
I am working on a project which need to consume an enterprise Web API(Https) and display the data on Win 10 live tile, it’s an UWP application.
But I found it only works when I ran it in IDE(Visual Studio 2015 debug mode) .
When I created a package for this app and run it by powershell for installation, request.GetResponseAsync method throws exception “The login request was denied”.
I tried to check Enterprise Authentication and Private Networks(Client & Server) options in Package.appxmanifest. But there was no effect.
Any idea how to make it work normally? Thanks.

Related

Using an asp web api in wpf

So i have got a simple question, when using our cms we can attach a driver as an executable.
The driver we want to make is an httpreceiver or just an api endpoint. SO i tought lets use asp.net web api for it -> using version .net 4.6.1. altough asp.net application requires a webserver and is not an executable, But i read on google you can use it inside a wpf application since our cms is wpf in the first place.
So my question is is there a way i can use my mvc web api project inside a wpf application? and if not what would be the best bet to have an httpreceiver or httppost receiver into an executable?
Main reason is we want to send httppost requests to the server as a desktop application. I know it's complicated but thats how it needs to be as far as I know.
In the case where asp is not an option, what the best way to make a postreqst/ httpreceiver as a desktop application?
EDit:
the resource guide from microsoft beneath was perfectly however i still have a question:
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
// Create HttpClient and make a request to api/values
HttpClient client = new HttpClient();
string username = "test".ToUpper().Trim();
string password = "test123";
//Mock data
var body = new PostTemplate1();
body.Description = "test";
body.StateDesc = "httpdriver/username";
body.TimeStamp = DateTime.Now;
body.Message = "This is a post test";
var json = JsonConvert.SerializeObject(body);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var authToken = Encoding.ASCII.GetBytes($"{username}:{password}");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
var response = await client.PostAsync(baseAddress + #"api/Post", data);
var result = response.StatusCode;
}
As the guide says you post to url with port 9000
is there a possibility to use another port and use https?
if yes where to manage certificates for handling https?

Using WebClient to get a intranet files

In our I have company intranet a server, that is responsible for storing files. Initially, the server had to operate only in an intranet environment, but now there is a need to share files with external web applications. Making this server accessible from the internet is not an option.
I want to create a ASP.NET MVC solution that uses the WebClient to get these files from the intranet server and send back them to the user through FileResult of the external app. This client would be provided with custom domain user credentials. So far I have tried to create a CredentialCache class, set correct credentials and append it to WebClients Credentials property like in the following code:
public ActionResult Download(int id, string fileName)
{
var fileService = new FilesService();
var documentUrl = fileService.GetUrlFileByFileId(id);
string filePath = "http://my.intranet.com/" + documentUrl;
var fileNameFromUrl = filePath.Substring(filePath.LastIndexOf("\\") + 1);
byte[] filedata;
CredentialCache cc = new CredentialCache();
cc.Add(new Uri("http://my.intranet.com/"),
"ntlm",
new NetworkCredential("myUserName", "myPassword", "myDomain"));
using (var client = new WebClient())
{
client.Credentials = cc;
filedata = client.DownloadData(filePath);
}
string contentType = MimeMapping.GetMimeMapping(filePath);
var cd = new ContentDisposition
{
FileName = fileName,
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
According to the question posted in Domain credentials for a WebClient class don't work it should work, but it’s not. It’s running only if I run the problem on localhost, but when I publish my solution on a test server, it return 401 error. My question is did how to get this working? And is it possible to download files through this method?
UPDATE--- I've published my test app on another server and it started to working. Now the test app is on another server than the server That stores files. Any ideas why it's not working when both are on the same machine?
401 error is unauthorized, so perhaps the issue is related to permissions. Are you sure the user account you are using to login to that folder has the proper access?
Ok, I found the solution on this site: https://blogs.msdn.microsoft.com/distributedservices/2009/11/10/wcf-calling-wcf-service-hosted-in-iis-on-the-same-machine-as-client-throws-authentication-error/
The solution was to add an registry entry and add my web apps to this entry to allow back connections.

Google Drive APi with clean WEB API 2

i wanted to use the Google Drive API along with a simple WEB API 2 - Project.
Somehow the GoogleWebAuthorizationBroker.cs is missing.
What i use:
Visual Studio 2013 Update 4
Empty Template with WEB API
My steps:
Creating the empty project including WEB API
building the project
updating packages via Nuget Packager
Install-Package Google.Apis.Drive.v2 (using this guide: https://developers.google.com/drive/web/quickstart/quickstart-cs)
Copy and Paste the code from the above link into a clean api-controller:
public IEnumerable<string> Get()
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "228492645857-5599mgcfnhrr74a7er1do1chpam4rnbt.apps.googleusercontent.com",
ClientSecret = "onoyJQaUazQK4VsKUjD63sDu",
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
File body = new File();
body.Title = "My document";
body.Description = "A test document";
body.MimeType = "text/plain";
byte[] byteArray = System.IO.File.ReadAllBytes(#"C:\Projects\VS\DataAnime\DataAnime\document.txt");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
request.Upload();
File file = request.ResponseBody;
return new string[] { file.Id, "value2" };
}
building
6.1 Error: GoogleWebAuthorizationBroker.cs is missing
6.2 Google says following error in browser:
That’s an error.
Error: redirect_uri_mismatch
Application: Project Default Service Account
You can email the developer of this application at: xxxx#gmail.com
The redirect URI in the request: http://example.com:63281/authorize/ did not match a registered
redirect URI.
http://example.com:63281/authorize/ was neither the url i am using for my project nor the url i registered in my developer console (this errorshowing-port is changeing everytime i run this project.
Has anyone an idea why is that?
No other sources helped fixing this weird issue.
I solved it by creating a new project on https://console.developers.google.com for a native software instead of a web-client project, even i am using a web client.
There is just one weird thing:
If i debug my code, it still says that GoogleWebAuthorizationBroker.cs is missing.
Without debugging i can do everything i want.
Thank you very much for your help.

Publishing with Core Service and Impersonation

I have a Tridion Core Service Web Application to publish pages. When logged into the server and running it from there via a browser client calling a web service with ajax it works fine. However, when I run the application from my desktop it does nothing, and also throws no error messages.
*Edit:
The Web App hosting the web service is running as an 'Application' under the Tridion 2011 CMS website. This is done to avoid cross-domain ajax issues/
Update: The code below is working fine - both with the impersonate and also with Nick's solution. My issue was actually in how I was calling the web service from jQuery and using the appropriate URL. I am leaving the code and question so maybe it will help others.
My code is:
string binding = "wsHttp_2011";
using (var client = new SessionAwareCoreServiceClient(binding))
{
client.Impersonate("company\\cms_svc");
// ** Get Items to Publish
List<string> itemsToPublish = GetItemsToPublish(publishItem.TcmUri, client);
PublishInstructionData instruction = new PublishInstructionData
{
ResolveInstruction = new ResolveInstructionData() { IncludeChildPublications = false },
RenderInstruction = new RenderInstructionData()
};
PublicationTargetData pubtarget = (PublicationTargetData)client.Read(publishItem.PubTargetUri, readoptions);
List<string> target = new List<string>();
target.Add(pubtarget.Id);
client.Publish(itemsToPublish.ToArray(), instruction, target.ToArray(), GetPublishPriority(publishItem.Priority), readoptions);
}
Have at look at this page on SDL Live Content, which explains various types of scenarios for connecting as different users:
http://sdllivecontent.sdl.com/LiveContent/content/en-US/SDL_Tridion_2011_SPONE/task_87284697A4BB423AAD5387BBD6884735
As per the docs, instead of impersonation you may want to establish your Core Service connection as follows using NetworkCredential:
using (ChannelFactory<ISessionAwareCoreService> factory =
new ChannelFactory<ISessionAwareCoreService>("netTcp_2011"))
{
NetworkCredential networkCredential =
new NetworkCredential("username", "password", "domain");
factory.Credentials.Windows.ClientCredential = networkCredential;
ISessionAwareCoreService client = factory.CreateChannel();
Console.WriteLine(client.GetCurrentUser().Title);
}

Sent HTTP request with Credential in blackberry

I am trying to call HTTP request with network credential in blackberry. i have already implement on Java, Android it's working fine but not working on blackberry. Following step i have done in blackberry.
For set Network credential i have added three following jar.
commons-codec-1.6.jar
commons-httpclient-3.0.1.jar
commons-logging-1.1.1.jar
add this jar files are in blackberry project.
Following sample Code that work fine in Core Java.
try{
HttpClient client = new HttpClient();
GetMethod get = new GetMethod("http://www.google.com");
get.setDoAuthentication( true );
try {
int status = client.executeMethod( get );
System.out.println(status + "\n" + get.getResponseBodyAsString());
} finally {
get.releaseConnection();
}
}catch(Exception e){
System.out.println("Error:>>>>>>"+e);
}
Now there are not error on code but whenever try to click on application icon error face like "error starting appName: Module 'commons-httpclient-3.0.1' not found"
Can any one suggest what's this error say.
BB does not support HttpClient. But it does support J2ME's HttpConnection and is quite similar to HttpClient, so you can easily adjust with it. Here's some sample code to get you started:
try{
HttpConnection mConn = (HttpConnection)Connector.open(urlToPost);
mConn.setRequestMethod(HttpConnection.POST);
mConn.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
mConn.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
mConn.setRequestProperty("Content-Language", "en-CA");
//---------------------------------------------------
mConn.setRequestProperty("User",usr);
mConn.setRequestProperty("pass",pass);
//---------------------------------------------------
catch(Exception e){//---handle your exceptions---//}
} finally {
mConn.close();//don't forget to close connections, only a limited number are available
}
This is a good article for beter understanding.

Resources