Detect USB devices event - wmi

I made a console application which detects plugin and plugout events for all type of usb devices. but I wanted some filteration in it like I wanted to detect only webcams . This was done by using GUID class. The class for webcam is 'Image' class with GUID "{6bdd1fc5-810f-11d0-bec7-08002be2092f}" .The problem is that this 'Image' class is also used for scanners and I dont want to detect scanners.The code is given below:
static void Main(string[] args)
{
WqlEventQuery weqQuery = new WqlEventQuery();
weqQuery.EventClassName = "__InstanceOperationEvent";
weqQuery.WithinInterval = new TimeSpan(0, 0, 3);
weqQuery.Condition = #"TargetInstance ISA 'Win32_PnPEntity'";
ManagementEventWatcher m_mewWatcher = new ManagementEventWatcher(weqQuery);
m_mewWatcher.EventArrived += new EventArrivedEventHandler(m_mewWatcher_EventArrived);
m_mewWatcher.Start();
Console.ReadLine();
}
static void m_mewWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
bool bUSBEvent = false;
string deviceCaption = "";
string deviceType = "";
foreach (PropertyData pdData in e.NewEvent.Properties)
{
try
{
ManagementBaseObject mbo = (ManagementBaseObject)pdData.Value;
if (mbo != null)
{
foreach (PropertyData pdDataSub in mbo.Properties)
{
Console.WriteLine(pdDataSub.Name + " = " + pdDataSub.Value);
if (pdDataSub.Name == "Caption")
{
deviceCaption = pdDataSub.Value.ToString();
}
if (pdDataSub.Name == "ClassGuid" && pdDataSub.Value.ToString() == "{6bdd1fc5-810f-11d0-bec7-08002be2092f}")
{
bUSBEvent = true;
deviceType = "Image";
}
}
if (bUSBEvent)
{
if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
{
Console.WriteLine("A " + deviceType + " device " + deviceCaption + " was plugged in at " + DateTime.Now.ToString());
}
else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
{
Console.WriteLine("A " + deviceType + " device " + deviceCaption + " was plugged out at " + DateTime.Now.ToString());
}
}
}
}
catch (Exception ex)
{
}
}
}
for references check this link

I waited but no body answered this question so, after seeing all properties of ManagementBaseObject I found that there is a property named Service which is different for scanners. In scanners the value of Service property is usbscan while in cameras it is usbvideo.
eg.
you can do something like this
if (mbo.Properties["Service"].Value.ToString() == "usbscan")
{
//then it means it is a scanner
}
else
{
//then it means it is a camera
}
note: The main question was that how can we differentiate between a scanner and a webcam because they both use same GUID.

Related

Bukkit Player check achievements

I don't know what I should put into player.getAdvancementProgress(Here).
if (player.getAdvancementProgress().isDone()) {
}
Maybe someone knows something?
You should use an Advancement object, specially the advancement that you are looking for informations.
You can get it with Bukkit.getAdvancement(NamespacedKey.fromString("advancement/name")) where advancement/name can be nether/all_potions for example. You can get all here (column: "Resource location). If you are getting it from command, I suggest you to add tab complete.
Example of TAB that show only not-done success :
#Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] arg) {
List<String> list = new ArrayList<>();
if(!(sender instanceof Player))
return list;
Player p = (Player) sender;
String prefix = arg[arg.length - 1].toLowerCase(Locale.ROOT); // the begin of the searched advancement
Bukkit.advancementIterator().forEachRemaining((a) -> {
AdvancementProgress ap = p.getAdvancementProgress(a);
if((prefix.isEmpty() || a.getKey().getKey().toLowerCase().startsWith(prefix)) && !ap.isDone() && !a.getKey().getKey().startsWith("recipes"))
list.add(a.getKey().getKey());
});
return list;
}
Then, in the command you can do like that:
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg) {
if(!(sender instanceof Player)) // not allowed for no-player
return false;
Player p = (Player) sender;
// firstly: try to get advancement
Advancement a = Bukkit.getAdvancement(NamespacedKey.fromString(arg[0]));
if(a == null)
a = Bukkit.getAdvancement(NamespacedKey.minecraft(arg[0]));
if(a == null) // can't find it
p.sendMessage(ChatColor.RED + "Failed to find success " + arg[0]);
else { // founded :
AdvancementProgress ap = p.getAdvancementProgress(a);
p.sendMessage(ChatColor.GREEN + "Achivement " + a.getKey().getKey() + " stay: " + ChatColor.YELLOW + String.join(", ", ap.getRemainingCriteria().stream().map(this::getCleaned).collect(Collectors.toList())));
}
return false;
}
private String getCleaned(String s) { // this method is only to make content easier to read
String[] args = s.split("/");
return args[args.length - 1].replace(".png", "").replace(".jpg", "").replace("minecraft:", "").replace("_", " ");
}
Else, if you want to get all advancements, you should use Bukkit.advancementIterator().

UWP C++ PrintTask PreviewPage Duplication Error

I'm currently working on a print task within my app to print a couple of pages to either printer or PDF. I'm using the microsoft printsample as the basis for my code and it all works with the exception of one thing. When I change printers, the printer preview creates duplicate pages of the content I sent to the printer preview.
Here is all my code that handles the printing. Does anyone know what might be causing the print UI to create duplicate preview pages when changing between printers and or print to PDF? thanks.
void MainPage::Print_Test_Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
if (isPrinting) {
pDocument->InvalidatePreview();
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
printMan->PrintTaskRequested -= printTaskRequestedEventToken;
isPrinting = false;
}
this->Certificate_SV_1->ScrollToVerticalOffset(0.0);
this->Certificate_SV_2->ScrollToVerticalOffset(0.0);
// CREATE THE PRINT DOCUMENT
pDocument = ref new Windows::UI::Xaml::Printing::PrintDocument();
// SAVE DOCUMENT SOURCE
pDocumentSource = pDocument->DocumentSource;
// CLEAR CACHE OF PREVIEW PAGES
printPreviewPages.clear();
// Add an event handler which creates preview pages.
pDocument->Paginate += ref new Windows::UI::Xaml::Printing::PaginateEventHandler(this, &MainPage::CreatePrintPreviewPages);
// Add an event handler which provides a specified preview page.
pDocument->GetPreviewPage += ref new Windows::UI::Xaml::Printing::GetPreviewPageEventHandler(this, &MainPage::GetPrintPreviewPage);
// Add an event handler which provides all final print pages.
pDocument->AddPages += ref new Windows::UI::Xaml::Printing::AddPagesEventHandler(this, &MainPage::AddPrintPages);
// PRINT MANAGER
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
// RAISE NEW PRINT TASK REQUEST
printTaskRequestedEventToken = printMan->PrintTaskRequested += ref new Windows::Foundation::TypedEventHandler<Windows::Graphics::Printing::PrintManager^, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^>(this, &MainPage::PrintTaskRequested);
// SHOWS THE PRINTER UI
printMan->ShowPrintUIAsync();
}
.
void MainPage::CreatePrintPreviewPages(Object^ sender, Windows::UI::Xaml::Printing::PaginateEventArgs^ e)
{
Windows::UI::Xaml::Printing::PrintDocument^ printDocument = safe_cast<Windows::UI::Xaml::Printing::PrintDocument^>(sender);
hasOverFlow = false;
StackPanel^ PrinterPage = ref new StackPanel();
PrinterPage->Width = 794; PrinterPage->Height = 1123;
PrinterPage = safe_cast<StackPanel^>(this->Certificate_Page_1);
// ADD PAGE TO THE COLLECTION
printPreviewPages.push_back(PrinterPage);
PrinterPage = safe_cast<StackPanel^>(this->Certificate_Page_2);
printPreviewPages.push_back(PrinterPage);
// Report the number of preview pages created
printDocument->SetPreviewPageCount(printPreviewPages.size(), Windows::UI::Xaml::Printing::PreviewPageCountType::Final);
}
.
void MainPage::GetPrintPreviewPage(Object^ sender, Windows::UI::Xaml::Printing::GetPreviewPageEventArgs^ e)
{
Windows::UI::Xaml::Printing::PrintDocument^ localprintDocument = safe_cast<Windows::UI::Xaml::Printing::PrintDocument^>(sender);
localprintDocument->SetPreviewPage(e->PageNumber, printPreviewPages[e->PageNumber - 1]);
}
.
void MainPage::AddPrintPages(Object^ sender, Windows::UI::Xaml::Printing::AddPagesEventArgs^ e)
{
Windows::UI::Xaml::Printing::PrintDocument^ printDocument = safe_cast<Windows::UI::Xaml::Printing::PrintDocument^>(sender);
for (uint8_t i = 0; i < printPreviewPages.size(); i++) {
printDocument->AddPage(printPreviewPages[i]);
}
// Indicate that all of the print pages have been provided
printDocument->AddPagesComplete();
}
.
void MainPage::PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e) {
Windows::Graphics::Printing::PrintTask^ printTask = e->Request->CreatePrintTask("PRINT TASK", ref new Windows::Graphics::Printing::PrintTaskSourceRequestedHandler([=](Windows::Graphics::Printing::PrintTaskSourceRequestedArgs^ args)
{
args->SetSource(pDocumentSource);
}));
// Print Task event handler is invoked when the print job is completed.
printTask->Completed += ref new Windows::Foundation::TypedEventHandler<Windows::Graphics::Printing::PrintTask^, Windows::Graphics::Printing::PrintTaskCompletedEventArgs^>([=](Windows::Graphics::Printing::PrintTask^ sender, Windows::Graphics::Printing::PrintTaskCompletedEventArgs^ e)
{
// Notify the user when the print operation fails.
if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Failed)
{
auto callback = ref new Windows::UI::Core::DispatchedHandler([=]()
{
this->DataStreamWindow->Text = "Printing Failed!";
pDocument->InvalidatePreview();
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
printMan->PrintTaskRequested -= printTaskRequestedEventToken;
isPrinting = false;
});
Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
}
else if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Canceled)
{
auto callback = ref new Windows::UI::Core::DispatchedHandler([=]()
{
this->DataStreamWindow->Text = "Printing Cancelled!";
pDocument->InvalidatePreview();
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
printMan->PrintTaskRequested -= printTaskRequestedEventToken;
isPrinting = false;
});
Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
}
pDocument->InvalidatePreview();
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
printMan->PrintTaskRequested -= printTaskRequestedEventToken;
isPrinting = false;
});
}

Sitecore.Analytics.Tracker.Current is null when invoked through a pipeline

I need to redirect based on the country location the user is trying to access. For example when user trying to access http://www.example.com/ from china my site should as http://www.example.com/zh. I am checking using the sitecore tracker in pipeline process to get the country code using the below method.
public void Process(HttpRequestArgs args)
{
Assert.ArgumentNotNull(args, "args");
if (HttpContext.Current == null
|| Context.Site == null
////TODO: || Sitecore.Context.PageMode...
|| Context.Database == null || Context.Site.Name == "shell" || !this._sites.Contains(Context.Site.Name))
{
return;
}
// contains path including language and query string
// (not anchor name), but not hostname.
// We can use this to add the language back into the path.
string rawPath = Sitecore.Context.RawUrl;
if (!rawPath.StartsWith("/sitecore") && !rawPath.StartsWith("/" + Sitecore.Context.Language.Name + "/") && !rawPath.StartsWith("/" + Sitecore.Context.Language.Name) && !rawPath.StartsWith("/default.aspx"))
{
string langCode = "";
if(!string.IsNullOrEmpty(GeoIPUtils.GetUserGeoIP()))
{
try
{
string country = GeoIPUtils.GetUserGeoIP();;
if (country.Trim().ToUpper() == "China".ToUpper())
langCode = "zh";
else if (country.Trim().ToUpper() == "Japan".ToUpper())
langCode = "jp";
else if (country.Trim().ToUpper() == "Thailand".ToUpper())
langCode = "th";
else
langCode = "en";
}
catch(Exception)
{
langCode = "en";
}
}
else
{
langCode = HttpContext.Current.Request.Cookies["avc#lang"].Value.ToString();
}
if (!string.IsNullOrEmpty(langCode))
{
Language language = null;
if (Language.TryParse(langCode, out language))
{
//then try to get the language item id from the language or two letter iso code
ID langID = LanguageManager.GetLanguageItemId(language, Sitecore.Context.Database);
if (!ID.IsNullOrEmpty(langID))
{
//sometimes the language found is slightly different than official language item used in SC
language = LanguageManager.GetLanguage(language.CultureInfo.TwoLetterISOLanguageName);
if (Context.Item != null)
{
List<string> availableLangs = LanguagesWithContent(Context.Item);
if (availableLangs != null && availableLangs.Count > 0 && !availableLangs.Contains(language.CultureInfo.TwoLetterISOLanguageName.ToString()))
{
langCode = availableLangs.FirstOrDefault().ToString();
}
}
else
{
langCode = "en";
}
}
else
{
langCode = "en";
}
}
}
HttpContext.Current.Response.RedirectPermanent("/" + (String.IsNullOrEmpty(langCode) ? Sitecore.Context.Language.Name : langCode) + rawPath);
}
}
Below is the GetUserGeoIP function
public static string GetUserGeoIP()
{
string countryCode = "";
try
{
countryCode = Sitecore.Analytics.Tracker.Current.Interaction.GeoData.Country;
}
catch(Exception ex)
{
Log.Error("GetUserGeoIP Error: " + ex.Message + " Source: " + ex.Source + " Stack Trace :" + ex.StackTrace + " Inner Ex : " + ex.InnerException, ex);
countryCode = "GB";
}
if (!string.IsNullOrEmpty(countryCode))
{
var countryItem = ISO3166.FromAlpha2(countryCode);
if (countryItem != null)
return countryItem.Name;
}
return "Other";
}
But I am getting an below exception
7904 10:43:25 ERROR Cannot create tracker.
Exception: System.InvalidOperationException
Message: session is not initialized
Source: Sitecore.Analytics
at Sitecore.Analytics.Data.HttpSessionContextManager.GetSession()
at Sitecore.Analytics.Pipelines.EnsureSessionContext.EnsureContext.Process(InitializeTrackerArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Analytics.DefaultTracker.EnsureSessionContext()
at Sitecore.Analytics.Pipelines.CreateTracker.GetTracker.Process(CreateTrackerArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Analytics.Tracker.Initialize()
Note: The same GetUserGeoIP method is used in API which gets the correct countryName. I am using Sitecore.NET 8.0 (rev. 151127) version
Any help on this highly appreciated
Your processor is probably too soon in the pipeline(s). You can find an overview of the request pipelines here: http://sitecoreskills.blogspot.be/2015/02/a-sitecore-8-request-from-beginning-to.html
You should put your processor after the tracker has been initialized and the geo data has been fetched. I did something similar a while ago and placed my processor in the startAnalytics pipeline.
Fetching the geo data is async so that might (will) give issues when doing this in the first request pipeline. Read this article to tackle that issue by calling UpdateGeoIpData with a timespan.

Object reference not set to an instance Of Object

Good day to all,
Please I need somebody to help me have a look at my codes.I am having this error of** Object reference not set to an instance Of Object**.It appears the error is within this lines of codes
if (_scrollingTimer == null)
{
_scrollingTimer = new Timer()
{
Enabled = false,
Interval = 500,
Tag = (sender as TrackBar).Value
};
but unfortunately I was unable to resolve this error.I would be very glad if somebody could help me out.thank you for the usual support.best regards.
Firstoption.
Below are the remaining part of the codes.
byte[] data = new byte[5];
private Timer _scrollingTimer = null;
private void button3_Click(object sender, EventArgs e)
{
UInt32 numBytesWritten = 0;
data[0] = 1;
myFtdiDevice.Write(data, 1, ref numBytesWritten);
data[0] = 0x6A;
myFtdiDevice.Write(data, 1, ref numBytesWritten);
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
if(!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
UInt32 numBytesWritten = 1;
string dataToWrite = "#0";
if (_scrollingTimer == null)
{
_scrollingTimer = new Timer()
{
Enabled = false,
Interval = 500,
Tag = (sender as TrackBar).Value
};
_scrollingTimer.Tick += (s, ea) =>
{
if (trackBar1.Value == (int)_scrollingTimer.Tag)
{
_scrollingTimer.Stop();
myFtdiDevice.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten);
int percent = (int)(((double)trackBar1.Value / (double)trackBar1.Maximum) * 100);
label2.Text = (percent.ToString()) + "%";
data[0] = Convert.ToByte(percent);
data[1] = 0x6A;
myFtdiDevice.Write(data, 2, ref numBytesWritten);
_scrollingTimer.Dispose();
_scrollingTimer = null;
}
else
{
_scrollingTimer.Tag = trackBar1.Value;
}
};
_scrollingTimer.Start();
}
}
sender is not a TrackBar. Looks like it's probably backgroundWorker1.

Player name on auto pick option for invitation

We have developed a multiplayer game using google play services.
When we send a request to the api for inviting friends to play, on clicking auto pick, the opponent's name does not show, instead the list shows any random name as in Player_1231,Player_3333 etc.
We need help regarding this issue. We need proper player names to play the game.Kindly check the screenshots attached.
Immediate help will be appreciated.
Please find the code below:
public void onRoomConnected(int statusCode, Room room) {
// TODO Auto-generated method stub
if (statusCode != mGamesClient.STATUS_PARTICIPANT_NOT_CONNECTED) {
// Toast.makeText(this, " is PARTICIPANT_CONNECTED.",
// Toast.LENGTH_SHORT).show();
roomId = room.getRoomId();
room_creator_id = room.getCreatorId();
// participantId = p.getParticipantId();
current_player_id = room.getParticipantId(mGamesClient
.getCurrentPlayerId());
Asset.self = Asset.username;
if (room_creator_id != null) {
if (room_creator_id.equals(current_player_id)) {
Server = true;
}
}
// Toast.makeText(this,
// " is PARTICIPANT_CONNECTED."+room_creator_id,
// Toast.LENGTH_SHORT).show();
par = null;
par = room.getParticipants();
for (Participant p : par) {
if (!p.getParticipantId().equals(current_player_id)) {
System.out.println(current_player_id
+ " After 1 connect " + p.getParticipantId());
participantId = p.getParticipantId();
Asset.opponent = p.getDisplayName();
break;
}
}
menu.initPage(GameConst.SELECTLEVEL_PAGE_ONLINE);
menu.Start_Selection_Timer();
}
// Toast.makeText(this, " is onRoomConnected.",
// Toast.LENGTH_SHORT).show();
}
PLAY ONLINE---------------
public void startQuickGame() {
// automatch criteria to invite 1 random automatch opponent.
// You can also specify more opponents (up to 3).
if (mGamesClient.isConnected()) {
Bundle am = RoomConfig.createAutoMatchCriteria(1, 1, 0);
// build the room config:
RoomConfig.Builder roomConfigBuilder = makeBasicRoomConfigBuilder();
roomConfigBuilder.setAutoMatchCriteria(am);
RoomConfig roomConfig = roomConfigBuilder.build();
// create room:
mGamesClient.createRoom(roomConfig);
} else {
Toast.makeText(con, "Wait for connection or try after some time",
Toast.LENGTH_SHORT).show();
mGamesClient.connect();
}
// go to game screen
}