InvalidCastException on LyncClient.GetClient()

I cget an exception on "LyncClient.GetClient()" - I've tried this one two different machines, and I'm getting the same results. Here are the details:
Visual Studio 2012
Lync 2013 Client installed, with silverlight (part of Office 2013), and running/signed in
Lync 2013 SDK installed
I've first tried writing my own test project, but I'm also getting the same error on the sample projects (sample project: ContactInformation, MainWindow.xaml.cs, line 66). Here's the exception details:
InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Uc.UCOfficeIntegration'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{6A222195-F65E-467F-8F77-EB180BD85288}'
failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
Stack Trace:    at Microsoft.Lync.Model.LyncClient.EnsureOI()
   at Microsoft.Lync.Model.LyncClient.GetClient()
   at ContactInformation.MainWindow.Window_Loaded(Object sender, RoutedEventArgs e) in c:\Program Files (x86)\Microsoft Office\Office15\LyncSDK\samples\ContactInformation\MainWindow.xaml.cs:line 66
Note: I've also tried adding a reference to C:\Program Files (x86)\Microsoft Office\Office15\LyncSDK\Assemblies\Desktop\Microsoft.Office.Uc.dll
When doing the "GetClient()", I get the following exception, instead: "The type initializer for 'Microsoft.Lync.Model.LyncClient' threw an exception."
InnerException:
{"Could not load file or assembly 'Microsoft.Office.Uc, Version=15.0.4454.1509, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. The system cannot find the file specified.":"Microsoft.Office.Uc, Version=15.0.4454.1509,
Culture=neutral, PublicKeyToken=71e9bce111e9429c"}

The Microsoft.office.uc.dll file and/or the Microsoft.Lync.Model.dll files that are reference by the ContactInformation sample project are not compatible with the Lync client you have installed.  It may be that you have the CU2 version of the SDK and
RTM or CU1 version of the client.
The client that you should run is
here
The SDK you should install is here
Be sure that the Microsoft.Lync.Model.dll that is referenced in the sample project is the assembly that is installed with the SDK.  This is found in the C:\Program Files (x86)\Microsoft Office 2013\LyncSDK\Assemblies\Desktop folder.
John Austin Senior Programming Writer Microsoft

Similar Messages

  • Lync Phones Disconnect Events are Firing when a call is answered

    Im working with Lync client SDk 2013. I am trying to write a simple desktop application to determine when a call is Ringing, Answered, and Disconnected. I testing my application using Lync Desk phone (polycom phones). When i call my Lync phone, i get a "Notified"
    event, and when That call is answered, i get a "Disconnected" event.
    private static LyncClient _client;
    private static void Main()
    _client = LyncClient.GetClient();
    _client.ConversationManager.ConversationAdded += ConversationManager_ConversationAdded;
    _client.ConversationManager.ConversationRemoved += ConversationManager_ConversationRemoved;
    Console.ReadLine();
    static void ConversationManager_ConversationAdded(object sender, ConversationManagerEventArgs e)
    e.Conversation.Modalities[ModalityTypes.AudioVideo].ModalityStateChanged += Program_ModalityStateChanged;
    static void Program_ModalityStateChanged(object sender, ModalityStateChangedEventArgs e)
    Console.WriteLine("Modality state changed "+ String.Format("{0} => {1}", e.OldState, e.NewState));
    static void ConversationManager_ConversationRemoved(object sender, ConversationManagerEventArgs e)
    //....some code.
    }output from this code isModality state changed Disconnected => NotifiedModality state changed Notified=> DisconnectedI did come across few nice articles, but those don't seem to help me.http://blog.thoughtstuff.co.uk/2013/01/tracking-lync-conversations-in-code/http://msdn.microsoft.com/en-us/library/office/hh345194(v=office.14).aspxIs there any way to determine when the call is answered and disconnected?Thanks

    Hi,
    You might post the issue on Lync MSDN forum and more developing expert will help to verify if this can be achieved using Lync SDK. Thank you for your understanding.
    http://social.msdn.microsoft.com/Forums/en-US/communicatorsdk/threads
    Best Regards,
    Eason Huang
    Eason Huang
    TechNet Community Support

  • Lync SDK Memory Leak?

    Hi,
    I've recently launched an application that interacts with Lync Clients using Lync SDK (2010 or 2013)
    It seems to me I've done something very wrong, because once I'm attached to the Lync SDK, the process memory starts growing without any limit. I wrote a basic test application to debug this, but the memory still seems to be leaking. The process used memory
    grows by 100-300 KB for every conversation added - even though i do not even subscribe to any Lync events. I doubt this leak has a limit, bug I stopped checking at ~120MB
    Call to the .NET Garbage Collector does not seem to solve this. 
    Here is the code I am using to test this:
    class Program
    static LyncClient _LyncClient;
    static void Main(string[] args)
    _LyncClient = LyncClient.GetClient();
    Console.ReadLine();
    Has anyone noticed this leak before? 
    Thanks, 

    The history actually relates to an accessor method. I seemed to have misunderstood the documentation ("Accessor Methods"), the retain shouldn't be there.
    I'll give it ago without retain and see what happens.

  • InvalidCastException was unhandled

    Hi,
    working with some in-house developed software, and after installing, and then uninstalling, a patch for VS2010, I suddenly get an "InvalidCastException was unhandled"
    The software is built on CodedUI, and the error appears when running the line 
    bw = BrowserWindow.Launch(data);
    The broswerwindow is opened, and the error is thrown before the next line is interpreted. 
    The error text reads:
    Unable to cast COM object of type 'Microsoft.VisualStudio.TestTools.UITest.Extension.IE.Communication.Interop.IECommunicatorClass' to interface type 'Microsoft.VisualStudio.TestTools.UITest.Extension.IE.Communication.Interop.IIECommunicator'. This operation
    failed because the QueryInterface call on the COM component for the interface with IID '{95D738E9-E1F4-45EB-9DFF-E39671AF0CB7}' failed due to the following error: Library not registered. (Exception from HRESULT: 0x8002801D (TYPE_E_LIBNOTREGISTERED)).
    Anyone have an idea?

    Hi HakonRamanujan,
    >>Get the same message when trying to record steps with CodedUI, when trying to access some controls on web pages.
    Do you mean that you still get this issue if you record a simple coded UI test? I mean that whether all coded UI tests have the same issue, maybe you could install the VS2010 sp1. Test it again.
    Please also make sure that the Coded UI test supports these controls.
    https://msdn.microsoft.com/en-us/library/dd380742(v=vs.100).aspx
    In addition, whether you recorded the test in the latest version like VS2013 before? Maybe you could test it in VS2013 version.
    Best Regards,
    Jack 
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Unexpected InvalidCastException With DataTemplate

    I have the following Xaml for which I set the ItemsSource property as follows:
    <ItemsControl x:Name="itmRecipients" Grid.Column="0" Grid.Row="2" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollMode="Auto" ScrollViewer.BringIntoViewOnFocusChange="True">
    <ItemsControl.ItemsPanel><ItemsPanelTemplate><StackPanel/></ItemsPanelTemplate></ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate><DataTemplate><RadioButton Style="{StaticResource BasicToggleButton}" GroupName="Recipients" Checked="Recipient_Checked" Content="{Binding Name}" Tag="{Binding Index}"/></DataTemplate></ItemsControl.ItemTemplate>
    </ItemsControl>
    Me.itmRecipients.ItemsSource = Me.Recipients.Select(Function(r, i) New With {.Name = r.Name, .Index = i})
    As you can see, the DataTemplate is just a RadioButton which uses the Name and Index properties of the bound items. The bound items are an anonymous type with the properties Name and Index. But when I run the code, I get the following error:
    A first chance exception of type 'System.InvalidCastException' occurred in GiftTrackerUnivAppTest_Windows.exe
    After looking at App.g.i.vb, I found the following in unhandledExceptionArgs:
    "System.InvalidCastException: Unable to cast object of type 'VB$AnonymousType_0`2[System.String,System.Int32]' to type 'Windows.UI.Xaml.Controls.RadioButton'.
        at GiftTrackerUnivAppTest_Windows.MainPage.MainPage_Loaded(Object sender, RoutedEventArgs e)"
    'VB$AnonymousType_0`2[System.String,System.Int32]' is obviously my anonymous type with the Name and Index properties. Why is it trying to convert my anonymous type to a RadioButton instead of applying it to the DataTemplate? Thanks.
    Nathan Sokalski [email protected] http://www.nathansokalski.com/

    Hi Nathan,
    I used the following code snippet to test in store app, but I worked. I could not reproduce your problem. Can you post a repro project or post more information to explain your scenario?
    Private Sub Page_Loaded(sender As Object, e As RoutedEventArgs)
    list = New System.Collections.ObjectModel.ObservableCollection(Of Employee)()
    Dim rnd As New Random()
    For i As Integer = 0 To 99
    Dim ee As New Employee()
    ee.Name = "herro" & i.ToString()
    ee.Index = rnd.Next(0, 101)
    list.Add(ee)
    Next
    itmRecipients.ItemsSource = list.Where(Function(w) w.Index > 10).[Select](Function(s) New With { _
    Key .Name = s.Name, _
    Key .Index = s.Index _
    End Sub
    Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place. Click HERE to participate
    the survey.

  • CrystalReports  'System.InvalidCastException' occurred

    Hi Team, I'm getting the below error. Can some one please assist me on this? I'm using Windows 2012 R2 server and CrystalReport Runtime 13.0.x version installed on the server. Application built on Any CPU using VisualStudio 2010 Error Message: HandlingInstanceID: c68a0e37-5eb5-4cb5-9587-6d6030b79b48  An exception of type 'System.InvalidCastException' occurred and was caught.  ---------------------------------------------------------------------------  01/13/2015 16:26:11  Type : System.InvalidCastException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089  Message : Unable to cast object of type 'FileStreamDeleteOnClose' to type 'System.IO.MemoryStream'.

    Hi Don,
    I gave this a try and I got the same results I was getting before the change the ExportToStream is returning a object of type FileStreamDeleteOnclose instead of an object of type IO.Stream.
    You have what I had before already, but here is what I changed it to in order to do what the developer asked:
    Protected Friend Function GetPDF(ByVal genColsolidatedPDF As String) As IO.
    Stream
    Dim exportStream As System.IO.Stream = GenerateReport(genColsolidatedPDF).ExportToStream(ExportFormatType
    .PortableDocFormat)
    Using fileStream As New IO.FileStream(expPath, System.IO.FileMode.Create, System.IO.FileAccess
    .Write)exportStream.CopyTo(fileStream)fileStream.Dispose()
    exportStream.Close()
    Return
    exportStream
    End Function
    Private Function GenerateReport(ByVal genConsolPDF As String) As
    ReportDocument
    Dim connInfo As New
    ConnectionInfo
    Dim databaseLoginInfo As New
    TableLogOnInfos
    Dim reportDoc As New
    ReportDocument
    Dim tableSet As
    Tables
    'reportDoc = New ActiveSignatures 
    reportDoc.Load(rptPath)
    reportDoc.SetParameterValue(DAL.ParmName.MRId, BLL.SessionData
    .EssInfo.MRID)reportDoc.SetParameterValue(cCONSOLIDATEPDF, genConsolPDF)
    connInfo.ServerName = [Lib].ApplicationData.db_Server
    connInfo.DatabaseName = [Lib].ApplicationData.db_Name
    connInfo.UserID = [Lib].ApplicationData.db_UserId
    connInfo.Password = [Lib].ApplicationData.db_Password
    tableSet = reportDoc.Database.Tables
    For Each singleTable As Table In
    tableSet
    Dim singleTableLogoninfo As TableLogOnInfo
    = singleTable.LogOnInfo
    singleTableLogoninfo.ConnectionInfo = connInfo
    singleTable.ApplyLogOnInfo(singleTableLogoninfo)
    Next
    Return reportDoc
    End Function
    It seemed like the developer maybe wanted more information about how the report is then used, so this is what happens.  The report is then supposed to be returned as type IO.Stream and then it is to be converted to an IO.MemoryStream: 
    Dim sourceFiles(sourceSize as MemoryStream)
    sourceFiles(i) = New MemoryStream(GetByteArray(CType(parameters.SignaturePage, IO.MemoryStream)))
    parameters.SignaturePage is the crytal report that is being returned, that is what needs to be IO.Stream, but is coming back as FileStreamDeleteOnclose.
    When the application then tries to convert from FileStreamDeleteOnClose to IO.MemoryStream, that is where the error occurrs:  Exception: System.InvalidCastException: Unable to cast object of type 'FileStreamDeleteOnClose' to type 'System.IO.MemoryStream'.  But this is only occurring because I am getting back the incorrect object type from the ExportToStream call. 
    Before I upgraded to SP 13 this worked fine, and has been working fine for years.  It is after SP13 that this ExportToStream stopped giving me the IO.Stream object type and is now returning the FileStreamDeleteOnClose.
    I hope that helps!
    Thank you,
    Leah

  • System.InvalidCastException at DataReader.GetInt64 or DataReader.GetInt16

    Hallo,
    we have an application which gets data from a view in an Oracle 9.2.0.7 database:
    SELECT CAST (1138923 AS NUMBER (10)) AS object_id,
    CAST (MIN.universal_time AS NUMBER (10)) AS universal_time,
    MIN.local_time AS local_time, 0 AS mod_time, 0 AS COUNT,
    CAST ((MIN.VALUE + MAX.VALUE) / 2 AS NUMBER (38, 19)) AS VALUE,
    CAST (9 AS NUMBER (2)) AS flag
    FROM TimeSeries
    WHERE object_id = 1138923
    We access this view with a ODP.NET 9.2.0.7 provider using a DataReader.
    On our development machine and at the most customers the acces works very fine !!
    But only at one customer we get an InvalidCastException iif we use the GetInt64 or GetInt16 DataReader method.
    While debugging we recognized that the datareader method returns a decimal, although it is casted to number 10
    We don't want to use a GetDecimal or CAST command in the .NET code, the view or table should return a double !
    Is this a known behaviour ?
    Many thanks in advance and
    Best regards
    George
    Edited by: hakomdba on 23.02.2009 11:04

    How did you go about recreating the Managed Metadata Service Application? Did you point the service application at the existing database when recreating it or did you create it with a 'dummy' database and use the following PowerShell to point it at
    the old database?
    $app = Get-SPServiceApplication -Name "<ServiceApplicationName>"
    Set-SPMetadataServiceApplication -Identity $app -DatabaseName "<DbName>"
    Also, I have seen scenarios where the MMD service application db is completely corrupt and the only way to retain data is through the commands specified here:
    http://social.technet.microsoft.com/wiki/contents/articles/5233.sharepoint-2010-import-export-termset.aspx
    Regards,
    Andrew J Billings
    Portal Systems Engineer//MCSA,MCSE
    Blog:
    http://www.andrewjbillings.com 
    Twitter:   LinkedIn:
      

  • AppFabric Installation Error System.InvalidCastException

    Hi everyone,
    I tried to install AppFabric on Windows 7 Enterprise (Service Pack1) 64-bit operating system computer.  For development and testing reasons.
    I tried some popular workarounds for appfabric including environment variable changes and others, none of them solved my problem. Can you help me please?
    When i double click WindowsServerAppFabricSetup_x64.exe,  i got System.InvalidCastException which is detailed below.
    Unable to cast COM object of type 'CbsSession' to interface type 'ICbsSession'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{75207391-23F2-4396-85F0-8FDB879ED0ED}' failed due to the following error:
    Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
    Description:
      Stopped working
    Problem signature:
      Problem Event Name: CLR20r3
      Problem Signature 01: setup.exe
      Problem Signature 02: 1.0.0.0
      Problem Signature 03: 4ed52225
      Problem Signature 04: Setup
      Problem Signature 05: 1.0.0.0
      Problem Signature 06: 4ed52225
      Problem Signature 07: 1fb
      Problem Signature 08: 6
      Problem Signature 09: System.InvalidCastException
      OS Version: 6.1.7601.2.1.0.256.4
      Locale ID: 1055

    Hello yilmazuur,
    It looks like your post is not related to Outlook at all. That is why I would recommend asking such questions in the
    AppFabric Service and Workflow Management  forum instead. There you will get the most qualified answers.

  • OracleDataReader GetInt32 throws invalidcastexception

    The example below shows an example of calling the OracleDataReader GetInt32 accessor where field 0 is defined as a NUMBER type in the db. This throws an InvalidCastException with the message "specified cast is invald"
    OracleDataReader dr = cmd.ExecuteReader();
    dr.Read();
    int id = dr.GetInt32(0);
    dr.Close();
    The documentation specifies that this accessor returns an int from a NUMBER column.
    I can work around this using a GetDecimal and casting to an int.
    Will this bug be fixed in the next release and when is the next release.

    Chris,
    I have tried the code you have posted with a table created as follows:
    create table int32_tab(col1 Number(9));
    insert into int32_tab values(999999999);
    and do not see the InvalidCastException. Could you please provide me with more details of your test case.
    -Naveen

  • DeltaSynchronization Error 29181 InvalidCastException

    I started getting errors on the DeltaSynchronization but have not been able to determine the cause or who to fix it.
    I have already increased the timeout values in ConfigService.config on all the management servers, although i didn't think this would resolve the issue.
    Any help or suggestions would be appreciated.
    Below is the full error message:
    OpsMgr Management Configuration Service failed to execute 'DeltaSynchronization' engine work item due to the following exception
    Microsoft.EnterpriseManagement.ManagementConfiguration.DataAccessLayer.DataAccessException: Data access operation failed
    at Microsoft.EnterpriseManagement.ManagementConfiguration.DataAccessLayer.DataAccessOperation.ExecuteSynchronously(Int32 timeoutSeconds, WaitHandle stopWaitHandle)
    at Microsoft.EnterpriseManagement.ManagementConfiguration.CmdbOperations.CmdbDataProvider.GetConfigurationDelta(String watermark)
    at Microsoft.EnterpriseManagement.ManagementConfiguration.Engine.TracingConfigurationDataProvider.GetConfigurationDelta(String watermark)
    at Microsoft.EnterpriseManagement.ManagementConfiguration.Engine.DeltaSynchronizationWorkItem.TransferData(String watermark)
    at Microsoft.EnterpriseManagement.ManagementConfiguration.Engine.DeltaSynchronizationWorkItem.ExecuteSharedWorkItem()
    at Microsoft.EnterpriseManagement.ManagementConfiguration.Interop.SharedWorkItem.ExecuteWorkItem()
    at Microsoft.EnterpriseManagement.ManagementConfiguration.Interop.ConfigServiceEngineWorkItem.Execute()
    System.InvalidCastException: Specified cast is not valid.
    at Microsoft.EnterpriseManagement.ManagementConfiguration.CmdbOperations.EntityChangeDeltaReadOperation.ReadManagedEntitiesProperties(SqlDataReader reader)
    at Microsoft.EnterpriseManagement.ManagementConfiguration.CmdbOperations.EntityChangeDeltaReadOperation.ReadData(SqlDataReader reader)
    at Microsoft.EnterpriseManagement.ManagementConfiguration.DataAccessLayer.ReaderSqlCommandOperation.SqlCommandCompleted(IAsyncResult asyncResult)

    Figured it out for my issue. A clustered server created additional windows computer objects with IsVirtualNode set to True, representing the cluster. It's an annoyance, but you need to know how to weed these out if your discovery will be run against Microsoft.Windows.Server.Computer
    and where your SCOM box is monitoring clustered servers.
    My discovery script tries to push the discovered object down to the agent. Which is impossible for these weird virtual computer objects.
        $global:discoveryData.AddInstance($instance)
        # force the seed down the the agent
        # To force the RMS to re-assign the local agent as the managing agent for the discovered physical server object ($instance)
        # we have to get a reference to the local health service class and then create a SPECIAL SECRET relationship :)
        $oHealthServiceInstance = $global:discoveryData.CreateClassInstance("$MPElement[Name='SC!Microsoft.SystemCenter.HealthService']$")
        $oHealthServiceInstance.AddProperty("$MPElement[Name='Windows!Microsoft.Windows.Computer']/PrincipalName$", $PrincipalName)
        $global:discoveryData.AddInstance($oHealthServiceInstance)
        $oHsCnRel = $global:discoveryData.CreateRelationshipInstance("$MPElement[Name='SC!Microsoft.SystemCenter.HealthServiceShouldManageEntity']$")
        $oHsCnRel.Source = $oHealthServiceInstance
        $oHsCnRel.Target = $instance
        $global:discoveryData.AddInstance($oHsCnRel)
    It works find if all your servers are unclustered, but if they're clustered you can't push the object down to the agent, there isn't one.  This seems to be the culprit of the call stack described at the beginning of this discussion.
    So... to fix it (ignore the offending objects) ...
    If you're doing a filtered registry discovery, add this to your filter expression...
          <Expression>
            <SimpleExpression>
              <ValueExpression>
                <Value Type="String">IsVirtualNode:$Target/Property[Type="Windows!Microsoft.Windows.Server.Computer"]/IsVirtualNode$</Value>
              </ValueExpression>
              <Operator>NotEqual</Operator>
              <ValueExpression>
                <Value Type="String">IsVirtualNode:True</Value>
              </ValueExpression>
            </SimpleExpression>
          </Expression>
    The SCOM object returns NULL when the property is not True, so this is the best way to check (by prepending $Target with some token text like 'IsVirtualNode:')   The resulting generated text will be with 'IsVirtualNode:True' for the target objects
    we want to ignore, and 'IsVirtualNode:' for the target objects we want to process (these are the non-virtual, real physical computers that you thought you were getting all along).  If you do not prepend the $Target... with 'IsVirtualNode:'  I've
    seen SCOM not even process this with the expression evaluation, presumably because it's trying to compare a null instead of a generated string (which is what you get with my hack).
    Ok, enough of that...  If you're trying to do discovery with a script, you can do something like this, where you return early with an empty discovery payload otherwise proceed with normal discovery:
        $isvirtualnode = "IsVirtualNode:$Target/Property[Type="Windows!Microsoft.Windows.Server.Computer"]/IsVirtualNode$"
        if ($isvirtualnode -eq "IsVirtualNode:True")
            #Write-ErrorInfo "Tried to discover Active/Idle for $PrincipalName (IsVirtualNode: $isvirtualnode)"
            #return the empty payload back to SCOM
            $discoveryData
            return
        else
            #Write-Info "Tried to discover Active/Idle for $PrincipalName (IsVirtualNode: $isvirtualnode)"
        # proceed with normal discovery
    Hope this helps someone out there. I spent a lot of time learning about how SCOM deals with clusters a few years back. It was quite a painful experience trying to develop a cluster-aware SCOM pack using the minimal white papers that were available. 
    This piece of info that I'm sharing took some digging as it wasn't documented well in the white papers.

  • Bitmap loading generates InvalidCastException

    Hello all,
    i'm on compact framework 2 (CLR Version: 2.0.7045.0), and i keep getting these first chance exceptions (disabled breaking on them) in my code when trying to load a bitmap from a file. However, the bitmap is created correctly.
    I've seen it happen with both jpg and png, others i haven't tried yet.
    Bitmap tmp;
    tmp = new Bitmap(BackgroundImage);
    or silimar ones all generate this.
    A first chance exception of type 'System.InvalidCastException' occurred in System.Drawing.dll
    The error is happening here:
    System.Drawing.dll!Microsoft.AGL.Common.MISC.CreateMemoryStream(System.IO.Stream stream = {System.IO.FileStream}) + 0xb bytes   
    and detailed one is:
    System.InvalidCastException occurred
      Message="InvalidCastException"
      StackTrace:
        at Microsoft.AGL.Common.MISC.CreateMemoryStream()
        at System.Drawing.Bitmap..ctor()
        at OctopusCF.UI.xml.SkinConfig.GetBackgroundImage()
        at Octopuscf.Program.Main()
    Anyone have any idea where they come from? As the bitmap gets created correctly, could it be that something is happening internally in the system.drawing dll, from which it can recover and still load the bitmap?
    Thanks,
    Kristof

    Yes. You should cache bitmaps you're going to reuse not just because of exception but mostly because it takes a long time to decompress bitmaps. Exception take may be 1-2% of that time. Watch out for available memory though, don’t cache too much.

  • Managed ODP: InvalidCastException when returning large number

    I get an InvalidCastException "Specified cast is not valid" when trying to get a value bigger than Decimal.MaxValue as a scalar result from a select.
    From the stack trace and inspection of the Oracle.ManagedDataAccess.dll code I would expect OracleDataReader to cast to OracleDecimal (or System.Numerics.BigInteger) instead of System.Decimal for large numbers.
    Is this a bug?
    Stack trace:
       at Oracle.ManagedDataAccess.Client.OracleDataReader.GetDecimal(Int32 i)
       at Oracle.ManagedDataAccess.Client.OracleDataReader.GetValue(Int32 i)
       at Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteScalar()
       at Cora.Data.DBProvider.Tests.CoraParameterTest.BigIntegerOracleTest() in D:\svnroot\tech\lib\Cora.Data.DBProvider\Cora.Data.DBProvider.Tests\CoraParameterTest.cs:line 98
    How to reproduce:
    - create a table NUNITTEST_PARAM_SIMPLE with a column BIG of type NUMBER(38)
    - run sample code
                using ( OracleConnection conn = new OracleConnection(ORACONN) )
                    conn.Open();
                    using ( OracleCommand cmd = conn.CreateCommand() )
                        cmd.CommandText = "insert into NUNITTEST_PARAM_SIMPLE (BIG) values (1234567890123456789012345678901234567)";
                        cmd.ExecuteNonQuery();
                    using ( OracleCommand cmd = conn.CreateCommand() )
                        cmd.CommandText = "select BIG from NUNITTEST_PARAM_SIMPLE";
                        object result = cmd.ExecuteScalar();          // Exception
                    conn.Close();

    There is no safe type mapping for ExecuteScalar. It's an uncommon use case.
    Even if there was, making the correct conversion implicitly would lead to more work for the application developer. Let's assume ODP.NET performs the "right" conversion. Now, the app needs to manipulate the data. What data type does it treat the returned value as: string or decimal? It could be either. That means twice as much code. One set deals with the data if a decimal was returned. The second deals with the data if a string is returned.
    It would be much easier to write code for one scenario, rather than two. That is why ODP.NET safe type mapping is an explicit conversion the developer makes.

  • IUriToStreamResolver.UriToStreamAsync - InvalidCastException in TaskToAsyncOperationWithProgress

    Hi,
    I'm developping a book reader application and to display EPUb  I'm using a webview with a IUriToStreamResolver to get the resources (from disk or from server). My business code return Stream object (MemoryStream) and I'm using "AsRandomAccessStream"
    extension method to get a WinRt Stream (also tried with "AsInputStream").
    The issue is that I cannot return the result of these methods to the webview due to an InvalidCastException. The exception is not raised by the webview but by the "TaskToAsyncOperationWithProgressAdapter" in "OnCompleted" method.
    If I'm creating an "InMemoryRandomAccessStream" an copy the bytes in it's working. Copying mutiple times the same data (from server to stream/from stream to WinRt Stream/from WinRt stream to webview) is using too much memory and CPU for a mobile
    application.
    Is it a known issue? Did anyone have a fix for that?Thanks,
    Thanks,
    Max.

    Hi,
    After multiple try I found the reason but cannot fix it.
    It seems that if the UriToStreamAsync method of IUriToStreamResolver doesn't return a WinRT implement of "IInputStream" ("InMemoryRandomAccessStream" or "FileRandomAccessStream") the webview (or
    the component that use the "IUriToStreamResolver") call the "ReadAsync" method.
    This method return a "IAsyncOperationWithProgress<IBuffer, uint>". But there is a bug when setting the "Completed" handler on this instance. The type needed by the "Completed" property is "AsyncOperationWithProgressCompleteHandler<IBuffer,
    uint>". BUT the type passed to this property is in fact a "AsyncOperationCompleteHandler<IInputStream>" which indeed is not correct and throw a "InvalidCastException". I tried to create my own implementation of "IAsyncOperationWithProgress"
    to handle this specific case but a "AccessViolationException" is thrown when called the "Complete" delegate.
    Please note that this issue doesn't appears with "InMemoryRandomAccessStream" or "FileRandomAccessStream". I assume these two classes follow a more optimized way.
    I really need to use a custom IRandomAccessStream to handle encryption of the data that I need to display.
    Thanks for the help.
    Max.

  • AssociatedXMLElement InvalidCastException

    Hi
    I've tried asking this in the Scripting forum but no reaction so far..
    Maybe some of you C++ guys have worked with InDesign as a COM object in VS and have an idea on how to solve this.
    I can't use AssociatedXMLElement property in CS3.
    It throws an InvalidCastException with the message, "Return argument has an invalid type." if a TextFrame or Rectangle has a Tag
    What is wrong with this code...?
    Dim Rec As InDesign.TextFrame
    Rec = myDocument.TextFrames.FirstItem
    Dim x As Object
    x = Rec.AssociatedXMLElement
    /Andy
    Using VS2005 and CS3 5.0.3.662

    Hi Andy,
    I've somehow missed your question in the other forum, but the short answer is: don't use Dim. Turn Option Explicit off. In essence, act as if you are working in VBScript (member of the VB family supported by InDesign), and you'll get much better results. InDesign scripting relies on the Variant type, and is loosly-typed by design. Trying to use stronger typing will only cause problems.
    Thanks,
    Ole

  • System.InvalidCastException error

    Hi,
    I have a form with a matrix and an import button. Users can import records from a text file into a user defined table. After the import into table is complete, the form is refreshed with records from the table. It all works fine when there are only a few records. But if it takes longer to import, I get the following error multiple times during form refresh.
    System.InvalidCastExcpet: QueryInterface for interfaceSAPbouiCOM.itemEvent failed at SAPbouiCOM.ItemEventClass.Get_FormUID
    This happens even if the focus is on my form. If I switch to another application, I get this error even if the I import only a few records.
    All the records get imported, the error is only during form refresh.
    Can anybody help? Thanks in advance.
    Thanks,
    Aparna

    Hi Gianluigi,
    Sorry for not posting an update in the past month. I have been trying quite a few things to resolve this issue. I did try using the .Net Profiler but it was not of much use. The only message I get in the profiler is as follows:
    Type: System.Runtime.InteropServices.COMException
    Call: thrown
    Type: System.InvalidCastException
    Call: Thrown
    I think the error is somehow related to UI API and window refresh. But I am not sure what it is. Interestingly, I get the error only while dealing with large data set.
    Thanks,
    Aparna

Maybe you are looking for