underlying connection was closed using webclient from azure - winforms

I am windows application developer currently am working in a tutorial based application.my application is built in framework 2.0,c#.net ,i have a task that i need to download zip files from azure cloud storage, i know i can simply done this using windows azure nuget package in higher framework but the problem is i can't upgrade the application framework i need to done the task with this framework. can anyone please help me how to solve this, i got a small hint and i tried on that time i got an error "underlying connection was closed". please help me
my code
string spath = Application.StartupPath.ToString();
string lPath = spath + "\\EncryptedFiles";
string dTo = Path.Combine(lPath, File);
if (System.IO.File.Exists(dTo))
{
System.IO.File.Delete(dTo);
}
NetworkCredential credential = new NetworkCredential("*****", "*****");
CredentialCache cCache = new CredentialCache();
cCache.Add(new Uri(fileName), "Basic", credential);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });
WebClient wClient = new WebClient();
wClient.Credentials = cCache;
wClient.DownloadFile(fileName, dTo);

Related

ASP.NET Core using Distributed SQL Server Cache for session state

I am trying to use distributed SQL Server Cache for session state for a ASP.NET 6 application.
The code example on Microsoft documentation shows how to set up session state using in memory cache:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0
But our application will be deployed to multiple servers. So I am looking for an approach to use distributed SQL Server Cache for session state.
Here is the code I am using in Program.cs:
builder.Services.AddDistributedSqlServerCache(options =>{
options.ConnectionString = builder.Configuration.GetConnectionString(
"DistCache_ConnectionString");
options.SchemaName = "dbo";
options.TableName = "TestCache";}); // we have the corresponding table "TestCache" set up
builder.Services.AddSession(options =>{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.IsEssential = true;});
...
app.UseSession();
When trying to set a session value in a controller, id is empty and a is null. And the "TestCache" table is also empty.
HttpContext.Session.SetString("name", "test");
var id = HttpContext.Session.Id;
var a = HttpContext.Session.GetString("name");
Did I miss anything for configuration? I searched online and found some examples using similar code, but all of them seem to use .NET Core 2.* or .NET Core 3.*
Did anything change for .NET 6?

How to pass google credential to google pub sub

I am trying publish to google PubSub from my .NET Core App. I have already created the PubSub and a Topic in Google PubSub. I downloaded the private key json file and included in my project. I am able to read the file and create the credential but I don't see a way to pass the credential to Google's PubSub Publisher client. I have looked at the GitHub Post but unfortunately I am not seeing a property named DefaultEndPoint.
Running my code generates an error which is looking for environment variable for credential. I do not want to set the environment variable for now and if there is no alternative I will try that.
Following is my code and let me know what I am doing wrong of is something that got changed recently.
var credential = GoogleCredential.FromFile("app-services.json");
PublisherClient publisher = PublisherClient.CreateAsync(topicName).Result;
Agreed that this isn't at obvious as it should be.
using Grpc.Auth;
var credential = GoogleCredential.FromFile("app-services.json");
var createSettings = new PublisherClient.ClientCreationSettings(
credentials: credential.ToChannelCredentials());
var publisher = await PublisherClient.CreateAsync(topicName,
clientCreationSettings: createSettings);
Creating a PublisherServiceApiClient without environment variables:
var credential = GoogleCredential.FromJson(#"{""your_credentials_json_itself"":""here""}");
var channel = new Grpc.Core.Channel(PublisherServiceApiClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
var publisher = PublisherServiceApiClient.Create(channel);
Check out the "Passing the path to the service account key in code" (for .NET) here:
https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually

Application Insights for WPF Application

There is a WPF application written in Visual Studio.
Can I add Application Insights to this WPF app?
I would like to know how many times a button/tile is clicked. Since there are multiple installations
of the same application, I would like to know which button was clicked how many times from which user/installation. Can this be done with Application Insights?
Thanks
Avanti
While not listed as a supported app type this means there isn't default telemetry data collected/sent to application insights nor is there support for adding AI/creating an application insights resource. That being said it is possible to add to your WPF with a few manual steps so that you can track the specific scenarios you mention (like a button/tile click).
-From Visual studio add the "Application Insights API" NuGet to the project (.11 is the latest today).
This will add the Application Insights API reference and create an application insights configuration file to your project.
The applicationinsights.config file needs to be updated with your instrumentation key as follows:
<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings" schemaVersion="2014-05-30">
<TelemetryChannel>
<DeveloperMode>false</DeveloperMode>
</TelemetryChannel>
<TelemetryModules>
<Add Type="Microsoft.ApplicationInsights.Tracing.DiagnosticsTelemetryModule, Microsoft.ApplicationInsights"/>
</TelemetryModules>
<InstrumentationKey>**your-instrumentation-key-guid**</InstrumentationKey>
</ApplicationInsights>
To create an application insights instrumentation key login to your azure subscription.
https://portal.azure.com
Click + to create an Application Insights resource.
Then choose the properties tile on the application insights blade and copy the Instrumentation key and add it to your applicationinsights.config file.
Now in your WPF app you can use the Application Insights sdk as described here: http://blogs.msdn.com/b/visualstudioalm/archive/2014/10/21/application-insights-sdk-0-11-0-prerelease.aspx
your events will be visible in the diagnostic search blade which can be selected on the application insights blade.
Note: telemetry is batched locally for 1 min before being sent to the service unless > 500 telemetry events are queued at which point they are sent.
https://azure.microsoft.com/en-us/documentation/articles/app-insights-windows-desktop/
An official link from Microsoft on how to add Application Insights to a Windows Forms application. From the link:
In Azure - portal.azure.com
Create an Application Resource. ::New / Developer Services / Application Insights.
Notice the instrumentation key generated, grab a copy and set it aside, we'll need it when we configure your application.
In Your Application
NuGet - Add 'Application Insights API'
Configure your TelemetryClient.
I'm using MvvmCross in a WPF application, on startup I create a single TelemetryClient that I re-use throughout the application.
var telemetryClient = new TelemetryClient();
telemetryClient.InstrumentationKey = "your key here from Azure";
telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
telemetryClient.Context.User.AccountId = Username;
telemetryClient.Context.Component.Version = Settings.Default.Version;
telemetryClient.TrackEvent("Application Start");
Mvx.RegisterSingleton<TelemetryClient>(telemetryClient);
Record an event/screen/exception, etc
Any time 'something happens' I'll resolve the TelemetryClient and record the event. This is just like any other Application Insights implementation with regards to tracking and recording.
As an example -
//Resolve the telemetry client
readonly TelemetryClient telemetryClient = Mvx.Resolve<TelemetryClient>();
//Record a page View with some extra information
var pageviewTelemetry = new PageViewTelemetry("Observations");
pageviewTelemetry.Properties.Add("Breadcrumb", breadcrumb);
telemetryClient.TrackPageView(pageviewTelemetry);
//Track an event
var eventTelemetry = new EventTelemetry("Observation Saved");
eventTelemetry.Properties.Add("Saved Observation", observation);
telemetryClient.TrackEvent(eventTelemetry);
//Track an exception
try
{
// do work here
}
catch (Exception ex)
{
telemeteryClient.TrackException(ex);
}
Flush on Application Exit
Application Insights for Windows Desktop applications does not automatically gather/send anything. As a developer one needs to force a flush at application exit.
private void PowerButton_OnClick(object sender, RoutedEventArgs e)
{
var tc = Mvx.Resolve<TelemetryClient>();
if (null != tc)
{
tc.Flush(); // only for desktop apps
}
Application.Current.Shutdown();
}
Or setup an RxTimer to flush on a schedule...I decided to flush every 30 minutes:
var observable = Observable.Interval(new TimeSpan(0, 0, 30, 0));
observable.Subscribe(_ => Application.Current.Dispatcher.Invoke(new Action(() =>
{
var tc = Mvx.Resolve<TelemetryClient>();
if (null != tc)
{
tc.Flush(); // only for desktop apps
Console.WriteLine("Flush TC");
}
})));
FYI - As of 0.17.0 of the Application Insights API NuGet Package if you are offline the flush call doesn't hang, but appears to. Online, the call completes immediately, offline there is a solid 5 second pause before the call completes.
Application Insights (AI) for desktop applications is being deprecated in favor of HockeyApp. It's not overly mature yet, but it works (events essentially reach the same place AI events go).
For example, here's how it looks in RoslynPad (a WPF C# Editor):
using Microsoft.HockeyApp;
//In your initialization method:
var hockeyClient = (HockeyClient)HockeyClient.Current;
hockeyClient.Configure(HockeyAppId)
.RegisterCustomDispatcherUnhandledExceptionLogic(OnUnhandledDispatcherException)
.UnregisterDefaultUnobservedTaskExceptionHandler();
var platformHelper = (HockeyPlatformHelperWPF)hockeyClient.PlatformHelper;
platformHelper.AppVersion = _currentVersion.ToString();
hockeyClient.TrackEvent("App Start");
//sometime later:
hockeyClient.TrackEvent("Something happened");
EDIT Looks like the following NuGet package is required in order for this to work properly: https://www.nuget.org/packages/HockeySDK.WPF.TelemetryWorkaround (see https://github.com/bitstadium/HockeySDK-Windows/pull/88).

How to upload data to local datastore?

I can update the live datastore using the remote API but is there something similar for the local datastore ? My data is in CSV format.
When I try to connect locally using below code
String username = "test";
String password = "test";
RemoteApiOptions options = new RemoteApiOptions().server("localhost", 8888).credentials(username, password);
RemoteApiInstaller installer = new RemoteApiInstaller();
installer.install(options);
I get an exception :
Exception in thread "main" java.net.UnknownHostException: http
The exception is thrown at line :
installer.install(options);
The local server is running, am I connecting correctly ? Do I need to start the local remote_api server separately ?
I finally got this to work through alot of searching. The dev url/password is XXXX/XXXX
Taken from here : https://groups.google.com/forum/?fromgroups=#!topic/google-appengine-java/1cQWn0UEoMc
I havent been able to find this specified anywhere in the google app engine documentation.

Attempting to debug WCF Service added to a solution created with a MVVM Light Toolkit template fails

The goal here is to be able to step into the WCF service code, as well as the Silverlight app code.
File new project > MvvmLight(SL4)
Add new project > WCF Service app
Add service ref to new service in SL proj
In Model\DataService.cs replace GetData with the code below
public void GetData(Action<DataItem, Exception> callback)
{
// Use this to connect to the actual data service
//var item = new DataItem("Welcome to MVVM Light");
var client = new ServiceReference1.Service1Client();
client.GetDataCompleted += (s, e) =>
{
var userCallback = e.UserState as Action;
var item = new DataItem(e.Result);
userCallback(item, null);
};
client.GetDataAsync(123, callback);
}
Place a breakpoint in the GetData method of Service1.svc.cs
F5 to start debugging.
You’ll get a dialog saying you can’t debug.
“The Silverlight project you are about to debug uses web services. Calls to the web service will fail unless the Silverlight project is hosted in and launched from the same web project that contains the web services.”
What do I need to change to allow me to debug the WCF service?
It sounds like your Silverlight application and WCF Service application are using two different ASP.Net projects within your solution. To debug them in a single solution they'd need to be in the same ASP.Net website.

Resources