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

Math.Round Problem

$
0
0
Hi all,

can anyone help me to round a number to its nearest 10. i have a text box in my application to display the answer of an arithmetical operation. so the requirement is that if the answer is 64 it should display as 70. if the answer is 61 the rounding should round it to its nearest highest 10. so if its 61 the answer should be 70.


 i found this Math.round(value,1)*10 as a option but i dont think its is working.

any help?

--sri--

Asynchronous HttpWebRequest abort causes application to crash

$
0
0

Hi We have noticed on our production server an extremely rare race condition with HttpWebRequest that is causing our application to crash from time to time.

The race condition is caused when HttpWebRequest is used in async mode and the Abort method.

In some critical points calling the abort method can cause a background thread (not under our control) to get an unhandled exception with the following stack trace: 

Unhandled Exception: System.ObjectDisposedException: Safe handle has been closed

   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success
)
   at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolea
n& success)
   at System.Net.UnsafeNclNativeMethods.OSSOCK.setsockopt(SafeCloseSocket socket
Handle, SocketOptionLevel optionLevel, SocketOptionName optionName, Int32& optio
nValue, Int32 optionLength)
   at System.Net.Sockets.Socket.SetSocketOption(SocketOptionLevel optionLevel, S
ocketOptionName optionName, Int32 optionValue, Boolean silent)
   at System.Net.Sockets.NetworkStream.SetSocketTimeoutOption(SocketShutdown mod
e, Int32 timeout, Boolean silent)
   at System.Net.ConnectStream.DrainSocket()
   at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean abort
ing)
   at System.Net.ConnectStream.System.Net.ICloseEx.CloseEx(CloseExState closeSta
te)
   at System.Net.HttpWebRequest.SetAndOrProcessResponse(Object responseOrExcepti
on)
   at System.Net.ConnectionReturnResult.SetResponses(ConnectionReturnResult retu
rnResult)
   at System.Net.Connection.ReadComplete(Int32 bytesRead, WebExceptionStatus err
orStatus)
   at System.Net.Connection.ReadCallback(IAsyncResult asyncResult)
   at System.Net.Connection.ReadCallbackWrapper(IAsyncResult asyncResult)
   at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
   at System.Net.ContextAwareResult.Complete(IntPtr userToken)
   at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr u
serToken)
   at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32
 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32
errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

as you can the thread is a system thread dealing with the async IO. After some tests we managed to reproduce the rare crash easily with the following code: (The code launches many http requests and cancels them after a random period of time)

 while ( true )
            {
                var req = HttpWebRequest.Create("http://www.amazon.com?s=" + i ) as HttpWebRequest;
                var ares = 
                    req.BeginGetResponse((res) =>
                        {
                            try
                            {
                                var resp = req.EndGetResponse(res);
                                new StreamReader(resp.GetResponseStream()).ReadToEnd();
                                resp.Dispose();
                            }
                            catch
                            {

                            }
                            
                        },null);

                Timer timer = null;
                timer = 
                    new Timer((o) =>
                    {
                        try
                        {
                            req.Abort();
                        }
                        catch
                        {

                        }
                        timer.Dispose();
                    }, null, rnd.Next(0, 1200), System.Threading.Timeout.Infinite);

                tm.Add(timer);                    
            }

  Any ideas?





































































































































































































































Integrating OCR software and MS Forefront

$
0
0
Hello,

Does anyone have experience integrating OCR software like http://www.card-reader.com/ with Microsoft Forefront?
We are looking to integrate them to get real-time info about visitors in the organization and wanted to know if anyone has experience running a project like that.

Thanks!

shared data in dll

$
0
0

I'm using vb.net with vs2010 and i have a requirement to share data between two different applications, a windows form application and a service. i thought i could use a dll as an intermediate for holding the data, but can't get the two applications to see the same data, they have there own copies! any ideas on how i can do this? thanks in advance.

how to tag clipboard text

$
0
0

Hi,

Is it possible if windows tag the clipboard to check if it's related my application or to other application?

Thanks,

Jassim

Can i define the TSource type in the method of Single()

$
0
0

Hi,

I have an issue of the Single<TSource>()

Why I can't set the TSource of the a concrete type while the collection is the astract type. The following is the example of my question.

public abstract class TestBase

{

}

public class Test : TestBase

{

    public string Code {get; set;}

}

public static void Main(string[] args)

{

    List<TestBase> tests = new List<TestBase>();

    tests.Add(new Test() { Code = "A"});

    Test theTest = tests.Single<Test>();

}

Thanks


Jobria

Could not find any resources appropriate for the specified culture or the neutral culture.

$
0
0

Hi,

 

I am working in VS2010 and getting this error when my project tries to access resx file. Resx file is local to this project. It works fine if I exclude and include again in my project. but it does not work when I load fresh solution and hit f5

{"Could not find any resources appropriate for the specified culture or the neutral culture. 
Make sure \"ABC.resources\" was correctly embedded or linked into assembly \"ABC\"
at compile time, or that all the satellite assemblies required are loadable and fully signed."}
 System.Exception {System.Resources.MissingManifestResourceException}

 

Can anyone explain how to fix this?

 

Thanks

Will C# classes will clean virus after I cropped / shrink an upload image with virus?

$
0
0

Hi everyone,

I do have a question about the uploaded file with virus.

I know the common way to deal with this issue is to do a virus scan while uploading.

But my question is will the C# code will clean the virus after I cropped or shrink an uploaded image with virus?

Or will it thrown an exception?

The working scenario is:

1, user upload an file using my web service. (I am passing the byte array to the server.)

2,  create  an image code info.

ImageCodecInfo jpgInfo = ImageCodecInfo.GetImageEncoders().Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();

3, use Bitmap and Graphics classes to adjust the image to an fix width.

4, use Image.Save method to save the new image on the server.

I am not so familiar with how virus work, so,

Will this process clean the virus for me? Or is there any Exception will thrown if the uploaded image has virus with it?

Thank you so much for your help.


AutomationElement FromPoint on metro

$
0
0

The method AutomationElement.FromPoint (cursor position as point) dose not recognize AutomationElements on the metro screen.

The function returns the elements under the metro (as if the metro isnt up). Yet I can see the Elements using the FromHandle method , and the TreeWalker class (I input the handle manually).

Any help would be much appreciated :)

Concurrentbag vs Blockingcollection

$
0
0

I have a telephony application, in which there are many calls. Each call can be done with a process(method). Now I want to make 100 call simultaneously. I also want to return the call result(success or fail). Of course thread safe is required. Which one should I use?

Concurrentbag vs Blockingcollection or something else?

And I can limit the upbound "100" in the collection?

How can I extract a file from a System.IO.Packaging.Package hosted on a URL, without downloading the package?

$
0
0

I need to get the stream associated with the file (if present) from a OPC based package hosted on a URL, without downloading the package, as the package could be >1GB as well. I just need an XML file from the package.

I came across System.IO.Packaging.Package class which can work with packages (OPC based) but I am unable to find a way to extract a file without downloading the package.

Is there any way I can get it working with non-seekable streams without downloading or copying stream to MemoryStream etc. Just to re-iterate I just need a small XML file from a huge (>1GB package).

Thank you.


how to convert eml files to pst format

$
0
0
any idea about converting multiple eml's into single pst

Is the default Process.MaxWorkingSet bogus?

$
0
0

I have one of the worlds simpilest applications:

publicstaticvoid Main()
{using (Process p = Process.GetCurrentProcess())
  {
    Console.WriteLine("MaxWorkingSet: {0}", p.MaxWorkingSet);
    Console.WriteLine("MinWorkingSet: {0}", p.MinWorkingSet);
    Console.WriteLine("NonpagedSystemMemorySize64: {0}", p.NonpagedSystemMemorySize64);
    Console.WriteLine("PagedMemorySize64: {0}", p.PagedMemorySize64);
    Console.WriteLine("PagedSystemMemorySize64: {0}", p.PagedSystemMemorySize64);
    Console.WriteLine("PrivateMemorySize64: {0}", p.PrivateMemorySize64);
    Console.WriteLine("VirtualMemorySize64: {0}", p.VirtualMemorySize64);
    Console.WriteLine("WorkingSet64: {0}", p.WorkingSet64);
    Console.WriteLine(p.ProcessName);
    Console.ReadLine();
  }
}

When I run it I get the output of:

MaxWorkingSet: 1413120
MinWorkingSet: 204800
NonpagedSystemMemorySize64: 31748
PagedMemorySize64: 37216256
PagedSystemMemorySize64: 313816
PrivateMemorySize64: 37216256
VirtualMemorySize64: 592412672
WorkingSet64: 24170496

This output tells me that the WorkingSet is nearly twice as much of MaxWorkingSet. One of these values has to be wrong, and I suspect it's MaxWorkingSet. Is my suspicion correct?

VOTE: Long filepaths > 260 characters are not supported by the .NET Framework

$
0
0

Hey All,

Some of you may know the background behind this, while others may not.  The bottom line is that with the release of Windows XP, Windows and the Win32 API have supported filepaths up to 32,767 characters in lenght as long as each folder name and file name is not more than 255 characters.  However, the .NET Framework does not and it can no longer be considered a Feature Limitation after 12 years, it is a BUG.

I have opened the ticket below on Microsoft Connect, their public facing issue tracking system.  If you agree, please go to the URL below, log in, and vote by clicking on the up arrow.

CLICK THIS LINK AND VOTE!https://connect.microsoft.com/VisualStudio/feedback/details/932051/long-filepaths-260-characters-are-not-supported

Take it easy,
Will






Unable to determine the identity of domain." exception when saving larger XLSX file

$
0
0

 Hi all,

I am having an issue saving a large XLSX file. SmallerXLSX files seem fine, but this larger one I'm trying to generate keeps failing with the above error.

For research around, many solution mention using Application domain. I tried but it not working. This is my sample code

           AppDomainSetup setup = new AppDomainSetup();
            setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory.ToString();
            setup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            setup.LoaderOptimization = LoaderOptimization.MultiDomainHost;
            setup.PrivateBinPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;


            Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
            evidence.AddAssembly(Assembly.GetExecutingAssembly().FullName);
            evidence.AddHost(new Zone(SecurityZone.MyComputer));

            AppDomain ad = AppDomain.CreateDomain("HoGoExcelAddIn", evidence, setup);           
            StreamWriterXMLUtil StreamWriterXML = (StreamWriterXMLUtil)ad.CreateInstanceAndUnwrap(typeof(StreamWriterXMLUtil).Assembly.FullName, typeof(StreamWriterXMLUtil).FullName);
            
            try
            {
                Stream StreamXMLpart = customXMLPart.GetStream(FileMode.OpenOrCreate, FileAccess.ReadWrite);
                StreamWriterXML.WriteCustomXMLContent(StreamXMLpart, customXMLContent);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                AppDomain.Unload(ad);
            }

StreamWriterXMLUtil  class

 [Serializable]
    public class StreamWriterXMLUtil : MarshalByRefObject
    {

        public void WriteCustomXMLContent(Stream customXMLPart, string customXMLContent)
        {
           
            using (StreamWriter xmlStreamWriter = new StreamWriter(customXMLPart))
            {
                xmlStreamWriter.Write(customXMLContent); //=> "exception here, unable to determine the identity of domain." 

                xmlStreamWriter.Flush();
                xmlStreamWriter.Close();
            }
        }
    }

Anyone can help could be appreciated.

Thank you,

Johnny




Passing a System.Array to a VB6 ActiveX EXE from C#

$
0
0

I have a C# app written in VS2005 using Net Framework 2.0. I call a function in a VB6 ActiveX EXE and pass a System.Array by ref. I recently upgraded the app to VS2010 but still using Net Framework 2.0. No problems. Then I decided to change the Target Platform to Net Framework 4.0 and now the call to that function generates an unhandled exception of type INVALID ARGUMENT. I tried Net Framework 3.5 and it works fine. Is this a known issue with Net Framework 4.0?

The array I am passing is of a custom type defined in the VB6 ActiveX EXE named RDOPack. I define the array with 8 elements then run this code:

           Array RDOPackSA = Array.CreateInstance(typeof(RDOPack), 8);

           // then copy the data from the local data structure into the system array

           Array.Copy(RDOPack, RDOPackSA, 8);

           // then pass the ActiveX EXE the pointer to the System.Array which now contains

          //  the data from the local data structure array

           Object.ReadData(ref RDOPackSA);  // this line generates the exception

This all works in Net Framework 2.0 and 3.5 but not in 4.0. I have not tried VS2012 or VS2013 yet but I think I may have to.

One of my colleagues who is using my ActiveX EXE discovered this problem.

Thanks in advance for any help.

chiselca

ApplicationSettingsBase and the initialization of the SettingsProvider

$
0
0

Hej!

The documentation of the "Application Settings Architecture" (http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx) states the following:

"...For example, suppose that you want to develop and use SqlSettingsProvider , a provider that will store all settings data in a Microsoft SQL Server database. YourSettingsProvider-derived class would receive this information in its Initialize method as a parameter of type System.Collections.Specialized. NameValueCollection."

I have so far found not possibility to influence this "NameValueCollection". The ApplicationSettingsBase seem to call the Initialize method of the SettingsProvider always with the arguments "null, null" (C#). Is there any way to change this behaviour? I would love to be able to transfer configuration information to the (custom) SettingsProvider. (The only chance I currently see is to reimplement the ApplicationSettingsBase class, but I would prefer not to do that.)

Thanks a lot!

Stephan

 

Generate PDF from HTML page programmatically using .NET assembly

$
0
0

Hi,

I am trying to generate a PDF file from HTML page. I have searched the web and found 3rd party components which does this but I can't seem to find if this could be done with only .net assemblies. I would be glad if you could direct me to right path.

Thanks in advance.

Wait for an async-continuation before proceeding

$
0
0

I'm using async/await to provide a continuation for a task that needs to be run in the UI context. However, the continuation may be pre-empted by another block of code that needs to wait for it to finish. Using Task.Wait() will return as soon as the Task finishes but will not guarantee that the async continuation has also completed. Is there any (elegant) way to force the continuations to be run before continuing excecution? (Using semaphores etc. will obviously deadlock because the pre-empting code will just block never allowing the continuation to happen, because they both run on the same thread).

Thanks.

sending mailmessage using smtp.office365.com and framework 1.1

$
0
0

How I can send mailmessage using smtp.office365.com and framework 1.1 ?

I need to use port 587 and TLS I think .

It is possible?

Viewing all 8156 articles
Browse latest View live


Latest Images

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