Looking to write Bluetooth 'hcitool' equivelant in Windows - windows

I have used Bluez Bluetooth stack in Linux which comes with a handy utility 'hcitool'. Looking to build something like that in Windows with same or equivalent functionality. Specifically, 'hcitool name < MAC >', which shows if the specified device is within range.
Any guidance will be appreciated.
I have Windows SDK v7 with Visual Studio 2010, using C/C++
thanks.

Using my 32feet.NET library something like the following.
EDIT 3rd March: I've now added code to directly lookup the device by address rather than by using device discovery; so that's a simple 'new BluetoothDeviceInfo(...)'.
See if that finds the device you want. This requires the remote device to only be in "Connectable" mode whereas the former requires it to be in "Discoverable" mode. (BTW I've left the discovery code in place.)
EDIT 8th March: Now does a connect (using the SDP API) to check that the device is in range (and in connectable mode).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using System.Diagnostics;
using System.Net.Sockets;
namespace hcitool
{
partial class Program
{
static bool infoRatherThanName;
static BluetoothAddress _searchAddress;
static int Main(string[] args)
{
if (args.Length < 1) {
Console.WriteLine("Please specify command.");
return 2;
}
var cmd = args[0];
switch (cmd) {
case "name":
infoRatherThanName = false;
break;
case "info":
infoRatherThanName = true;
break;
//-
case "dev":
return ShowRadios();
//case "auth":
// return CauseAuth(GETADDRESS());
default:
throw new NotImplementedException("Command: '" + cmd + "'");
}
if (args.Length < 2) {
Console.WriteLine("Please specify device address.");
return 2;
}
var addrS = args[1];
_searchAddress = BluetoothAddress.Parse(addrS);
//
var dev = new BluetoothDeviceInfo(_searchAddress);
bool isInRange = GetCanConnectTo(dev);
if (isInRange) {
PrintDevice(dev);
} else {
Console.WriteLine("Can't see that device.");
}
//
Console.WriteLine("simple");
return Simple();
//return Fancier();
}
//----
private static int ShowRadios()
{
BluetoothRadio[] list;
try {
list = BluetoothRadio.AllRadios;
} catch (Exception) {
return 1;
}
Debug.Assert(list.Length != 0, "Expect zero radios case to raise an error.");
foreach (var curR in list) {
Console.WriteLine("* {0} '{1}'", curR.LocalAddress, curR.Name);
Console.WriteLine("{0}", curR.SoftwareManufacturer);
Console.WriteLine("{0}", curR.Manufacturer);
Console.WriteLine("{0}", curR.Mode);
}//for
return 0;
}
private static int CauseAuth(BluetoothAddress addr)
{
BluetoothSecurity.PairRequest(addr, null);
return 0;
}
//----
static int Simple()
{
BluetoothDeviceInfo[] devices;
BluetoothDeviceInfo foundDev = null;
var cli = new BluetoothClient();
// Fast: Remembered/Authenticated
devices = cli.DiscoverDevices(255, true, true, false, false);
SimpleCheckDevice(devices, ref foundDev);
if (foundDev == null) {
// Slow: Inquiry
cli.DiscoverDevices(255, false, false, true, false);
SimpleCheckDevice(devices, ref foundDev);
}
//
if (foundDev != null) {
return 0;
} else {
return 1;
}
}
private static void SimpleCheckDevice(IEnumerable<BluetoothDeviceInfo> devices,
ref BluetoothDeviceInfo foundDev)
{
foreach (var cur in devices) {
if (cur.DeviceAddress == _searchAddress) {
foundDev = cur;
PrintDevice(cur);
}
}//for
}
private static void PrintDevice(BluetoothDeviceInfo cur)
{
Console.WriteLine("* Found device: '{0}' ", cur.DeviceName);
if (infoRatherThanName) {
try {
var vs = cur.GetVersions();
Console.WriteLine(vs.Manufacturer);
Console.WriteLine(vs.LmpVersion);
Console.WriteLine(vs.LmpSubversion);
Console.WriteLine(vs.LmpSupportedFeatures);
} catch (Exception ex) {
Console.WriteLine("Failed to get remote device versions info: "
+ ex.Message);
}
}
}
//----
private static bool GetCanConnectTo(BluetoothDeviceInfo device)
{
bool inRange;
Guid fakeUuid = new Guid("{F13F471D-47CB-41d6-9609-BAD0690BF891}");
try {
ServiceRecord[] records = device.GetServiceRecords(fakeUuid);
Debug.Assert(records.Length == 0, "Why are we getting any records?? len: " + records.Length);
inRange = true;
} catch (SocketException) {
inRange = false;
}
return inRange;
}
}
}

Related

ZKEmkeeper: Events not triggering on Windows Service

I'm stucked for a while trying to use zkemkeeper sdk to use on a Windows Service that uses a InBios(Controller) for fingerprint.
i first connect to the device and then i add the event OnAttTransactionEx, someone can point me what i'm doing wrong.
Here is the code snippet
`
protected override void OnStart(string[] args)
{
Thread TT = new Thread(new ThreadStart(WorkedThread));
TT.IsBackground = true;
TT.SetApartmentState(ApartmentState.STA);
this.isServiceStarted = true;
TT.Start();
}
private void WorkedThread()
{
WriteToFile("Worker Thread Started.");
ZKemClient objZkeeper = new ZKemClient(filepath);
this.isDeviceConnected = objZkeeper.Connect_Net("19x.x.x.24x", 4370);
if (this.isDeviceConnected)
{
WriteToFile("Device connected.");
WriteToFile("While loop execution starting.");
while (true)
{
WriteToFile(filepath, "While loop execution started.");
}
}
else
{
WriteToFile("Failed to connect to Device.");
}
}
// ZMClient class
public bool Connect_Net(string IPAdd, int Port)
{
bool bResult = false;
try
{
// Actual SDK class
CZKEM objCZKEM = new CZKEM();
if (objCZKEM.Connect_Net(IPAdd, Port))
{
if (objCZKEM.RegEvent(1, 32767))
{
// [ Register your events here ]
objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
}
bResult = true;
}
}
catch (Exception ex)
{
WriteToFile("Connect_Net() Exception->" + ex.Message);
}
return bResult;
}
`
After playing a lot with threading, found a solution.
For windows service - Add reference to System.Windows.Forms
Thread TT1 = new Thread(() =>
{
this.objCZKEM = new CZKEM();
Application.Run();
});
TT1.IsBackground = true;
TT1.SetApartmentState(ApartmentState.STA);
TT1.Start();
Simply continue with current thread
if (this.objCZKEM.Connect_Net(IP, 4370))
{
this.WriteToFile("ZKEM device connected");
if (this.objCZKEM.RegEvent(1, 32767))
{
this.WriteToFile("ZKEM device events registration started");
// [ Register your events here ]
this.objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
this.WriteToFile("Done with ZKEM device events registration.");
}
You should not able to receive finger events from device.

using xam.Plugin.DownloadManager Xamarin forms

i am using xam.plugin.downloadmanager to download files in my app,once file download i wnats to redirect to downloads native page to view which i was download from server. is there any way ?? plesae help me
this is my code Anroid main activity class
using Android.OS;
using Plugin.DownloadManager;
using Plugin.DownloadManager.Abstractions;
using Xamarin.Forms.PlatformConfiguration;
using System.Linq;
using System.IO;
namespace Expertential.Droid
{
[Activity(Label = "Expertential", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
Downloaded();
global::Xamarin.Forms.Forms.Init(this, bundle);
Rg.Plugins.Popup.Popup.Init(this, bundle);
LoadApplication(new App());
}
public void Downloaded()
{
CrossDownloadManager.Current.PathNameForDownloadedFile = new System.Func<IDownloadFile, string>(file =>
{
string fileName = Android.Net.Uri.Parse(file.Url).Path.Split('/').Last();
return Path.Combine(ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath, fileName);
});
}
}
}
viewmodel in here iam calling download .netstandard library
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using Expertential.Models;
using Expertential.Services;
using Expertential.ViewModels;
using Plugin.DownloadManager;
using Plugin.DownloadManager.Abstractions;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace Expertential.ViewModels
{
class CustomPopupViewModel :BaseViewModel
{
private CustomPopupViewModelService customPopupViewModelService;
private ObservableCollection<Attachments> attachment;
public ObservableCollection<Attachments> Attachment
{
get { return attachment; }
set
{
attachment = value;
RaisePropertyChanged(nameof(Attachment));
}
}
public CustomPopupViewModel()
{
}
private int _requertAttHeight;
public int requertAttHeight { get { return _requertAttHeight; }
set { _requertAttHeight = value;
RaisePropertyChanged(nameof(requertAttHeight));
}
}
private Boolean _taskLoader;
public Boolean taskLoader
{
get { return _taskLoader; }
set
{
_taskLoader = value;
RaisePropertyChanged(nameof(taskLoader));
}
}
public IDownloadFile File;
Boolean isDownloading = true;
#region custom function
public void GetAttachments(List<Attachments> attachment)
{
Attachment = new ObservableCollection<Attachments>();
if (attachment.Count > 0)
{
foreach (Attachments att in attachment)
{
var title = att.title;
string[] titleArray = title.Split('.');
if (titleArray.Length > 1)
{
setIconVisible(titleArray[1],att);
}
Attachment.Add(att);
}
requertAttHeight = 40 * attachment.Count;
}
}
public void setIconVisible(string content, Attachments att)
{
switch (content)
{
case "png":
case "jpg":
case "jpeg":
att.isWord = false;
att.isExcel = false;
att.isPdf = false;
att.isPpt = false;
att.isImage = true;
break;
case "ppt":
case "pptx":
att.isWord = false;
att.isExcel = false;
att.isPdf = false;
att.isPpt = true;
att.isImage = false;
break;
case "xlsx":
case "xls":
att.isWord = false;
att.isExcel = true;
att.isPdf = false;
att.isPpt = false;
att.isImage = false;
break;
case "docx":
att.isWord = true;
att.isExcel = false;
att.isPdf = false;
att.isPpt = false;
att.isImage = false;
break;
}
}
public async Task<string> GetFileFullUrl(string fileName)
{
var strValue = "";
customPopupViewModelService = new CustomPopupViewModelService();
strValue = await customPopupViewModelService.GetFileFullUrl(fileName);
return strValue;
}
public async void DownloadFile(string FileName)
{
Boolean target = false;
this.taskLoader = true;
var DownloadManager = CrossDownloadManager.Current;
var file = DownloadManager.CreateDownloadFile(FileName);
await Task.Yield();
await Task.Run(() =>
{
DownloadManager.Start(file, true);
while (isDownloading)
{
Task.Delay(100);
isDownloading = IsDownloading(file);
}
});
if (!isDownloading)
{
this.taskLoader = false;
target = await Application.Current.MainPage.DisplayAlert("Alert", "File Download Goto Download page to view", "Ok", "Cancel");
}
if (target)
{
// Device.OpenUri(new Uri("Downloads"));
try
{
await PopupNavigation.Instance.PopAsync();
// here i want to redirect to downloads app ->
// Intent myIntent = new Intent(Android.App.DownloadManager.ActionDownloadComplete);
}
catch (Exception e)
{
//// TODO: handle exception
//String data = e.getMessage();
}
// Environment.GetFolderPath(Environment.SpecialFolder.)
//var x = file.DestinationPathName;
//Device.OpenUri(new Uri(x));
}
}
public Boolean IsDownloading(IDownloadFile file)
{
if (file == null) return false;
switch (file.Status)
{
case DownloadFileStatus.INITIALIZED:
case DownloadFileStatus.PAUSED:
case DownloadFileStatus.PENDING:
case DownloadFileStatus.RUNNING:
return true;
case DownloadFileStatus.COMPLETED:
case DownloadFileStatus.CANCELED:
case DownloadFileStatus.FAILED:
return false;
default:
return false;
}
}
public void AbortDownloading()
{
CrossDownloadManager.Current.Abort(File);
}
#endregion
}
}
My understanding of your question tells me you want to open the default downloads application that Android has and it can be done as follows:
Intent intent = new Intent(DownloadManager.ActionViewDownloads);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
Yes this is what i expected, i accomplished with some changes in your code
Intent intent = new Intent(DownloadManager.ActionViewDownloads);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);

MediaFormat options, the KEY_ROTATION is not work

The current image is encoded and stored in the output buffer as it is.
However, Samsung (Galaxy S6(Nouga), 7(Nouga), 8(Nouga)) KEY_ROTATION option works well,
This option does not work on the Google reference phone (Pixel 2 XL -> Oreo, Nexus 5 -> Lollipop).
In other words, while the KEY_ROTATION option works well on the Samsung device, the value output to the output buffer is rotated,
This option does not work on Google reference phones.
The surface created by encoderSurface () serves as an input buffer
Check the output buffer through onOutputBufferAvailable of MediaCodec.Callback.
Anyone who knows the reason needs help.
Here is the code I wrote.
private final MediaCodec.Callback _mediaCodecCallback = new MediaCodec.Callback() {
#Override
public void finalize(){
}
#Override
public void onInputBufferAvailable(#NonNull MediaCodec mediaCodec, int i) {
}
#Override
public void onOutputBufferAvailable(#NonNull MediaCodec mediaCodec, int i, #NonNull MediaCodec.BufferInfo bufferInfo) {
ByteBuffer buffer = mediaCodec.getOutputBuffer(i);
byte[] outData = new byte[bufferInfo.size];
buffer.get(outData);
mediaCodec.releaseOutputBuffer(i, false);
switch (bufferInfo.flags) {
case MediaCodec.BUFFER_FLAG_CODEC_CONFIG:
if(DEBUG_LOG) {
Log.v(TAG, "CONFIG FRAME");
}
_configFrame = new byte[bufferInfo.size];
System.arraycopy(outData, 0, _configFrame, 0, outData.length);
break;
case MediaCodec.BUFFER_FLAG_KEY_FRAME:
// I Frame;
if(DEBUG_LOG) {
Log.v(TAG, "I FRAME" +
", SIZE = " + bufferInfo.size + ", " + currentDateandTime);
}
try {
_outputFrame.reset();
_outputFrame.write(_configFrame);
_outputFrame.write(outData);
} catch (IOException e) {
e.printStackTrace();
}
break;
default:
// P Frame;
if(DEBUG_LOG) {
Log.v(TAG, "P FRAME" +
", SIZE = " + bufferInfo.size);
}
break;
}
}
//
public boolean initialize(int width,int height) {
try {
_mediaCodec = MediaCodec.createEncoderByType(MIME_TYPE);
} catch (IOException e) {
e.printStackTrace();
return false;
}
MediaCodecInfo codec = selectCodec(MIME_TYPE);
if (codec == null) {
return false;
}
MediaCodecInfo.CodecCapabilities cap = codec.getCapabilitiesForType(MIME_TYPE);
MediaFormat mediaFormat = MediaFormat.createVideoFormat(MIME_TYPE, width, height);
mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 30);
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
mediaFormat.setInteger(MediaFormat.KEY_BIT_RATE, bitRateInfo.getInstance().getBitRate()); // 300000
mediaFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1);
mediaFormat.setInteger(MediaFormat.KEY_ROTATION, 90);
// in under API 21, not use MediaFormat.KEY_ROTATION, but use "rotation-degrees"
// This does not work on a Google reference phone.
_mediaCodec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
_surface = _mediaCodec.createInputSurface();
_mediaCodec.setCallback(_mediaCodecCallback);
_mediaCodec.start();
Log.d(TAG,"Encoder Start SUCCESS");
return true;
}
public Surface encoderSurface() {
//Return the value of this function and use it as the input surface.
return _surface;
}
please Help me ..

Unexpected character ''

Upon migrating from VS2013 to VS2017 i'm running into an unexpected character issue.
Everything builds fine in msbuild 12.0 and VS2013, but when moving to 15.0 I receive hundreds of:
CS1519 Invalid token '?' in class, struct, or interface member declaration
in msbuild command line.
Building inside VS2017 returns:
CS1056 Unexpected character ''
var businessRuleData = principal.GetBusinessRule(​
BusinessRuleEnum.CONTENT_REPOSITORY);
Error occurs at Ch66 which is (B in between that area. The character that is hidden becomes a ? in WordPad. However, as mentioned the same code builds fine in msbuild 12.0. Deletion of all code and re-downloading form TFS didn't solve the issue
Solution Code
Note: Search in code for change_me and make sure to change to whatever your desired items are.
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace FixZeroWidthSpace
{
class Program
{
static void Main(string[] args)
{
// change to your directory
var files = Directory.GetFiles(#"D:\change_me", "*.cs", SearchOption.AllDirectories);
var counter = 0;
var counterEdited = 0;
var totalFiles = files.Length;
var failed = new List<string>();
var found = new List<string>();
TfsTeamProjectCollection tpc = null;
Workspace ws = null;
foreach (var file in files)
{
if(counter % 10 == 0)
{
Console.WriteLine("Searched {0} or {1} files, {2} have been edited.", counter, totalFiles, counterEdited);
}
// change to any folders you want to ignore or remove if none
if (!file.Contains("change_me_ignore_folder_name"))
{
string text = File.ReadAllText(file);
var regex = new Regex("[\u200B-\u200D\uFEFF]");
var newText = regex.Replace(text, "");
if (text != newText)
{
try
{
if (ws == null || tpc == null)
{
// change to your TFS server
tpc = new TfsTeamProjectCollection(new Uri(#"http://change_me_your_tfs_url/tfs/DefaultCollection"));
ws = FindWorkspaceByPath(tpc, file);
}
FileAttributes attributes = File.GetAttributes(file);
if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
File.SetAttributes(file, attributes);
}
ws.PendEdit(file);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make the file RW
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
File.SetAttributes(file, attributes);
}
File.WriteAllText(file, newText);
found.Add(file);
counterEdited++;
}
catch(Exception ex)
{
failed.Add(file);
}
}
}
counter++;
}
tpc.Dispose();
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\found.txt", found);
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\failed.txt", failed);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
private static Workspace FindWorkspaceByPath(TfsTeamProjectCollection tfs, string workspacePath)
{
VersionControlServer versionControl = tfs.GetService<VersionControlServer>();
WorkspaceInfo workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(workspacePath);
if (workspaceInfo != null)
{
return versionControl.GetWorkspace(workspaceInfo);
}
// No Workspace found using method 1, try to query all workspaces the user has on this machine.
Workspace[] workspaces = versionControl.QueryWorkspaces(null, Environment.UserName, Environment.MachineName);
foreach (Workspace w in workspaces)
{
foreach (WorkingFolder f in w.Folders)
{
if (f.LocalItem.Equals(workspacePath))
{
return w;
}
}
}
if (workspaces.Length > 0)
{
return workspaces[0];
}
throw new Exception(String.Format("TFS Workspace cannot be determined for {0}.", workspacePath));
}
}
}
Solution
Remove all invalid characters as MSBuild 15.0 and VS2017 are more strict on these unicode characters.
The following code can be utilized to accomplish the removal of all code in a Folder that is an issue. I utilized this as the changes required were too large to be done by hand.
C# Code
Variables
[Insert Folder to Scan] : Example C:\TFS\Code\Branch\Folder
[Insert Folder To Ignore] : Example 3rdPartyCode
Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace FixZeroWidthSpace
{
class Program
{
static void Main(string[] args)
{
var files = Directory.GetFiles(#"D:\TFS\210-219\212\MCET_212", "*.cs", SearchOption.AllDirectories);
var counter = 0;
var counterEdited = 0;
var totalFiles = files.Length;
var failed = new List<string>();
var found = new List<string>();
foreach (var file in files)
{
if(counter % 10 == 0)
{
Console.WriteLine("Searched {0} or {1} files, {2} have been edited.", counter, totalFiles, counterEdited);
}
if (!file.Contains("[Insert Folder To Ignore]"))
{
string text = File.ReadAllText(file);
var regex = new Regex("[\u200B-\u200D\uFEFF]");
var newText = regex.Replace(text, "");
if (text != newText)
{
try
{
FileAttributes attributes = File.GetAttributes(file);
if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
File.SetAttributes(file, attributes);
}
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make the file RW
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
File.SetAttributes(file, attributes);
}
File.WriteAllText(file, newText);
found.Add(file);
counterEdited++;
}
catch(Exception ex)
{
failed.Add(file);
}
}
}
counter++;
}
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\found.txt", found);
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\failed.txt", failed);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
}
}
C# Code w/ TFS Checkout
Variables
[Insert Folder to Scan] : Example C:\TFS\Code\Branch\Folder
[Insert Folder To Ignore] : Example 3rdPartyCode
[Insert URI to TFS Server Collection] : Example http://tfs.company.com:8080/tfs/DefaultCollection
Code
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace FixZeroWidthSpace
{
class Program
{
static void Main(string[] args)
{
var files = Directory.GetFiles(#"[Insert Folder to Scan]", "*.cs", SearchOption.AllDirectories);
var counter = 0;
var counterEdited = 0;
var totalFiles = files.Length;
var failed = new List<string>();
var found = new List<string>();
TfsTeamProjectCollection tpc = null;
Workspace ws = null;
foreach (var file in files)
{
if(counter % 10 == 0)
{
Console.WriteLine("Searched {0} or {1} files, {2} have been edited.", counter, totalFiles, counterEdited);
}
if (!file.Contains("3rdparty"))
{
string text = File.ReadAllText(file);
var regex = new Regex("[\u200B-\u200D\uFEFF]");
var newText = regex.Replace(text, "");
if (text != newText)
{
try
{
if (ws == null || tpc == null)
{
tpc = new TfsTeamProjectCollection(new Uri(#"[Insert URI to TFS Server Collection]"));
ws = FindWorkspaceByPath(tpc, file);
}
FileAttributes attributes = File.GetAttributes(file);
if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
File.SetAttributes(file, attributes);
}
ws.PendEdit(file);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// Make the file RW
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
File.SetAttributes(file, attributes);
}
File.WriteAllText(file, newText);
found.Add(file);
counterEdited++;
}
catch(Exception ex)
{
failed.Add(file);
}
}
}
counter++;
}
tpc.Dispose();
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\found.txt", found);
File.WriteAllLines(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\failed.txt", failed);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
{
return attributes & ~attributesToRemove;
}
private static Workspace FindWorkspaceByPath(TfsTeamProjectCollection tfs, string workspacePath)
{
VersionControlServer versionControl = tfs.GetService<VersionControlServer>();
WorkspaceInfo workspaceInfo = Workstation.Current.GetLocalWorkspaceInfo(workspacePath);
if (workspaceInfo != null)
{
return versionControl.GetWorkspace(workspaceInfo);
}
// No Workspace found using method 1, try to query all workspaces the user has on this machine.
Workspace[] workspaces = versionControl.QueryWorkspaces(null, Environment.UserName, Environment.MachineName);
foreach (Workspace w in workspaces)
{
foreach (WorkingFolder f in w.Folders)
{
if (f.LocalItem.Equals(workspacePath))
{
return w;
}
}
}
throw new Exception(String.Format("TFS Workspace cannot be determined for {0}.", workspacePath));
}
}
}
I recently found this happening in one of my solutions. It is nothing present in my code.
If I do a solution clean (right click on the solution -> Clean Solution) the problem goes away.

How to scan all images available in a blackberry device

I am trying to display all the images available in a blackberry device inside a list. How can I scan and fetch all images names in blackberry using java apis?
Use the following class to locate all the images in the device. At the beginning, you call the function without giving any value to the string: checkImages("");
public void checkImages(String imagePath) {
String path = "";
if (imagePath.equals(""))
path = "file:///SDCard/";
else
path = imagePath;
try {
FileConnection fileConnection = (FileConnection)Connector.open(path);
if (fileConnection.isDirectory()) {
Enumeration directoryEnumerator = fileConnection.list("*", true);
Vector contentVector = new Vector();
while(directoryEnumerator.hasMoreElements()) {
contentVector.addElement(directoryEnumerator.nextElement());
}
fileConnection.close();
for (int i = 0 ; i < contentVector.size() ; i ++) {
String name = (String) contentVector.elementAt(i);
checkImages(path + name);
}
}
else {
if (path.toLowerCase().endsWith(".jpg")) {
imm.addElement(path); // your Vector
fileConnection.close();
}
}
} catch (Exception ex) { }
}

Resources