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

Sslstream Mutual Authentication : Client Certificate is NULL at Server

$
0
0
I am trying to establish a mutual authentication between a TCP Server and Client using SSLStream asynchronus APIs. I am using two self signed certificates in PFX format that is installed in Trusted Root Authority in both LocalComputer and Current User Account at both Server and Client Machine.

When I am running Server at my machine(Windows 7 OS 64 Bit) and Client at (Windows 7 OS 32 Bit)  there is no error and both client server are authenticating each other. But when I reversed the Client and Server PC , At Server machine I am getting an exception saying that "Remote Certificate is invalid according to validation Procedure". Please suggest if I am missing anything.

    **Server Code:**
     _
    
        securestream = new SslStream(tcpClient.GetStream(), false,new RemoteCertificateValidationCallback(ValidateClientCertificate));
        
        string certPath = System.Reflection.Assembly.GetEntryAssembly().Location;
                                    certPath = Path.GetDirectoryName(certPath);
                                    certPath = Path.Combine(certPath, "MyServer.pfx");
        serverCertificate = new X509Certificate2(certPath,"password");
        
        _securestream.BeginAuthenticateAsServer(serverCertificate, true, SslProtocols.Ssl3, true, new AsyncCallback(AuthenticationCallback), _securestream);
        
        private bool ValidateClientCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                {
                    if (certificate != null)
                    {} else {//Always Comes Here in Problem Situation}
         private void AuthenticationCallback(IAsyncResult result)
         {
             try
             {
                  if (result.IsCompleted)
                  {
                     _securestream.EndAuthenticateAsServer(result);......}
        catch(Exception e){//Always gets exception here}
    
    **Client Code:**
    
    string certPath = System.Reflection.Assembly.GetEntryAssembly().Location;
                        certPath = Path.GetDirectoryName(certPath);
                        certPath = Path.Combine(certPath, ConfigurationManager.AppSettings["SSLClientCertName"]);
                        certCollection=new X509Certificate2Collection();
                        certCollection.Add(new X509Certificate2(certPath, ConfigurationManager.AppSettings["SSLClientCertPassword"], X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable));
    
    _securestream = new SslStream(_tcpSocket.GetStream(),true,new RemoteCertificateValidationCallback( ValidateServerCertificate));
    
     _securestream.BeginAuthenticateAsClient(_targetHost, certCollection, SslProtocols.Default, true, new AsyncCallback(AuthenticationCallback), _securestream);

...........

New to VS, looking for Data Grid alternative to build in data grid (using VB)

$
0
0

Hi, I'm building a web page and need to display data in  a table (data grid?) and would like to allow users to edit the data via text box and dropdowns. the built in data grid isn't what I'm looking for.

I found a jQuery tool from google, but it's for c# and I'm a VB programmer.

I like how the jQuery tool looks but would prefer a VS tool.

any one know were I can find such tools?  Like I said - I"m green in the area and just not even sure what to search for.

I've also looked at the forum, but again not even sure what I'm looking for is called.

Thanks for any help

Decoding the encoded string is not getting the special characters correctly

$
0
0

Hi,

I am using the below code to encode the content of *.ser file

foreach(string file inDirectory.EnumerateFiles("","*.SER")){byte[] content =File.ReadAllBytes( file ); xmlWriter.WriteStartElement("SerializedFile"); xmlWriter.WriteElementString("FileName",Path.GetFileName(file)); xmlWriter.WriteElementString("Content",System.Convert.ToBase64String( content )); xmlWriter.WriteEndElement();}

Now i have to decode the encoded content and create *.ser file, i tried with below code but the size of original *.ser file and generated *.ser file after i decode differs and if i check the content i can see some difference with the special characters.

encodedContent = xmlnode[i].ChildNodes.Item(1).InnerText;
                byte[] data = Convert.FromBase64String(encodedContent);
                string decodedContent = Encoding.UTF8.GetString(data);

Please help me out to solve this issue. Thanks in advance.

Regards,

Chetan.


Chetan Rajakumar

Desktop App: Directory.Exists returns false but new FileStream inside it works?

$
0
0

Hi,

I have a weird case with one of our deployments. The application is a Desktop .NET 4 Client Profile Winforms app that is usually started from a network share. During startup, our application does a couple of sanity checks, one of them being checks to see if the directories it requires exist and if the user running the application has write permissions in those folders etc.

The weird thing is that at one deployment only, the initial Directory.Exists check returns false, but subsequent attempts to write files inside that directory work and our application runs just fine.

To make things more interesting: Our users start a small launcher application (from the network share) that in turn starts the most up-to-date version of our program from a subdirectory. The mentioned problem with Directory.Exists returning false happens only if the program is started via the launcher. If the user starts the exe file from the subdirectory directly, then Directory.Exists on those same directories returns true.

The Launcher starts the the versioned executable via a simple Process.Start(exePath, arguments);

The erratic behaviour of Directory.Exists is really puzzling me. Any hints on what might be going on would be much appreciated!

Thanks,

Daniel

.net dbml generator bug

$
0
0

If your database contains a table with a column that is called 'string' , the .NET dbml generator fails. It fails due to each partial class that is generated contains the static field 'emptyChangingEventArgs' of type 'PropertyChangingEventArgs' , this is set in the following manner:

private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);

As you can see from the above, String.Empty is passed into the constructor, this is an issue (for some reason) due to the fact that this tries to access the private field 'String' and discovers it is not static and errors with the following:

Error30 A field initializer cannot reference the non-static field, method, or property 'ConsoleApplication1.Methods.String.get'.

Fix1: Replace String.Empty in the constructor argument with System.String.Empty.

More preferably due to languages like F# using the dbml generation automatically: Fix2 Modify column name to not be 'string'.

Here is the section of the DBML in XML format:

<Table Name="dbo.methods" Member="Methods">
    <Type Name="Methods">
      <Column Name="Id" Type="System.Int32" DbType="Int NOT NULL" IsPrimaryKey="true" CanBeNull="false" />
      <Column Name="name" Member="Name" Type="System.String" DbType="NVarChar(MAX) NOT NULL" CanBeNull="false" UpdateCheck="Never" />
      <Column Name="call" Member="Call" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
      <Column Name="field" Member="Field" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
      <Column Name="string" Member="String" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
      <Column Name="hash" Member="Hash" Type="System.Int32" DbType="Int NOT NULL" CanBeNull="false" />
    </Type>
  </Table>

Split and Convert Sets of Union to Binary

$
0
0

How to fix this Code. I cant get the right code to deliver the string to split and connect to convert union set into binary

The A u B is the process combining the Set A and Set B which the result handle by txtunion.Text.
question 1: how and who i will submit to Split method?

Next is the Split method. Where to split the Union Set ("1,2,3,4,5") String value into array {"1","2","3","4","5"}

question 2: how and who i will submit to convert method?

'A U B'If cbnum.Text="A"And cbope.Text="∪"And cbdem.Text="B"Then
            txtunion.Visible=True
            lblU1.Text="A"
            lblU2.Text="∪"
            lblU3.Text="B  ="
            lblUnion.Visible=True'Union.'Dim owns_either AsNewHashSet(OfString)(A)
            owns_either.UnionWith(B)
            txtunion.Text=String.Join(", ", owns_either.ToArray())EndIf'---------------------------------------------------------------------------------
        'SplitDimunionAsString= txtunion.TextDim split AsString()=union.Split(New[Char](){","c," "c})ForEach s AsStringIn splitIf s.Trim()<>""ThenConsole.WriteLine(s)EndIfNext s'---------------------------------------------------------------------------------''convert union set to binary'Dim dec AsNewHashSet(OfString)From{2,4,5,6,9}Dim bin AsLong=0ForEach i In dec
            bin = bin Or(1L<<(i -1))Next'Result'
        txtbinary.Text=String.Concat(Convert.ToString(bin,2).Reverse())

Handling "Server does not support secure connections" using an SmtpException.StatusCode?

$
0
0

I would like to attempt to send mail via SSL first, and then only if that fails, revert back to EnableSsl = false and try again.  I would prefer to check the exception for a StatusCode that indicates this, however the StatusCode that is returned is StatusCode.GeneralFailure.  The only way I can determine that it failed because of lack of secure connection support is to check the Exception.Message, which is not ideal.

The resulting code is below.  Any ideas for improvement?

try
        {
            client.Send(oMail);
        }
        catch (System.Net.Mail.SmtpException e)
        {
            //If the server does not support TLS, try again without it.
            //Exception will have a SmtpException.StatusCode.GeneralFailure, so only way to check is to check the message
            if (((System.Net.Mail.SmtpException)e).Message.Contains("secure connections"))
            {
                try
                {
                    client.EnableSsl = false;
                    client.Send(oMail);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                throw e;
            }

        }
        catch (Exception e)
        {
            throw e;
        }

how to divide string array

$
0
0

Hello, I have a problem to operate two numbers two much big, I have two numbers in two string arrays but I have to think the worse case, if the numbers are two much big I have to Split them before calculate the sum. How can I do it? with String.Substring or String.Split()?

Thank you.


MembershipUser.ChangePassword method returns false at all time

$
0
0

i having trouble with mvc4 membership issue , i cant change the user's password like

publicboolSetNewPassword(string newPassword){var generatedPassword = membershipUser.ResetPassword();return membershipUser.ChangePassword(generatedPassword, newPassword);}

it is always returning false , i checked that the user is not lockedout , and is approved, how can i handle this? please help , i am driving myself crazy upon this point.


type exists in BOTH assemblies (BUT FOR GOOD REASONS)

$
0
0

Hi Folks

I've been kind of forced between a "rock and a hard place" in terms of what we refer to as our "Global Directory" (SSO - single sign-on services) and how SQL Server 2012 SSRS works as well.

1. What I need to do with SSRS 2012 is a "hardwired" at .Net v3.5 (its a Microsoft.ReportServices.Interfaces.dll kind of thing).

2. What we've hardwired into our own development for SSO is .Net v4.5.1 (and no, unfortunately our software environment is NOT VERSIONED/wasn't history'd and checkpointed for use at various versions (for adaptability in area like this), etc..

3. I've managed to construct a CONSOLE application which does the up-n-down "thunking" between the .Net versions with a main program and 2 dlls. So we basically go back and forth WITHOUT ISSUE (SSRS v3.5-up/down thunk-v4.5.1 SSO). If you REALLY want the previous gory details, you can look here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/d27d3c40-66cd-45a8-b036-b3d1211ace2f/typegettypefromprogid-not-returning-systemmarshalbyrefobject?forum=netfxbcl&prof=required (there's diagrams, discussions, etc.)

The way this up-and-down thunking was done, was via  Interfaces (and was the only way I know of to do anything like this). The "trickery" was binding Interfaces from different DLLs with the same name.

This works great in a simple CONSOLE application, but in the context of SSRS and COM registered assemblies it can come around and bite you quickly ;)

Back to my problem... When I execute this code:

            try
            {
                Type myClassAdapterType = Type.GetTypeFromProgID("Net35ToNet4xAdapter.MyClassAdapter");
                Object myClassAdapterInstance = Activator.CreateInstance(myClassAdapterType);
                Net35ToNet4xAdapter.IMyClassAdapter myClassAdapter = (Net35ToNet4xAdapter.IMyClassAdapter)myClassAdapterInstance;

on the last line, I get the error:

The type 'Net35ToNet4xAdapter.IMyClassAdapter' exists in both 'DMx.CustomDataProcessingExtension.dll' and 'Net35ToNet4xAdapter.dll'...

Which is correct, IMyClassAdapter DOES exist in both.  This is the only way to go back and forth in .NET.

Is there a simple way to cast/cast as the myClassAdapterInstance as a particular dll with that mentioned interface?

Thanks

Rob





Rob K

CLR20r3 error

$
0
0

I had developed a Winform app with using Telerik RadGridview before.
All clients use it without any problem.
But a few days ago, a client called me and told that it crashes anytime when he/she clicked any row in gridview.

We haven't thought that it could be related to telerik dll because any other clients use it successfully...
So we made a thorough search on net and tried any cause/solution possibilities but it didn't work out.

The most interesting side of the issue is that it happens only whenever i click, double-click or select any row in radGridview...
it just crashes and try to close the app directly...

The error is very odd! couldn't think any solution to overcome...
I believe that it is related to windows 7 operating system configuration or .net framework class libraries...

What can i do to work the app out? Urgent help, please???

----------------------------------------------------------------------------------------------------------------------------------------------------

The event log of the machine shows me the below error log:

Windows Error Reporting
Problem signature:
  Problem Event Name: CLR20r3
  Problem Signature 01: Menu.exe
  Problem Signature 02: 2013.2.814.2
  Problem Signature 03: 520bcf56
  Problem Signature 04: mscorlib
  Problem Signature 05: 4.0.30319.19075
  Problem Signature 06: 515a73c2
  Problem Signature 07: 2b00
  Problem Signature 08: 0
  Problem Signature 09: 5O2O3I2ORVH4ZJ0NRQ1HQUEQ4B3YAU4U

Serial Port Communication

$
0
0

Hi,

I am having a Win-7 PC. In that i install VM Ware Player (Linux OS). I need to write the data in serial port and how to get those data in VM-Ware. need help. pls. urgent....

Single C# API to access dropbox, iCloud, SkyDrive, etc.?

$
0
0

Hi all;

Is there a library that provides access to all the different cloud storage systems out there? What we need is pretty simple:

  1. A way to get folder contents for a FileOpen dialog box.
  2. A way to read the selected file.
  3. Optional: a FileOpen dialog that does all the work to show the files and select one.

thanks - dave


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

.NET 4 with EventLog dumps entire log

$
0
0

My app has the following code to capture security event logs

Dim SecobjLog As EventLog = New EventLog("Security")
AddHandler SecobjLog.EntryWritten, AddressOf SecurityLog_OnEntryWritten
SecobjLog.EnableRaisingEvents = True

Sub SecurityLog_OnEntryWritten(ByVal [source] As Object, ByVal e As EntryWrittenEventArgs)
'--- Process Logs
End Sub

This code has been working for years.   When a new security event is generated on the server, the .EntryWritten function fires and my program processes it.  However, I recently upgraded my app to use .NET 4.0 and something went wrong.  Now, at seemingly random intervals, the ENTIRE security log is captured.  At over 100,000 logs, you can see where my program would have some issues.   Why is the .EntryWritten function in VB dumping the entire security log?   It should only be dumping the latest logs as they happen.

I have tried this with .NET 4.0 and .NET 4.5 and both seem to have this issue.  If I go back to using .NET 3.5, everything works fine again.  What changed?

Does anyone have any idea why this is happening?





"MC"

decimal in a datatable - == and equals disagreeing

$
0
0

In a simple data table, with a decimal column I am getting different results when using Equals and ==.  I'm sure there is a good reason for this, I just cannot find it - can anyone please explain to me why these would be different?  

using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("amount", typeof(int)));
            dt.Columns.Add(new DataColumn("code", typeof(string)));

            DataRow dr = dt.NewRow();
            dr["amount"] = 10;
            dr["code"] = "A";

            dt.Rows.Add(dr);
            dr.AcceptChanges();

            bool a = dr["amount", DataRowVersion.Current].Equals(dr["amount", DataRowVersion.Original]);
            bool b = dr["amount", DataRowVersion.Current] == dr["amount", DataRowVersion.Original];

            bool c = dr["code", DataRowVersion.Current].Equals(dr["code", DataRowVersion.Original]);
            bool d = dr["code", DataRowVersion.Current] == dr["code", DataRowVersion.Original];
        }
    }
}

While I fully expect c and d to be equal, notice that a and b are not considered equal when using the == operator.  ??


Need suggestion for developing print version of the .NET web site.

$
0
0

Friends,

I am having a requirement where i need to develop a print version separately to the web pages. web site is basically a presentation site. client is expecting print versions to be high on quality. So need suggestions how we can do that with ASP.NET

Cheers                                                                                                                                                         Balaji S


Thread in a threadpool not being executed on time

$
0
0

My Windows Service is written in VB.NET Visual Studio 2010 (.NET framework 4).
The service is using a threadpool like below:
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf clsA.ProcessIt))

In my case, sometimes the thread is not being executed, even though there are plenty of available threads, also plenty of CPU and memory.
For example below, there are 32736 available threads in the pool, but yet sub ProcessIt is not being executed until 1 minute later.

Let's say sub ProcessIt is executed per message.
It looks like in between the time I call "ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf clsA.ProcessIt))", and sub ProcessIt being executed, the service is doing sub ProcessIt for other messages.

In the example below, let's say sub ProcessIt is called for message 1 until 10.
Then, for message 11, even though "ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf clsA.ProcessIt))" is already called, and there are 32736 available threads in the pool, sub ProcessIt for message 11 is not executed until 1 minute later, and in the mean time the service is doing sub ProcessIt for message 1 until 10.

What can cause this, and how can I fix it ?

                ThreadPool.GetMaxThreads(x, y)
                 WriteToFile("GetMaxThreads x = " & x & " y = " & y) '--> x = 32767 y = 1000
                 ThreadPool.GetAvailableThreads(x, y)
                 WriteToFile("GetAvailableThreads x = " & x & " y = " & y) '--> x = 32736 y = 1000
                 ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf clsA.ProcessIt))

Thank you.

Generic singleton instance generator

$
0
0

Hi,

I am looking for a class which can return singleton instance of the type that client specifies. I want to use "Lazy" keyword feature so that I don't need to make the method thread-safe.

Current working solution I have is below but I need to take care of thread safe here :(

public class InstanceGenerator
    {
        static Dictionary<string, object> typeDict = new Dictionary<string, object>();
        static readonly object lockObj = new object();
        public static object GetInstance(string type)
        {
            lock (lockObj)
            {
                if (!typeDict.ContainsKey(type))
                    typeDict.Add(type, Activator.CreateInstance(Type.GetType(type)));
            }
            return typeDict[type];
        }
    }


// Client

var obj = InstanceGenerator.GetInstance("GenericSingleton.Sample");

While I am looking for something like below but I want to pass type value as string from client-

public abstract class SingletonBase<T> where T : class
    {
        private static readonly Lazy<T> sInstance = new Lazy<T>(
            () => CreateInstanceOfT());
        public static T Instance(string typeName)
        {
            return sInstance.Value;
        }
        private static T CreateInstanceOfT()
        {
            return Activator.CreateInstance(typeof(T), true) as T;
        }
    }

DataSet does not support System.Nullable

$
0
0

Hello every one, I have a following piece of code
 
dt = new DataTable();
var result = from row in ObjContext.Users
select row;
dt = result.CopyToDataTable();
 
when I execute this I am getting this error "DataSet does not support System.Nullable<>."
 
In my table there are some blank Columns, and I must want to get its result in DataTable.
 

I also used following code from googling:
 
var result = from r in ObjContext.Users
select new
{
ID=r.ID,
Username= r.Username==null?"":r.Username,
Password= r.Password==null?"":r.Password,
SecLevel = r.SecLevel == null ? 3 : r.SecLevel,

Firstname = r.Firstname == null ? "" : r.Firstname,
Lastname = r.Lastname == null ? "" : r.Lastname,
BCC = r.BCC == null ? "" : r.BCC,
SenderEmail = r.SenderEmail == null ? "" : r.SenderEmail,

};
dt = result.CopyToDataTable();
 
but same porblem has comes.

Any help is much appreciated!!


Regarding Crystal report issue

$
0
0

Hi

The assembly with display name 'BusinessObjects.Licensing.KeycodeDecoder' failed to load in the 'Load' binding context of the AppDomain with ID 1. The cause of the failure was: System.IO.FileNotFoundException: Could not load file or assembly 'BusinessObjects.Licensing.KeycodeDecoder, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified

Getting this error 

Viewing all 8156 articles
Browse latest View live


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