Changing SO-Pin in PKCS11 Interop - pkcs11interop

A straightforward question. Do you have any idea if there is a possibility to change the SO-pin of a token (ePass2003 in my case) using pkcs11 Interop? Many thanks in advance.

Right now I can't find my ePass2003 to test but I would try with this code:
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI;
namespace ConsoleApp1
{
class Program
{
static string pkcs11Library = "opensc-pkcs11";
static string oldSoPin = "1111111111";
static string newSoPin = "2222222222";
static void Main(string[] args)
{
using (Pkcs11 pkcs11 = new Pkcs11(pkcs11Library, AppType.SingleThreaded))
{
Slot firstSlot = pkcs11.GetSlotList(SlotsType.WithTokenPresent)[0];
using (Session session = firstSlot.OpenSession(SessionType.ReadWrite))
{
session.Login(CKU.CKU_SO, oldSoPin);
session.SetPin(oldSoPin, newSoPin);
}
}
}
}
}

Related

How get current url in Microsoft Edge? [duplicate]

I'm trying to read out the TITLE & URL from the Microsoft EDGE Browser.
Doing this with System.Windows.Automation most preferably since the code base already uses this for other problems.
Is it possible with System.Windows.Automation?
How to access the URL?
I'm currently this far:
AutomationId "TitleBar"
ClassName "ApplicationFrameWindow"
Name = [string]
=> Reading out this element gives me the TITLE
=> Walking it's children, I find the item "addressEditBox":
AutomationId "addressEditBox"
ClassName "RichEditBox"
Name "Search or enter web address"
=> I always get back the string "Search or enter web address"
=> This is the control where the url is in, though it isn't updated as the user goes to a website, it always returns a fixed string.
In code:
var digger1 = AutomationElement.FromHandle(process.MainWindowHandle).RootElement.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach(AutomationElement d1 in digger1 {
if(d1.Current.ClassName.Equals("ApplicationFrameWindow")) {
var digger2 = d1.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach(AutomationElement d2 in digger2) {
if(d2.Current.ClassName.Equals("Windows.Ui.Core.CoreWindow")) {
var digger3 = d2.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach(AutomationElement d3 in digger3) {
if(d3.Current.AutomationId.Equals("addressEditBox")) {
var url = d3.Current.Name;
return url;
}
}
}
}
}
}
You're almost there. You just need to get the TextPattern from the addressEditBox element. Here is a full sample Console app that dumps out all currently running Edge's windows on the desktop:
class Program
{
static void Main(string[] args)
{
AutomationElement main = AutomationElement.FromHandle(GetDesktopWindow());
foreach(AutomationElement child in main.FindAll(TreeScope.Children, PropertyCondition.TrueCondition))
{
AutomationElement window = GetEdgeCommandsWindow(child);
if (window == null) // not edge
continue;
Console.WriteLine("title:" + GetEdgeTitle(child));
Console.WriteLine("url:" + GetEdgeUrl(window));
Console.WriteLine();
}
}
public static AutomationElement GetEdgeCommandsWindow(AutomationElement edgeWindow)
{
return edgeWindow.FindFirst(TreeScope.Children, new AndCondition(
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
new PropertyCondition(AutomationElement.NameProperty, "Microsoft Edge")));
}
public static string GetEdgeUrl(AutomationElement edgeCommandsWindow)
{
var adressEditBox = edgeCommandsWindow.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.AutomationIdProperty, "addressEditBox"));
return ((TextPattern)adressEditBox.GetCurrentPattern(TextPattern.Pattern)).DocumentRange.GetText(int.MaxValue);
}
public static string GetEdgeTitle(AutomationElement edgeWindow)
{
var adressEditBox = edgeWindow.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.AutomationIdProperty, "TitleBar"));
return adressEditBox.Current.Name;
}
[DllImport("user32")]
public static extern IntPtr GetDesktopWindow();
}

Creating an instance of a generic type in DART

I was wondering if is possible to create an instance of a generic type in Dart. In other languages like Java you could work around this using reflection, but I'm not sure if this is possible in Dart.
I have this class:
class GenericController <T extends RequestHandler> {
void processRequest() {
T t = new T(); // ERROR
}
}
I tried mezonis approach with the Activator and it works. But it is an expensive approach as it uses mirrors, which requires you to use "mirrorsUsed" if you don't want to have a 2-4MB js file.
This morning I had the idea to use a generic typedef as generator and thus get rid of reflection:
You define a method type like this: (Add params if necessary)
typedef S ItemCreator<S>();
or even better:
typedef ItemCreator<S> = S Function();
Then in the class that needs to create the new instances:
class PagedListData<T>{
...
ItemCreator<T> creator;
PagedListData(ItemCreator<T> this.creator) {
}
void performMagic() {
T item = creator();
...
}
}
Then you can instantiate the PagedList like this:
PagedListData<UserListItem> users
= new PagedListData<UserListItem>(()=> new UserListItem());
You don't lose the advantage of using generic because at declaration time you need to provide the target class anyway, so defining the creator method doesn't hurt.
You can use similar code:
import "dart:mirrors";
void main() {
var controller = new GenericController<Foo>();
controller.processRequest();
}
class GenericController<T extends RequestHandler> {
void processRequest() {
//T t = new T();
T t = Activator.createInstance(T);
t.tellAboutHimself();
}
}
class Foo extends RequestHandler {
void tellAboutHimself() {
print("Hello, I am 'Foo'");
}
}
abstract class RequestHandler {
void tellAboutHimself();
}
class Activator {
static createInstance(Type type, [Symbol constructor, List
arguments, Map<Symbol, dynamic> namedArguments]) {
if (type == null) {
throw new ArgumentError("type: $type");
}
if (constructor == null) {
constructor = const Symbol("");
}
if (arguments == null) {
arguments = const [];
}
var typeMirror = reflectType(type);
if (typeMirror is ClassMirror) {
return typeMirror.newInstance(constructor, arguments,
namedArguments).reflectee;
} else {
throw new ArgumentError("Cannot create the instance of the type '$type'.");
}
}
}
I don't know if this is still useful to anyone. But I have found an easy workaround. In the function you want to initialize the type T, pass an extra argument of type T Function(). This function should return an instance of T. Now whenever you want to create object of T, call the function.
class foo<T> {
void foo(T Function() creator) {
final t = creator();
// use t
}
}
P.S. inspired by Patrick's answer
2022 answer
Just came across this problem and found out that although instantiating using T() is still not possible, you can get the constructor of an object easier with SomeClass.new in dart>=2.15.
So what you could do is:
class MyClass<T> {
final T Function() creator;
MyClass(this.creator);
T getGenericInstance() {
return creator();
}
}
and when using it:
final myClass = MyClass<SomeOtherClass>(SomeOtherClass.new)
Nothing different but looks cleaner imo.
Here's my work around for this sad limitation
class RequestHandler {
static final _constructors = {
RequestHandler: () => RequestHandler(),
RequestHandler2: () => RequestHandler2(),
};
static RequestHandler create(Type type) {
return _constructors[type]();
}
}
class RequestHandler2 extends RequestHandler {}
class GenericController<T extends RequestHandler> {
void processRequest() {
//T t = new T(); // ERROR
T t = RequestHandler.create(T);
}
}
test() {
final controller = GenericController<RequestHandler2>();
controller.processRequest();
}
Sorry but as far as I know, a type parameter cannot be used to name a constructor in an instance creation expression in Dart.
Working with FLutter
typedef S ItemCreator<S>();
mixin SharedExtension<T> {
T getSPData(ItemCreator<T> creator) async {
return creator();
}
}
Abc a = sharedObj.getSPData(()=> Abc());
P.S. inspired by Patrick
simple like that.
import 'dart:mirrors';
void main(List<String> args) {
final a = A<B>();
final b1 = a.getInstance();
final b2 = a.getInstance();
print('${b1.value}|${b1.text}|${b1.hashCode}');
print('${b2.value}|${b2.text}|${b2.hashCode}');
}
class A<T extends B> {
static int count = 0;
T getInstance() {
return reflectClass(T).newInstance(
Symbol(''),
['Text ${++count}'],
{Symbol('value'): count},
).reflectee;
}
}
class B {
final int value;
final String text;
B(this.text, {required this.value});
}
Inspired by Patrick's answer, this is the factory I ended up with.
class ServiceFactory<T> {
static final Map<Type, dynamic> _cache = <String, dynamic>{};
static T getInstance<T>(T Function() creator) {
String typeName = T.toString();
return _cache.putIfAbsent(typeName, () => creator());
}
}
Then I would use it like this.
final authClient = ServiceFactory.getInstance<AuthenticationClient>(() => AuthenticationClient());
Warning: Erik made a very good point in the comment below that the same type name can exist in multiple packages and that will cause issues. As much as I dislike to force the user to pass in a string key (that way it's the consumer's responsibility to ensuring the uniqueness of the type name), that might be the only way.

How can i call dynamic object like a function?

I am studying orchard architecture.i have faced with a strange concept in display management section.
in Partial view page there is a 'function call like' syntax like so Display(Model.Head). that is not a function thought, it is a dynamic object defined in orchard WebViewPage.
I am wondering how to define a dynamic object so that you can call it (and pass it an argument as well) like a function as i mentioned.
thanks in advance.
A lighter weight way to do it without clay would be to subclass the built-in DynamicObject class.
public static dynamic Display;
void Main()
{
Display = new MyCallableObject();
//this is what i was after
Console.Write(Display("bla bla bla"));
}
public class MyCallableObject:DynamicObject
{
public override bool TryInvoke(InvokeBinder binder, object[] args, out Object result)
{
result = string.Format("This is response for {0}",args.FirstOrDefault());
return true;
}
}
I finally found it my self!
all the operations have done with Clay Library behind the scene.i have wrote a sample console app for demonstrating the process.
class Program
{
static void Main(string[] args)
{
Display = ClayActivator.CreateInstance<MyResponser>(new List<IClayBehavior> {new MyFunctionCallBehavior()});
//this is what i was after
Console.Write(Display("bla bla bla"));
}
public static dynamic Display;
}
public class MyFunctionCallBehavior : IClayBehavior
{
public object InvokeMember(Func<object> proceed, object self, string name, INamedEnumerable<object> args)
{
return ((MyResponser)self).ResponseForRequest(args.FirstOrDefault().ToString());
}
}
public class MyResponser
{
public string ResponseForRequest(string param)
{
return string.Format("This is response for {0}",param);
}
}

Get a specific TestSuite by Id using the TFS API

I am trying to get a specific TestSuite using the TFS API for a TestPlan.
The TestSuite could exist anywhere within a TestSuite hierarchy, so, of course I could write a recursive function. I want something more efficient however.
Is there a method I am missing, or maybe a query that I could write?
If you already know the testSuiteId things are quite straightforward. You only need to know the name of your TeamProject teamProjectName:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
namespace GetTestSuite
{
class Program
{
static void Main()
{
int testSuiteId = 555;
const string teamProjectName = "myTeamProjectName";
var tpc =
TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
new Uri("http://tfsURI"));
var tstService = (ITestManagementService)tpc.GetService(typeof(ITestManagementService));
var tProject = tstService.GetTeamProject(teamProjectName);
var myTestSuite = tProject.TestSuites.Find(testSuiteId);
}
}
}
If you don't, you probably need to go for a solution similar to the one presented here (it's a S.Raiten post), where recursion does come into picture. Access to a testPlanId is assumed:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
namespace GetTestSuite
{
class Program
{
static void Main()
{
int testPlanId = 555;
const string teamProjectName = "myTeamProjectName";
var tpc =
TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
new Uri("http://tfsURI"));
var tstService = (ITestManagementService)tpc.GetService(typeof(ITestManagementService));
var tProject = tstService.GetTeamProject(teamProjectName);
var myTestPlan = tProject.TestPlans.Find(testPlanId);
GetPlanSuites(myTestPlan.RootSuite.Entries);
}
public static void GetPlanSuites(ITestSuiteEntryCollection suites)
{
foreach (ITestSuiteEntry suiteEntry in suites)
{
Console.WriteLine(suiteEntry.Id);
var suite = suiteEntry.TestSuite as IStaticTestSuite;
if (suite != null)
{
if (suite.Entries.Count > 0)
GetPlanSuites(suite.Entries);
}
}
}
}
}

Print Sample for MonoMac

Does anyone know of a MonoMac sample that shows how to implement Print (to a printer)? I haven't been able to find one.
I don't know of one, but the conceptual docs from Apple are relevant, and their sample snippets should be straightforward to port to C#: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Printing/Printing.html
I created a PrintDocument class a bit like this:
(You'd need to set a proper size and add some drawing in drawrect)
public class PrintDocument:NSView {
NSPrintOperation MyPrinter = null;
static IntPtr selCurrentContext = Selector.GetHandle ("currentContext");
static IntPtr classNSGraphicsContext = Class.GetHandle ("NSGraphicsContext");
public PrintDocument ()
{
MyPrinter=NSPrintOperation.FromView(this);
this.SetFrameSize(new SizeF(600,800));
}
public void Print ()
{
MyPrinter.RunOperation()
}
public override void DrawRect (RectangleF dirtyRect)
{
var context = new NSGraphicsContext (Messaging.IntPtr_objc_msgSend (classNSGraphicsContext, selCurrentContext));
//NSPrintOperation.CurrentOperation
}
}

Resources