Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to pass an array of pointers of LPCWSTR to a Win32 API function from .NET

Posted on 2009-02-09
8
Medium Priority
?
1,602 Views
Last Modified: 2012-06-21
Can anyone post a sample or explain how to successfully call a COM method or Win32 API function that takes an Array of Pointers of LPCWSTR as one of its parameters?

Here is my unsuccessful attempt at it:

Calling the IOfflineFilesCache::Pin method (http://msdn.microsoft.com/en-us/library/bb530498(VS.85).aspx) fails with error

    System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I think the issue is with the Array of Pointers expected by the rgpszPaths parameter.
I suspect the problem lies with either the Pin method declaration where "[in]  LPCWSTR *rgpszPaths" becomes "ByVal rgpszPaths As IntPtr()" OR with the way I'm converting the array of strings into an array of pointers using StringToHGlobalAuto. I've also tried using StringToCoTaskMemAuto and I still get the same error.
Here is a summary of my code:

Create Array of Strings containing valid UNC Paths
Convert Array of Strings to Array of Pointers by calling the StringToHGlobalAuto method of the Marshal class for each string in the array
Call the Pin method of the IOfflineFilesCache interface passing ByVal the array of pointers along with other parameters


Here is my code:

'====Here is the code that calls the Pin method  =====
        Dim RetVal As Integer  
        Dim strArray(1) As String  
        strArray(0) = "\\TestServer\TestShare\Folders\1"  
        strArray(1) = "\\TestServer\TestShare\Folders\2"  
  
        Dim Pointers() As IntPtr = StringsToPointers(strArray)   
        Try  
        '*** The following line fails with AccessViolationException ***   
            RetVal = iOFC.Pin(0, Pointers, Pointers.Length, True, False, PinControlFlags.OFFLINEFILES_PIN_CONTROL_FLAG_FILL, Nothing)   
        Catch ex As Exception   
            MsgBox("Error executing API Call." & vbCrLf & ex.Message, MsgBoxStyle.Critical)   
        Finally  
            FreeMemory(Pointers)   
        End Try  
 
 
'====Here is the function that converts an array of strings into pointers to unmanaged memory =====
     Private Function StringsToPointers(ByVal strArray As String()) As IntPtr()   
        Dim Pointers(strArray.Length - 1) As IntPtr   
  
        Dim index As Integer = 0   
        For Each str As String In strArray   
            Try  
                Pointers.SetValue(Marshal.StringToHGlobalAuto(str), index)   
            Catch ex As Exception   
                MsgBox("Error in StringsToPointers(): " & ex.Message)   
            End Try  
  
            index = index + 1   
        Next  
        Return Pointers   
    End Function  
 
 
'==== Here is the code that defines the IOfflineFilesCache interface (http://msdn.microsoft.com/en-us/library/bb530486(VS.85).aspx) ====
Imports System   
Imports System.Runtime.InteropServices   
  
<Guid("855d6203-7914-48b9-8d40-4c56f5acffc5")> <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _   
Public Interface IOfflineFilesCache   
    Function Synchronize(ByVal hwndParent As Integer, _   
        ByVal rgpszPaths As IntPtr(), _   
        ByVal cPaths As UInt32, _   
        ByVal bAsync As Boolean, _   
        ByVal dwSyncControl As OFFLINEFILES_SYNC_CONTROL, _   
        ByVal pISyncConflictHandler As Object, _   
        ByVal pIProgress As Object, _   
        ByVal pSyncId As Guid) As Integer  
  
    Function DeleteItems(ByVal rgpszPaths As IntPtr(), _   
        ByVal cPaths As UInt32, _   
        ByVal dwFlags As OFFLINEFILES_DELETE_FLAG, _   
        ByVal bAsync As Boolean, _   
        ByVal pIProgress As IntPtr) As Integer  
  
  
    Function DeleteItemsForUser(ByVal pszUser As String, _   
        ByVal rgpszPaths As IntPtr(), _   
        ByVal cPaths As UInt32, _   
        ByVal dwFlags As OFFLINEFILES_DELETE_FLAG, _   
        ByVal bAsync As Boolean, _   
        ByVal pIProgress As IntPtr) As Integer  
  
    Function Pin(ByVal hwndParent As Integer, _   
        ByVal rgpszPaths As IntPtr(), _   
        ByVal cPaths As UInt32, _   
        ByVal bDeep As Boolean, _   
        ByVal bAsync As Boolean, _   
        ByVal dwPinControlFlags As PinControlFlags, _   
        ByVal pIProgress As IntPtr) As Integer  
  
    Function Unpin(ByVal hwndParent As Integer, _   
        ByVal rgpszPaths As IntPtr(), _   
        ByVal cPaths As UInt32, _   
        ByVal bDeep As Boolean, _   
        ByVal bAsync As Boolean, _   
        ByVal dwPinControlFlags As PinControlFlags, _   
        ByVal pIProgress As IntPtr) As Integer  
  
    Function GetEncryptionStatus(ByRef pbEncrypted As Boolean, _   
        ByRef pbPartial As Boolean) As Integer  
  
    Function Encrypt(ByVal hwndParent As Integer, _   
        ByVal bEncrypt As Boolean, _   
        ByVal dwEncryptionControlFlags As OFFLINEFILES_ENCRYPTION_CONTROL, _   
        ByVal bAsync As Boolean, _   
        ByVal pIProgress As IntPtr) As Integer  
  
    Function FindItem(ByVal pszPath As String, _   
        ByVal dwQueryFlags As OFFLINEFILES_ITEM_QUERY, _   
        ByRef ppItem As IntPtr) As Integer  
  
    Function FindItemEx(ByVal pszPath As String, _   
        ByVal pIncludeFileFilter As IntPtr, _   
        ByVal pIncludeDirFilter As IntPtr, _   
        ByVal pExcludeFileFilter As IntPtr, _   
        ByVal pExcludeDirFilter As IntPtr, _   
        ByVal dwQueryFlags As OFFLINEFILES_ITEM_QUERY, _   
        ByRef ppItem As IntPtr) As Integer  
  
    Function RenameItem(ByVal pszPathOriginal As String, _   
        ByVal pszPathNew As String, _   
        ByVal bReplaceIfExists As Boolean) As Integer  
  
    Function GetLocation(ByRef ppszPath As IntPtr) As Integer  
  
    Function GetDiskSpaceInformation(ByRef pcbVolumeTotal As Long, _   
        ByRef pcbLimit As Long, _   
        ByRef pcbUsed As Long, _   
        ByRef pcbUnpinnedLimit As Long, _   
        ByRef pcbUnpinnedUsed As Long) As Integer  
  
    Function SetDiskSpaceLimits(ByVal cbLimit As Long, _   
        ByVal cbUnpinnedLimit As Long) As Integer  
  
    Function ProcessAdminPinPolicy(ByVal pPinProgress As IntPtr, _   
        ByVal pUnpinProgress As IntPtr) As Integer  
  
    Function GetSettingObject(ByVal pszSettingName As String, _   
        ByRef ppSetting As IntPtr) As Integer  
  
    Function EnumSettingObjects(ByRef ppEnum As IntPtr) As Integer  
  
    Function IsPathCacheable(ByVal pszPath As String, _   
        ByRef pbCacheable As Boolean, _   
        ByRef pShareCachingMode As OFFLINEFILES_CACHING_MODE) As Integer  
End Interface  
  
Public Enum OFFLINEFILES_CACHING_MODE   
    OFFLINEFILES_CACHING_MODE_NONE = 0   
    OFFLINEFILES_CACHING_MODE_NOCACHING = 1   
    OFFLINEFILES_CACHING_MODE_MANUAL = 2   
    OFFLINEFILES_CACHING_MODE_AUTO_DOC = 3   
    OFFLINEFILES_CACHING_MODE_AUTO_PROGANDDOC = 4   
End Enum  
  
Public Enum OFFLINEFILES_SYNC_CONTROL   
    OFFLINEFILES_SYNC_CONTROL_FLAG_FILLSPARSE = &H1   
    OFFLINEFILES_SYNC_CONTROL_FLAG_SYNCIN = &H2   
    OFFLINEFILES_SYNC_CONTROL_FLAG_SYNCOUT = &H4   
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINNEWFILES = &H8   
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINLINKTARGETS = &H10   
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINFORUSER = &H20   
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINFORUSER_POLICY = &H40   
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINFORALL = &H80   
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINFORREDIR = &H100   
    OFFLINEFILES_SYNC_CONTROL_FLAG_LOWPRIORITY = &H200   
    OFFLINEFILES_SYNC_CONTROL_FLAG_ASYNCPROGRESS = &H400   
    OFFLINEFILES_SYNC_CONTROL_FLAG_INTERACTIVE = &H800   
    OFFLINEFILES_SYNC_CONTROL_FLAG_CONSOLE = &H1000   
    OFFLINEFILES_SYNC_CONTROL_FLAG_SKIPSUSPENDEDDIRS = &H2000   
    OFFLINEFILES_SYNC_CONTROL_FLAG_BACKGROUND = &H10000   
    OFFLINEFILES_SYNC_CONTROL_CR_MASK = &HF0000000   
    OFFLINEFILES_SYNC_CONTROL_CR_DEFAULT = &H0   
    OFFLINEFILES_SYNC_CONTROL_CR_KEEPLOCAL = &H10000000   
    OFFLINEFILES_SYNC_CONTROL_CR_KEEPREMOTE = &H20000000   
    OFFLINEFILES_SYNC_CONTROL_CR_KEEPLATEST = &H30000000   
End Enum  
  
Public Enum OFFLINEFILES_DELETE_FLAG   
    OFFLINEFILES_DELETE_FLAG_NOAUTOCACHED = &H1   
    OFFLINEFILES_DELETE_FLAG_NOPINNED = &H2   
    OFFLINEFILES_DELETE_FLAG_DELMODIFIED = &H4   
    OFFLINEFILES_DELETE_FLAG_ADMIN = &H80000000   
End Enum  
  
Public Enum PinControlFlags   
    OFFLINEFILES_PIN_CONTROL_FLAG_FILL = &H1   
    OFFLINEFILES_PIN_CONTROL_PINLINKTARGETS = &H10   
    OFFLINEFILES_PIN_CONTROL_FLAG_FORUSER = &H20   
    OFFLINEFILES_PIN_CONTROL_FLAG_FORUSER_POLICY = &H40   
    OFFLINEFILES_PIN_CONTROL_FLAG_FORALL = &H80   
    OFFLINEFILES_PIN_CONTROL_FLAG_FORREDIR = &H100   
    OFFLINEFILES_PIN_CONTROL_FLAG_LOWPRIORITY = &H200   
    OFFLINEFILES_PIN_CONTROL_FLAG_ASYNCPROGRESS = &H400   
    OFFLINEFILES_PIN_CONTROL_FLAG_INTERACTIVE = &H800   
    OFFLINEFILES_PIN_CONTROL_FLAG_CONSOLE = &H1000   
    OFFLINEFILES_PIN_CONTROL_FLAG_BACKGROUND = &H10000   
End Enum  
  
Public Enum OFFLINEFILES_ENCRYPTION_CONTROL   
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_LOWPRIORITY = &H200   
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_ASYNCPROGRESS = &H400   
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_INTERACTIVE = &H800   
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_CONSOLE = &H1000   
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_BACKGROUND = &H10000   
End Enum  
  
Public Enum OFFLINEFILES_ITEM_QUERY   
    OFFLINEFILES_ITEM_QUERY_REMOTEINFO = &H1   
    OFFLINEFILES_ITEM_QUERY_CONNECTIONSTATE = &H2   
    OFFLINEFILES_ITEM_QUERY_ADMIN = &H80000000   
End Enum  
 
 
 
Report post as abusive
Subject:  
 
      
          Font NameReal font size                       
 
DesignHTMLPreview       
 
 
      
 Post OptionsThis option will split a single thread into a new thread at the specified post. Please include a subject for the new thread, a reason for the split and choose the forum where the new thread should be created. Note: any posts split will lose Proposed Answer or Answered state.This option will merge the currently selected thread into a target thread. Note: Answers and Proposed Answers will be removed after moving and this action cannot be undone. Please enter the thread ID to merge to. The thread ID is the portion of the URL after /thread/ which looks something like this: 8138b571-18b6-475a-85d0-63423e506875.This option allows the user to change the thread type. Note: changing the thread type will remove any Answers or Proposed Answers from question threads.
Use the  icon to add code.
 Has Code 
Create Thread In: 
.NET Base Class Library.NET Compact Framework.NET Framework inside SQL Server.NET Framework Networking and Communication.NET Framework Setup.NET Remoting and Runtime Serialization.NET Services - Technical Discussions.NET Services and SQL Data Services - On-boarding Issues.NET StockTrader Sample Application64-Bit .NET Framework Development.AcropolisADO.NET Data ProvidersADO.NET Data ServicesADO.NET DataSetADO.NET Entity Framework and LINQ to EntitiesApplication Compatibility for Windows DevelopmentArchitecture EventsArchitecture GeneralArchitecture, Tools, and Process for ISVsASMX Web Services and XML SerializationBizTalk Server Adapters and Adapter PackBizTalk Server EDI and AS2BizTalk Server GeneralBizTalk Server RFIDBug Reporting for Forums Platform (not product support)Building Development and Diagnostic Tools for .NetChart Controls for .NET FrameworkCharts & Reports in the Visual Studio 2010 and .NET Framework 4.0 CTPCHESS  Find and Reproduce Concurrency HeisenbugsClaims based access platform (CBA), code-named GenevaClickOnce and Setup & Deployment ProjectsCommerce Server 2002 and EarlierCommerce Server 2007Commerce Server 2009Common Language RuntimeCommunity Technology Preview (CTP)Components/Run-time IssuesConnected Services FrameworkCore Coding Experience in Visual Basic and Visual C# in the Visual Studio 2010 and .NET Framework 4.0 CTPCore Coding Experience in Visual C++ in the Visual Studio 2010 and .NET Framework 4.0 CTPCrystal Reports for Visual StudioCustomer Care FrameworkData MiningDatabase MirroringDeveloper Documentation and Help SystemDevelopers and CustomizationDeveloping Applications with Power ManagementDevelopment for Windows Accessibility and AutomationDevelopment with the Windows Sensor and Location PlatformDirect3D 10DirectShow DevelopmentDocumentation on StandardsEmbedded Enabling Features (EEFs)Feature RequestsFederationFeedback for Visual Basic Bug Submission PilotFile ServicesFrequently Asked QuestionsGame Technolgies: XNA BuildGame Technologies: Audio / XACTGame Technologies: DirectX 101Game Technologies: GeneralGeneral Troubleshooting & Support for the Visual Studio 2010 and .NET Framework 4.0 CTPGeneral Windows Development IssuesGetting started with SQL ServerGetting Started With Visual Studio Team SystemHD DVD Interactivity AuthoringHealthVaultHealthVault Data TypesHot TechnologyInk, Windows Touch, and Other Tablet PC DevelopmentInnovate on OfficeInstallation, Configuration and AdministrationInstalling and Registering Visual Studio Express EditionsInteractive Media Manager Internet Explorer Extension DevelopmentInternet Explorer Web DevelopmentISV Community DaysISV Open DiscussionsJScript for the .NET FrameworkJScript NativeKnown Bugs and WorkaroundsLicencjonowanie produktówLINQ Project GeneralLINQ to SQLLive FrameworkManaged Extensibility FrameworkMDM Business Rules and WorkflowMDM Data Quality and ProfilingMDM Entity and Hierarchy ManagementMDM General DiscussionsMDM IntegrationMDM Setup, Configuration and SecurityMedia Foundation DevelopmentMicrosoft Accessibility LabsMicrosoft adCenter: DevelopmentMicrosoft Atlas APIs: DevelopmentMicrosoft Automatic Graph LayoutMicrosoft Codename 'Dublin'Microsoft Codename 'Oslo'Microsoft Device EmulatorMicrosoft ESP Platform DevelopmentMicrosoft Live Labs VoltaMicrosoft Office Communications Server 2007 SDKMicrosoft Office Communicator 2007 SDKMicrosoft Project Code Named VelocityMicrosoft Robotics - CommunityMicrosoft Robotics - Concurrency and Coordination Runtime (CCR)Microsoft Robotics - Decentralized Software Services (DSS)Microsoft Robotics - Hardware Configuration and TroubleshootingMicrosoft Robotics - SimulationMicrosoft Robotics - Visual Programming LanguageMicrosoft Security Development Lifecycle (SDL) - Threat ModelingMicrosoft Unified Communications AJAX SDKMicrosoft Unified Communications Client SDKMicrosoft Unified Communications Managed API SDKMiscModeling and ToolsMSBuildMS-Build, Multi-Targeting and WiX in the Visual Studio 2010 and .NET Framework 4.0 CTPMSDN and TechNet Search FeedbackMSDN Online: Future PlansMSDN SandboxMSDN Site FeedbackMSXMLNetwork Class Library (System.Net)Network Quality of Service (QoS/qWAVE)Office Binary File FormatsOffice Development with Visual Studio 2010 CTPOffice Live Basics, Essentials and PremiumOffice Live Small Business - Business ApplicationsOffice Live Small Business - General TopicsOffice Live Small Business - Web SiteOffice Open Document Format ImplementationOff-Topic Posts (Do Not Post Here)Open Packaging Conventions (OPC)Open XML Format SDKOptical Platform DiscussionParallel Computing in C++ and Native CodeParallel Extensions to the .NET FrameworkPartnering with MicrosoftPeer-to-Peer NetworkingPexPhoenixPopfly Bugs and SuggestionsPopfly ExplorerPopfly Game CreatorPopfly General DiscussionProject Codename:  JasperRamp UpReference Source Server DiscussionRegular ExpressionsReport a BugSearch, Organize, and Visualize in WindowsSecureLM General DiscussionSecurity for Applications in Microsoft WindowsServer Core DevelopersServer VirtualizationSharePoint - AccessibilitySharePoint - Business Data CatalogSharePoint - Business IntelligenceSharePoint - CollaborationSharePoint - Community AdvancementSharePoint - Design and CustomizationSharePoint - Development and ProgrammingSharePoint - Enterprise Content ManagementSharePoint - Excel ServicesSharePoint - General Question and Answers and DiscussionSharePoint - InfoPath Forms ServicesSharePoint - Knowledge NetworkSharePoint - SearchSharePoint - Setup, Upgrade, Administration and OperationSharePoint - Social ComputingSharePoint - WorkflowShow and TellSidebar Gadget DevelopmentSilverlight (formerly WPF/E) Designer IssuesSilverlight (formerly WPF/E) Developer IssuesSilverlight (formerly WPF/E) General DiscussionSLP Server 2008SLPS Code Protector and Software Protection DiscussionSLPS Developer DiscussionSLPS Microsoft's Online Service DiscussionSmall BasicSmall Business Application DevelopmentSocial Bookmarks Discussion ForumSoftware Licensing and Protection Business DiscussionSoftware Testing DiscussionSQL Data Services (SDS) - Getting StartedSQL Server Analysis ServicesSQL Server CompactSQL Server Data AccessSQL Server Data WarehousingSQL Server Database EngineSQL Server Disaster Recovery and AvailabilitySQL Server DocumentationSQL Server Driver for PHPSQL Server ExpressSQL Server Integration ServicesSQL Server Notification ServicesSQL Server ReplicationSQL Server Reporting ServicesSQL Server Samples and Community ProjectsSQL Server SearchSQL Server SecuritySQL Server Setup & UpgradeSQL Server SMO/DMOSQL Server SpatialSQL Server Tools GeneralSQL Server XMLSQL Service BrokerStorage Platform  ATASuggestions and Feedback for the ForumsSyncFx - FeedbackSyncFx - GeneralSyncFx - Microsoft Synchronization Services for ADO.NETSyncFx - SyncToy-File SynchronizationSyncFx - Technical DiscussionTeam Foundation Server - AdministrationTeam Foundation Server - Build AutomationTeam Foundation Server - GeneralTeam Foundation Server  Power Tools & Add-onsTeam Foundation Server - Process TemplatesTeam Foundation Server - Reporting & WarehouseTeam Foundation Server - SetupTeam Foundation Server - Team System Web AccessTeam Foundation Server - Version ControlTeam Foundation Server - Work Item TrackingTeam Foundation Server in Visual Studio Team System 2010 CTP - Feedback ForumTellme StudioThe Architect RoleToolsTraining and CertificationTransactions ProgrammingTransact-SQLUI Development for WindowsUsing the Exchange Server ProtocolsUsing the Microsoft SQL Server ProtocolsUsing the Office ProtocolsUsing the Open SpecificationsUsing the SharePoint Products and Technologies ProtocolsUsing Visual Round Trip AnalyzerVirtual Earth: Map Control DevelopmentVisual Basic 2008 (Pre-release)Visual Basic Express 2008 (Pre-release)Visual Basic Express EditionVisual Basic for Applications (VBA)Visual Basic GeneralVisual Basic IDEVisual Basic Interop and UpgradeVisual Basic LanguageVisual Basic Power PacksVisual C# 2008 (Pre-release)Visual C# Express 2008 (Pre-release)Visual C# Express EditionVisual C# GeneralVisual C# IDEVisual C# LanguageVisual C++ 2008 (Pre-release)Visual C++ Express 2008 (Pre-release)Visual C++ Express EditionVisual C++ GeneralVisual C++ LanguageVisual FoxPro GeneralVisual J# GeneralVisual Studio 2008 (Pre-release) Install and SetupVisual Studio 2008 Express Editions - Installation and SetupVisual Studio 2008 IDE, Debugger, Build, Deployment, Help, etc. Visual Studio 2008 SP1 (Beta)Visual Studio Class DesignerVisual Studio Code Analysis and Code MetricsVisual Studio DebuggerVisual Studio Editor in the Visual Studio 2010 and .NET Framework 4.0 CTPVisual Studio ExtensibilityVisual Studio Guidance Automation ToolkitVisual Studio Performance Tools (Profiler)Visual Studio Report ControlsVisual Studio Setup and InstallationVisual Studio Smart Device Development - Native C++ ProjectVisual Studio Smart Device Development  Visual Basic and C# ProjectsVisual Studio Source Control and SourceSafeVisual Studio Team System - Architecture & DesignVisual Studio Team System - Database EditionVisual Studio Team System - Microsoft Solutions Framework (MSF)Visual Studio Team System - TestingVisual Studio Team System - Web and Load TestingVisual Studio Team System 2010Visual Studio Tools for OfficeVisual Studio Tools for Office 2008 (Pre-release)Visual Studio Web Developer Express EditionVisual Studio WPF DesignerWeb Development in Visual Studio in the Visual Studio 2010 and .NET Framework 4.0 CTPWeb Gadget DevelopmentWeb Sandbox - ExploitsWeb Sandbox - GeneralWhere is the Forum For&?Windows AzureWindows CardSpace ('InfoCard')Windows Communication FoundationWindows Desktop Search DevelopmentWindows Desktop Search HelpWindows Error Reporting for ISVsWindows Filtering Platform (WFP)Windows Forms Data Controls and DatabindingWindows Forms DesignerWindows Forms GeneralWindows Forms Sample ApplicationsWindows Imaging Component (WIC)Windows Live  Spaces: DevelopmentWindows Live Agents DevelopmentWindows Live Alerts Development ForumWindows Live Controls DevelopmentWindows Live Data DevelopmentWindows Live General: DevelopmentWindows Live ID: DevelopmentWindows Live Messenger Client: DevelopmentWindows Live Messenger Web APIs: DevelopmentWindows Live Search: DevelopmentWindows Live Writer: DevelopmentWindows Mobile DevelopmentWindows Performance ToolkitWindows Presentation Foundation (WPF)Windows Pro-Audio Application DevelopmentWindows ProtocolsWindows Ribbon DevelopmentWindows SDKWindows Server 2008 Application Compatibility and CertificationWindows SideShow DevelopmentWindows Vista Wireless SDKWindows Web Services APIWindows Workflow FoundationWindows XP Wireless SDKWinsock Kernel (WSK)Working with Data and XML in the Visual Studio 2010 and .NET Framework 4.0 CTPWorking with Data in WPF Applications in the Visual Studio 2010 and .NET Framework 4.0 CTPXML and the .NET FrameworkXML in Visual Studio 2008 (Pre-release)XML Paper Specification (XPS)XNA FrameworkXNA Game Studio Express
Thread Type: 
 General Discussion Question
Tags:
 Sticky Until  Subscribe to Alerts for this thread.
Alert Me  Merge to Thread ID:  Reason:  Display Name:  
 
 
 Submit 
 Cancel 
Subject must be 1 to 255 characters long. 
A reason is required between 4 and 255 characters. 
Body must be 4 to 60000 characters long. 
Please select a forum for your thread. 
The tag contains illegal characters. 
Sticky Date must be greater than current date. 
Sticky Date format is invalid. 
Invalid Thread ID 
 
Required Field: Display Name must be between 2 and 32 characters 
Invalid User: The user entered cannot be found or is not a Microsoft Employee 
Related Messages

Open in new window

0
Comment
Question by:TrialWorks
  • 4
  • 3
8 Comments
 
LVL 8

Expert Comment

by:davesgonebananas
ID: 23596099
Just a theory - you are marshalling the strings into unmanaged memory, but not the array of pointers. Since the array is the thing that is passed to the API surely this needs to be in unmanaged memory too?
0
 
LVL 8

Expert Comment

by:davesgonebananas
ID: 23600387
Second theory - since the API expects an array of LPCWSTR you should be using Marshall.StringToHGlobalUni as StringToHGlobalAuto converts to ANSI and the API expects Unicode.
0
 
LVL 2

Author Comment

by:TrialWorks
ID: 23600682
That sounds right. Any idea how to marshal the array of pointers into unmanaged memory?

I will use StringToHGlobalUni instead of StringToHGlobalAuto.

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 8

Assisted Solution

by:davesgonebananas
davesgonebananas earned 2000 total points
ID: 23600854

Function Pin(ByVal hwndParent As Integer, _   
        ByVal <MarshalAs(UnmanagedType.LPArray, SizeParamIndex:=2)>rgpszPaths As IntPtr(), _   
        ByVal cPaths As UInt32, _   
        ByVal bDeep As Boolean, _   
        ByVal bAsync As Boolean, _   
        ByVal dwPinControlFlags As PinControlFlags, _   
        ByVal pIProgress As IntPtr) As Integer  Function Pin(ByVal hwndParent As Integer, _   
        ByVal rgpszPaths As IntPtr(), _   
        ByVal cPaths As UInt32, _   
        ByVal bDeep As Boolean, _   
        ByVal bAsync As Boolean, _   
        ByVal dwPinControlFlags As PinControlFlags, _   
        ByVal pIProgress As IntPtr) As Integer  

Open in new window

0
 
LVL 8

Expert Comment

by:davesgonebananas
ID: 23600864
I think the correct way is to use MarshalAsAttribute as per http://msdn.microsoft.com/en-us/library/z6cfh6e6.aspx#cpcondefaultmarshalingforarraysanchor2
0
 
LVL 2

Author Comment

by:TrialWorks
ID: 23602210
I've implemented your suggestions and I no longer get the System.AccessViolationException. However the Pin method executes immediately without any errors and does not actually make the folders available offline. The same behavior occurs if I populate the strings array with empty strings rather than with  actual valid UNC paths. This suggests that the COM method is not reading the UNC paths because they are not being sent properly. Below is my current Pin method definition and all the other variations I've tried without any success.
    Function Pin(ByVal hwndParent As Integer, _
        <MarshalAs(UnmanagedType.LPArray)> ByVal rgpszPaths As IntPtr(), _
        ByVal cPaths As UInt32, _
        ByVal bDeep As Boolean, _
        ByVal bAsync As Boolean, _
        ByVal dwPinControlFlags As PinControlFlags, _
        ByVal pIProgress As IntPtr) As Integer
 
 
    '=== Other unsuccessful variations of marshalling the Array of pointers parameter ===
    '   ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, SizeParamIndex:=2)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, SizeParamIndex:=1)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.LPWStr)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.FunctionPtr, SizeParamIndex:=1)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.FunctionPtr, SizeParamIndex:=0)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.FunctionPtr, SizeParamIndex:=2)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.FunctionPtr)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.SysInt, SizeParamIndex:=2)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.SysInt, SizeParamIndex:=0)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.SysInt, SizeParamIndex:=1)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.SysInt)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.SysUInt)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.SysUInt, SizeParamIndex:=1)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.SysUInt, SizeParamIndex:=0)> ByVal rgpszPaths As IntPtr(), _
    '   <MarshalAs(UnmanagedType.LPArray, ArraySubType:=UnmanagedType.SysUInt, SizeParamIndex:=2)> ByVal rgpszPaths As IntPtr(), _

Open in new window

0
 
LVL 2

Accepted Solution

by:
TrialWorks earned 0 total points
ID: 23716671
The correct Pin method definition is the same as I had before (Thanks davesgonebananas for your help). The problem with the Pin method executing immediately without any errors and not actually making the folders available offline was due to the way it was being called. After a call to MS they finally figured out that the flag PinControlFlags.OFFLINEFILES_PIN_CONTROL_FLAG_FORUSER need it to be specified.
In case anyone is interested below is the working code.
'====Here is the code that calls the Pin method  =====
        Dim RetVal As Integer  
        Dim strArray(1) As String  
        strArray(0) = "\\TestServer\TestShare\Folders\1"  
        strArray(1) = "\\TestServer\TestShare\Folders\2"  
  
        Dim Pointers() As IntPtr = StringsToPointers(strArray)   
        Try  
        '
            RetVal = iOFC.Pin(0, Pointers, Pointers.Length, True, False, PinControlFlags.OFFLINEFILES_PIN_CONTROL_FLAG_FILL + PinControlFlags.OFFLINEFILES_PIN_CONTROL_FLAG_FORUSER, Nothing)   
        Catch ex As Exception   
            MsgBox("Error executing API Call." & vbCrLf & ex.Message, MsgBoxStyle.Critical)   
        Finally  
            FreeMemory(Pointers)   
        End Try  
 
 
'====Here is the function that converts an array of strings into pointers to unmanaged memory =====
    Private Function StringsToPointers(ByVal strArray As String()) As IntPtr()
        Dim Pointers(strArray.Length - 1) As IntPtr
 
        Dim index As Integer = 0
        For Each str As String In strArray
            Try
                'Pointers.SetValue(Marshal.StringToCoTaskMemAuto(str), index)
                'Pointers.SetValue(Marshal.StringToHGlobalAuto(str), index)
                Pointers.SetValue(Marshal.StringToHGlobalUni(str), index)
            Catch ex As Exception
                MsgBox("Error in StringsToPointers(): " & ex.Message)
            End Try
 
            index = index + 1
        Next
        Return Pointers
    End Function
 
 
'==== Here is the code that defines the IOfflineFilesCache interface (http://msdn.microsoft.com/en-us/library/bb530486(VS.85).aspx) ====
 
 
Imports System
Imports System.Runtime.InteropServices
 
<Guid("855d6203-7914-48b9-8d40-4c56f5acffc5")> <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _
Public Interface IOfflineFilesCache
    Function Synchronize(ByVal hwndParent As Integer, _
        ByVal rgpszPaths As IntPtr(), _
        ByVal cPaths As UInt32, _
        ByVal bAsync As Boolean, _
        ByVal dwSyncControl As OFFLINEFILES_SYNC_CONTROL, _
        ByVal pISyncConflictHandler As Object, _
        ByVal pIProgress As Object, _
        ByVal pSyncId As Guid) As Integer
 
    Function DeleteItems(ByVal rgpszPaths As IntPtr(), _
        ByVal cPaths As UInt32, _
        ByVal dwFlags As OFFLINEFILES_DELETE_FLAG, _
        ByVal bAsync As Boolean, _
        ByVal pIProgress As IntPtr) As Integer
 
 
    Function DeleteItemsForUser(ByVal pszUser As String, _
        ByVal rgpszPaths As IntPtr(), _
        ByVal cPaths As UInt32, _
        ByVal dwFlags As OFFLINEFILES_DELETE_FLAG, _
        ByVal bAsync As Boolean, _
        ByVal pIProgress As IntPtr) As Integer
 
   
    Function Pin(ByVal hwndParent As Integer, _
        <MarshalAs(UnmanagedType.LPArray)> ByVal rgpszPaths As IntPtr(), _
        ByVal cPaths As UInt32, _
        ByVal bDeep As Boolean, _
        ByVal bAsync As Boolean, _
        ByVal dwPinControlFlags As PinControlFlags, _
        ByVal pIProgress As IntPtr) As Integer
 
    Function Unpin(ByVal hwndParent As Integer, _
        <MarshalAs(UnmanagedType.LPArray)> ByVal rgpszPaths As IntPtr(), _
        ByVal cPaths As UInt32, _
        ByVal bDeep As Boolean, _
        ByVal bAsync As Boolean, _
        ByVal dwPinControlFlags As PinControlFlags, _
        ByVal pIProgress As IntPtr) As Integer
 
    Function GetEncryptionStatus(ByRef pbEncrypted As Boolean, _
        ByRef pbPartial As Boolean) As Integer
 
    Function Encrypt(ByVal hwndParent As Integer, _
        ByVal bEncrypt As Boolean, _
        ByVal dwEncryptionControlFlags As OFFLINEFILES_ENCRYPTION_CONTROL, _
        ByVal bAsync As Boolean, _
        ByVal pIProgress As IntPtr) As Integer
 
    Function FindItem(ByVal pszPath As String, _
        ByVal dwQueryFlags As OFFLINEFILES_ITEM_QUERY, _
        ByRef ppItem As IntPtr) As Integer
 
    Function FindItemEx(ByVal pszPath As String, _
        ByVal pIncludeFileFilter As IntPtr, _
        ByVal pIncludeDirFilter As IntPtr, _
        ByVal pExcludeFileFilter As IntPtr, _
        ByVal pExcludeDirFilter As IntPtr, _
        ByVal dwQueryFlags As OFFLINEFILES_ITEM_QUERY, _
        ByRef ppItem As IntPtr) As Integer
 
    Function RenameItem(ByVal pszPathOriginal As String, _
        ByVal pszPathNew As String, _
        ByVal bReplaceIfExists As Boolean) As Integer
 
    Function GetLocation(ByRef ppszPath As IntPtr) As Integer
 
    Function GetDiskSpaceInformation(ByRef pcbVolumeTotal As Long, _
        ByRef pcbLimit As Long, _
        ByRef pcbUsed As Long, _
        ByRef pcbUnpinnedLimit As Long, _
        ByRef pcbUnpinnedUsed As Long) As Integer
 
    Function SetDiskSpaceLimits(ByVal cbLimit As Long, _
        ByVal cbUnpinnedLimit As Long) As Integer
 
    Function ProcessAdminPinPolicy(ByVal pPinProgress As IntPtr, _
        ByVal pUnpinProgress As IntPtr) As Integer
 
    Function GetSettingObject(ByVal pszSettingName As String, _
        ByRef ppSetting As IntPtr) As Integer
 
    Function EnumSettingObjects(ByRef ppEnum As IntPtr) As Integer
 
    Function IsPathCacheable(ByVal pszPath As String, _
        ByRef pbCacheable As Boolean, _
        ByRef pShareCachingMode As OFFLINEFILES_CACHING_MODE) As Integer
End Interface
 
Public Enum OFFLINEFILES_CACHING_MODE
    OFFLINEFILES_CACHING_MODE_NONE = 0
    OFFLINEFILES_CACHING_MODE_NOCACHING = 1
    OFFLINEFILES_CACHING_MODE_MANUAL = 2
    OFFLINEFILES_CACHING_MODE_AUTO_DOC = 3
    OFFLINEFILES_CACHING_MODE_AUTO_PROGANDDOC = 4
End Enum
 
Public Enum OFFLINEFILES_SYNC_CONTROL
    OFFLINEFILES_SYNC_CONTROL_FLAG_FILLSPARSE = &H1
    OFFLINEFILES_SYNC_CONTROL_FLAG_SYNCIN = &H2
    OFFLINEFILES_SYNC_CONTROL_FLAG_SYNCOUT = &H4
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINNEWFILES = &H8
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINLINKTARGETS = &H10
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINFORUSER = &H20
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINFORUSER_POLICY = &H40
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINFORALL = &H80
    OFFLINEFILES_SYNC_CONTROL_FLAG_PINFORREDIR = &H100
    OFFLINEFILES_SYNC_CONTROL_FLAG_LOWPRIORITY = &H200
    OFFLINEFILES_SYNC_CONTROL_FLAG_ASYNCPROGRESS = &H400
    OFFLINEFILES_SYNC_CONTROL_FLAG_INTERACTIVE = &H800
    OFFLINEFILES_SYNC_CONTROL_FLAG_CONSOLE = &H1000
    OFFLINEFILES_SYNC_CONTROL_FLAG_SKIPSUSPENDEDDIRS = &H2000
    OFFLINEFILES_SYNC_CONTROL_FLAG_BACKGROUND = &H10000
    OFFLINEFILES_SYNC_CONTROL_CR_MASK = &HF0000000
    OFFLINEFILES_SYNC_CONTROL_CR_DEFAULT = &H0
    OFFLINEFILES_SYNC_CONTROL_CR_KEEPLOCAL = &H10000000
    OFFLINEFILES_SYNC_CONTROL_CR_KEEPREMOTE = &H20000000
    OFFLINEFILES_SYNC_CONTROL_CR_KEEPLATEST = &H30000000
End Enum
 
Public Enum OFFLINEFILES_DELETE_FLAG
    OFFLINEFILES_DELETE_FLAG_NOAUTOCACHED = &H1
    OFFLINEFILES_DELETE_FLAG_NOPINNED = &H2
    OFFLINEFILES_DELETE_FLAG_DELMODIFIED = &H4
    OFFLINEFILES_DELETE_FLAG_ADMIN = &H80000000
End Enum
 
Public Enum PinControlFlags
    OFFLINEFILES_PIN_CONTROL_FLAG_FILL = &H1
    OFFLINEFILES_PIN_CONTROL_PINLINKTARGETS = &H10
    OFFLINEFILES_PIN_CONTROL_FLAG_FORUSER = &H20
    OFFLINEFILES_PIN_CONTROL_FLAG_FORUSER_POLICY = &H40
    OFFLINEFILES_PIN_CONTROL_FLAG_FORALL = &H80
    OFFLINEFILES_PIN_CONTROL_FLAG_FORREDIR = &H100
    OFFLINEFILES_PIN_CONTROL_FLAG_LOWPRIORITY = &H200
    OFFLINEFILES_PIN_CONTROL_FLAG_ASYNCPROGRESS = &H400
    OFFLINEFILES_PIN_CONTROL_FLAG_INTERACTIVE = &H800
    OFFLINEFILES_PIN_CONTROL_FLAG_CONSOLE = &H1000
    OFFLINEFILES_PIN_CONTROL_FLAG_BACKGROUND = &H10000
End Enum
 
Public Enum OFFLINEFILES_ENCRYPTION_CONTROL
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_LOWPRIORITY = &H200
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_ASYNCPROGRESS = &H400
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_INTERACTIVE = &H800
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_CONSOLE = &H1000
    OFFLINEFILES_ENCRYPTION_CONTROL_FLAG_BACKGROUND = &H10000
End Enum
 
Public Enum OFFLINEFILES_ITEM_QUERY
    OFFLINEFILES_ITEM_QUERY_REMOTEINFO = &H1
    OFFLINEFILES_ITEM_QUERY_CONNECTIONSTATE = &H2
    OFFLINEFILES_ITEM_QUERY_ADMIN = &H80000000
End Enum

Open in new window

0
 

Expert Comment

by:evegter
ID: 37131611
Hello!
This thread seems very usefull but unfortunately my Visual Studio expertise is limited.
Basically everything I want to do is in here, but using the final code TrainWorks post above, I don't have a definition of the iOFC object.
If I add "Dim iOFC as IOfflineFilesCache" it throws a warning "Variable 'iOFC' is used before it has been assigned a value. A null reference exception could result at runtime.".
And while executing the code in a simple form with an inputbox and a button that calls the pin-method I get object not set to an instance of an object.

Can anyone tell me how to properly use the interface definition IOfflineFilesCache to get the iOFC object?

Thanks a lot!!

The end goal I wish to achieve is a GUI utility that supersedes the Windows 7 Offline Files "management" utility in functionality. I run into the situation that some network-locations (also printers) end up in our offline files cache and when trying to delete them nothing happens. Maybe nothing happens using my own application too when I unpin (forced or not), but at least I hope te get some more information back then...

best regards,

Eric
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Loops Section Overview

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question