Logout using adal4j - azure-active-directory

How should i implement logout using adal4j ? Currently i dont see any methods in this library for doing this. Here is my example.
AuthenticationContext context = new AuthenticationContext("https://login.windows.net/" + "test.onmicrosoft.com" + "/", true, service);
try {
final Future<AuthenticationResult> resultFuture = context.acquireTokenByAuthorizationCode(
code, new URI(redirectUri), new ClientCredential(clientId, clientSecret), "https://graph.windows.net/", null);
result = resultFuture.get();
} catch (InterruptedException | ExecutionException e) {
} catch (URISyntaxException e) {
}

Related

WebView2 not initializing

I created a simple WPF client app in .net6.0 and incorporated WebView2 control.
I deployed/copied this app to a different machine and also installed .NET6.0 runtime there.
Upon running this app, I only see the main window and NO WebView2 initialized/created.
Note this the same implementation is working on my dev machine.
public MainWindow()
{
InitializeComponent();
InitializeWebView2();
}
private async Task InitializeWebView2()
{
//myPanel.Children.Add(webView2);
//await webView2.EnsureCoreWebView2Async();
((Action)(async () =>
{
try
{
CoreWebView2Environment env = await CoreWebView2Environment.CreateAsync(null, "another_dir");
WebView2 webview = new WebView2();
/*
webview.Source = new Uri("https://www.bing.com");
*/
var result = webview.EnsureCoreWebView2Async(env).GetAwaiter();
result.OnCompleted(() =>
{
try
{
result.GetResult();
}
catch (Exception e)
{
Console.WriteLine(e);
}
});
myPanel.Children.Add(webview);
webview.NavigateToString("https://google.com");
}
catch (Exception e)
{
Console.WriteLine(e);
}
})).Invoke();
}
EnsureCoreWebView2Async is supposed to be awaited before you set the Source:
private async Task InitializeWebView2()
{
var webview = new WebView2();
myPanel.Children.Add(webview);
var env = await CoreWebView2Environment.CreateAsync(null, "another_dir");
var result = await webview.EnsureCoreWebView2Async(env);
webview.Source = new Uri("https://www.bing.com");
}

How to set a Camel exchangeProperty from a unit test

I have a bunch of unit tests that run camel routes with code like
// setup code here...
String route = "direct:someroute";
try (CamelContext context = new DefaultCamelContext()) {
Object response = runCamelRoute(context, route, ci);
checkResponse(route, response);
}
but this route expects an exchange property to be set before it gets here - how can I set it? CamelContext has a whole lot of methods but I can't seem to find something like:
CamelRoute cr = context.getRoute(route);
cr.getExchange().setProperty("propertyName", "propetyValue");
Here is my camel run method for unit testing, with a bit of extra code for setting up an Oracle connection, etc.
protected Object runCamelRoute(CamelContext context, String route, Object message) throws Exception {
context.addRoutes(new MyRouteBuilder() {
});
setupRegistry(context);
context.start();
FluentProducerTemplate template = context.createFluentProducerTemplate();
template.withBody(message)
.withHeader("hello", "goodbye")
.withProcessor(e -> e.setProperty("propertyName", "propertyValue")) // fail use header instead
.to(route);
try {
Future<Object> future = template.asyncRequest();
return future.get();
}
catch(Exception ex) {
System.out.println(route + " " + ex.getClass().getCanonicleName() + " " + ex.getMessage());
throw ex;
}
finally {
template.stop();
context.stop();
}
}
private void setupRegistry(CamelContext context) {
DataSource ds = DataSourceHelper.createConnectionPoolDev();
context.getRegistry().bind("dataSource", ds);
context.getRegistry().bind("Transformer", new Transformer());
}
public static OracleDataSource createConnectionPoolDev() {
try {
OracleDataSource ds = new OracleDataSource();
ds.setConnectionCacheName("oraCache");
ds.setURL("jdbc:oracle:thin:#//cluster:1521/server.domain.ca");
ds.setUser("user");
ds.setPassword("pass");
return ds;
}
catch (Exception ex) {
logger.error("Failed to create connection to the database " + ex.getMessage());
}
return null;
}
Something like this may be ?
context.createFluentProducerTemplate()
.withBody(...)
.withHeader(..., ...)
.withProcessor( e -> e.setProperty(propertyName, propertyValue) )
.to("direct:someroute")
.send();

Error 401 Not Unauhtorized LinqToTiwtter API

I Follow the demo for linqtotiwwter.codeplex.com
I tried to fallow the demo webformrtimeline so I wrote this code for a DotNetNuke Module when a push the bottom btnAutorizar for beginauthorization always the response is Error 401 Unauhtorized . there are the configuration that i put into the settings of my module.
ConsumerKey: lcgG6BXQpwQtHSzwqWA
ConsumerSecret: 6MoV8PlLBktgVaAP5ezDYEHGMKcHGEDe8eDuk5mpas
and my aplicattion in twitter call dnnPrueba
What is my mistake in the code??, what more i need? please help me! and sorry for my English!
public partial class ViewTwitterAndrea : PortalModuleBase {
private ConfiguracionTwitterAndrea configuracion;
private WebAuthorizer wbAuthorizer;
protected void Page_Load(object sender, EventArgs e) {
try {
configuracion = new ConfiguracionTwitterAndrea(this.TabModuleId);
string consumerKey = configuracion.ConsumerKey;
string consumerSecret = configuracion.ConsumerSecret;
if (string.IsNullOrEmpty(consumerKey) || string.IsNullOrEmpty(consumerSecret))
{ this.mvTwitterAndrea.SetActiveView(this.vwConfiguracion); }
else {
IOAuthCredentials objCredenciales = new SessionStateCredentials();
if (objCredenciales.ConsumerKey == null || objCredenciales.ConsumerSecret == null)
{
objCredenciales.ConsumerKey = configuracion.ConsumerKey;
objCredenciales.ConsumerSecret = configuracion.ConsumerSecret;
}
wbAuthorizer = new WebAuthorizer {
Credentials=objCredenciales,
PerformRedirect = authUrl => Response.Redirect(authUrl) };
if(!Page.IsPostBack){
wbAuthorizer.CompleteAuthorization(Request.Url);
}
if(string.IsNullOrEmpty(objCredenciales.ConsumerKey) || string.IsNullOrEmpty(objCredenciales.ConsumerSecret)){
lblRegistrado.Text = "No estas autorizado aun";
btnAutorizar.Visible = true;
btnTweets.Visible = false;
}else if(wbAuthorizer.IsAuthorized){
lblRegistrado.Text = "Estas Autorizado.";
btnAutorizar.Visible = false;
btnTweets.Visible = true;
}
this.mvTwitterAndrea.SetActiveView(vwAutorizacion);
}}catch (Exception ex) {Exceptions.ProcessModuleLoadException(this, ex);
}
}
protected void BtnEnviar_Click(object sender, EventArgs e) {
ComunicacionTwitter objTwitter = new ComunicacionTwitter(this.TabModuleId);
Status objStatus= objTwitter.ActualizarEstado(wbAuthorizer, this.txtEstado.Text);
}
protected void btnAutorizar_Click(object sender, EventArgs e) {
try {
wbAuthorizer.BeginAuthorization(Request.Url);
}catch(Exception ex){ }
}
protected void btnTweets_Click(object sender, EventArgs e) {
try {
wbAuthorizer = new WebAuthorizer {
Credentials = new SessionStateCredentials() };
ComunicacionTwitter objTwitter = new ComunicacionTwitter(this.TabModuleId);
var UltimosTweets = objTwitter.getHomeTimeLine(wbAuthorizer, intCantidadTweets);
foreach (var Tweet in UltimosTweets) {
this.spnTweets.InnerHtml = "<div class='twitterTweet'>" +
"<div class='twitterUsuario'>Usuario " + Tweet.ScreenName + "</div>" +
"<div class='twitterContenido'>" + Tweet.Text + "</div>" +
"<div class='twitterFecha'>" + Tweet.CreatedAt + "</div>" +
"</div>";
}
this.mvTwitterAndrea.SetActiveView(this.vwTweets);
}catch(Exception ex){ }
}
}
}
********** And I have another class
Class ConfiguracionTwitter{
public ConfiguracionTwitter(){}
public IEnumerable<Status> getHomeTimeLine(WebAuthorizer auth,int intCantidadTweets) {
twitterContexto= new TwitterContext(auth);
var tweets =
(from tweet in twitterContexto.Status
where tweet.Type == StatusType.Home
select tweet).Take(intCantidadTweets).ToList();
return tweets;
}
}
A "401 Unauthorized" means that your application is unable to authenticate with Twitter. There are many things that can cause a 401. I've compiled a FAQ that will give you a list of things to check:
http://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20FAQ&referringTitle=Documentation
BTW, posting your OAuth keys makes your application insecure. You should visit your app on the Twitter page as soon as possible and generate a new set of keys.
Joe

Sending SMS from BlackBerry Simulator

I'm developing a BlackBerry Application where I should send Text SMS from BlackBerry Device.
As I'm new to Blackberry, started few days back I'm unable to proceed.
Can anyone Help with providing code snippets for send SMS from BlackBerry Device or Simulator?
Thanks in Advance.
Suresh.
public static void sendSMS(final String no, final String msg) {
// try {
new Thread() {
public void run() {
boolean smsSuccess = false;
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
// / send successfully
smsSuccess = true;
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
smsSuccess = false;
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector
.open("sms://" + no);
TextMessage tmsg = (TextMessage) conn
.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
conn.send(tmsg);
smsSuccess = true;
} catch (Exception e) {
smsSuccess = false;
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
if(smsSuccess)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("success");
}
});
}else
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("failure");
}
});
}
}
}.start();
}
Check out the the above code function .... to send SMS from Blackberry
You haven't specified what language you are developing in, but if you are developing in java and, if you are using Eclipse for your development with the Blackberry Java plugins, you will find a wealth of sample applications in the plugins folder hierarchy. The actual location will depend on where you have installed Eclipse, but e.g. on my machine they are at: C:\Program Files\Eclipse\eclipse 3.6.2 BlackBerry\plugins\net.rim.ejde.componentpack7.0.0_7.0.0.33\components\samples\com\rim\samples\device for the OS7 samples. Similar samples will exist for the different OS plugins you have installed.
There is a long standing sample in most OS sample sets called smsdemo which should give you all the code you need. Even if you are not developing in java, this sample should give you an indication of the path you need to take to fulfil your requirement.

How do I update the UI from a HttpWebRequest?

In my Mainpage.xaml.cs file I have a function that creates an instance of another class and tries to download a webpage using a HttpWebRequest from that instance. The problem is, once I've managed to download the webpage I can't send it back to the main UI thread. I've tried using Deployment.Current.Dispatcher.BeginInvoke to send the webpage back to a TextBlock I have waiting, but when I try I get an error telling me that I can't access the TextBlock from the other class. Is there any way to pass data between two threads without using LocalStorage?
EDIT: code below:
MainPage:
private void button1_Click(object sender, RoutedEventArgs e)
{
Member m = new Member(name, id);
}
Member class:
public Member(String Member, String API)
{
APIKey = API;
MemberName = Member;
this.super = super;
DoSend(method, string, "", null);
}
public void DoSend(string method, string url, string body, string mimetype)
{
if (WebRequest.RegisterPrefix("https://",System.Net.Browser.WebRequestCreator.ClientHttp)) {
HttpWebRequest request = WebRequest.Create(makeURI(url)) as HttpWebRequest;
request.Method = method;
request.Headers["X-NFSN-Authentication"] = MakeAuthHeader(url,body);
if (body != "")
{
byte[] bodyData = Encoding.UTF8.GetBytes(body);
request.ContentType = mimetype;
//Stuff Should Happen Here
}
else
doStuff(request);
}
public void doStuff(HttpWebRequest httpReq)
{
httpReq.BeginGetResponse(r =>
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
ResponseBlock.Text = response; //Invalid cross-thread reference
}
}, httpReq);
}
MainPage:
customClass.DownloadPage((result) =>
{
textBlock.Text = result;
},
(exception) =>
{
MessageBox.Show(exception.Message);
});
CustomClass:
public void DownloadPage(Action<string> callback, Action<Exception> exception)
{
WebClient webClient = new WebClient();
webClient.DonwloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
callback(e.Result);
});
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
exception(e.Error);
});
}
};
webClient.DonwloadStringAsync();
}

Resources