Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all 8156 articles
Browse latest View live

Request aborted: Could not create SSL/TLS secure channel

$
0
0

Hi everyone,

First, some background: I'm maintaining a content filter that was built with C# / .NET 4.6.1 / .NET Standard

I'm currently running into an issue where .NET fails to open a secure channel to a particular website. The URL I'm trying to access with C# is https://portal.worldpay.us

Here's the error I'm getting:

Exception: System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at InternetTesting.Program.Main(String[] args) in c:\users\kent friesen\source\repos\InternetTesting\InternetTesting\Program.cs:line 22
---> (Inner Exception #0) System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
   --- End of inner exception stack trace ---<---
The portal.worldpay.us is encrypted with TLSv1 and an AES-128SHA cipher, according to OpenSSL.

Code which replicates the problem:

class Program
{
    static void Main(string[] args)
    {
        HttpClient client = new HttpClient();
        HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, "https://portal.worldpay.us");

        HttpResponseMessage response = null;

        try
        {
            response = client.SendAsync(message).Result;
        }
        catch(Exception ex)
        {
            Console.WriteLine("Exception: {0}", ex);
        }

        if (response != null)
        {
            Console.WriteLine("Response {0}", response.StatusCode);
        }

        Console.ReadKey();
    }
}

At first, I thought it was an Schannel problem, but now I'm not sure, because no Schannel error appears in event viewer, and I am able to access the site with IE11 and Edge just fine.

Does anyone have any ideas what the problem might be? I'd be inclined to say there's a bug somewhere in the .NET software stack, but I'd like to be proven wrong.

Thanks

Edit: Tested with .NET 4.6.1, 4.7.2 and got the same results. Testing with .NET Core 2.0 worked, but that's not an option for a short-term fix.

Try ... Catch ... there is NO way to determine the line of code that triggered the error?

$
0
0

This is something that I've never been able to resolve in any version of Visual Studio (Ultimate 2012 currently).  I'm using VB.NET but the Try ... Catch exception handling does NOT provide any information on exactly what line of code triggered the error when I'm in a debug session.  It'll tell me what the exception issue, but NOTHING about what line actually triggered the exception.

If I have several 100's of lines of code in a Try ... Catch, this becomes a huge issue ... in most cases I stop execution and but a break point at the first line of code in the Try ... Catch and re-run my debug session (definitely NOT efficient).  I have to look for hints based on inspecting all the variables/structures.  This is TIME consuming and not helping the speed of my development work.

Many years ago it was easy to get to the offending line of code ... before the invention of .NET and Try ... Catch, but now I seem to have lost that ability, such a basic and fundamental ability.  I've gone on for years just dealing with the lack of functionality in VS 2008+ series.  

I hoping I'm wrong and there is a way that I just never discovered all these years, if so, can someone please tell me how?

I've seen lots of silly suggestions such as put a Try ... catch on every line of code, but that's not productive.

So have I really lost a fundamental debugging feature?  If so, how is this progress?

Rob

 

Microsoft Graph API, sending email response: StatusCode: 401 ReasonPhrase: 'Unauthorized'

$
0
0

I am trying to send an email using the Microsoft Graph API, and getting the following response:

StatusCode: 401, ReasonPhrase: 'Unauthorized'...

I'm trying to find out if there's something wrong with my code, or if the user account is lacking permissions.

Here is the code below:

string accessToken = GetADToken();
            string graphRequest = "https://graph.microsoft.com/v1.0/me/sendMail";

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            // client.DefaultRequestHeaders.Add("ContentType", "application/json");

            var email = new
            {
                message = new
                {
                    subject = "test subject",
                    body = new
                    {
                        contentType = "Text",
                        content = "The cafeteria is open"
                    },
                    toRecepients = new List<object> { new {
                            emailAddress = new {
                                address = "test.user@emailprovider.com"
                            }
                        }
                    },
                    ccRecipients = new List<object> { new {
                            emailAddress = new {
                                address = "test.user@emailprovider.com"
                            }
                        }
                    }
                },
                saveToSentItems = false
            };

            // var requestContent = new StringContent(JsonConvert.SerializeObject(email), Encoding.UTF8, "application/json");

            string requestContent = JsonConvert.SerializeObject(email);
            var buffer = Encoding.UTF8.GetBytes(requestContent);
            var byteContent = new ByteArrayContent(buffer);
            byteContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

            var response = client.PostAsync(graphRequest, byteContent).Result;

            return response;


CheckSignature on some SAML responses fails.

$
0
0

Hi Team,

We have implemented SAML authentication and using .Net framework 4.6.2

CheckSignature is failing on some SAML responses, so far we have found one such case. CheckSignature passes for all other SAML responses.

1. SAML response is valid

2. Certificate is valid

3. SAML response text was not altered.

Found this article on the web --> https://github.com/dotnet/corefx/issues/19198

Here is the code which checks signature on SAML response.

 XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
            manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            manager.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            manager.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");

            XmlNodeList nodeList = xmlDoc.SelectNodes("//ds:Signature", manager);

            SignedXml signedXml = new SignedXml(xmlDoc);

            if (nodeList?.Count != 1)
            {
                return false;
            }

            //Load signedXml from SAML Response 

            signedXml.LoadXml((XmlElement) nodeList[0]);

            // Load certificate from file store
            X509Certificate2 cert = (certificate from file store.)

            //Verifiy signature using the public key in the signature and key signing ceritificate.

            return (signedXml.CheckSignature() || signedXml.CheckSignature(cert, true));

Please let me know, if there I am missing anything here.

regards,

Prashant.

Cookie Authentication Not working in .Net Core 2.1 Call to HttpContext.SignInAsync doesn't set the identity.

$
0
0

Starting to Porting our project from .Net 4.6 to .Net Core 2.1.  I got cookie Authentication working at some point. I've upgraded my libraries and changed some configuration and now only the users that have a cookie can login. No new users can login. Calling  HttpContext.SignInAsync doesn't set the identity. 

In my startup I have the following code to build the middle ware to support cookie authentication:

public void ConfigureServices(IServiceCollection services)
{


services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
...


 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddSessionStateTempDataProvider();

            services.AddAuthentication(options =>
                {
                    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {                 
                    options.Cookie.Name = "researchCookie";
                    options.AccessDeniedPath = new PathString("/account/create");
                    options.LoginPath = new PathString("/account/create");
                    options.Cookie.HttpOnly = true;
                    options.ExpireTimeSpan = TimeSpan.FromDays(365);
                    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
                    options.SlidingExpiration = true;
                });

}





public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{


...

 app.UseAuthentication();

...

 app.UseCookiePolicy(new CookiePolicyOptions
            {
                HttpOnly = HttpOnlyPolicy.Always,
                MinimumSameSitePolicy = SameSiteMode.Lax,
                Secure = CookieSecurePolicy.Always,
});

...

  app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "home",
                    template: "                   {controller=default}/{action=Index}");
            });

}

When I authenticate this is the code I have:

 List<Claim> claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, loginResult.AccessData.FirstName + " " + loginResult.AccessData.LastName),
                    new Claim(ClaimTypes.Email, loginResult.AccessData.Email),
                    new Claim(ClaimTypes.GivenName, loginResult.AccessData.FirstName),
                    new Claim(ClaimTypes.Surname, loginResult.AccessData.LastName),
                    new Claim(ClaimTypes.NameIdentifier, loginResult.AccessData.AccessID.ToString())
                };
                ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                var authProperties = new AuthenticationProperties
                {
                    AllowRefresh = true,
                    // Refreshing the authentication session should be allowed.

                    ExpiresUtc = DateTimeOffset.UtcNow.AddYears(2),
                    // The time at which the authentication ticket expires. A 
                    // value set here overrides the ExpireTimeSpan option of 
                    // CookieAuthenticationOptions set with AddCookie.

                    IsPersistent = true,
                    // Whether the authentication session is persisted across 
                    // multiple requests. Required when setting the 
                    // ExpireTimeSpan option of CookieAuthenticationOptions 
                    // set with AddCookie. Also required when setting 
                    // ExpiresUtc.

                    IssuedUtc = DateTime.Now.ToUniversalTime(),
                    // The time at which the authentication ticket was issued.

                    //RedirectUri = <string>
                    // The full path or absolute URI to be used as an http 
                    // redirect response value.
                };


                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), authProperties);

I must be doing something wrong or something in the library updates has broken this. But Like I said only people who previously logged in can login. If you delete the cookies then the identity never gets set. 

Any suggestions would be greatly appreciated. 

excessive use comctl32.dll with .net framework 4.x under win10

$
0
0

With processmonitor we traced a winforms application using comctl32.dll. Under Win7 with Framework 4.x the application starts fast an there is a normal using of comctl32.dll. Unter win10 with framework 4.x the same applikation start two oder three times slower. Reason is the excessive use comctl32.dll, which we see with the processmonitor.

Problem seems the function in Framework 4.x with win10 GetModuleHandle("comctl32.dll")

Details:
https://stackoverflow.com/questions/39673069/windows-10-exessive-use-of-comctl32-dll-in-net-4-0-and-up

Multipoint mouse SDK

$
0
0

Hello,

I am looking for the multipoint mouse SDK for download or something similar if it no longer exists (I tried various search engines and the search result directly associated with msdn - but no luck).

Similarly, I need something for the keyboard as well.

I am working with macros - however, I am facing the problem that my mouse and keyboard cannot be left alone inorder for me to work on my other screens.

I am fine to have the application be placed within a container (such as a windows form's panel) - where it will have its own mouse and keyboard (or something similar to it) - which will perform actions such as mouse click, enter text etc.

Thanks!


The 'http://www.w3.org/XML/1998/namespace:lang' attribute is not declared problem when using XmlReader in .Net Standard 2.0

$
0
0
I am facing a problem to read HTML string in XmlReader with some reader settings.

Project details :
.Net Standard 2.0 target project

Issue details:
Below exception message thrown when creating XmlReader with settings as per the code snippet.
"System.Xml.Schema.XmlSchemaValidationException
  HResult=0x80131941
  Message=The 'http://www.w3.org/XML/1998/namespace:lang' attribute is not declared."

Exception thrown in line : XmlReader reader = XmlReader.Create(new StringReader(html), settings);


Code snippet:

FileStream stream = new FileStream("xhtml1-transitional.xsd", FileMode.Open, FileAccess.ReadWrite); XmlSchema schema = XmlSchema.Read(stream, new ValidationEventHandler(OnValidation)); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas.Add(schema); string html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title></title></head><body><p>hello</p></body></html>";

XmlReader reader = XmlReader.Create(new StringReader(html), settings);

XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(reader); reader.Close();

The mentioned exception doesn't throws in WindowsForms application for the same code. Is there any limitation for .Net Standard 2.0 ? Or Is any other approach to achieve my requirement in .Net Standard 2.0?

do i need admin rights to run exe file(which is generated from vbs)

$
0
0

Hi,

i have .vbs file and i am converting it into .exe file(using 3rd party tool).

the question is: once exe file generated, do i need admin rights to run exe file or not?

i need to run exe file on windows: xp,win7 and 10

Regards,

Yogesh


yogi

How can I find where ConfigurationManager is getting its values from?

$
0
0

Hi all;

I have the following call:

var coll =(NameValueCollection)ConfigurationManager.GetSection("WindwardReports");

When I look at coll in the debugger, it lists 3 keys. Two of those keys do not exist anywhere on my computer. I didn't just look in the config files (machine as well as app.config),I did a grep of every file on my computer and those text strings don't exist.

How can I determine where .NET is pulling those from? One note, this is a Word AddIn (and yes I looked at winword.exe.config too).

thanks - dave


What we did for the last 6 months - Made the world's coolest reporting & docgen system even more amazing

Error on .Net V4.0 - the c++ module failed to load during appdomain initialization

$
0
0

HI All

I run software that is dependent on .Net 4.0 and every so often the application which is web based fails to connect to the SQL DB on the server and throws a COM exception with the following message: This is taken from Event viewer:

the c++ module failed to load during appdomain initialization

I see on the forums i need to add a line into a config file however i dont know which config file to edit.

Can someone please let me know how to get this warning message to go away and to prevent this from happening

How to write Excel File in C#

$
0
0
I want to write excel file from the datatable

How to call a class method from another class using delegates

$
0
0
How to call a class method from another class using delegates

Directory.CreateDirectory Throws IOException "file or directory with the same name already exists"

$
0
0

Hi all,

I'm seeing strange behavior in an application with a certain filesystem.  If across multiple threads (generally 5 or more) in the app, I try to create an identical directory structure between all of them.  Some of the threads are throwing an IOException with a messaging that one of the intermediate directories already exists.  This seems to only happen if the file system is a network server and if I do NOT have ProcMon tracing running on the Client (App) side, but I can get it to happen if I have ProcMon tracing on the Server side.

The app is using .NET 4.5.2, but I've been able to reproduce it using the latest .NET as well.

E.g. I try call Directory.CreateDirectory with the following path across 5 threads: Y:\asdf\006\0\0\0\0

A typical error I will get is the following: Cannot create "Y:\asdf\006\0" because a file or directory with the same name already exists.    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

   at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost)
   at System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean checkHost)
   at System.IO.Directory.CreateDirectory(String path)

I've read the source code for Directory.CreateDirectory and the key point seems to be the creation of the stackDir for the intermediate directories: https://referencesource.microsoft.com/#mscorlib/system/io/directory.cs,e3885fef9f6af9de

What I don't get is, reading that code, it looks to me like the ONLY time this function would throw this exception would be if that error code was encountered AND the library looks up the already created directory to see if a.) its a file or b.) it got access denied trying to querying it.  Is anyone else available to confirm my analysis of that code?

What's frustrating is that the Directory.CreateDirectory says it won't throw that exception if the directory already exists and I can see that the directory already exists. I can also see, when the filesystem is returning NAME COLLISION, that from the server side, I DO NOT see the app requerying the entry to see if its a directory. That also speaks to potential metadata caching on the client side, but I don't see why that would ever return that its not a directory.


Adam

Reference to type 'CompressionLevel' claims it is defined in 'System', but it could not be found

$
0
0

trying to build a project application in vs 2017 community version. the application worked fine with vs 2012 pro

System.IO.Compression.ZipFile.CreateFromDirectory(dbFolder, defltBkpTarget,
				System.IO.Compression.CompressionMode.Compress, zipIncludeBaseDir);

// where vs2007 red underline the code: System.IO.Compression.ZipFile.CreateFromDirectory
// where System.IO.Compression.CompressionMode.Compress is not underlined

what gives


Getting error while using GetUserContextEx via Web Application

$
0
0

Hi,

We have a web application developed in .NET Framework 2.0 which fetches details of AD objects from the DC using the secure32.dll. However, when the web application is deployed on a member server, the below error is thrown while fetching the details of the administrator:

Inner Exception: GetUserNameEx 1317
System.Exception: GetUserNameEx 1317

When the web application is installed on the DC, the fetching operation is successful. Please suggest, as this is blocking us. Let me know if further information is required.

Please note that we have two DCs with 2008R2 and 2012R2 OS and a member server with 2012R2 OS.

Enumerating instances of the Binding class

$
0
0

For educational purposes I want to enumerate all instances of the WPF Binding class.

This might be a WPF question but instead of moving this to the WPF forum, if someone can confirm that I am using reflection properly then that would be better.

I have tried the following (in my MainWindow class).

MemberInfo[] members = GetType().GetMember("Binding");

That gets nothing. So yes, each instance will be a member of some other object. Is there a way, using code, to get all instances (of the assembly) regardless of where they are? Something else that could help is a relevant tool.

WPF binding is confusing and I think that studying actual instances is one way to learn how it works. I am asking how to use reflection to list them.

And again, I will create a separate question for the parts specific to WPF.



Sam Hobbs
SimpleSamples.Info

Get line number at unhandled exception during runtime (no debugger)

$
0
0
Hello!

I like to find a way to get the line numbers when I trap my UnhandledExceptions (that I set up in the ApplicationEvents.vb file).

During debugging mode (under the IDE.e) I can get this from the StackTrace method but this seems to not be available during run time outside the IDE.

Is there any way to achieve this?? For instance, if I run my app without trapping the unhandled exceptions .NET Framework shows it own dialogue box with trace info including a line number! Where does the MS people get this from?

Best regards/
Magnus

Tips on Posting Good Questions

$
0
0
Here are a few suggestions that make it sure you get the best answer to your question as quickly as possible:
  1. Search for your question on the forums or in Visual Studio's help system first -- it's likely someone may have already answered your question, and you won't have to waste time waiting for it to be answered again
  2. Post in the correct forum (see below) -- since the experts in various subject matters tend to stick to the set of forums that focus on those topics, a question about the C# yield keyword posted in the Common Language Runtime forum will likely take a lot longer to be answered than the same question in the C# Language forum.
  3. Make sure your title summarizes the specific problem you have --  since we try to answer the maximum number of questions we can with our time, we often skim through question subjects to quickly find the ones that we know the answers to.  A question with a title of "Urgent! Help needed!" is not as likely to get answered as a question with a title of "How to define a sealed class using CodeDOM".  A more specific, detailed title is far more likely to get a response than a general one. 
  4. Give details about your problem --  rather than "When I call Process.Start I get an exception, please help", provide the exception type, message, and call stack.  If possible provide a succinct code snippet that demonstrates the problem.  This lets us reproduce the problem on our end, and allows us to come up with an answer where just a general question may not have had enough details.  Having this information means we can answer your question more quickly, without having to ask you for these details and wait for your response.
  5. Once you've received a correct answer to your question, either from a Microsoft employee, an MVP, or the community in general, please mark the post as answered .  You can do this with the "Mark as correct answer" button that appears on the entry containing your answer.  This step is important, since it lets the Visual Studio search engine know that there is an answer in that thread for others who may also have your problem.  It also lets people scanning the forums know that they can find an answer to that question by reading the thread.
  6. Report bugs through Microsoft Connect instead of on the forums -- Microsoft Connect allows us to see the bugs in our bug tracking database and get them assigned to the correct person.  It also allows you to follow the problem through to its resolution, and is a much better way for us to handle issues you find than a bug report posted on the forums.

When trying to figure out which forum is right for your question, here are some good candidates:

Of course there are dozens of other forums available if your question doesn't fit into one of those categories.

Finally -- as moderators we try to keep spam and inflammatory comments out of the forums.  However if you do catch something that we missed, don't hesitate to use the report button so that we can keep the forums on-topic and a friendly place to go for help with your .NET questions!

-Shawn

Autocomplete Match on Contains, not StartsWith

$
0
0

I have a ToolStripTextBox, using it for a filter for a SQL Query.

If I have the list:

Apple, Orange, Pineapple

The suggest and append features will pick out "Apple" when I filter for "App".

I want to alter the Suggest part to include "Pineapple" also (match on string.Contains, not just string.Startswith)

Is there a way to intercept something like OnSuggestFiltering(), or whatever routine handles the filter?


I'd rather live with false hope than with false despair.

Viewing all 8156 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>