Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all 1710 articles
Browse latest View live

AccessViolationException with HandleProcessCorruptedStateExceptions not handled at runtime

$
0
0

I am calling a third-party unmanaged DLL from vb.net (framework 4.5) and on rare occasions the third party DLL thows an AccessViolationExcpetion ("Attempted to read or write protected memory. This is often an indication that other memory is corrupt."). 

I have added the <HandleProcessCorruptedStateExceptions> attribute to the method which calls the DLL as follows: -

    <Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions> _
    <SecurityCritical> _
    Private Sub CallThirdParty()
            Try
                UnmanagedFunction(_outputFilename) ' this is the referenced with a DLLImport
            Catch ex As Exception
                ' example code to demonstrate handler
                Environment.Exit(0)
            End Try
    End Sub

When running in debug mode in VS2013 the exception is handled and the application quits as expected. However when I build and run the app outside of VS2013 it just hangs at this point and no exception is handled. The program doesn't even crash.

Is there anything I have missed here which makes debug vs build different?

Thanks for reading this...


PropertyChangedEventManager causes memory leak

$
0
0

I've an application where I'm not able to remove event handlers because I don't know when the last reference will be freed.

My application contains a PropertyChanged event source that is put into a container class that also implements INotifyPropertyChanged. This hierarchy contains more than 6 levels. Each instance of a level could be placed into multiple other instances. That's the reason why I couldn't determine when to free those instances.

The instances on the lowest level will live for the whole application runtime. This causes that all other instances will not be freed and I got a memory leak.

To avoid this event driven memory leak I tried to use WeakEventManager(TEventSource, TEventArgs). This class is only available in .Net 4.5 and because of compatibility to existing hardware I’ve to use .Net 4.0.

In .Net 4.0 is a PropertyChangedEventManager available that should do the same for INotifyPropertyChanged.

My classes are freed correctly.

But there is still a memory leak.

I simplified my application to the following code that produces a memory leak:

// This code will force the memory leak
while (true)
{
    var eventSource = new StateChangedEventSource();
    var eventReceiver = new StateChangedEventReceiver();

    PropertyChangedEventManager.AddListener(eventSource, eventReceiver, string.Empty);
}

public class EventSource : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
}

public class  EventReceiver : IWeakEventListener
{
    public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
    {
        return true;
    }
}

Yes I know there is no RemoveListener call. I couldn’t determine when an instance is never used and could be freed. If I knew that I could use normal event registration and deregistration. In that case I don’t have to use the PropertyChangedEventManager.

What is the problem of my sample code? Why does it produce a memory leak?

I used JetBrains Memory Profiler to detect my memory leak. I could reduce the memory consumption a lot by using the PropertyChangedEventManager but there's still a memory leak left that could be simply reproduced using the sample code of this question.


Windows 8 Bluetooth Low Energuy no API for BLE device to discovery and pairing????

CoCreateInstance error -2147221164 on Windows Server 2008

$
0
0

Greetings.

We have some old code in our system and I'm trying to get it to work on a newer platform.  We have a C++ 6.0 dll that we call from an old MicroFocus COBOL application.  The C++ dll serves as a wrapper to call a .NET web service since we can't call it directly from COBOL.  It has been running without any problems on Windows XP, but on Windows Server 2008, I get an error code -2147221164 on the call to CoCreateInstance.  I understand this error indicates that the dll is not registered.  I never had to register it on the XP machines.

This is the actual code being executed that is throwing the error:

 CComPtr<IServerXMLHTTPRequest>spServerXMLHTTP1;
 HRESULT hr = spServerXMLHTTP1.CoCreateInstance(CLSID_ServerXMLHTTP40);
 if (hr < 0)
 {
  ierror = sprintf(errmsg,"Critical Error CoCreateInstance %+8d",hr);
  throw (errmsg);
 }

Here is the code for the entire function:

//------------------------------------------------------------------------------
//  Function uses ServerXMLHTTP to send a GET/POST/SOAP request to a .NET Web Services,
//  and then uses MSXML DOM to process the response XML text.
// 
//  Illustrates calling a .NET Web Service either by sending a GET request,
//  or a HTTP POST or by using the SOAP method.
//
//  iMethod parameter:
//    0 : (Default) HTTP GET
//    1 : HTTP POST
//    2 : SOAP
//------------------------------------------------------------------------------
//_bstr_t CallWebService(LPCTSTR szSOAPRequest, LPCTSTR szSOAPAction, LPCTSTR szSOAPEndPoint)
//_bstr_t CallWebService(TCHAR * szSOAPRequest, TCHAR * szSOAPAction, TCHAR * szSOAPEndPoint)
_bstr_t CallWebService(TCHAR * szSOAPRequest, TCHAR * szSOAPAction, TCHAR * szSOAPEndPoint, int iMethod)
{
  try
  {
	char errmsg [100] = {0};
	int ierror;
	_bstr_t bstrRequest;
	bstrRequest = ConvertStringToBSTR(szSOAPRequest);
//iMethod = 0 uses HTTP GET
//	int iMethod=0;
//iMethod = 2 uses SOAP.
//	int iMethod=2;
	LPCTSTR szZipCode="";
	USES_CONVERSION;
  //  Create an instance of ServerXMLHTTP Class
	CComPtr<IServerXMLHTTPRequest>spServerXMLHTTP1;
	HRESULT hr = spServerXMLHTTP1.CoCreateInstance(CLSID_ServerXMLHTTP40);
	if (hr < 0)
	{
		ierror = sprintf(errmsg,"Critical Error CoCreateInstance %+8d",hr);
		throw (errmsg);
	}
	TCHAR szGetURL[MAX_PATH*2]={0};
	TCHAR szPostValue[MAX_PATH*2]={0};
	TCHAR szSOAPReq[MAX_PATH*2]={0};
	int iPostDataLen =0;
	TCHAR szDataLen[10]={0};
	switch(iMethod)
	{
	case 0:  //  HTTP GET
		sprintf(szGetURL, szSOAPRequest);
    //  Initialize the Synchronous HTTP GET request
		hr = spServerXMLHTTP1->open(_bstr_t(_T("GET")), szGetURL, VARIANT_FALSE);
		if (hr < 0)
		{
			ierror = sprintf(errmsg,"Critical Error spServerXMLHTTP1->open %+8d",hr);
			throw (errmsg);
		}
    //  Send the HTTP GET request
		hr = spServerXMLHTTP1->send();
		if (hr < 0)
		{
			ierror = sprintf(errmsg,"Critical Error spServerXMLHTTP1->send %+8d",hr);
			throw (errmsg);
		}
		break;
	case 1:  //  HTTP POST
		_tcscpy(szPostValue, _T("connectionid="));
		_tcscat(szPostValue, szZipCode);
		iPostDataLen = _tcslen(szPostValue);
		itoa(iPostDataLen, szDataLen, 10);
    //  Initialize the Synchronous HTTP GET request
		hr = spServerXMLHTTP1->open(_bstr_t(_T("POST")), g_lpszPostURL, VARIANT_FALSE);
		if (hr < 0)
		{
			ierror = sprintf(errmsg,"Critical Error spServerXMLHTTP1->open %+8d",hr);
			throw (errmsg);
		}
		spServerXMLHTTP1->setRequestHeader(_T("Content-Type"), 
		_T("application/x-www-form-urlencoded"));
		spServerXMLHTTP1->setRequestHeader(_T("Content-Length"), szDataLen);
    //  Send the HTTP POST request, along with the SOAP request envelope text
		hr = spServerXMLHTTP1->send(szPostValue);
		if (hr < 0)
		{
			ierror = sprintf(errmsg,"Critical Error spServerXMLHTTP1->send %+8d",hr);
			throw (errmsg);
		}
		break;
	case 2:  //  SOAP
    //sprintf(szSOAPReq, g_lpszSOAPReq, szZipCode);
		hr = spServerXMLHTTP1->open(_bstr_t(_T("POST")), szSOAPEndPoint, VARIANT_FALSE);
		if (hr < 0)
		{
			ierror = sprintf(errmsg,"Critical Error spServerXMLHTTP1->open %+8d",hr);
			throw (errmsg);
		}
    //  Set the required SOAPAction and Content-Type headers
		hr = spServerXMLHTTP1->setRequestHeader(_T("SOAPAction"), szSOAPAction);
		if (hr < 0)
		{
			ierror = sprintf(errmsg,"Critical Error spServerXMLHTTP1->setRequestHeader 1 %+8d",hr);
			throw (errmsg);
		}
		hr = spServerXMLHTTP1->setRequestHeader(_bstr_t(_T("Content-Type")), 
		_bstr_t(_T("text/xml")));
		if (hr < 0)
		{
			ierror = sprintf(errmsg,"Critical Error spServerXMLHTTP1->setRequestHeader 2 %+8d",hr);
			throw (errmsg);
		}
    //  Send the POST request, along with the SOAP request envelope text
		MSXML2::_SERVERXMLHTTP_OPTION srvval = SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS;
//		MSXML2::_SXH_SERVER_CERT_OPTION valopt = SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS;
		_variant_t srvopt = spServerXMLHTTP1->getOption(srvval);
//		MSXML2::_SXH_SERVER_CERT_OPTION srvopt = SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS;
		spServerXMLHTTP1->setOption(srvval, srvopt);
		hr = spServerXMLHTTP1->send (bstrRequest);
		if (hr < 0)
		{
			ierror = sprintf(errmsg,"Critical Error spServerXMLHTTP1->send %+8d",hr);
			throw (errmsg);
		}
		break;
	}
	if(200 == spServerXMLHTTP1->status) //Success
	{
    //  using MSXML DOM to process the response XML text
		CComQIPtr <IXMLDOMDocument2> spResponseXMLDoc;
		_bstr_t svcresp(spServerXMLHTTP1->GetresponseText());
		spResponseXMLDoc = spServerXMLHTTP1->responseXML;
		return svcresp;
	}
	else
	{
		_bstr_t svcresp(W2A(spServerXMLHTTP1->statusText));
		return svcresp;
	}
  }
	catch (char * errmsg)
	{
		_bstr_t svcresp (errmsg);
		return svcresp;
	}
	catch (_bstr_t bstrerr)
	{
	  	int ierror;
		char errmsg [100] = {0};
		ierror = sprintf(errmsg,"Critical Error trying to execute IG Web Service???");
		_bstr_t svcresp (errmsg);
		return svcresp;
	}
	catch(_com_error e)
	{
	  	int templen;
		char errmsg [1000] = "Critical Error - COM ";
		_bstr_t bstrErrMsg;
		bstrErrMsg = ConvertStringToBSTR (e.ErrorMessage());
		templen = strlen((char *)bstrErrMsg) + 1;
		memmove(errmsg + 21,(char *) bstrErrMsg, templen);		
//		ierror = sprintf(errmsg,"Critical Error - COM Error trying to execute IG Web Service???");
		_bstr_t svcresp (errmsg);
		return svcresp;
	}
    catch (unsigned int e)
    {
	  	int ierror;
		char errmsg [100] = {0};
        if (e == EXCEPTION_INT_DIVIDE_BY_ZERO)
        {
			ierror = sprintf(errmsg,"Divide by zero Error trying to execute IG Web Service???");
			_bstr_t svcresp (errmsg);
			return svcresp;
        }
        if (e == EXCEPTION_ACCESS_VIOLATION)
        {
			ierror = sprintf(errmsg,"Access Violation C++ proxy Error");
			_bstr_t svcresp (errmsg);
			return svcresp;
        }
        if (e == EXCEPTION_PRIV_INSTRUCTION)
        {
			ierror = sprintf(errmsg,"Attempt to execute privileged instruction proxy Error");
			_bstr_t svcresp (errmsg);
			return svcresp;
        }
        if (e == EXCEPTION_STACK_OVERFLOW)
        {
			ierror = sprintf(errmsg,"Stack Overflow proxy Error");
			_bstr_t svcresp (errmsg);
			return svcresp;
        }
        if (e == EXCEPTION_INT_OVERFLOW)
        {
			ierror = sprintf(errmsg,"Integer Overflow proxy Error");
			_bstr_t svcresp (errmsg);
			return svcresp;
        }
		ierror = sprintf(errmsg,"Critical Error trying to execute IG Web Service???");
		_bstr_t svcresp (errmsg);
		return svcresp;
	}
	catch (std::exception& e)
	{
	  	int templen;
		char errmsg [1000] = "Critical Error - COM ";
		_bstr_t bstrErrMsg;
		bstrErrMsg = ConvertStringToBSTR (e.what());
		templen = strlen((char *)bstrErrMsg) + 1;
		memmove(errmsg + 21,(char *) bstrErrMsg, templen);		
		_bstr_t svcresp (errmsg);
		return svcresp;
	}
	catch(...)
	{
	//TODO: Error handling
	  	int ierror;
//		double dwTarget;
		char errmsg [100] = {0};
//		dwTarget = AFX_STACK_DUMP_TARGET_CLIPBOARD   
//        AfxDumpStack(dwTarget);
		ierror = sprintf(errmsg,"Critical Error trying to execute IG Web Service???");
		_bstr_t svcresp (errmsg);
		return svcresp;
	}
}

Any clues?

Fully transparent custom CCW

$
0
0
I'm trying to attach a custom CCW to a managed object using Marshal.CreateAggregatedObject. This works fine. The problem is that I can't cast back to the managed object after a reference has been passed to COM and then passed back to managed code. The object is only identified as ComObject. Some research led me to interface IManagedObject. I've added that to the CCW but I'm not able to implement it correctly. Specifically, the method GetObjectIdentity is the problem. I don't know how to correctly fill in the returned values for GUID and CCW. So my question is, how do I configure a custom CCW so that I can get back to the managed object when a COM reference is passed back into managed code? The documentation is incomplete.

WeakEventManager and PropertyChangedEventManager causes memory leak

$
0
0

I've an application where I'm not able to remove event handlers because I don't know when the last reference will be freed.

My application contains a PropertyChanged event source that is put into a container class that also implements INotifyPropertyChanged. This hierarchy contains more than 6 levels. Each instance of a level could be placed into multiple other instances. That's the reason why I couldn't determine when to free those instances.

The instances on the lowest level will live for the whole application runtime. This causes that all other instances will not be freed and I got a memory leak.

To avoid this event driven memory leak I tried to use WeakEventManager(TEventSource, TEventArgs). This class is only available in .Net 4.5 and because of compatibility to existing hardware I’ve to use .Net 4.0.

In .Net 4.0 is a PropertyChangedEventManager available that should do the same for INotifyPropertyChanged.

My classes are freed correctly.

But there is still a memory leak.

I simplified my application to the following code that produces a memory leak:

// This code will force the memory leak
while (true)
{
    var eventSource = new StateChangedEventSource();
    var eventReceiver = new StateChangedEventReceiver();

    PropertyChangedEventManager.AddListener(eventSource, eventReceiver, string.Empty);
}

public class EventSource : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
}

public class  EventReceiver : IWeakEventListener
{
    public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
    {
        return true;
    }
}

Yes I know there is no RemoveListener call. I couldn’t determine when an instance is never used and could be freed. If I knew that I could use normal event registration and deregistration. In that case I don’t have to use the PropertyChangedEventManager.

What is the problem of my sample code? Why does it produce a memory leak?

I used JetBrains Memory Profiler to detect my memory leak. I could reduce the memory consumption a lot by using the PropertyChangedEventManager but there's still a memory leak left that could be simply reproduced using the sample code of this question.



Problem generating manifest. Insufficient memory to continue the execution of the program.

$
0
0

Hi,

      I am using visual studio 2008 when i am start debugging some times it showing the error

Problem generating manifest. Insufficient memory to continue the execution of the program.

for this again i am restarting visual studio

so please give a solution to this error

waiting for reply...................

table doesn't have primary key (already tried other people's solutions, also my database table has a primary key!)

$
0
0
Dim con As New OleDb.OleDbConnection
    Dim da As New OleDb.OleDbDataAdapter
    Dim ds As New DataSet
    Dim sql As String
    Dim pass As Integer
    Dim cmd As New OleDb.OleDbCommand
    Dim dr As OleDb.OleDbDataReader
    Dim dRow As DataRow

con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Drug Emporium.accdb"
        con.Open()
        cmd.CommandText = "Select * From Inventory"
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        sql = "Select * From Inventory"
        dr = cmd.ExecuteReader()
        da = New OleDb.OleDbDataAdapter(sql, con)
        da.FillSchema(ds, SchemaType.Source, "Drug Emprorium")
        da.Fill(ds, "Drug Emporium")
        Dim cb As New OleDb.OleDbCommandBuilder(da)
        dRow = ds.Tables("Drug Emporium").Rows.Find(intItemNum)
        dRow.Delete()
        con.Close()


Export managed function to unmanaged

$
0
0

Hi,

I have a question about managed dll and i want to known if it is a good idea to modify the IL code in order to exports managed methods from dll.

I have read the chapter 18 of the book "expert .net 2.0 IL Assembler" and made an example on how to exports managed methods as unmanaged.

the example is to that :

change the flags to .corflags 0x00000002

and thid ect ....vtfixup [1] int32 fromunmanaged at VT_01

and inside the method:

.method public static void Yabba()
{
.vtentry 1:1
.export [1]

Clipboard.Clear() call causes explorer.exe to crash

$
0
0

We have an Excel VSTO AddIn which has a call to Clipboard.Clear().

After the above call is executed once, explorer.exe keeps crashing randomly until the machine is restarted.

This happens on Windows 7 64bit machines, we are using .NET 4.

Any suggestion or workarounds?

ServiceActivationException: Request cannot be dispatched because the virtual application is shutting down

$
0
0

We are having a problem with our virtual application shutting down. Site is running ASP.NET 4.5, IIS 7.5

Exception summary:

System.InvalidOperationException: Request to the service at '~/Services/ServiceExceptionLogger.svc' cannot be dispatched because the virtual application at '/Site' is shutting down.

Stack trace:

System.ServiceModel.ServiceActivationException: Request to the service at 
'~/Services/ServiceExceptionLogger.svc' cannot be dispatched because the virtual application
 at '/Site' is shutting down. ---> System.InvalidOperationException: Request to the service at '~/Services/ServiceExceptionLogger.svc' cannot be dispatched because the virtual 
application at '/Site' is shutting down.
 --- End of inner exception stack trace ---
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar)

Or here is another version of it that shows up in the event logs

Stack Trace:

System.ServiceModel.ServiceActivationException: Request to the service at '~/Services/Service.svc' cannot be dispatched because the virtual application at '/Site' is shutting down. ---> System.InvalidOperationException: Request to the service at '~/Services/Service.svc' cannot be dispatched because the virtual application at '/Site' is shutting down.
   --- End of inner exception stack trace ---
   at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
   at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
   at System.Web.HttpApplication.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar)

Anyone have any ideas or seen this before? Seems to happen quite frequently on one of our environments, like 10+ times a day. On the QA environment its not happening at all. Idle timeout is set to 20minutes on both environments. Reason for 20 minute timeout is to avoid wasted memory

Apparently the app pool is not recycling when the above exception occurs. We are watching the process in task manager and it is not shutting down or reducing the memory when this exception occurs. Also, we turned on all logging, and no app pool recycle event log entry occurs in the System Log when this exception happens



Windows service stable APPCRASH in clr.dll after 3.5 to 4.0 .NET platform change

$
0
0

I have windows service project created with .NET 3.5 some time ago. It uses managed class library with native code via PInvoke. Recently 4.0 .NET version of that class library was created. I had to change windows service configurstion to 4.0 .NET client also.

Wierd problem started to appear after 4.0 version compilation. After about 1 minute of run service is terminated. In the Windows Events Application Error entry is created (event code 1000, task category (100)):

Application name:MyService.exe, version:1.0.0.0, timestamp:0x4d87107f 
Module name: clr.dll, version:4.0.30319.1, timestamp 0x4ba1d9ef 
Exception code:0xc00000fd 
Error offset:0x000ccd3c 
Process id:0x1680 
Time:0x01cbe7b1aaafc5a0 
Application path: C:\projects\MyService\release\MyService.exe 
Module path C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll 
Report code:024b8ca0-53a5-11e0-9963-544249093872 

With 2 more entries in the events with information from Windows Error Reporting:

 Contaier error , type 0 
 
Event name: APPCRASH 
 
Reply:No data 
 CAB
Identifier:0 
 
 
Problem signature: 
 P1
:MyService.exe 
 P2
:1.0.0.0 
 P3
:4d87107f 
 P4
: clr.dll 
 P5
:4.0.30319.1 
 P6
:4ba1d9ef 
 P7
: c00000fd 
 P8
:000ccd3c 
 P9
: 
 P10
: 

With crash dump files reported to be found in C:\ProgramData\Microsoft\Windows\WER\ReportQueue\AppCrash_MyServ_c7f32a85ba9f45a9b76ff6beb5fac592fa5396f3_cab_047b1b2c

There is no specific point in the service it stops to work as I looked in the service logs dumped to text file. Any function call that follows after about 1 minute of work results in the termination. Service has a timer that fires with specific delays which invokes its functionality.

If I comment out managed class library call that uses native code the service termination stops. If I run the same class library with the same service functionality in original 4.0 console project there are no problems either.

Are there any bugs in 4.0 clr related to native code call in windows service applications?

I have not got installed any 4.0 updates or fixes neither VS 2010 SP1

AwareLock::Contention spin count

$
0
0

We're using Monitor.Enter to protect a shared data structure and we're seeing high CPU on a 24-core box. A profile shows that most threads are spinning waiting for a lock. No thread is doing extensive work while holding the lock and everyone eventually acquires the lock after the spin wait.

Spinning is great, if done in moderation, but what we're seeing is that the spinning is dominating the CPU, preventing real work from getting done thus freeing the lock.

Digging into the sscli20 code (yeah, ancient, but it's what we have) we found this comment in AwareLock::Contention (sscli20\clr\src\vm\syncblk.cpp):

                // Delay by approximately 2*i clock cycles (Pentium III).
                // This is brittle code - future processors may of course execute this
                // faster or slower, and future code generators may eliminate the loop altogether.
                // The precise value of the delay is not critical, however, and I can't think
                // of a better way that isn't machine-dependent.  

And the while condition that determines how long to spin is:

while (i < 20000*g_SystemInfo.dwNumberOfProcessors);

A couple questions:

1) Is that algorithm still accurate or have modern high-core-count machines been factored in? My guess is that it's the same given our observations.

2) Is there any way to control the spin count? I don't see anything in the sscli20 code, but maybe something was added later.

The error "configuration system failed to initialize" occurred

$
0
0

Hi

When I converted and built the solution file that was developed by Visual Studio .net 2003 using Visual Studio 2005, the application program was abnormal-ended at the following step:

m_TCPChannel = New System.Runtime.Remoting.Channels.Tcp.TcpChannel(tcp_properties, Nothing, Nothing)

The error message was "configration system failed to initialize".  The Exception.ToString said that the root <configuration> tag was not included in the configuration file. Therefore, I changed <configopt> tag to <configuration> tag in the app.config file of the target project, and then executed again. Next time, the application program was abnormal-ended by the unrecognized section <xs:schema>. Therefore, I changed the app.config file to the simple one (only <configuration> and </configuration> tags), and then executed again. The error didn't occur.

app.config file is copied as XXXX.exe.config into the same folder with XXXX.exe.

I think ...
When running on Windows XP and .NET Framework 1.1, XXXX.exe.config is not checked (or initilized) at the above TcpChannel step. However, when running on Windows 7 and .NET Framework 2.0, RFID.exe.config is checked (or initialized) at the above TcpChannel step.

I think there are the differences of behavior between .NET Framework 1.1 and .NET Framework 2.0. Is my guessing correct?

app.config file:
 
<?xml version="1.0" standalone="yes"?>
 <configopt>
 <xs:schema id="configopt" xmlns="" xmlns:xs="URL Link" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
 <xs:element name="configopt" msdata:IsDataSet="true" msdata:Locale="en-AU">
 <xs:complexType>
 <xs:choice maxOccurs="unbounded">
 <xs:element name="Environment">
 <xs:complexType>
 <xs:sequence>
 <xs:element name="Name" type="xs:string" minOccurs="0" />
 <xs:element name="System" type="xs:string" minOccurs="0" />
 <xs:element name="DataLibrary" type="xs:string" minOccurs="0" />
 <xs:element name="Default" type="xs:boolean" minOccurs="0" />
 <xs:element name="UserId" type="xs:string" minOccurs="0" />
 </xs:sequence>
 </xs:complexType>
 </xs:element>
 </xs:choice>
 </xs:complexType>
 </xs:element>
 </xs:schema>
 <Environment>
 <Name>Test</Name>
 <System>XXXX.COM</System>
 <DataLibrary>XXXTEST</DataLibrary>
 <Default>false</Default>
 <UserId></UserId>
 </Environment>
 <Environment>
 <Name>Production</Name>
 <System>XXXXX.COM</System>
 <DataLibrary>XXXPROD</DataLibrary>
 <Default>true</Default>
 <UserId />
 </Environment>
 </configopt>

Perfview Exception Opening CPU Stack

$
0
0

When trying to open the CPU Stack for ETL data I've collected for my application (a Win32 application that has a mixture of managed and unmanaged code...if that matters), the following exception is raised and appears at the end of the log:

Started: Computing Stack Traces

SafeMode enable, turning off parallelism

Completed: Computing Stack Traces   (Elapsed Time: 0.092 sec)

Exception Occured: System.IndexOutOfRangeException: Index was outside the bounds of the array.

   at Microsoft.Diagnostics.Tracing.Stacks.TraceEventStackSource.GetCallerIndex(StackSourceCallStackIndex callStackIndex)

   at Microsoft.Diagnostics.Tracing.Stacks.CopyStackSource.GetCallerIndex(StackSourceCallStackIndex callStackIndex)

   at Diagnostics.Tracing.StackSources.FilterStackSource.GenerateStackInfo(StackSourceCallStackIndex stackIndex, StackInfo stackInfoRet)

   at Diagnostics.Tracing.StackSources.FilterStackSource.GetStackInfo(StackSourceCallStackIndex stackIndex)

   at Diagnostics.Tracing.StackSources.FilterStackSource.<>c__DisplayClass1.<ForEach>b__0(StackSourceSample sample)

   at Microsoft.Diagnostics.Tracing.Stacks.CopyStackSource.ForEach(Action`1 callback)

   at Diagnostics.Tracing.StackSources.FilterStackSource.ForEach(Action`1 callback)

   at Microsoft.Diagnostics.Tracing.Stacks.CallTree.set_StackSource(StackSource value)

   at PerfView.StackWindow.<>c__DisplayClass3.<SetStackSource>b__0()

   at PerfView.StatusBar.<>c__DisplayClass8.<StartWork>b__6(Object param0)

An exceptional condition occured, see log for details.

Using latest (1.6 version) of PerfView on Windows 2008 R2 Server.  Any suggestions?

Thanks,


Kelly Hilliard


code first approach

$
0
0

Hi,

I am working on code first approach. I am having problem, How to convert the datatype of column using code first approach ? Please suggest me if anyone have idea.

Thanks & Regards

Ravideep Bansal

Assembly error for System.Management.Automation in .NET Framework 4.0, but not in .NET Framework 4.5

$
0
0

I have a C# .NET Framework 2 application with the following configuration:

<?xml version="1.0" encoding="utf-8" ?><configuration><startup><supportedRuntime version="v4.0"/><supportedRuntime version="v2.0.50727"/></startup></configuration>

Using Assembly Binding Log Viewer (fuslogvw.exe) I get failures like this with .NET Framework 4.0:

The operation failed.

Bind result: hr = 0x80070002. The system cannot find the file specified.

...

LOG: Start binding of native image System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. WRN: No matching native image found.

Using .NET Framework 2.0 and 4.5 the operation is successful.

I tried: Adding in the .csproj file:

    <Reference Include="System.Management.Automation">

Adding this entries in the registry: reg add hklm\software\microsoft.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1 reg add hklm\software\wow6432node\microsoft.netframework /v OnlyUseLatestCLR /t REG_DWORD /d 1

Referencing C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll in the project.

Adding

<startup useLegacyV2RuntimeActivationPolicy="true"   in the application config.

Any suggestions are appreciated.

Thank you

VB.NET WebDAV standalone server implementation

$
0
0

Hello.

    

I'm currently developing a WebDAV server in VB.NET. The server I'm trying to build should be standalone, so no IIS, nor Apache,...
I'm using the HttpListener class to wait for HTTP/WebDAV requests.
The server will be used to map files/folders that are contained in a SQL Server DB.

I tried to map a simple local folder to the Windows Explorer (as a network drive) with IIS, and with Apache, and it works "out of the box". But when I try to map my own WebDAV server to the Windows Explorer as a network drive, Windows says it's not a valid folder...

My server receives 3 requests from the Windows Explorer : OPTIONS, PROPFIND, and again PROPFIND.
The server sends a response to all these requests, and if I snif the network traffic with RawCap, I can't see anything wrong in the XML response, nor in the HTTP headers...
I also sniffed the traffic when I tried with IIS or Apache, and there were a few differences, which I tried to correct, but nothing made a difference, the server is still not working as a network drive in Windows Explorer...

I also compared my code to other open-source WebDAV servers, but I can't figure out why it is not working...

I also tried to take the XML sent as a response from IIS or Apache, and to send it with my server, without success.

So, are there any specific things to implement to make it work with the Windows Explorer ?
Maybe I forgot a little thing that's needed, maybe someone can help me out...

The main code :

Module WebServer

    #Region "Main"
        Sub Main()
            Dim prefixes(0) As String
            prefixes(0) = "http://*:80/"
            ProcessRequests(prefixes)
        End Sub
    #End Region

    #Region "Request processing"

        Private Sub HandleRequest(context As HttpListenerContext)
            Dim sw = Stopwatch.StartNew()
            Dim response As HttpListenerResponse = Nothing
            Dim requestHandler As IMethodHandler = Nothing


            Console.WriteLine(String.Format("{0:hh:mm:ss} >>> ", DateTime.Now) + context.Request.HttpMethod + " Request from : " + context.Request.UserAgent)
            Console.WriteLine("    KeepAlive: {0}", context.Request.KeepAlive)
            Console.WriteLine("    Local end point: {0}", context.Request.LocalEndPoint.ToString())
            Console.WriteLine("    Remote end point: {0}", context.Request.RemoteEndPoint.ToString())
            Console.WriteLine("    Is local? {0}", context.Request.IsLocal)
            Console.WriteLine("    HTTP method: {0}", context.Request.HttpMethod)
            Console.WriteLine("    Protocol version: {0}", context.Request.ProtocolVersion)
            Console.WriteLine("    Is authenticated: {0}", context.Request.IsAuthenticated)
            Console.WriteLine("    Is secure: {0}", context.Request.IsSecureConnection)

            ' Create the response
            response = context.Response

            response.ContentType = "text/xml"
            response.ContentEncoding = System.Text.Encoding.UTF8

            ' User authentication
            'Dim identity As HttpListenerBasicIdentity = context.User.Identity

            'If Not identity.Name.Equals("test") Or Not identity.Password.Equals("test") Then
            'response.StatusCode = HttpStatusCode.Unauthorized
            'response.AddHeader("WWW-Authenticate", "Basic realm=""Server""")

            'Else
            Select Case context.Request.HttpMethod.ToUpper()
                Case "OPTIONS"
                    requestHandler = New OPTIONS_Handler(context)
                Case "GET"
                    requestHandler = New GET_Handler(context)
                Case "HEAD"
                    requestHandler = New HEAD_Handler(context)
                Case "PUT"
                    requestHandler = New PUT_Handler(context)
                Case "POST"
                    requestHandler = New POST_Handler(context)
                Case "DELETE"
                    requestHandler = New DELETE_Handler(context)
                Case "COPY"
                    requestHandler = New COPY_Handler(context)
                Case "MOVE"
                    requestHandler = New MOVE_Handler(context)
                Case "MKCOL"
                    requestHandler = New MKCOL_Handler(context)
                Case "PROPFIND"
                    requestHandler = New PROPFIND_Handler(context)
                Case "PROPPATCH"
                    requestHandler = New PROPPATCH_Handler(context)
                Case Else
                    Console.WriteLine("Unknown Command")
                    response.StatusCode = HttpStatusCode.NotImplemented
            End Select

            If Not requestHandler Is Nothing Then
                requestHandler.processRequest()
            End If

            If response IsNot Nothing Then
                response.Close()
            End If
            Console.WriteLine("Time : {0}", sw.Elapsed)
            'End If
        End Sub

        Private Sub ProcessRequests(ByVal prefixes() As String)
            If Not System.Net.HttpListener.IsSupported Then
                Console.WriteLine( _
                    "Windows XP SP2, Server 2003, or higher is required to " & _"use the HttpListener class.")
                Exit Sub
            End If

            ' URI prefixes are required
            If prefixes Is Nothing OrElse prefixes.Length = 0 Then
                Throw New ArgumentException("prefixes")
            End If

            ' Create a listener and add the prefixes
            Dim listener As System.Net.HttpListener = New System.Net.HttpListener()
            For Each s As String In prefixes
                listener.Prefixes.Add(s)
            Next

            Try
                ' Start the listener to begin listening for requests and set authentication
                'listener.AuthenticationSchemes = AuthenticationSchemes.Basic
                listener.Start()
                Console.WriteLine("Listening...")

                While True
                   Try
                        ' Note: GetContext blocks while waiting for a request
                        Dim context As HttpListenerContext = listener.GetContext()
                        Dim t As New Threading.Thread(Sub() HandleRequest(context))
                        t.Start()

                    Catch ex As HttpListenerException
                        Console.WriteLine(ex.Message)
                    End Try
                End While

            Catch ex As HttpListenerException
                Console.WriteLine(ex.Message)
            Finally
                ' Stop listening for requests
                listener.Close()
                Console.WriteLine("Done Listening...")
            End Try
        End Sub
    #End Region

    End Module


The OPTIONS handler :

Public Class OPTIONS_Handler : Implements IMethodHandler

        Private context As HttpListenerContext
        Private response As HttpListenerResponse

        Public Sub New(ByVal ctxt As HttpListenerContext)
            context = ctxt
            response = context.Response
        End Sub

        Public Sub processRequest() Implements IMethodHandler.processRequest
            response.AppendHeader("Allow", "OPTIONS, GET, HEAD, POST, PUT, DELETE, COPY, MOVE, MKCOL, PROPFIND, PROPPATCH")
            response.AppendHeader("Public", "OPTIONS, GET, HEAD, POST, PUT, DELETE, COPY, MOVE, MKCOL, PROPFIND, PROPPATCH")
            response.AppendHeader("DAV", "1, 2, ordered-collections")
            response.AppendHeader("Versioning-Support", "DAV:basicversioning")
            response.AppendHeader("MS-Author-Via", "DAV")
            'response.AppendHeader("X_MSDAVEXT", "1")
            'response.AppendHeader("Translate", "f")

            response.StatusCode = HttpStatusCode.OK
        End Sub
    End Class


And the PROPFIND handler :

Public Class PROPFIND_Handler : Implements IMethodHandler

        Private context As HttpListenerContext
        Private response As HttpListenerResponse

        Public Sub New(ByVal ctxt As HttpListenerContext)
            context = ctxt
            response = context.Response
        End Sub

        Public Sub processRequest() Implements IMethodHandler.processRequest
            Try
                context.Response.SendChunked = False

                ' Check if the XML request is valid and well-formed
                Dim request As HttpListenerRequest = context.Request
                Dim reader As XmlReader = XmlReader.Create(request.InputStream)

                ' See if the inputstream includes some data. If not --> Exception
                Dim buffer(16 * 1024) As Byte
                Dim read As Integer
                Dim memstr As New MemoryStream

                While (read = request.InputStream.Read(buffer, 0, buffer.Length)) > 0
                    memstr.Write(buffer, 0, read)
                End While

                If memstr.Length <> 0 Then
                    Dim doc As XDocument = XDocument.Load(reader)
                End If

                response.StatusCode = 207
                Dim xmlWriter As XmlTextWriter = New XmlTextWriter("test.xml", New System.Text.UTF8Encoding(False))
                'xmlWriter.Formatting = Formatting.Indented

                xmlWriter.WriteStartDocument()
                xmlWriter.WriteStartElement("D:multistatus")
                xmlWriter.WriteAttributeString("xmlns:D", "DAV:")
                xmlWriter.WriteAttributeString("xmlns:b", "urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882")

                ' Get the requested URI
                Dim requestedURI As String = context.Request.Url.LocalPath

                ' Get the files and folders list from the mapped folder
                Dim mappedFolderInfo
                If requestedURI.Equals("/") Then
                    mappedFolderInfo = New IO.DirectoryInfo("MappedFolder")
                Else
                    mappedFolderInfo = New IO.DirectoryInfo("MappedFolder" + requestedURI)
                End If

                Dim filesList As IO.FileInfo() = mappedFolderInfo.GetFiles()
                Dim foldersList As IO.DirectoryInfo() = mappedFolderInfo.GetDirectories()

                ' List all the files and folders and build the corresponding XML response
                Dim tempFile As IO.FileInfo
                Dim tempFolder As IO.DirectoryInfo
                For Each tempFolder In foldersList
                    Dim webDavItem As New WebDAVItem()
                    webDavItem.CollectionYN = True
                    webDavItem.ContentLength = 0
                    webDavItem.CreationDate = tempFolder.CreationTime
                    webDavItem.LastModifDate = tempFolder.LastWriteTime
                    webDavItem.Name = tempFolder.Name + "/"
                    webDavItem.Path = requestedURI
                    webDavItem.BuildXmlResponse(xmlWriter)
                Next
                For Each tempFile In filesList
                    Dim webDavItem As New WebDAVItem()
                    webDavItem.CollectionYN = False
                    webDavItem.ContentLength = tempFile.Length
                    webDavItem.CreationDate = tempFile.CreationTime
                    webDavItem.LastModifDate = tempFile.LastWriteTime
                    webDavItem.Name = tempFile.Name
                    webDavItem.Path = requestedURI
                    webDavItem.BuildXmlResponse(xmlWriter)
                Next

                xmlWriter.Close()


                Dim f As FileStream = File.OpenRead("test.xml")
                Dim fileData(f.Length) As Byte

                response.ContentLength64 = f.Length
                f.Read(fileData, 0, f.Length)
                f.Close()

                response.OutputStream.Write(fileData, 0, response.ContentLength64)

            Catch ex As Exception
                Console.WriteLine("Exception while handling PROPFIND : " + ex.Message)
                response.StatusCode = HttpStatusCode.BadRequest
            End Try
        End Sub
    End Class


Thank you very much !

                                                                                                                                                                         

C++ project builds are failing with error MSB4014: The build stopped unexpectedly because of an internal failure

$
0
0

Recently our VS1010 solutions are failing with error MSB4014: The build stopped unexpectedly because of an internal failure.

error MSB4014: The build stopped unexpectedly because of an internal failure.
intspt.vcxproj : error MSB4014: Microsoft.Build.Exceptions.BuildAbortedException: Build was canceled. MSBuild.exe could not be launched as a child node as it could not be found at the location "C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe". If necessary, specify the correct location in the BuildParameters, or with the MSBUILD_EXE_PATH environment variable.
\intspt.vcxproj : error MSB4014:    at Microsoft.Build.BackEnd.NodeManager.AttemptCreateNode(INodeProvider nodeProvider, NodeConfiguration nodeConfiguration)
intspt.vcxproj : error MSB4014:    at Microsoft.Build.BackEnd.NodeManager.CreateNode(NodeConfiguration configuration, NodeAffinity nodeAffinity)
intspt.vcxproj : error MSB4014:    at Microsoft.Build.Execution.BuildManager.PerformSchedulingActions(IEnumerable`1 responses)
intspt.vcxproj : error MSB4014:    at Microsoft.Build.Execution.BuildManager.HandleNewRequest(Int32 node, BuildRequestBlocker blocker)
intspt.vcxproj : error MSB4014:    at Microsoft.Build.Execution.BuildManager.IssueRequestToScheduler(BuildSubmission submission, Boolean allowMainThreadBuild, BuildRequestBlocker blocker)

I have installed KBKB2298853 and repaired VS2010 and related SP1 also.  But still the builds are failing.

In this https://connect.microsoft.com/VisualStudio/feedback/details/535129/error-msb4014-when-building-any-visual-c-project thread i saw this is the bug in .Net framework and it is fixed in next version of Framework.

May i know the version of .Net framework which i can install ?

Thanks

What the returned ContextID from ICorProfilerInfo::GetThreadContext can be used? Can ThreadLocalStorage data be access via it?

$
0
0

 I am coding a CLR profiler, want to get the TLS data, is there a way by profiler?

 Thanks.

YongMing

Viewing all 1710 articles
Browse latest View live


Latest Images