Error 401 Not Unauhtorized LinqToTiwtter API - dotnetnuke

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

Related

WPF C# Cefsharp Ver. 71, each load of user control creates new CefSharp.BrowserSubprocess.exe

Please check the code snippets below, this get loaded everytime i navigate to my view(user control) and it creates new CefSharp.BrowserProcess.exe on each load and renders last visited URL.
Problem with is is that it does not maintain the session storage of the site (URL) And load is incorrect with data is lost.
viewModel (main) code:
private void OnLoad()
{
IsBusy = true;
try
{
if (string.IsNullOrEmpty(TieAddress))
{
TieAddress = _serviceJournalsBaseSettings.GetTieUrl();
}
var cookieManager = Cef.GetGlobalCookieManager();
Cookie cookie = new Cookie
{
Name = BaseSettings.GetTieCookieName(),
Value = BaseSettings.GetTieCookie()
};
cookieManager.SetCookie(BaseSettings.GetTieCookieUrl(), cookie);
}
catch (Exception ex)
{
ShowErrorNotification(ex.Message);
}
finally
{
IsBusy = false;
}
}
View (User control) Code:
<wpf:ChromiumWebBrowser
Grid.Row="1" Grid.ColumnSpan="2"
x:Name="BrowserTieView"
Address="{Binding TieAddress, Mode=TwoWay}"
Title="Browser Tie View"
AllowDrop="True"/>
View.Xaml.cs
public partial class ServiceJournalsView : UserControl
{
public ServiceJournalsView()
{
InitializeComponent();
BrowserTieView.DownloadHandler = new DownloadHandler();
BrowserTieView.BrowserSettings = new BrowserSettings()
{
ApplicationCache = CefState.Enabled,
FileAccessFromFileUrls = CefState.Enabled,
Javascript = CefState.Enabled,
LocalStorage = CefState.Enabled,
WebSecurity = CefState.Disabled,
JavascriptCloseWindows = CefState.Enabled,
JavascriptDomPaste = CefState.Enabled,
};
BrowserTieView.LoadError += (sender, args) =>
{
// Don't display an error for downloaded files.
if (args.ErrorCode == CefErrorCode.Aborted)
{
return;
}
// Display a load error message.
var errorBody = string.Format(
"<html><body bgcolor=\"white\"><h2>Failed to load URL {0} with error {1} ({2}).</h2></body></html>",
args.FailedUrl, args.ErrorText, args.ErrorCode);
args.Frame.LoadHtml(errorBody, base64Encode: true);
};
Unloaded += async delegate (object sender, RoutedEventArgs args)
{
BrowserTieView.WebBrowser.Dispose();
BrowserTieView.Dispose();
await Task.Delay(10);
};
}
public ServiceJournalsViewModel VMServiceJournalsViewModel
{
get => (ServiceJournalsViewModel) DataContext;
set { DataContext = value; }
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
try
{
BrowserTieView.RegisterJsObject("serviceJournalsJsModel", VMServiceJournalsViewModel.ServiceJournalsJsModel);
}
catch (Exception ex)
{
}
}
}
As per discussion in the comments of the question posted( and as per #amaitland) Multiple instances of Cefsharp.BrowserSubprocess.exe is perfectly normal.

No value for JSONArray

Problem with JSONArray. This is my code, help me
This is my JsonObject and error..
Json errore: No value for {"Username":"rafyluc","Record":"500"}{"Username":"inkinati","Record":"600"}{"Username":"rafyluc","Record":"500"}{"Username":"inkinati","Record":"600"}
public class ListaAlunni extends AppCompatActivity {
private static ArrayList<Alunni> alunni;
AlunniListAdapter customAdapter;
private String TAG = ListaAlunni.class.getSimpleName();
private static String url = "http://192.168.1.11:80/webservice/lista.php";
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_alunni);
getSupportActionBar().setTitle("Lista Alunni");
alunni = new ArrayList<Alunni>(10);
popola();
}
private void setTextLista() {
ListView ll = (ListView) findViewById(R.id.lista);
ll.setAdapter(new AlunniListAdapter(ListaAlunni.this, R.layout.lista_row, alunni));
}
private void popola() {
new AsyncTask<Object, Object, Object>() {
#Override
protected void onPreExecute() {
alunni = new ArrayList<Alunni>(10);
}
#Override
protected Object doInBackground(Object... params) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("Debug_object", String.valueOf(jsonObj));
// Getting JSON Array node
// try {
//JSONArray jArray=new JSONArray(jsonStr);
JSONArray jArray = jsonObj.getJSONArray(jsonStr);
Log.d("DEBUG_json", String.valueOf(jArray));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("TEST", "Username: " + json_data.getString("Username") +
", record: " + json_data.getString("Record")
);
String nome= json_data.getString("Username");
String record=json_data.getString("Record");
// alunni.add(new Alunni(nome,record));
HashMap<String, String> item = new HashMap<>();
item.put("Username", nome);
item.put("Record", record);
// adding item to item list
itemList.add(item);
}
} catch (final JSONException e) {
Log.e(TAG, "Json errore: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json errore: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Object o) {
setTextLista();
}
}.execute();
}
}
classe HttpHandler:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Looking at your code, it seems JSONArray jArray = jsonObj.getJSONArray(jsonStr);
is causing the problem.
jsonObj.getJSONArray requires name of the property to be passed E.g. jsonObj.getJSONArray("array_property") but instead, it seems you are passing JSON string.
Also, before calling jsonObj.getJSONArray("array_property") you need to make sure that the array_property exists in the jsonObj

Codenameone closing a socket

There seems to be no way of disconnecting a socket without causing a connection reset error on the server side.
I'm using the com.codename1.io.Socket and com.codename1.io.SocketConnection implementations within a tester app. My code is as follows:
private SpanLabel lblStatus;
private SpanLabel lblIncoming;
private CustomSocketConnection con;
private Thread tIncoming;
public ConnectForm() {
con = getSocketConnection();
Button btnConnect = getConnectButton();
Button btnDisconnect = getDisconnectButton();
Button btnSendMessage = getSendMessageButton();
lblStatus = getInfoLabel();
lblIncoming = getIncomingLabel();
setLayout(new BoxLayout(BoxLayout.Y_AXIS));
addComponent(btnConnect);
addComponent(btnDisconnect);
addComponent(btnSendMessage);
addComponent(lblStatus);
addComponent(lblIncoming);
}
private Button getConnectButton() {
Button btn = new Button("Connect (localhost)");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Socket.connect("localhost", 8687, con);
}
});
return btn;
}
private Button getDisconnectButton() {
Button btn = new Button("Disconnect");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//??? I don't know how to do this
try {
tIncoming.join();
} catch (Exception e) {
e.printStackTrace();
tIncoming.interrupt();
}
}
});
return btn;
}
private Button getSendMessageButton() {
Button btn = new Button("Send Message");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
con.os.write("Hello".getBytes());
con.os.write(Integer.parseInt("04", 16)); //end of transmit
con.os.flush();
lblStatus.setText("Message Sent");
} catch (Exception e) {
e.printStackTrace();
}
}
});
return btn;
}
private SpanLabel getInfoLabel() {
return new SpanLabel("Disconnected");
}
private SpanLabel getIncomingLabel() {
return new SpanLabel("...");
}
private CustomSocketConnection getSocketConnection() {
return new CustomSocketConnection();
}
class CustomSocketConnection extends SocketConnection {
public OutputStream os;
public InputStream is;
#Override
public void connectionError(int errorCode, String message) {
lblStatus.setText("Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
}
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
lblStatus.setText("Connected :)");
this.is = is;
this.os = os;
spawnIncomingMessageWatcher();
}
}
private void spawnIncomingMessageWatcher() {
tIncoming = new Thread(new Runnable() {
public void run() {
String s = "";
int eot = Integer.parseInt("04", 16);
while (con.isConnected()) {
try {
int temp;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (((temp = con.is.read()) != -1) && (temp != eot)) {
baos.write(temp);
}
lblIncoming.setText(new String(baos.toByteArray()));
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
tIncoming.start();
}
With the getDisconnectButton() method, I do not know how to properly disconnect from the server, as the SocketConnection object does not seem to have an appropriate method for this.
If you call close() on either the Input- or OutputStream then you close the Socket, code from Socket.SocketInputStream class link.
public void close() throws IOException {
closed = true;
if(Util.getImplementation().isSocketConnected(impl)) {
Util.getImplementation().disconnectSocket(impl);
con.setConnected(false);
}
}
So first send close instruction to Server and then close a stream.
Hope this helps,

ServiceStack Exception handling in Silverlight

I am trying to understand how to handle an Exception in Silverlight that come from a ServiceStack service.
public class TestService : Service
{
public object Any (TestRequest request)
{
throw new Exception("Name");
var lst = new List<TestResponse>();
for (int i = 0; i < 20; i++)
{
var item = new TestResponse { ID = i, Descrizione = string.Format("Descr_{0}", i) };
lst.Add(item);
{
}
return lst;
}
}
}
I have seen in the wiki that the generic exception are handled as a 500 InternalServerError, but when i throw an Exception like in the example i do not receive the Exception data in the argument(but using fiddler i can see all the data in the Json).
My SilverLight code is
private ServiceClient<TestRequest, ContainerTestResponse> serviceClient;
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
serviceClient = new ServiceClient<TestRequest, ContainerTestResponse>();
serviceClient.Completed += serviceClient_Completed;
}
void serviceClient_Completed(object sender, ServiceClientEventArgs<ContainerTestResponse> e)
{
var webEx = e.Error as WebException;
if (webEx != null)
{
//can't figure out where "Name" is...
var webResponse = (HttpWebResponse)webEx.Response;
MessageBox.Show(webResponse.StatusDescription);
return;
}
if (e.Error != null)
throw e.Error;
var result = e.Response.Dati;
}
}
My JSon response is
{"ResponseStatus":{"ErrorCode":"Exception","Message":"Name","StackTrace":"[TestRequest: 19/11/2013 15:39:29]:\n[REQUEST: {}]\nSystem.Exception: Name\r\n at SSAuthenticationProvider.TestService.Any(TestRequest request) in c:\\projects\\2013\\Demo\\SSAuthenticationProvider\\SSAuthenticationProvider\\TestService.cs:line 20\r\n at ServiceStack.ServiceHost.ServiceRunner`1.Execute(IRequestContext requestContext, Object instance, TRequest request)","Errors":[]}}
Am I doing some mistake?
Thanks all

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