Microsoft.WindowsAzure.Storage version : 9.3.2.0 - Microsoft.WindowsAzure.Storage.StorageException: Remote server returned an error: (403) Forbidden - azure

I am using Microsoft.WindowsAzure.Storage (Azure Storage SDK for Windows) version : 9.3.2.0 for uploading the blob.
Here is logic of c# code for the same.
private class FileBlock
{
internal string Id { get; set; }
internal byte[] Content { get; set; }
}
public static async Task<Uri> UploadFileToAzureStorageAsync(string azureStorageUri, string filePath)
{
var bytes = File.ReadAllBytes(filePath);
var cloudBlockBlob = new CloudBlockBlob(new Uri(azureStorageUri));
var blocks = new HashSet<string>(); `enter code here`
try
{
foreach (var block in GetFileBlocks(bytes))
{
cloudBlockBlob.PutBlock(block.Id, new MemoryStream(block.Content, true), null);
blocks.Add(block.Id);
}
await cloudBlockBlob.PutBlockListAsync(blocks);
}
catch (Exception ex)
{
Logging.logger.Error(ex);
}
return cloudBlockBlob.Uri;
}
private static IEnumerable<FileBlock> GetFileBlocks(byte[] fileContent)
{
if (fileContent.Length == 0)
return new HashSet<FileBlock>();
var maxBlockSize = 4 * 1024 * 1024;
var hashSet = new HashSet<FileBlock>();
var blockId = 0;
var index = 0;
var currentBlockSize = maxBlockSize;
while (currentBlockSize == maxBlockSize)
{
if ((index + currentBlockSize) > fileContent.Length)
currentBlockSize = fileContent.Length - index;
var chunk = new byte[currentBlockSize];
Array.Copy(fileContent, index, chunk, 0, currentBlockSize);
hashSet.Add(new FileBlock
{
Content = chunk,
Id = Convert.ToBase64String(BitConverter.GetBytes(blockId))
});
index += currentBlockSize;
blockId++;
}
return hashSet;
}
I am seeing this issue intermittently for few packages. If i publish again it will be successful. I read few blogs which suggest to change machine to UTC time zone. I tried that as well but still the same error occurs as shown below.
I wanted to know if there is issue for the below exception.
Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (403) Forbidden.
---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
StatusMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
ErrorCode:AuthenticationFailed
ErrorMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
Thanks,
Sangamesh

Related

Azure IOT Message Body, ContentEncoding Method not found

References :
https://azure.microsoft.com/en-us/blog/iot-hub-message-routing-now-with-routing-on-message-body/
How to send a json object instead of a string with Azure Client SDK
I can send IOT messages successfully and store these messages in Azure storage.
On reviewing the messages, the body is BASE64 encoded. I want the JSON within the body in the message to be shown as a string so I can process the contents in ADF.
I have added to my message the properties as below, as suggested by the reference posts above:
mes.ContentEncoding = "utf-8";
mes.ContentType = "application/json";
On doing this, I get the message below when I try and send the message. The app compiles ok, it's only when my app sends the message.
Method not found: 'Void Microsoft.Azure.Devices.Client.Message.set_ContentEncoding(System.String)'.
Comment the lines out, and it works fine again.
What am I doing wrong?
private async void SendDeviceToCloudMessagesAsyncDcbIot(DcbIotPayload dataPayload)
{
if (string.IsNullOrWhiteSpace(dataPayload.did))
{
DpmIotLog.LogToFile("no deviceId in data payload", DpmIotLog.LogCondition.High);
return;
}
dataPayload.t = DateTime.Now.ToString();
var messageString = JsonConvert.SerializeObject(dataPayload);
var messageSize = Encoding.ASCII.GetByteCount(messageString);
DpmIotLog.LogToFile($"Message Len {messageSize}", DpmIotLog.LogCondition.Verbose);
DpmIotLog.LogToFile($"Message {messageString}", DpmIotLog.LogCondition.Verbose);
byte[] messageBytes = Encoding.UTF8.GetBytes(messageString);
using (var mes = new Message(messageBytes))
{
// Set message body type and content encoding.
mes.ContentEncoding = "utf-8";
mes.ContentType = "application/json";
try
{
if (messageSize > 7000)
{
var ex = new Exception("PayloadSizeException");
DpmIotLog.LogToFile("payload over 7000 bytes", ex, DpmIotLog.LogCondition.High);
throw ex;
}
DpmIotLog.LogToFile($"Submitting Message to HUB", DpmIotLog.LogCondition.Verbose);
Task t = deviceClient.SendEventAsync(mes);
if (await Task.WhenAny(t, Task.Delay(10000)) == t)
{
MessageSent?.Invoke(true);
DpmIotLog.LogToFile($"Message Sent", DpmIotLog.LogCondition.Verbose);
deviceClient.Dispose();
}
else
{
MessageSent?.Invoke(false);
DpmIotLog.LogToFile($"Message Fail", DpmIotLog.LogCondition.Verbose);
deviceClient.Dispose();
}
}
catch (DeviceNotFoundException)
{
DpmIotLog.LogToFile($"invalid or disabled device ID : {dataPayload.did}", DpmIotLog.LogCondition.Critical);
}
catch (DeviceDisabledException)
{
DpmIotLog.LogToFile($"IOT disabled device ID : {dataPayload.did}", DpmIotLog.LogCondition.Critical);
}
catch (Exception ex)
{
DpmIotLog.LogToFile("task to upload payload to server failure", ex, DpmIotLog.LogCondition.Critical);
}
}
}
I created an entirely new project and updated all the dependences to the latest versions. This resolved the issue. (I was using a old IOT project as a starting point)

Trigger notification after Computer Vision OCR extraction is complete

I am exploring Microsoft Computer Vision's Read API (asyncBatchAnalyze) for extracting text from images. I found some sample code on Microsoft site to extract text from images asynchronously.It works in following way:
1) Submit image to asyncBatchAnalyze API.
2) This API accepts the request and returns a URI.
3) We need to poll this URI to get the extracted data.
Is there any way in which we can trigger some notification (like publishing an notification in AWS SQS or similar service) when asyncBatchAnalyze is done with image analysis?
public class MicrosoftOCRAsyncReadText {
private static final String SUBSCRIPTION_KEY = “key”;
private static final String ENDPOINT = "https://computervision.cognitiveservices.azure.com";
private static final String URI_BASE = ENDPOINT + "/vision/v2.1/read/core/asyncBatchAnalyze";
public static void main(String[] args) {
CloseableHttpClient httpTextClient = HttpClientBuilder.create().build();
CloseableHttpClient httpResultClient = HttpClientBuilder.create().build();;
try {
URIBuilder builder = new URIBuilder(URI_BASE);
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/octet-stream");
request.setHeader("Ocp-Apim-Subscription-Key", SUBSCRIPTION_KEY);
String image = "/Users/xxxxx/Documents/img1.jpg";
File file = new File(image);
FileEntity reqEntity = new FileEntity(file);
request.setEntity(reqEntity);
HttpResponse response = httpTextClient.execute(request);
if (response.getStatusLine().getStatusCode() != 202) {
HttpEntity entity = response.getEntity();
String jsonString = EntityUtils.toString(entity);
JSONObject json = new JSONObject(jsonString);
System.out.println("Error:\n");
System.out.println(json.toString(2));
return;
}
String operationLocation = null;
Header[] responseHeaders = response.getAllHeaders();
for (Header header : responseHeaders) {
if (header.getName().equals("Operation-Location")) {
operationLocation = header.getValue();
break;
}
}
if (operationLocation == null) {
System.out.println("\nError retrieving Operation-Location.\nExiting.");
System.exit(1);
}
/* Wait for asyncBatchAnalyze to complete. In place of this wait, can we trigger any notification from Computer Vision when the extract text operation is complete?
*/
Thread.sleep(5000);
// Call the second REST API method and get the response.
HttpGet resultRequest = new HttpGet(operationLocation);
resultRequest.setHeader("Ocp-Apim-Subscription-Key", SUBSCRIPTION_KEY);
HttpResponse resultResponse = httpResultClient.execute(resultRequest);
HttpEntity responseEntity = resultResponse.getEntity();
if (responseEntity != null) {
String jsonString = EntityUtils.toString(responseEntity);
JSONObject json = new JSONObject(jsonString);
System.out.println(json.toString(2));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
There is no notification / webhook mechanism on those asynchronous operations.
The only thing that I can see right know is to change the implementation you mentioned by using a while condition which is checking regularly if the result is there or not (and a mechanism to cancel waiting - based on maximum waiting time or number of retries).
See sample in Microsoft docs here, especially this part:
// If the first REST API method completes successfully, the second
// REST API method retrieves the text written in the image.
//
// Note: The response may not be immediately available. Text
// recognition is an asynchronous operation that can take a variable
// amount of time depending on the length of the text.
// You may need to wait or retry this operation.
//
// This example checks once per second for ten seconds.
string contentString;
int i = 0;
do
{
System.Threading.Thread.Sleep(1000);
response = await client.GetAsync(operationLocation);
contentString = await response.Content.ReadAsStringAsync();
++i;
}
while (i < 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1);
if (i == 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1)
{
Console.WriteLine("\nTimeout error.\n");
return;
}
// Display the JSON response.
Console.WriteLine("\nResponse:\n\n{0}\n",
JToken.Parse(contentString).ToString());

CmisInvalidArgumentException bad request exception

i am getting below error while run this program
i am using SharePoint server 2010 and recently i am install danish language pack in SharePoint server for client environment . but after this when ever i am run below code
i am getting below exceptions
org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException: Bad Request
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.convertStatusCode(AbstractAtomPubService.java:453)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.AbstractAtomPubService.read(AbstractAtomPubService.java:601)
at org.apache.chemistry.opencmis.client.bindings.spi.atompub.NavigationServiceImpl.getChildren(NavigationServiceImpl.java:86)
at org.apache.chemistry.opencmis.client.runtime.FolderImpl$2.fetchPage(FolderImpl.java:285)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterator.getCurrentPage(AbstractIterator.java:132)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterator.getTotalNumItems(AbstractIterator.java:70)
at org.apache.chemistry.opencmis.client.runtime.util.AbstractIterable.getTotalNumItems(AbstractIterable.java:94)
at ShareTest1.main(ShareTest1.java:188)
public class ShareTest
{
static Session session = null;
static Map<String,Map<String, String>> allPropMap=new HashMap<String,Map<String, String>>();
static void getSubTypes(Tree tree)
{
ObjectType objType = (ObjectType) tree.getItem();
if(objType instanceof DocumentType)
{
System.out.println("\n\nType name "+objType.getDisplayName());
System.out.println("Type Id "+objType.getId());
ObjectType typeDoc=session.getTypeDefinition(objType.getId());
Map<String,PropertyDefinition<?>> mp=typeDoc.getPropertyDefinitions();
for(String key:mp.keySet())
{
PropertyDefinition<?> propdef=mp.get(key);
HashMap<String,String> propMap=new HashMap<String,String>();
propMap.put("id",propdef.getId());
propMap.put("displayName",propdef.getDisplayName());
System.out.println("\nId="+propMap.get("id")+" DisplayName="+propMap.get("displayName"));
System.out.println("Property Type = "+propdef.getPropertyType().toString());
System.out.println("Property Name = "+propdef.getPropertyType().name());
System.out.println("Property Local Namespace = "+propdef.getLocalNamespace());
if(propdef.getChoices()!=null)
{
System.out.println("Choices size "+propdef.getChoices().size());
}
if(propdef.getExtensions()!=null)
{
System.out.println("Extensions "+propdef.getExtensions().size());
}
allPropMap.put(propdef.getId(),propMap);
}
List lstc=tree.getChildren();
System.out.println("\nSize of list "+lstc.size());
for (int i = 0; i < lstc.size(); i++) {
getSubTypes((Tree) lstc.get(i));
}
}
}
public static void main(String[] args)
{
/**
* Get a CMIS session.
*/
String user="parag.patel";
String pwd="Admin123";
/*Repository : Abc*/
String url="http://sharepointind1:34326/sites/DanishTest/_vti_bin/cmis/rest/6B4D3830-65E5-49C9-9A02-5D67DB1FE87B?getRepositoryInfo";
String repositoryId="6B4D3830-65E5-49C9-9A02-5D67DB1FE87B";
// Default factory implementation of client runtime.
// default factory implementation
SessionFactory factory = SessionFactoryImpl.newInstance();
Map<String, String> parameter = new HashMap<String, String>();
// user credentials
parameter.put(SessionParameter.USER, "parag.patel");
parameter.put(SessionParameter.PASSWORD, "Admin123");
// connection settings
parameter.put(SessionParameter.ATOMPUB_URL, "http://sharepointind1:34326/sites/DanishTest/_vti_bin/cmis/rest/6B4D3830-65E5-49C9-9A02-5D67DB1FE87B?getRepositoryInfo");
parameter.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
parameter.put(SessionParameter.REPOSITORY_ID, "6B4D3830-65E5-49C9-9A02-5D67DB1FE87B");
parameter.put(SessionParameter.LOCALE_ISO3166_COUNTRY, "DK");
parameter.put(SessionParameter.LOCALE_ISO639_LANGUAGE, "da");
parameter.put(SessionParameter.LOCALE_VARIANT, "");
parameter.put(SessionParameter.AUTHENTICATION_PROVIDER_CLASS, CmisBindingFactory.STANDARD_AUTHENTICATION_PROVIDER);
// create session
Session session = factory.createSession(parameter);
if(repositoryId!=null)
{
parameter.put(SessionParameter.REPOSITORY_ID, repositoryId);
session=factory.createSession(parameter);
RepositoryInfo repInfo=session.getRepositoryInfo();
System.out.println("Repository Id "+repInfo.getId());
System.out.println("Repository Name "+repInfo.getName());
System.out.println("Repository cmis version supported "+repInfo.getCmisVersionSupported());
System.out.println("Sharepoint product "+repInfo.getProductName());
System.out.println("Sharepoint version "+repInfo.getProductVersion());
System.out.println("Root folder id "+repInfo.getRootFolderId());
try
{
AclCapabilities cap=session.getRepositoryInfo().getAclCapabilities();
OperationContext operationContext = session.createOperationContext();
int maxItemsPerPage=5;
//operationContext.setMaxItemsPerPage(maxItemsPerPage);
int documentCount=0;
session.setDefaultContext(operationContext);
CmisObject object = session.getObject(new ObjectIdImpl(repInfo.getRootFolderId()));
Folder folder = (Folder) object;
System.out.println("======================= Root folder "+folder.getName());
ItemIterable<CmisObject> children = folder.getChildren();
long to=folder.getChildren().getTotalNumItems();
System.out.println("Total Children "+to);
Iterator<CmisObject> iterator = children.iterator();
while (iterator.hasNext()) {
CmisObject child = iterator.next();
System.out.println("\n\nChild Id "+child.getId());
System.out.println("Child Name "+child.getName());
if (child.getBaseTypeId().value().equals(ObjectType.FOLDER_BASETYPE_ID))
{
System.out.println("Type : Folder");
Folder ftemp=(Folder) child;
long tot=ftemp.getChildren().getTotalNumItems();
System.out.println("Total Children "+tot);
ItemIterable<CmisObject> ftempchildren = ftemp.getChildren();
Iterator<CmisObject> ftempIt = ftempchildren.iterator();
int folderDoc=0;
while (ftempIt.hasNext()) {
CmisObject subchild = ftempIt.next();
if(subchild.getBaseTypeId().value().equals(ObjectType.DOCUMENT_BASETYPE_ID))
{
System.out.println("============ SubDoc "+subchild.getName());
folderDoc++;
documentCount++;
}
}
System.out.println("Folder "+child.getName()+" No of documents="+(folderDoc));
}
else
{
System.out.println("Type : Document "+child.getName());
documentCount++;
}
}
System.out.println("\n\nTotal no of documents "+documentCount);
}
catch(CmisPermissionDeniedException pd)
{
System.out.println("Error ********** Permission Denied ***************** ");
pd.printStackTrace();
}
catch (CmisObjectNotFoundException co) {
System.out.println("Error ******** Root folder not found ***************");
co.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
else
{
System.out.println("Else");
Repository soleRepository=factory.getRepositories(
parameter).get(0);
session = soleRepository.createSession();
}
}
}
here it is my lib which i used in above code .
chemistry-opencmis-client-api-0.9.0
chemistry-opencmis-client-bindings-0.9.0
chemistry-opencmis-client-impl-0.9.0
chemistry-opencmis-commons-api-0.9.0
chemistry-opencmis-commons-impl-0.9.0
log4j-1.2.14
slf4j-api-1.6.1
slf4j-log4j12-1.6.1
it works fine when i am trying to connect repository (url) which is created in english language .
but when try to connect with the danish .repository then getting error.
The best thing you can do is to increase the SharePoint log level for CMIS. Sometimes the logs provide a clue.
The SharePoint 2010 CMIS implementaion isn't a 100% spec compliant. OpenCMIS 0.12.0 contains a few workarounds for SharePoint 2010 and 2013. Most of them a little things like an extra requied URL parameter that isn't in the spec. I wouldn't be supprised if this is something similar.

How to list Management Certificate In windows azure using REST Api

I am tring to list all the management certificates in a windows azure subcription. And I tried with the following code. But it gives me an exception. And I could find that response is null and the exception message is "The remote server returned an error: (403) Forbidden."
Please help me with this. Msdn doesn't provide an example for this :(
using System;
using System.Collections.Generic;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Xml;
using System.Xml.Linq;
class ManagemenCertificateViewer
{
public static void Runme()
{
string msVersion = "2012-03-01";
string subscriptionId = "I used the subscription Id here";
try
{
ListManagementCertificates(subscriptionId, msVersion);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught: ");
Console.WriteLine(ex.Message);
}
}
private static void ListManagementCertificates(string subscriptionId, string version)
{
string uriFormat = "https://management.core.windows.net/{0}/certificates";
Uri uri = new Uri(string.Format(uriFormat, subscriptionId));
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "GET";
request.Headers.Add("x-ms-version", version);
request.ContentType = "application/xml";
XDocument responseBody = null;
HttpStatusCode statusCode;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
// GetResponse throws a WebException for 400 and 500 status codes
response = (HttpWebResponse)ex.Response;
}
statusCode = response.StatusCode;
if (response.ContentLength > 0)
{
using (XmlReader reader = XmlReader.Create(response.GetResponseStream()))
{
responseBody = XDocument.Load(reader);
}
}
response.Close();
if (statusCode.Equals(HttpStatusCode.OK))
{
XNamespace wa = "http://schemas.microsoft.com/windowsazure";
XElement storageServices = responseBody.Element(wa + "SubscriptionCertificates");
int mngmntCertificateCount = 0;
foreach (XElement storageService in storageServices.Elements(wa + "SubscriptionCertificate"))
{
string publicKey = storageService.Element(wa + "SubscriptionCertificatePublicKey").Value;
string thumbprint = storageService.Element(wa + "SubscriptionCertificateThumbprint").Value;
string certificateData = storageService.Element(wa + "SubscriptionCertificateData").Value;
string timeCreated = storageService.Element(wa + "TimeCreated").Value;
Console.WriteLine(
"Certificate[{0}]{1} SubscriptionCertificatePublicKey: {2}{1} SubscriptionCertificateThumbprint: {3}{1} certificateData{4}{1} timeCreated{5}{1}",
mngmntCertificateCount++, Environment.NewLine, publicKey, thumbprint, certificateData, timeCreated);
}
}
else
{
Console.WriteLine("List Management certificates returned an error:");
Console.WriteLine("Status Code: {0} ({1}):{2}{3}",
(int)statusCode, statusCode, Environment.NewLine,
responseBody.ToString(SaveOptions.OmitDuplicateNamespaces));
}
return;
}
}
Thanks it's working as I expected. I just add the following line and the Method 'GetCertificate(arg1)'
request.ClientCertificates.Add(GetCertificate(certThumbprint));
One more thing, in Msdn help guide there's a tag in respond body called
<TimeCreated>time-created</TimeCreated>
But the api responds not the TimeCreated its just created.
<Created> ..... </Created>
403 error means something wrong with your management certificate used to authenticate your Service Management API requests. I don't see you attaching a management certificate along with your request in your code. You may find this link useful for authenticating service management API requests: http://msdn.microsoft.com/en-us/library/windowsazure/ee460782.
HTH.

Check if MOSS resource exists generating unexpected 401's

I have a webdav function listed below:
The behavior is completely unexpected....
When I first run the function and pass a URL to a resource (folder in sharepoint) that does not exist, I get a 404 which is expected. I then use another function to create the resource using THE SAME credentials as in this method. No problems yet...
However on 2nd run, after the resource has been created - when I check if resource exists, now I get a 401.
Whats important to note here is that the same credentials are used to check for 401 and create folder, so clearly the credentials are fine...
So it must be something else.... All I want to do is check if a resource exists in SharePoint.... any ideas how to improve this function? Or any theory as to why its giving this 401...
private bool MossResourceExists(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
// Create a new CredentialCache object and fill it with the network
// credentials required to access the server.
var myCredentialCache = new CredentialCache();
if (!string.IsNullOrEmpty(this.Domain ))
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password , this.Domain )
);
}
else
{
myCredentialCache.Add(new Uri(url),
"NTLM",
new NetworkCredential(this.Username , this.Password )
);
}
request.Credentials = myCredentialCache;
try
{
request.GetResponse();
return true;
}
catch (WebException ex)
{
var errorResponse = ex.Response as HttpWebResponse;
if (errorResponse != null)
if (errorResponse.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
else
{
throw new Exception("Error checking if URL exists:" + url + ";Status Code:" + errorResponse.StatusCode + ";Error Message:" + ex.Message ) ;
}
}
return true;
}
The only clue I have is that when using http://mysite.com/mydoclib/mytoplevelfolder it works.... any sub folders automatically give 401's....
The thing is that you can't pass the whole url that includes folders to the CredentialCache.Add() method.
For example:
http://MyHost/DocumentLibrary/folder1/folder2 will not work as an Uri to the Add() method, but
http://MyHost/DocumentLibrary/ will work.
I would guess that the lack of permissioning capabilities on folder level in SharePoint is the reason for this. Or the way that otherwise SharePoint handles folders.
What you can do is to separate the parameters in your method to accept a base url (including document libraries / lists) and a folder name parameter.
The CredentialCache gets the base url and the request object gets the full url.
Another way is to use the
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
credentials instead. And, if necessary, do an impersonation if you want to use another account than the executing one.
A third variation is to try with authentication type set to Kerberos instead of NTLM.
Here is my test code. I am able to reproduce the problem if I replace the problem with your code, and this code works for me.
static void Main(string[] args)
{
bool result = MossResourceExists("http://intranet/subtest/content_documents/", "testfolder/testfolder2");
}
private static bool MossResourceExists(string baseUrl, string folder)
{
string completeUrl = baseUrl + folder;
var request = (HttpWebRequest)WebRequest.Create(completeUrl);
request.Method = "HEAD";
// Create a new CredentialCache object and fill it with the network
// credentials required to access the server.
var myCredentialCache = new CredentialCache();
if (!string.IsNullOrEmpty(Domain))
{
myCredentialCache.Add(new Uri(baseUrl),
"NTLM",
new NetworkCredential(Username, Password, Domain)
);
}
else
{
myCredentialCache.Add(new Uri(baseUrl),
"NTLM",
new NetworkCredential(Username, Password)
);
}
request.Credentials = myCredentialCache;
//request.Credentials = System.Net.CredentialCache.DefaultCredentials;
try
{
WebResponse response = request.GetResponse();
return true;
}
catch (WebException ex)
{
var errorResponse = ex.Response as HttpWebResponse;
if (errorResponse != null)
if (errorResponse.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
else
{
throw new Exception("Error checking if URL exists:" + completeUrl + ";Status Code:" + errorResponse.StatusCode + ";Error Message:" + ex.Message);
}
}
return true;
}
Hope this helps.

Resources