How to access finder sidebar shared content in cocoa - macos

I want to access the shared content of left sidebar of finder in mac, so that i can get the system list connected to the same network. I can access favorite content, but could not get succeeded to access.
I am using this code to access favorite content of finder.
UInt32 seed;
LSSharedFileListRef sflRef = LSSharedFileListCreate(NULL,
kLSSharedFileListFavoriteItems,
NULL);
CFArrayRef items = LSSharedFileListCopySnapshot( sflRef, &seed );
for( size_t i = 0; i < CFArrayGetCount(items); i++ )
{
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(items, i);
if( !item )
continue;
CFURLRef outURL = NULL;
LSSharedFileListItemResolve( item, kLSSharedFileListNoUserInteraction, (CFURLRef*) &outURL, NULL );
if( !outURL )
continue;
//The actual path string of the item
CFStringRef itemPath = CFURLCopyFileSystemPath(outURL,kCFURLPOSIXPathStyle);
// TODO: Do whatever you want to do with your path here!!!!
CFRelease(outURL);
CFRelease(itemPath);
}
CFRelease(items);
CFRelease(sflRef);
Since i want to access systems available in shared network i change the key according to the key in the header file
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.fram‌​ework/Headers/LSSharedFileList.h
But i get nothing for shared content.
Can anyone help me for accessing this.
Thanks for your time to help me in advance.

You can use kLSSharedFileListRecentServerItems to get Recently connected network volumes.

Related

How can we open a hard drive using kernel extension in Mac OSx?

I am trying to open(access) a volume of hard drive using below code in app.
int mode=0;
int hd_h=-1;
const char* device = "/dev/rdisk1”
mode=O_RDWR|mode_basic;
hd_h = open(device, mode);
When I executed above code it returns error "Operation not permitted". Then I searched how it can be achieved and found one answer using kext we can achieve it. I created a sample kext(driver) to access harddrive in kernel space. can anybody assist how can I open volume in kext and return to user space. I have created a IOUserClient subclass and calling IOServiceOpen() in user space .
CFDictionaryRef matchingDict = NULL;
io_iterator_t iter = 0;
io_service_t service = 0;
kern_return_t kr;
// Create a matching dictionary that will find any USB device
matchingDict = IOServiceMatching("com_osxkernel_driver_IOKitTest");
// Create an iterator for all IO Registry objects that match the dictionary
kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter);
if (kr != KERN_SUCCESS)
return -1;

Find com-port used by serial mouse

How to find which com-port is occupied by serial mouse
Here is how I detect mouse in C# (adapted code from this answer)
var info = IntPtr.Zero;
try
{
var guid = new Guid("{4d36e96f-e325-11ce-bfc1-08002be10318}"); // mouses
info = SetupDiGetClassDevsW(ref guid, null, IntPtr.Zero, 0);
if ((int)info == -1) // INVALID_HANDLE_VALUE
throw new Exception(string.Format("Error({0}) SetupDiGetClassDevsW", Marshal.GetLastWin32Error()));
// enumerate mouses
var device = new SP_DEVINFO_DATA();
device.cbSize = (UInt32)Marshal.SizeOf(device);
for (uint i = 0; ; i++)
{
// get device info
if (!SetupDiEnumDeviceInfo(info, i, out device))
{
var error = Marshal.GetLastWin32Error();
if (error == 259) // ERROR_NO_MORE_ITEMS
break;
else
throw new Exception(string.Format("Error({0}) SetupDiEnumDeviceInfo", error));
}
string id = GetStringPropertyForDevice(info, device, 1); // SPDRP_HARDWAREID
if (id != null && id.Contains("*PNP0F09")) // Microsoft BallPoint Serial Mouse
{
// ...
// here I want to check com-port, how?
// ...
}
}
}
finally
{
if (info != IntPtr.Zero)
SetupDiDestroyDeviceInfoList(info);
}
Edit
Removing C# tag. Looking for general info (any language).
You can use Process Monitor from SysInternalSuite and open device manager then find out from where does the device manager getting its values
I tried it on USB Mouse and was able to get (on USB Input Device) as shown below
1. Open Mouse Properties (From Control Panel)
2. Open ProcMon
3. Click on the target icon and choose the mouse properties window
4. From the Mouse Properties window open the Hardware tab
5. In ProcMon Click on File-> Captuer Events
6. In ProcMon Edit->Find and look for "com" without quotation mark
7. Double click the found row (If you where able to find it)
Another solution would be to get device information using device manager command line utility devcon and parse the information from the output stream
More information on devcon:
* http://support.microsoft.com/kb/311272
* https://superuser.com/questions/414280/how-do-i-view-a-list-of-devices-from-the-command-line-in-windows
Hope this help
The subroutine that generates the "Location" string in Device Manager is devmgr.dll!GetLocationInformation.
The path in it that interests you - generating the value that is appended in brackets - can be represented with the following code (based on Hex-Rays' decompilation):
int __stdcall GetLocationInformation(DEVINST dnDevInst, wchar_t *lpsResult,
int cchBufferMax, HMACHINE hMachine)
{
int dwUiNumber;
HKEY hKey;
DWORD pulLength;
wchar_t sRawLocationInfo[260];
sRawLocationInfo[0] = 0;
DWORD Type = REG_SZ;
pulLength = 520;
if ( !CM_Open_DevNode_Key_Ex(dnDevInst, KEY_READ, 0, 1u, &hKey, 1u, hMachine) )
{
RegQueryValueExW(hKey, L"LocationInformationOverride", 0, &Type,
sRawLocationInfo, &pulLength);
RegCloseKey(hKey);
}
if ( !sRawLocationInfo[0] )
{
pulLength = 520;
CM_Get_DevNode_Registry_Property_ExW(
dnDevInst,
CM_DRP_LOCATION_INFORMATION,
0,
sRawLocationInfo,
&pulLength,
0,
hMachine);
}
pulLength = 4;
if ( CM_Get_DevNode_Registry_Property_ExW(
dnDevInst,
CM_DRP_UI_NUMBER,
0,
&dwUiNumber,
&pulLength,
0,
hMachine)
|| pulLength <= 0 )
{
<...> //this block always returns
}
else
{
<...>
if ( sRawLocationInfo[0] )
{
lstrcatW(lpsResult, L" (");
lstrcatW(lpsResult, sRawLocationInfo);
lstrcatW(lpsResult, L")");
}
return 0;
}
}
In a nutshell, the bracketed value is the device node's LocationInformationOverride or LocationInformation property and is only produced if the UiNumber property is absent (or bogus).
The CM_Open_DevNode_Key_Ex and CM_Get_DevNode_Registry_Property_ExW functions are marked "reserved" in the docs. You can
find their signatures e.g. in CM_Open_DevNode_Key_Ex - FileLog and Enumerate Properties of an Installed Device - The Code Project, respectively, or
use the publicly-documented CM_Open_DevNode_Key and CM_Get_DevNode_Registry_Property instead. They are exactly the same as the former ones save for missing the hMachine argument (they essentially directly call them substituting NULL for it).
There are corresponding SetupDi equivalents, SetupDiOpenDevRegKey and SetupDiGetDeviceRegistryProperty, as well but note that this API is new in Vista and uses different data types.
Seeing that you use it already though means that this is probably the way to go for you unless you need XP support.
If my guess is right, the "USB Serial Port (COM6)" you see in Device Manager is actually the name of the parent device (=the device this one is connected to as seen in Device Manager in "view devices by connection" mode). If this is correct, the "COM6" is but a part of the name rather than some independent property.

Which WinAPI function checks permissions of a specific file/folder? [duplicate]

In win32 c++; is there a way to determine if a folder/file is accessible? You know how if you try to access a certain folder in the C:/Windows directory & you will get a popup saying "This folder is not accessible".
Maybe there is a file attribute constant that signifies that the file is private? Maybe something like FILE_ATTRIBUTE_PRIVATE?
WIN32_FIND_DATA dirData;
while (FindNextFile( dir, &dirData ) != 0 )
{
// I made the following constant up
if ( !(fileData.dwFileAttributes & FILE_ATTRIBUTE_PRIVATE) )
{
// file is accessible so store filepath
files.push_back( fileData.cFileName );
}
else // file is not accessible so dont store
}
Or is the only way to know by going:
dir = FindFirstFileEx( (LPCTSTR)directory.c_str(), FindExInfoStandard, &dirData, FindExSearchNameMatch, NULL, 0 );
if ( dir == ??? ) { the file is inaccessible } [/code]
Best thing to do is just try to access it.
You can calculate the access granted by the access control list for a particular user account, but this is quite complicated, and the permission could change after you do the access check. So just open the file and handle access denied errors.
It wouldn't be a flag on the file itself because different accounts may have access to different files/directories. Instead, windows uses ACL's (access control lists), which are data structures that determine who has access to what.
ACLs in windows can be used with just about anything that is referred to by a handle (files, directories, processes, mutexes, named pipes...). You can view file ACLs by going to properties of a file and view "Security" tab.
So in your app you don't really want to check for a flag, but to compare file's ACL against the user account under which your app is running. Check out AccessCheck Win32 function. I think it's exactly what you are looking for.
Personally, I've never used that function, but if you are looking for Win32 solution and you want a function call, that's probably your best bet. However, as others have pointed out, it might be too complicated. I've always used _access (or _waccess) which is part of CRT, uber easy to use, and you don't take a performance hit of acquiring a file handle only to close it (depending on how tight your loop is, those calls can actually add up).
int _access(
const char *path,
int mode
);
Simple to use:
http://msdn.microsoft.com/en-us/library/1w06ktdy%28v=vs.80%29.aspx
Yes Aaron Ballman you are a boss! Oh man oh man! Which I could use some useful expletives to expressives my joy right now.
https://blog.aaronballman.com/2011/08/how-to-check-access-rights/ is a link to the example of checking accesss rights in win32 on a fpath. And the explanation behind the poorly documented AccessCheck win32 function. Below is the code.
bool canAccessPath( LPCTSTR folderName, DWORD genericAccessRights )
{
bool bRet = 0;
DWORD length = 0;
if (!::GetFileSecurity( folderName, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, NULL, 0, &length ) &&
ERROR_INSUFFICIENT_BUFFER == ::GetLastError())
{
PSECURITY_DESCRIPTOR security = static_cast< PSECURITY_DESCRIPTOR >( ::malloc( length ) );
if (security && ::GetFileSecurity( folderName, OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION, security, length, &length ))
{
HANDLE hToken = NULL;
if (::OpenProcessToken( ::GetCurrentProcess(), TOKEN_IMPERSONATE|TOKEN_QUERY|TOKEN_DUPLICATE|STANDARD_RIGHTS_READ, &hToken ))
{
HANDLE hImpersonatedToken = NULL;
if (::DuplicateToken( hToken, SecurityImpersonation, &hImpersonatedToken ))
{
GENERIC_MAPPING mapping = { 0xFFFFFFFF };
PRIVILEGE_SET privileges = { 0 };
DWORD grantedAccess = 0, privilegesLength = sizeof( privileges );
BOOL result = FALSE;
mapping.GenericRead = FILE_GENERIC_READ;
mapping.GenericWrite = FILE_GENERIC_WRITE;
mapping.GenericExecute = FILE_GENERIC_EXECUTE;
mapping.GenericAll = FILE_ALL_ACCESS;
::MapGenericMask( &genericAccessRights, &mapping );
if (::AccessCheck( security, hImpersonatedToken, genericAccessRights,
&mapping, &privileges, &privilegesLength, &grantedAccess, &result ))
{
bRet = result == TRUE;
}
::CloseHandle( hImpersonatedToken );
}
::CloseHandle( hToken );
}
::free( security );
}
}
return bRet;
}
Don't be shy to pop into his website and check out his work. I am sure he has more interesting stuff.

How to get users mail addresses on OS X Lion?

I was getting the users mail addresses from Libraray/Preferences/com.apple.mail.plist. They are not there any more in Lion :P Do I have to use scripting bridge? Any hints? Thanks
I would get them right out of Address Book. That should work regardless of what email app is being used.
// Find 'me' card in address book.
ABPerson* meCard = [[ABAddressBook sharedAddressBook] me];
if( meCard == nil ) {
NSLog( #"Could not find me!" );
return;
}
// Get my email addresses.
ABMultiValue* anEmailList = [meCard valueForProperty:kABEmailProperty];
if( anEmailList == nil ) {
NSLog( #"I have no email!" );
return;
}
// Output them.
for( NSUInteger index = 0; index < [anEmailList count]; index++ ) {
NSString* aLabel = [anEmailList labelAtIndex:index];
NSString* aValue = [anEmailList valueAtIndex:index];
NSLog( #"%#: %#", aLabel, aValue );
}
Mail in Lion stores the equivalent in ~/Library/Mail/V2/MailData/Accounts.plist. Note however that you are assuming that the user uses the Apple Mail program, unless that's what you really need you may want to have alternative methods for getting the address. You may for instance depending on how the system has been set up use the CSIdentity APIs, such as CSIdentityGetEmailAddress().
Apple script will get the job done.

Windows 7 - Taskbar - Pin or Unpin Program Links

As in title, is there any Win32 API to do that?
Don't do this.
I'm 99% sure there isn't an official API for it, for exactly the same reason that there wasn't programmatic access to the old Start Menu's pin list.
In short, most users don't want programs putting junk in their favorites, quick launch, taskbar, etc. so Windows doesn't support you doing as such.
I'm trying to implement a VirtuaWin (opensource virtual desktop software) plugin that allows me to pin different buttons to different virtual desktops. Completely valid reason to use this.
Found the way to pin/unpin it already:
Following code snippet is taken from Chromium shortcut.cc file, nearly unchanged, see also the ShellExecute function at the MSDN
bool TaskbarPinShortcutLink(const wchar_t* shortcut) {
int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarpin", shortcut,
NULL, NULL, 0));
return result > 32;
}
bool TaskbarUnpinShortcutLink(const wchar_t* shortcut) {
int result = reinterpret_cast<int>(ShellExecute(NULL, L"taskbarunpin",
shortcut, NULL, NULL, 0));
return result > 32;
}
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Seems pretty straightforward if you know the shortcut. For me though this is not sufficient, I also need to iterate over existing buttons and unpin and repin them on different desktops.
In the comments of a Code Project article it says all you have to do is create a symbolic link in the folder "C:\Users\Username\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar".
But it appears to generally be unsociable practice, as the other comments here have noted.
You can pin/unpin apps via Windows Shell verbs:
http://blogs.technet.com/deploymentguys/archive/2009/04/08/pin-items-to-the-start-menu-or-windows-7-taskbar-via-script.aspx
For API, there is a script-friendly COM library for working with the Shell:
http://msdn.microsoft.com/en-us/library/bb776890%28VS.85%29.aspx
Here is an example written in JScript:
// Warning: untested and probably needs correction
var appFolder = "FOLDER CONTAINING THE APP/SHORTCUT";
var appToPin = "FILENAME OF APP/SHORTCUT";
var shell = new ActiveXObject("Shell.Application");
var folder = shell.NameSpace(appFolder);
var folderItem = folder.ParseName(appToPin);
var itemVerbs = folderItem.Verbs;
for(var i = 0; i < itemVerbs.Count; i++)
{
// You have to find the verb by name,
// so if you want to support multiple cultures,
// you have to match against the verb text for each culture.
if(itemVerbs[i].name.Replace(/&/, "") == "Pin to Start Menu")
{
itemVerbs[i].DoIt();
}
}
Just to put some links on the info as microsoft now offer an official documentation on "Taskbar Extensions" :
A small set of applications are pinned
by default for new installations.
Other than these, only the user can
pin further applications; programmatic
pinning by an application is not
permitted.
So Kevin Montrose answer is the correct one : DON'T.
It works, but not for all OS, e.g. Windows 10:
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string dllName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int LoadString(IntPtr hInstance, uint uID, StringBuilder lpBuffer, int nBufferMax);
private static void PinUnpinTaskBar(string filePath, bool pin)
{
if (!File.Exists(filePath))
throw new FileNotFoundException(filePath + " not exists!");
int MAX_PATH = 255;
var actionIndex = pin ? 5386 : 5387; // 5386 is the DLL index for"Pin to Tas&kbar", ref. http://www.win7dll.info/shell32_dll.html
StringBuilder szPinToStartLocalized = new StringBuilder(MAX_PATH);
IntPtr hShell32 = LoadLibrary("Shell32.dll");
LoadString(hShell32, (uint)actionIndex, szPinToStartLocalized, MAX_PATH);
string localizedVerb = szPinToStartLocalized.ToString();
// create the shell application object
dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
string path = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
dynamic directory = shellApplication.NameSpace(path);
dynamic link = directory.ParseName(fileName);
dynamic verbs = link.Verbs();
for (int i = 0; i < verbs.Count(); i++)
{
dynamic verb = verbs.Item(i);
if ((pin && verb.Name.Equals(localizedVerb)) || (!pin && verb.Name.Contains(localizedVerb)))
{
verb.DoIt();
break;
}
}
}
I found there is no offical API to do that, but someone has do it through VBScript.
http://blog.ananthonline.net/?p=37
Thanks.
this folder contains shortcut of pinned application
C:\Users\Your-User-Name\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar

Resources