Acessing a url from windows application - c#

Does anyone know how to acess a url from a windows application?.
I have an address http://serverport/Page.I want to acess this page from my windows application.
Regards,
Harsh Suman

It's not clear what you want to do with the page.
If you want to display it on the form, you can use a WebBrowser control.
If you want to get the response and process it, use the System.Net.WebClient class.

If you want to download an HTML or any file you can use the WebClient class.
Example:
/// <summary>
/// Downloads a file from the given location
/// </summary>
/// <param name="url">Location of the file</param>
/// <param name="dest">The destination of the downloaded file</param>
/// <returns>False if there was an error, else True</returns>
public bool DownLoad(string url, string dest)
{
WebClient client = new WebClient();
try
{
//Downloads the file from the given url to the given destination
client.DownloadFile(url, dest);
return true;
}
catch (WebException)
{
// Handle exception
return false;
}
catch (System.Security.SecurityException)
{
// Handle exception
return false;
}
catch (Exception)
{
// Handle exception
return false;
}
}

I'm not sure what you're asking for,so I just give the answer to yet another way to interpret the question.
If you simply want to launch the default browser (to display a local or online html manual etc.), in windows (and probably similar in other OS'es) you can use some kind of "execute interface" to execute a correctly formatted url as the command, this will usually launch the default browser:
According to this page this code should launch a browser:
string targeturl= "http://stackoverflow.com";
try
{
System.Diagnostics.Process.Start(targeturl);
}
catch
(
System.ComponentModel.Win32Exception noBrowser)
{
if (noBrowser.ErrorCode==-2147467259)
MessageBox.Show(noBrowser.Message);
}
catch (System.Exception other)
{
MessageBox.Show(other.Message);
}
(It looks pretty ugly with magic numbers for error codes, though...)

Related

Grabbing Dropbox access token on Windows Form using Dropbox API

I have done a class which already works with the Dropbox API uploading files, downloading, deleting and so on. It has been working quite well since I was just using my own access token, but I need to register other users and a single but "big" problem appeared: retrieving the access token.
1.- Redirect URI? I'm starting to doubt why do I need this. I finally used this URI (https://www.dropbox.com/1/oauth2/redirect_receiver) because "The redirect URI you use doesn't really matter" Of course I included this one on my app config on Dropbox.
2.- I reach the user's account (I can see the user's count increased and I see the app has access to the user's account.
3.- I have a breakpoint on my code to inspect the variables in order to apply the DropboxOAuth2Helper.ParseTokenFragment but I have no success on there.
This is my code, but on the if before the try catch is where it gets stuck:
string AccessToken;
const string AppKey = "theOneAtmyAppConfigOnDropbox";
const string redirectUrl = "https://www.dropbox.com/1/oauth2/redirect_receiver";
string oauthUrl =
$#"https://www.dropbox.com/1/oauth2/authorize?response_type=token&redirect_uri={redirectUrl}&client_id={AppKey}";
private string oauth2State;
private bool Result;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Start(AppKey, webBrowser1);
webBrowser1.Navigating += Browser_Navigating;
}
private void Start(string appKey, WebBrowser w)
{
this.oauth2State = Guid.NewGuid().ToString("N");
Uri authorizeUri = DropboxOAuth2Helper.GetAuthorizeUri(OauthResponseType.Token, appKey, redirectUrl, state: oauth2State);
w.Navigate(authorizeUri);
}
private void Browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (!e.Url.ToString().StartsWith(redirectUrl, StringComparison.InvariantCultureIgnoreCase))
{
// we need to ignore all navigation that isn't to the redirect uri.
return;
}
try
{
OAuth2Response result = DropboxOAuth2Helper.ParseTokenFragment(e.Url);
if (result.State != this.oauth2State)
{
// The state in the response doesn't match the state in the request.
return;
}
this.AccessToken = result.AccessToken;
this.Result = true;
}
catch (ArgumentException)
{
// There was an error in the URI passed to ParseTokenFragment
}
finally
{
e.Cancel = true;
this.Close();
}
}
I've been fighting against this for hours and I'm starting to see the things a little cloudy at this point.
This is the tutorial I used, but I'm not moving forward. I would really appreciate any help!
EDIT: I finally made some steps forward. I changed the line which contains
Uri authorizeUri2 = DropboxOAuth2Helper.GetAuthorizeUri(appKey);
Now I'm showing the generated access token on the WebClient! Bad part comes when trying to get it (it gets inside the if) and it gets generated every time I ask the user for permission, so it gets overwrited.
EDIT 2: I noted the token I get generated on the browser is somehow malformed. I try to manually change it hardcored when I'm debugging and I get an exception when an AuthException when creating the DropboxClient object :( What the hell!
As Greg stated, the solution was using the event Browser_Navigated. Looks like the version of the embedded IE my Visual Studio (2015) uses didn't notice that if it's a redirect, it won't launch the event BrowserNavigating.

What is the namespace of Google.Apis.Authentication;

I'm trying to use this link to download a file from Google Drive using dotnet.
The problem is, I can't find this namespace in the nuget - using Google.Apis.Authentication; .
I'v downloaded everything that has the name 'Google' in nuget, but no luck.
Any idea where it can hide? Thanks
To access Google drive the only nugget package you need to download is PM> Install-Package Google.Apis.Drive.v2. It will automatically add anything else you need.
My download from drive method
/// <summary>
/// Download a file
/// Documentation: https://developers.google.com/drive/v2/reference/files/get
/// </summary>
/// <param name="_service">a Valid authenticated DriveService</param>
/// <param name="_fileResource">File resource of the file to download</param>
/// <param name="_saveTo">location of where to save the file including the file name to save it as.</param>
/// <returns></returns>
public static Boolean downloadFile(DriveService _service, File _fileResource, string _saveTo)
{
if (!String.IsNullOrEmpty(_fileResource.DownloadUrl))
{
try
{
var x = _service.HttpClient.GetByteArrayAsync(_fileResource.DownloadUrl );
byte[] arrBytes = x.Result;
System.IO.File.WriteAllBytes(_saveTo, arrBytes);
return true;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return false;
}
}
else
{
// The file doesn't have any content stored on Drive.
return false;
}
}
code ripped from google drive sample project
I think that there is a better sample for you (in the official samples repo, https://github.com/google/google-api-dotnet-client-samples/blob/master/Drive.Sample/Program.cs#L154).
...
await DownloadFile(service, uploadedFile.DownloadUrl);
...
/// <summary>Downloads the media from the given URL.</summary>
private async Task DownloadFile(DriveService service, string url)
{
var downloader = new MediaDownloader(service);
var fileName = <PATH_TO_YOUR_FILE>
using (var fileStream = new System.IO.FileStream(fileName,
System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
var progress = await downloader.DownloadAsync(url, fileStream);
if (progress.Status == DownloadStatus.Completed)
{
Console.WriteLine(fileName + " was downloaded successfully");
}
else
{
Console.WriteLine("Download {0} was interpreted in the middle. Only {1} were downloaded. ",
fileName, progress.BytesDownloaded);
}
}
}
More documentation about media download is available here:
https://developers.google.com/api-client-library/dotnet/guide/media_download

How to disable/enable network in Windows 8 by C#

This code works well on Windows 7, but not on Windows 8. Does anyone know why?
I don't know how to solve it.
The function to restart network
private static void RestartNetWork()
{
string manage = "SELECT * FROM Win32_NetworkAdapter";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(manage);
ManagementObjectCollection collection = searcher.Get();
List<string> netWorkList = new List<string>();
foreach (ManagementObject obj in collection)
{
if (obj["Name"].ToString() == "Qualcomm Atheros AR5B97 Wireless Network Adapter")
{
DisableNetWork(obj);//disable network
Thread.Sleep(3000);
EnableNetWork(obj);//enable network
return;
}
}
}
The function to disable the network
/// <summary>
/// 禁用网卡
/// </summary>5
/// <param name="netWorkName">网卡名</param>
/// <returns></returns>
private static bool DisableNetWork(ManagementObject network)
{
try
{
network.InvokeMethod("Disable", null);
return true;
}
catch
{
return false;
}
}
The function to enable the network
/// <summary>
/// 启用网卡
/// </summary>
/// <param name="netWorkName">网卡名</param>
/// <returns></returns>
private static bool EnableNetWork(ManagementObject network)
{
try
{
network.InvokeMethod("Enable", null);
return true;
}
catch
{
return false;
}
}
Assuming you are using the Win32_NetworkAdapter WMI class, make sure the current process is running in elevated mode. On top of that, you may want to just avoid catching every exception like you are doing and, instead, analyze the eventual exception which may be thrown, for additional details.
my code works well in Windows 10 so i think win8 is available but remember that it needs administrator permission please remember run as admin by right click .
here is my code:
if (manage["Name"].ToString() == "Realtek RTL8192DE Wireless LAN 802.11N PCI-E NIC MAC1")
{
Console.WriteLine(manage["Name"].ToString() + "\n");
try
{
//先enable再disable且要管理员权限执行
manage.InvokeMethod("Enable", null);
manage.InvokeMethod("Disable", null);
Console.WriteLine("设置成功");
}
catch
{
Console.WriteLine("设置失败");
}
}
}
I found the answer to my comment and wanted to share for anyone having similar problems...
Rather than "Enabling" the service, I changed the start mode to manual (you can use automatic if you prefer as well) and that solved my issue.
ManagementBaseObject startMode = service.GetMethodParameters("ChangeStartMode");
startMode["startmode"] = "Manual";
service.InvokeMethod("ChangeStartMode", startMode, null);
This did the trick for me!
I've just had the same issue. It turns out that when the same app I run as an administrator in Windows 8, everything started to work properly.
Win32_NetworkAdapter is deprecated. For Windows 8 / Server 2012 and forward you need to use MSFT_NetAdapter.
https://msdn.microsoft.com/en-us/library/hh968170(v=vs.85).aspx
Statement:
"The Win32_NetworkAdapter class is deprecated. Use the MSFT_NetAdapter class instead."
https://msdn.microsoft.com/en-us/library/aa394216%28v=vs.85%29.aspx

Marshalling C# com items when using recursion

I am using the SourceSafe COM object (SourceSafeTypeLib) from C# to automate a SourceSafe recursive get (part of a larger build process). The recursive function is shown below. How do I ensure that all the COM objects created in the foreach loop get released correctly?
/// <summary>
/// Recursively gets files/projects from SourceSafe (this is a recursive function).
/// </summary>
/// <param name="vssItem">The VSSItem to get</param>
private void GetChangedFiles(VSSItem vssItem)
{
// 'If the object is a file perform the diff,
// 'If not, it is a project, so use recursion to go through it
if(vssItem.Type == (int)VSSItemType.VSSITEM_FILE)
{
bool bDifferent = false; //file is different
bool bNew = false; //file is new
//Surround the diff in a try-catch block. If a file is new(doesn't exist on
//the local filesystem) an error will be thrown. Catch this error and record it
//as a new file.
try
{
bDifferent = vssItem.get_IsDifferent(vssItem.LocalSpec);
}
catch
{
//File doesn't exist
bDifferent = true;
bNew = true;
}
//If the File is different(or new), get it and log the message
if(bDifferent)
{
if(bNew)
{
clsLog.WriteLine("Getting " + vssItem.Spec);
}
else
{
clsLog.WriteLine("Replacing " + vssItem.Spec);
}
string strGetPath = vssItem.LocalSpec;
vssItem.Get(ref strGetPath, (int)VSSFlags.VSSFLAG_REPREPLACE);
}
}
else //Item is a project, recurse through its sub items
{
foreach(VSSItem fileItem in vssItem.get_Items(false))
{
GetChangedFiles(fileItem);
}
}
}
If it is a short running program and there is nothing to "commit" on the COM side, it is ok to let them go, believe it or not. The GC will come and properly release the interfaces when it needs to.
If it is a long running program (like a server component or takes hours and hours to complete), or you need to "commit" or "save" changes the best bet would be to release them as you would any VSSItem right after your call to GetChangedFiles(fileItem); in your foreach loop.
Example:
foreach (VSSItem fileItem in vssItem.get_Items(false))
{
GetChangedFiles(fileItem);
// fileItem.Release(); or fileItem.Dispose();
// or even Marshal.ReleaseComObject(fileItem);
}

Is there a way to automate turning a BizTalk Receive Location on or off through code?

Is there a way to automate the turning on or off of a Receive Location in BizTalk? It seems like there should be some kind of API or some such for this kind of thing. I would prefer to work in C#, but WMI or some kind of script would work too.
Besides ExplorerOM, as you've found out, you can also enable/disable receive locations (and control send ports) using WMI.
I have a sample PowerShell script that shows how to do those things here, if you're interested.
I found a solution. It appears that the Microsoft.BizTalk.ExplorerOM.dll is what I wanted. Here is an excerpt from the BizTalk documentation that should get anyone else started:
using System;
using Microsoft.BizTalk.ExplorerOM;
public static void EnumerateOrchestrationArtifacts()
{
// Connect to the local BizTalk Management database
BtsCatalogExplorer catalog = new BtsCatalogExplorer();
catalog.ConnectionString = "Server=.;Initial Catalog=BizTalkMgmtDb;Integrated Security=SSPI;";
// Enumerate all orchestrations and their ports/roles
Console.WriteLine("ORCHESTRATIONS: ");
foreach(BtsAssembly assembly in catalog.Assemblies)
{
foreach(BtsOrchestration orch in assembly.Orchestrations)
{
Console.WriteLine(" Name:{0}\r\n Host:{1}\r\n Status:{2}",
orch.FullName, orch.Host.Name, orch.Status);
// Enumerate ports and operations
foreach(OrchestrationPort port in orch.Ports)
{
Console.WriteLine("\t{0} ({1})",
port.Name, port.PortType.FullName);
foreach(PortTypeOperation operation in port.PortType.Operations)
{
Console.WriteLine("\t\t" + operation.Name);
}
}
// Enumerate used roles
foreach(Role role in orch.UsedRoles)
{
Console.WriteLine("\t{0} ({1})",
role.Name, role.ServiceLinkType);
foreach(EnlistedParty enlistedparty in role.EnlistedParties)
{
Console.WriteLine("\t\t" + enlistedparty.Party.Name);
}
}
// Enumerate implemented roles
foreach(Role role in orch.ImplementedRoles)
{
Console.WriteLine("\t{0} ({1})",
role.Name, role.ServiceLinkType);
}
}
}
}
One caveat, apparently this dll does not support 64 bit. Since I am only writing a simple utility it's not a big deal for me (just compiling as 32-bit), but it is something to be aware of.
Glad to see that you seem to have found a solution.
Wanted to mention a similar alternative which is also using Powershell, ExplorerOM, and the BizTalk API to set BizTalk artifacts to various statuses.
Receive Locations being one of them.
The script accepts XML configuration files, where you list the artifacts and what status you would like to set them to.
The script has been published to Microsoft Script Center:
http://gallery.technet.microsoft.com/scriptcenter/Set-Artifact-Status-270f43a0
In response to Alhambraeidos comment. Here's is some excerpts of code I used in a Windows app to disable a Receive Location remotely:
/// <summary>
/// Gets or sets the biz talk catalog.
/// </summary>
/// <value>The biz talk catalog.</value>
private BtsCatalogExplorer BizTalkCatalog { get; set; }
/// <summary>
/// Initializes the biz talk artifacts.
/// </summary>
private void InitializeBizTalkCatalogExplorer()
{
// Connect to the local BizTalk Management database
BizTalkCatalog = new BtsCatalogExplorer();
BizTalkCatalog.ConnectionString = "server=BiztalkDbServer;database=BizTalkMgmtDb;integrated security=true";
}
/// <summary>
/// Gets the location from biz talk.
/// </summary>
/// <param name="locationName">Name of the location.</param>
/// <returns></returns>
private ReceiveLocation GetLocationFromBizTalk(string locationName)
{
ReceivePortCollection receivePorts = BizTalkCatalog.ReceivePorts;
foreach (ReceivePort port in receivePorts)
{
foreach (ReceiveLocation location in port.ReceiveLocations)
{
if (location.Name == locationName)
{
return location;
}
}
}
throw new ApplicationException("The following receive location could not be found in the BizTalk Database: " + locationName);
}
/// <summary>
/// Turns the off receive location.
/// </summary>
/// <param name="vendorName">Name of the vendor.</param>
public void TurnOffReceiveLocation(string vendorName)
{
ReceiveLocation location = Locations[vendorName].ReceiveLocation;
location.Enable = false;
BizTalkCatalog.SaveChanges();
}
You'll notice that there is some I left out, like I was creating a dictionary of receive locations called "Locations", but you should be able to get the idea. The pattern pretty much holds true for any BizTalk object you want to interact with.

Categories

Resources