I am trying to override the certificate validation in a Windows Store App to accept a self-signed certificate on two external services (using HttpClient) to allow the Windows 8 app to accept the certificates and establish a trust relationship for SSL
EDIT:
I implemented the approach documented here : Installing certs by using the appmanifest
and added the relevant .cer files to my application and ensured they are 'Content' and 'Copy Always'.
My package.appxmanifest Extensions section looks like this:
<Extensions>
<Extension Category="windows.certificates">
<Certificates>
<Certificate StoreName="TrustedPeople" Content="Assets\ReportingServices.cer" />
<Certificate StoreName="TrustedPeople" Content="Assets\Crm.cer" />
<Certificate StoreName="CA" Content="Assets\DigiCertHighAssurance.cer" />
<TrustFlags ExclusiveTrust="true" />
<SelectionCriteria AutoSelect="true" />
</Certificates>
</Extension>
but this still does not work.
I have tried putting the app certificates in the 'Root' StoreName but still no success. Does anyone have any ideas why this might not work please?
This is a bit of old one, but seeing as there are quite a few watchers I will give my solution.
// Create the httpClient and send the request
HttpBaseProtocolFilter aHBPF = new HttpBaseProtocolFilter();
// If you want to ignore expired Certs
aHBPF.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
// Untrused because this is a self signed cert that is not installed
aHBPF.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
// Host names and certs names may not match
aHBPF.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
HttpClient httpClient = new HttpClient(aHBPF);
HttpResponseMessage response = await httpClient.SendRequestAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead).AsTask(cts.Token);
Just to save your time. I got to resolve this for 2 days of trial and error. Here you can solve it.
Add the .cer file to your project, Make the build action as "Content", copy as newer
then add this to your app manifest
<Capabilities>
<Capability Name="sharedUserCertificates" />
<Capability Name="enterpriseAuthentication" />
<Capability Name="privateNetworkClientServer" />
<Capability Name="internetClient" />
</Capabilities>
<Extensions>
<Extension Category="windows.certificates">
<Certificates>
<Certificate StoreName="Root" Content="Certificates\vibeapi.cer" />
<TrustFlags ExclusiveTrust="true" />
<SelectionCriteria AutoSelect="true" />
</Certificates>
</Extension>
</Extensions>
and to your code behind you can now access the file using this
//Testing https connection
HttpClientHandler msgHandler = new HttpClientHandler();
using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(msgHandler, true))
{
var HTTPSURL = new Uri("https://www.sample.net/");
var response = await httpClient.GetAsync(HTTPSURL);
var responseStr = await response.Content.ReadAsStringAsync();
}
see link for reference
help
It will work if you put cer file to the project root and change Content section in manifest file to Content="file.cer"
Related
I'm working on Hololens 2 application in Unity 3D. I'm trying to write a configuration file to the device and access it later via the device portal in a web browser. Within the application itself, I'm being told that the file is being written to AppData/Local/Packages/[App Name]/LocalState/[File Name].txt. However, when I go and take a look at LocalAppData/[App Name] the folder LocalState/ doesn't even exist. I suspect this has to do with an error in the Package.appxmanifest file of the VS project generated by Unity.
Here is the relevant C# code I'm using to write to file:
void ReadResolution()
{
string path = Path.Combine(Application.persistentDataPath, mResFilename);
mExcept = $"No exceptions thrown by file IO while writing to \n\"{path}\".";
if(System.IO.File.Exists(path) && new FileInfo(path).Length > 0)
{
try
{
StreamReader reader = new StreamReader(path);
if(reader != null)
{
string content = reader.ReadToEnd();
string[] split = content.Split(' ');
mWidth = Int32.Parse(split[0]);
mHeight = Int32.Parse(split[1]);
}
}
catch (Exception e)
{
mExcept = "File Read Exception: " + e.Message;
}
}
else
{
try
{
using (TextWriter writer = File.CreateText(path))
{
string line = mWidth.ToString() + " " + mHeight.ToString();
writer.WriteLine(line);
}
}
catch (Exception e)
{
mExcept = "File Write Exception: " + e.Message;
}
}
Debug.Log(mExcept);
}
I'm using the member field mExcept to record any messages or exceptions thrown during the process. It's telling me the file is written successfully, but maybe I'm just fooling myself somehow?
Here are the relevant sections from the project's Package.appxmanifest file:
<Package xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:uap2="http://schemas.microsoft.com/appx/manifest/uap/windows10/2"
xmlns:uap3="http://schemas.microsoft.com/appx/manifest/uap/windows10/3"
xmlns:uap4="http://schemas.microsoft.com/appx/manifest/uap/windows10/4"
xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10"
xmlns:mobile="http://schemas.microsoft.com/appx/manifest/mobile/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap uap2 uap3 uap4 mp mobile iot rescap"
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10">
.
.
.
<Capabilities>
<rescap:Capability Name="broadFileSystemAccess" />
<uap:Capability Name="documentsLibrary" />
<Capability Name="internetClient" />
<Capability Name="internetClientServer" />
<Capability Name="privateNetworkClientServer" />
<uap2:Capability Name="spatialPerception" />
<uap3:Capability Name="remoteSystem" />
<DeviceCapability Name="microphone" />
<DeviceCapability Name="gazeinput" />
<DeviceCapability Name="wiFiControl" />
<DeviceCapability Name="webcam" />
</Capabilities>
Any help is appreciated. Thanks in advance.
Ok everybody, I figured it out.
In order to write to persistent storage, VS project generated by Unity needs to have another capability included in its Package.appxmanifest file that mine was missing. Namely, you need to declare the uap capability "removableStorage", in addition to whatever else you're using. As an example, this is what the capabilities section of my manifest file now looks like:
<Capabilities>
<uap:Capability Name="documentsLibrary" />
<Capability Name="internetClient" />
<Capability Name="internetClientServer" />
<Capability Name="privateNetworkClientServer" />
<uap:Capability Name="removableStorage" />
<uap:Capability Name="videosLibrary" />
<uap:Capability Name="objects3D" />
<uap2:Capability Name="spatialPerception" />
<DeviceCapability Name="webcam" />
<DeviceCapability Name="microphone" />
<DeviceCapability Name="location" />
<DeviceCapability Name="wiFiControl" />
</Capabilities>
Also, make sure you uninstall completely any old build on your device before installing the fixed version. That was causing me problems too.
Have a nice day :)
I also used Application.persistentDataPath in Unity which had to work on Hololens 2.
But however it did not work, ie; the file was not getting saved because I made an error (The list which I wanted to save, was not initialized to a new one).
After I corrected it, the file with the list gets saved on the persistantDatapath, and works without adding the above capability.
I have task to get content's url when smth is changed on website. It like CRUD operation logging (In my case i am logging that urls to other system to further processing). It should work on version 6 and higher.
When i started it seems pretty simple subscribe to event then take item and generate url for it. I subscribed to two events publish:itemProcessing (because only here item is not yet removed from web database), publish:itemProcessed (for add and update).
This events give me object of time Item, so it seems to get url pretty simple like that
var options = LinkManager.GetDefaultUrlOptions();
options.AlwaysIncludeServerUrl = true;
options.SiteResolving = true;
var url = LinkManager.GetItemUrl(item, options);
And here my problem starts. First i need to have right url and the same way as it is generated on website but here url returns me smth like "http://domain/sitecore/content/Home.aspx".
So I added new methods to find right site from site definitions
private List<KeyValuePair<string, SiteContext>> GetSites()
{
return SiteManager.GetSites()
.Where(
s =>
!string.IsNullOrEmpty(s.Properties["rootPath"]) &&
!string.IsNullOrEmpty(s.Properties["startItem"]))
.Select(
d => new KeyValuePair<string, SiteContext>($"{d.Properties["rootPath"]}{d.Properties["startItem"]}",
new SiteContext(new SiteInfo(d.Properties))))
.ToList();
}
public virtual SiteContext GetSiteContext(Item item)
{
var site = _sites.LastOrDefault(s => item.Paths.FullPath.ToLower().StartsWith(s.Key.ToLower()));
return site.Value;
}
options.Site = GetSiteContext(Item item);
Again issue is not solved because sitecore returns "http://127.0.0.1/en.aspx"
Then i continue reading and understood that site definition should have targetHostName (it actually make sense since one site can have multiple domains) but when i add targetHostName now it returns me other link "://targetHostName/en.aspx" so http|https is missing. Second problem is that it returns me EN.aspx which means that this page can be accessible throw http://targetHostName/en.aspx and http://targetHostName
Now i have following site definitions
<sites>
<site name="shell" virtualFolder="/sitecore/shell" physicalFolder="/sitecore/shell" rootPath="/sitecore/content" startItem="/home" language="en" database="core" domain="sitecore" loginPage="/sitecore/login" content="master" contentStartItem="/Home" enableWorkflow="true" enableAnalytics="false" analyticsDefinitions="content" xmlControlPage="/sitecore/shell/default.aspx" browserTitle="Sitecore" htmlCacheSize="2MB" registryCacheSize="3MB" viewStateCacheSize="200KB" xslCacheSize="5MB" />
<site name="login" virtualFolder="/sitecore/login" physicalFolder="/sitecore/login" enableAnalytics="false" database="core" domain="sitecore" disableXmlControls="true" />
<site name="admin" virtualFolder="/sitecore/admin" physicalFolder="/sitecore/admin" enableAnalytics="false" enableWorkflow="true" domain="sitecore" loginPage="/sitecore/admin/login.aspx" />
<site name="service" virtualFolder="/sitecore/service" physicalFolder="/sitecore/service" />
<site name="modules_shell" virtualFolder="/sitecore modules/shell" physicalFolder="/sitecore modules/shell" rootPath="/sitecore/content" startItem="/home" language="en" database="core" domain="sitecore" content="master" enableAnalytics="false" enableWorkflow="true" />
<site name="modules_website" virtualFolder="/sitecore modules/web" physicalFolder="/sitecore modules/web" rootPath="/sitecore/content" startItem="/home" language="en" database="web" domain="extranet" allowDebug="true" cacheHtml="true" />
<site name="website" hostName="sitecore6.target|sitecore6.local" targetHostName="sitecore6.target" schema="http" virtualFolder="/" physicalFolder="/" rootPath="/sitecore/content" startItem="/home" database="web" domain="extranet" allowDebug="true" cacheHtml="true" htmlCacheSize="10MB" registryCacheSize="0" viewStateCacheSize="0" xslCacheSize="5MB" filteredItemsCacheSize="2MB" enablePreview="true" enableWebEdit="true" enableDebugger="true" disableClientData="false" />
<site name="scheduler" enableAnalytics="false" domain="sitecore" />
<site name="system" enableAnalytics="false" domain="sitecore" />
<site name="publisher" domain="sitecore" enableAnalytics="false" enableWorkflow="true" />
</sites>
And link manager settings
<linkManager defaultProvider="sitecore">
<providers>
<clear />
<add name="sitecore" type="Sitecore.Links.LinkProvider, Sitecore.Kernel" addAspxExtension="true" alwaysIncludeServerUrl="false" encodeNames="true" languageEmbedding="asNeeded" languageLocation="filePath" lowercaseUrls="false" shortenUrls="true" useDisplayName="false" />
</providers>
</linkManager>
The problem is occurring because of where you are generating the link. When you have the AlwaysIncludeServerUrl option set to true, Sitecore will use the current Sitecore.Context.Site information to work out the server Url.
To set the http or https section, you need to add an attribute called scheme to your site definition - I think you just have a typo as you had one called schema:
<sites>
<site name="website" hostName="sitecore6.target|sitecore6.local" targetHostName="sitecore6.target" scheme="http" virtualFolder="/" physicalFolder="/" rootPath="/sitecore/content" startItem="/home" database="web" domain="extranet" allowDebug="true" cacheHtml="true" htmlCacheSize="10MB" registryCacheSize="0" viewStateCacheSize="0" xslCacheSize="5MB" filteredItemsCacheSize="2MB" enablePreview="true" enableWebEdit="true" enableDebugger="true" disableClientData="false" />
</sites>
During a publish event, that Context.Site will be the shell website. So it will not pickup the targetHostName for your website definition.
To force that, you need to use a SiteContextSwitcher
var website = Sitecore.Configuration.Factory.GetSite("website");
using (new SiteContextSwitcher(website))
{
var options = LinkManager.GetDefaultUrlOptions();
options.AlwaysIncludeServerUrl = true;
options.SiteResolving = true;
var url = LinkManager.GetItemUrl(item, options);
}
Then the Url will be generated using the website's targetHostName and should generate how you are expecting.
Just one last note - best practice would be to patch the new Site definition via an include file rather than edit the main Sitecore config. Check out your include folder, there should be a SiteDefinition.config.example file in there. It shows you how to do it.
I have been asked to create a remote selenium web driver using browserstack to test the functionality across all browsers. I have checked the repository to which I have received some of the felds needed:
RemoteUrl: http://hub.browserstack.com:80/wd/hub/
browserstack.user = username
browserstack.key = password
browserstack.debug = true/false
browserstack.tunnel = true/false
os
OS_version
Version = the browser version
I have got the code to create the driver below:
DesiredCapabilities capability = DesiredCapabilities.Firefox();
capability.SetCapability("browserstack.user", "username");
capability.SetCapability("browserstack.key", "password");
driver = new RemoteWebDriver(
new Uri("http://hub.browserstack.com/wd/hub/"), capability
);
this creates the remote webdriver. However as i am using this with specbind I need to create this driver within the app.config. which will be stored under a <browserfactory> however I am unsure on how to do this, please help!
I have now resolved this issue. From the start URL you need to then put in this browser factory setting:
<browserFactory
provider="SpecBind.Selenium.SeleniumBrowserFactory, SpecBind.Selenium">
<settings>
<add name="RemoteUrl" value="http://hub.browserstack.com:80/wd/hub/"/>
<add name="browser" value="IE" />
<add name="browser_version" value="8.0"/>
<add name="os" value ="Windows"/>
<add name="os_version" value="7" />
<add name="browserstack.user" value="username" />
<add name="browserstack.key" value="key" />
</settings>
The various settings configure this to Windows 7 and IE 8. This can be changed accordingly and the Username and Key is given to you by browser stack.
Using Azure SDK 2.3 on my vs2013 development VM I can consume Service Bus queues hosted in Azure painlessly. However, on Windows Server 2008 R2 Standard SP1, it looks like Windows can not trust the involved certificates and an exception is thrown.
The line that throws :
// Send the message
await queueclient.SendAsync(message);
Exception message :
The X.509 certificate CN=servicebus.windows.net is not in the trusted
people store. The X.509 certificate CN=servicebus.windows.net chain
building failed. The certificate that was used has a trust chain that
cannot be verified. Replace the certificate or change the
certificateValidationMode. A certificate chain could not be built to a
trusted root authority.
The CAPI2 logs (attached below) pointed to a trust issue so I compared certificates installed on both machines. The following certificates are absent on the server :
Intermediate Certification Authorities > Microsoft Internet Authority
(Issued by Baltimore CyberTrust Root)
Intermediate Certification Authorities > MSIT Machine Auth CA 2
(Issued by Microsoft Internet Authority)
The questions :
Where does the certificates come from?
Why are they missing from the server?
How to fix this issue?
Possible trails (updated) :
Install Azure SDK 2.3 for Visual Studio 2013 on the server
Install all Windows Updates on the server
I tried :
<appSettings>
<add key="Microsoft.ServiceBus.X509RevocationMode" value="NoCheck"/>
</appSettings>
CAPI2 Verify Chain Policy event :
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Microsoft-Windows-CAPI2" Guid="{5bbca4a8-b209-48dc-a8c7-b23d3e5216fb}" />
<EventID>30</EventID>
<Version>0</Version>
<Level>2</Level>
<Task>30</Task>
<Opcode>0</Opcode>
<Keywords>0x4000000000000001</Keywords>
<TimeCreated SystemTime="2014-06-11T19:57:38.998656000Z" />
<EventRecordID>5642</EventRecordID>
<Correlation />
<Execution ProcessID="5280" ThreadID="8472" />
<Channel>Microsoft-Windows-CAPI2/Operational</Channel>
<Computer>ne-r026-310cn</Computer>
<Security UserID="S-1-5-82-1758914132-2364927631-3137608320-3227192193-3717738432" />
</System>
<UserData>
<CertVerifyCertificateChainPolicy>
<Policy type="CERT_CHAIN_POLICY_BASE" constant="1" />
<Certificate fileRef="3E560462C61B45BE1A59F1286B34A065A878AFA0.cer" subjectName="servicebus.windows.net" />
<CertificateChain chainRef="{19B5F58A-FA37-4213-A888-C81C340D019C}" />
<Flags value="1000" CERT_CHAIN_POLICY_IGNORE_PEER_TRUST_FLAG="true" />
<Status chainIndex="0" elementIndex="-1" />
<EventAuxInfo ProcessName="w3wp.exe" />
<CorrelationAuxInfo TaskId="{F8DE43DD-9E68-461E-8A2B-17215BA87E0C}" SeqNumber="1" />
<Result value="800B010A">A certificate chain could not be built to a trusted root authority.</Result>
</CertVerifyCertificateChainPolicy>
</UserData>
</Event>
CAPI2 Build Chain event :
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Microsoft-Windows-CAPI2" Guid="{5bbca4a8-b209-48dc-a8c7-b23d3e5216fb}" />
<EventID>11</EventID>
<Version>0</Version>
<Level>2</Level>
<Task>11</Task>
<Opcode>2</Opcode>
<Keywords>0x4000000000000003</Keywords>
<TimeCreated SystemTime="2014-06-11T19:57:38.998656000Z" />
<EventRecordID>5641</EventRecordID>
<Correlation />
<Execution ProcessID="5280" ThreadID="8472" />
<Channel>Microsoft-Windows-CAPI2/Operational</Channel>
<Computer>ne-r026-310cn</Computer>
<Security UserID="S-1-5-82-1758914132-2364927631-3137608320-3227192193-3717738432" />
</System>
<UserData>
<CertGetCertificateChain>
<Certificate fileRef="3E560462C61B45BE1A59F1286B34A065A878AFA0.cer" subjectName="servicebus.windows.net" />
<ValidationTime>2014-06-11T19:57:38.998Z</ValidationTime>
<AdditionalStore />
<ExtendedKeyUsage />
<Flags value="0" />
<ChainEngineInfo context="machine" />
<AdditionalInfo>
<NetworkConnectivityStatus value="1" _SENSAPI_NETWORK_ALIVE_LAN="true" />
</AdditionalInfo>
<CertificateChain chainRef="{19B5F58A-FA37-4213-A888-C81C340D019C}">
<TrustStatus>
<ErrorStatus value="10000" CERT_TRUST_IS_PARTIAL_CHAIN="true" />
<InfoStatus value="0" />
</TrustStatus>
<ChainElement>
<Certificate fileRef="3E560462C61B45BE1A59F1286B34A065A878AFA0.cer" subjectName="servicebus.windows.net" />
<SignatureAlgorithm oid="1.2.840.113549.1.1.5" hashName="SHA1" publicKeyName="RSA" />
<PublicKeyAlgorithm oid="1.2.840.113549.1.1.1" publicKeyName="RSA" publicKeyLength="2048" />
<TrustStatus>
<ErrorStatus value="0" />
<InfoStatus value="2" CERT_TRUST_HAS_KEY_MATCH_ISSUER="true" />
</TrustStatus>
<ApplicationUsage>
<Usage oid="1.3.6.1.5.5.7.3.2" name="Client Authentication" />
<Usage oid="1.3.6.1.5.5.7.3.1" name="Server Authentication" />
</ApplicationUsage>
<IssuanceUsage />
</ChainElement>
</CertificateChain>
<EventAuxInfo ProcessName="w3wp.exe" />
<CorrelationAuxInfo TaskId="{9077AB4E-95E3-449B-AF2F-0BF42E92E6B7}" SeqNumber="11" />
<Result value="800B010A">A certificate chain could not be built to a trusted root authority.</Result>
</CertGetCertificateChain>
</UserData>
</Event>
CAPI2 X509 Objects event :
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Microsoft-Windows-CAPI2" Guid="{5bbca4a8-b209-48dc-a8c7-b23d3e5216fb}" />
<EventID>90</EventID>
<Version>0</Version>
<Level>4</Level>
<Task>90</Task>
<Opcode>0</Opcode>
<Keywords>0x4000000000000200</Keywords>
<TimeCreated SystemTime="2014-06-11T19:57:38.998656000Z" />
<EventRecordID>5640</EventRecordID>
<Correlation />
<Execution ProcessID="5280" ThreadID="8472" />
<Channel>Microsoft-Windows-CAPI2/Operational</Channel>
<Computer>ne-r026-310cn</Computer>
<Security UserID="S-1-5-82-1758914132-2364927631-3137608320-3227192193-3717738432" />
</System>
<UserData>
<X509Objects>
<Certificate fileRef="3E560462C61B45BE1A59F1286B34A065A878AFA0.cer" subjectName="servicebus.windows.net">
<Subject>
<CN>servicebus.windows.net</CN>
</Subject>
<SubjectKeyID computed="false" hash="BD41618C22D8DBEE9D172C12A2C549D61711ED75" />
<SignatureAlgorithm oid="1.2.840.113549.1.1.5" hashName="SHA1" publicKeyName="RSA" />
<PublicKeyAlgorithm oid="1.2.840.113549.1.1.1" publicKeyName="RSA" publicKeyLength="2048" />
<Issuer>
<CN>MSIT Machine Auth CA 2</CN>
<DC>redmond</DC>
<DC>corp</DC>
<DC>microsoft</DC>
<DC>com</DC>
</Issuer>
<SerialNumber>70DB015B000100008C58</SerialNumber>
<NotBefore>2013-07-27T03:31:06Z</NotBefore>
<NotAfter>2015-07-27T03:31:06Z</NotAfter>
<Extensions>
<KeyUsage value="B0" CERT_DIGITAL_SIGNATURE_KEY_USAGE="true" CERT_KEY_ENCIPHERMENT_KEY_USAGE="true" CERT_DATA_ENCIPHERMENT_KEY_USAGE="true" />
<ExtendedKeyUsage>
<Usage oid="1.3.6.1.5.5.7.3.2" name="Client Authentication" />
<Usage oid="1.3.6.1.5.5.7.3.1" name="Server Authentication" />
</ExtendedKeyUsage>
<SubjectAltName>
<DNSName>*.servicebus.windows.net</DNSName>
<DNSName>servicebus.windows.net</DNSName>
</SubjectAltName>
<AuthorityKeyIdentifier>
<KeyID hash="EBDB115EF8099ED8D6629CFD629DE3844A28E127" />
</AuthorityKeyIdentifier>
</Extensions>
</Certificate>
<EventAuxInfo ProcessName="w3wp.exe" />
<CorrelationAuxInfo TaskId="{9077AB4E-95E3-449B-AF2F-0BF42E92E6B7}" SeqNumber="10" />
</X509Objects>
</UserData>
</Event>
The missing certificates were responsible for the exception.
I haven't been able to find the certificates online and I'm still unsure of how EXACTLY they managed to install themselves BUT I think I have an idea..
How we managed to obtain the certificates?
We isolated the Service Bus messaging code into a console application and executed it with admin rights on the production server. The certificates installed themselves automatically in the process.
Perhaps our application pool, running under ApplicationPoolIdentity with limited permissions was not allowing Windows to download or install the certificates.
This link seems to offer related information : http://netsekure.org/2011/04/automatic-ca-root-certificate-updates-on-windows/
Update : You can download the certificate chain here.
To eliminate certificate trust issues from Service Bus for Windows Server, use the following:
Create a list of the certificates you trust:
var trustedCertificates = new HashSet<string>(new[]
{
"1245…",
"4567…,
"8102…"
}, StringComparer.OrdinalIgnoreCase);
Trust those:
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
{
if (errors == SslPolicyErrors.None)
{
return true;
}
var hashString = certificate.GetCertHashString();
var isTrusted = trustedCertificates.Contains(hashString);
if (!isTrusted)
{
telemetryClient.TrackTrace($"Untrusted: {hashString} Errors: {errors} Cert: {certificate.ToString()}", SeverityLevel.Warning);
}
return isTrusted;
};
Calm Service Bus down too:
private static void SetCertificateValidator()
{
var retriableCertificateValidatorType = Type.GetType("Microsoft.ServiceBus.Channels.Security.RetriableCertificateValidator, Microsoft.ServiceBus", true, false);
var instanceProperty = retriableCertificateValidatorType.GetProperty("Instance", BindingFlags.Static | BindingFlags.NonPublic);
var instance = instanceProperty.GetValue(null);
var peerOrChainTrustNoCheck = retriableCertificateValidatorType.GetField("peerOrChainTrustNoCheck", BindingFlags.Instance | BindingFlags.NonPublic);
peerOrChainTrustNoCheck?.SetValue(instance, new EmptyOpX509CertificateValidator());
}
private sealed class EmptyOpX509CertificateValidator : X509CertificateValidator
{
public override void Validate(X509Certificate2 certificate)
{
}
}
I'm trying to save a string of user inputs to a file in a windows runtime app. However I'm getting the error System.UnauthorizedAccessException. How do I gain access to this Library?
static private async Task WriteDataToFileAsync(string fileName, string content)
{
byte[] data = Encoding.Unicode.GetBytes(content);
var folder = KnownFolders.DocumentsLibrary;
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var s = await file.OpenStreamForWriteAsync())
{
await s.WriteAsync(data, 0, data.Length);
}
}
"Documents library" capability in Visual Studio 2013 has been removed since it is only available for Windows Store Company accounts. Without this capability you will get "Access is denied".
For more information, read here: http://lunarfrog.com/blog/2013/07/05/documents-library-capability-winrt/
Like this, notice under 'Extensions' I specify the file type I want to access (.txt) and then under 'Capabilities' I have added 'documentsLibrary'.
Then to actually write or access a file from there, something like this.
var file = await KnownFolders.DocumentsLibrary.CreateFileAsync("myFile.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, data);
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest" xmlns:m2="http://schemas.microsoft.com/appx/2013/manifest">
<Identity Name="testapp" Publisher="CN=test.test" Version="1.5.0.3" />
<Properties>
<DisplayName>test.MetroApp</DisplayName>
<PublisherDisplayName>test.test</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Prerequisites>
<OSMinVersion>6.3.0</OSMinVersion>
<OSMaxVersionTested>6.3.0</OSMaxVersionTested>
</Prerequisites>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="test.MetroApp.App">
<m2:VisualElements DisplayName="test.MetroApp" Square150x150Logo="Assets\test.png" Square30x30Logo="Assets\SmallLogo.png" Description="test.MetroApp" ForegroundText="light" BackgroundColor="#464646">
<m2:SplashScreen Image="Assets\test.scale-620.png" BackgroundColor="#464646" />
<m2:InitialRotationPreference>
<m2:Rotation Preference="landscape" />
</m2:InitialRotationPreference>
</m2:VisualElements>
<Extensions>
<Extension Category="windows.fileTypeAssociation">
<FileTypeAssociation Name="1">
<DisplayName>AccessTXT</DisplayName>
<SupportedFileTypes>
<FileType>.txt</FileType>
</SupportedFileTypes>
</FileTypeAssociation>
</Extension>
</Extensions>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClient" />
<Capability Name="privateNetworkClientServer" />
<Capability Name="musicLibrary" />
<Capability Name="documentsLibrary" />
</Capabilities>
</Package>
According to the docs "your app must use the File Type Association declaration in the app manifest file to explicitly declare what file types (extensions) will be accessed or created in the Documents library".