Using the snmptrapd example I was able to receive v1 traps and v2 traps/informs easily. However, with v3 I am unable to receive traps. I am using AES128 and SHA1 for Privacy and Authentication.
When I "wireshark" port 162 I see "encryptedPDU: privKey unknown" coming from the device I am attempting to receive traps from. It is using NET-SNMP if that helps.
I was able to implement applications using SharpSNMP for gets and sets with no problem. What am I missing here?
Code snippet below:
Note: engine.Start() is called form the instantiating class.
registry = new UserRegistry();
var authProvider = new SHA1AuthenticationProvider(new OctetString("authsecret"));
var privacyProvider = new AESPrivacyProvider(new OctetString("privsecret"), authProvider);
registry.Add(new OctetString("informuser"), privacyProvider);
registry.Add(new OctetString("trapuser"), privacyProvider);
TrapV1Handler = new TrapV1MessageHandler();
TrapV1Handler.MessageReceived += WatcherTrapV1Received;
v1Mapping = new HandlerMapping("v1", "TRAPV1", TrapV1Handler);
TrapV2Handler = new TrapV2MessageHandler();
TrapV2Handler.MessageReceived += WatcherTrapV2Received;
v2Mapping = new HandlerMapping("v2,v3", "TRAPV2", TrapV2Handler);
InformHandler = new InformRequestMessageHandler();
InformHandler.MessageReceived += WatcherInformRequestReceived;
informMapping = new HandlerMapping("v2,v3", "INFORM", InformHandler);
store = new ObjectStore();
var v1 = new Version1MembershipProvider(new OctetString("public"), new OctetString("public"));
var v2 = new Version2MembershipProvider(new OctetString("public"), new OctetString("public"));
var v3 = new Version3MembershipProvider();
var membership = new ComposedMembershipProvider(new IMembershipProvider[] {v1, v2, v3});
var handlerFactory = new MessageHandlerFactory(new[] {v1Mapping, v2Mapping, informMapping});
var pipelineFactory = new SnmpApplicationFactory(store, membership, handlerFactory);
engine = new SnmpEngine(pipelineFactory, new Listener { Users = registry }, new EngineGroup());
engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, 162));
engine.ExceptionRaised += this.DoSomething;
}
private void DoSomething(object sender, ExceptionRaisedEventArgs args)
{
// never gets here
}
private void WatcherInformRequestReceived(object sender, InformRequestMessageReceivedEventArgs e)
{
// or here for v3 (works fine for v2)
}
private void WatcherTrapV2Received(object sender, TrapV2MessageReceivedEventArgs e)
{
// or here for v3 (works fine for v2)
}
private void WatcherTrapV1Received(object sender, TrapV1MessageReceivedEventArgs e)
{
// works fine
}
Related
a had successful connection with ExchangeVersion.Exchange2007_SP1, when I changed it on 2010 or latest I get the exception on this row:
service.AutodiscoverUrl(MailboxToAccess, RedirectionUrlValidationCallback);
->System.NullReferenceException: 'Object reference not set to an instance of an object.'
I tried with Packages:
Exchange.WebServices.Managed.Api v2.2.1.2 and Microsoft.Exchange.WebServices v2.2.0
static void Main(string[] args)
{
String MailboxToAccess = "username#domain";
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
SearchFilter sfSearchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
service.Credentials = new WebCredential("username#domain", "password");
service.AutodiscoverUrl(MailboxToAccess, RedirectionUrlValidationCallback);
SetStreamingNotifications(service);
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}
I set the Exchange service URL manually using
/ Create the binding.
ExchangeService service = new ExchangeService();
// Set the credentials for the on-premises server.
service.Credentials = new WebCredentials("user1#contoso.com", "password");
// Set the URL.
service.Url = new Uri("https://computername.domain.contoso.com/EWS/Exchange.asmx");
I still don't understand why It didn't work for me with
service.AutodiscoverUrl("User1#contoso.com");
I am developing a Windows Phone app in which I have to post a photo to facebook. And that particular photo is choosen by using PhotoChooserTask or CameraChooserTask.
Normally, I can post a particular photo successfully, but I am facing problem to post the selected photo. I saw some link like
link
So please if anyone know about the issue please help me out.
Thanx in advance.
EDIT
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
//var parameters1 = new Dictionary<>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
parameters["ContentType"] = "image/png";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
string imageName = "ic_launcher.png";
StreamResourceInfo sri = null;
Uri jpegUri = new Uri(imageName, UriKind.Relative);
sri = Application.GetResourceStream(jpegUri);
try
{
byte[] imageData = new byte[sri.Stream.Length];
sri.Stream.Read(imageData, 0, System.Convert.ToInt32(sri.Stream.Length));
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = imageName,
ContentType = "image/jpg"
};
fbUpload.SetValue(imageData);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Tribute";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1 + "\n" + d + "\n" + memoType + "\n" + message1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
//client.PostTaskAsync("me/photos", parameters1);
}
On clicking on a button I am calling PostClicked class and it will directly go to facebook mainpage and it will ask for login information. Like this I am doing.
Please check it out
Now I can share a photo to facebook successfully by using photochoosertask or cameratask.
I am sharing my experience so that if anyone face the same issue can use it.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
SaveImageToIsolatedStorage(image, tempJPEG);
this.image.Source = image;
}
public void SaveImageToIsolatedStorage(BitmapImage image, string fileName)
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
var fileStream = isolatedStorage.CreateFile(fileName);
if (image != null)
{
var wb = new WriteableBitmap(image);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
fileStream.Close();
}
}
With this you can able to save the selected image to IsolatedStorage.
And then at the time of posting the photo to facebook you have to select the image from IsolatedStorage.
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
try
{
byte[] data;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read))
{
data = new byte[fileStream.Length];
fileStream.Read(data, 0, data.Length);
fileStream.Close();
}
}
//MemoryStream ms = new MemoryStream(data);
//BitmapImage bi = new BitmapImage();
//// Set bitmap source to memory stream
//bi.SetSource(ms);
//this.imageTribute.Source = bi;
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = tempJPEG,
ContentType = "image/jpg"
};
fbUpload.SetValue(data);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Notice";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
Thanx to all....
you can do that by two methods :
1) by using mediasharetask in which it will show u all sharing account to which your phone is synced like facebook,gmail,linkdin,twitter,etc : it can be used like like this.
ShareMediaTask shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = path;
shareMediaTask.Show();
2) by using facebook sdk. you can get the package from nuget manager and then u can use it to share on facebook.
I hope this might help u.
I'm trying to create an application for windows phone 7 which acts as a client and which sends requests to a server which is written in Java. The client supposed to send a request, and wait for an answer from the server.
My problem is that I can't seem to communicate with the server properly. When I tried testing it in a simple .NET C# program and used blocking calls such as socket.send() and socket.receive() it works but the Windows Phone application doesn't have blocking calls.
This is what the server (Java) does once it detects a connection:
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
String message = reader.readLine();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"));
writer.println("hiBack");
writer.close();
and this is how the client(C#) is implemented:
public void sendRequest()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var connectionOperation = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(server, serverPort) };
connectionOperation.Completed += new EventHandler<SocketAsyncEventArgs>(onConnectCompleted);
socket.ConnectAsync(connectionOperation);
}
private void onConnectCompleted(object sender, SocketAsyncEventArgs e)
{
if (e.SocketError != SocketError.Success)
{
System.Console.WriteLine("Error! " + e.SocketError);
return;
}
var sendListener = new SocketAsyncEventArgs();
string msg = "hi";
var buffer = new System.Text.UTF8Encoding().GetBytes(msg + Environment.NewLine);
sendListener.SetBuffer(buffer, 0, buffer.Length);
sendListener = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(server, serverPort) };
sendListener.Completed += new EventHandler<SocketAsyncEventArgs>(onSendCompleted);
socket.SendToAsync(sendListener);
}
private void onSendCompleted(object sender, SocketAsyncEventArgs e)
{
socket.ReceiveAsync(e);
}
I've got a problem with the line: socket.SendToAsync(sendListener); on the C# side which end the program without doing anything (exit with return code 0).
the Java server starts it's work instantly when it detects the connection so it might also cause a problem?
What can I do to make the communication work?
I've to download an image from the server on button click.
The code is:
private void Button_Click(object sender, RoutedEventArgs e)
{
(sender as Button).IsEnabled = false;
progressbar.IsIndeterminate = true;
WebClient w = new WebClient();
w.OpenReadAsync(new Uri("http://example.com/xxx/image.png"));
w.OpenReadCompleted += new OpenReadCompletedEventHandler(w_OpenReadCompleted);
}
void w_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
progressbar.IsIndeterminate = false;
BitmapImage b = new BitmapImage();
b.SetSource(e.Result);
Image img = new Image();
img.Source = b;
LayoutRoot.Children.Add(img);
}
The problem which I'm facing is that for the first time the data is being downloaded from the server and shown correctly. However, if I quit the application and again start it, it downloads the old image even if I have deleted the image from the server or changed the image. I think the image is getting cached somewhere but don't know how to solve this problem.
I think this will be the same as your issue:
How do you disable caching with WebClient and Windows Phone 7
I haven't noticed this behaviour when using the HttpWebRequest to get data. But I'am not sure about it.
Update: HttpWebRequest has by default the same behaviour but can be disabled. This blogpost is talking about the options you have:
http://www.nickharris.net/2010/10/windows-phone-7-httpwebrequest-returns-same-response-from-cache/
Finally managed to fix it.The only change that was made is:
w.OpenReadAsync(new Uri("http://example.com/xxx/image.png?q="+Guid.NewGuid()));
You could also use HttpWebRequest to download fresh data every request. Here is a simple class which sets up the asynchronous calls
Here is a simple http client which will download data from the given uri.
public static class HttpClient
{
public static void Execute(Uri uri, Action<HttpWebRequest> onrequest, Action<HttpWebResponse> onresponse)
{
var request = HttpWebRequest.CreateHttp(uri);
onrequest(request);
request.BeginGetResponse
(
result =>
{
try
{
if (request.HaveResponse)
onresponse((HttpWebResponse)request.EndGetResponse(result));
}
catch { }
},
null
);
}
}
Using the HttpClient with your button click event you get this
private void Button_Click(object sender, RoutedEventArgs e)
{
(sender as Button).IsEnabled = false;
progressbar.IsIndeterminate = true;
HttpClient.Execute
(
new Uri(http://example.com/xxx/image.png),
request =>
{
request.UserAgent = "Custom HTTP Client";
},
response =>
{
progressbar.IsIndeterminate = false;
BitmapImage b = new BitmapImage();
b.SetSource(response.GetResponseStream());
Image img = new Image();
img.Source = b;
LayoutRoot.Children.Add(img);
}
);
}
Here is the code-
private void getImageIDs()
{
Uri serviceUri = new Uri("https://api.sqlazureservices.com/NasaService.svc/MER/Images?missionId=1&$format=raw");
WebClient recDownloader = new WebClient();
recDownloader.Headers["$accountKey"] = "<enter your key>";
recDownloader.Headers["$uniqueUserID"] = "<enter your id>";
recDownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(recDownloader_OpenReadCompleted);
recDownloader.OpenReadAsync(serviceUri);
}
private void recDownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
Stream responseStream = e.Result;
XNamespace ns = "http://www.w3.org/2005/Atom";
XElement marsStuff = XElement.Load(responseStream);
entries = marsStuff.Elements(ns + "entry");
string imageID = (string)entries.ElementAt<XElement>(index).Element(ns + "title").Value;
Console.WriteLine(imageID);
getImage(imageID);
}
}
private void getImage(string ID)
{
Uri serviceUri = new Uri("https://api.sqlazureservices.com/NasaService.svc/MER/Images/" + ID + "?$format=raw");
WebClient imgDownloader = new WebClient();
imgDownloader.Headers["$accountKey"] = "<enter your key>";
imgDownloader.Headers["$uniqueUserID"] = "<enter your id>";
imgDownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(imgDownloader_OpenReadCompleted);
imgDownloader.OpenReadAsync(serviceUri);
}
private void imgDownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
Stream imageStream = e.Result;
BitmapImage imgsrc = new BitmapImage();
imgsrc.SetSource(imageStream);
MarsImage.Source = imgsrc;
}
}
private void appbar_BackButton_Click(object sender, EventArgs e)
{
if (index > 0)
{
index--;
XNamespace ns = "http://www.w3.org/2005/Atom";
string imageID = (string)entries.ElementAt<XElement>(index).Element(ns + "Title").Value;
getImage(imageID);
}
}
private void appbar_ForwardButton_Click(object sender, EventArgs e)
{
if ( (index + 1) < entries.Count<XElement>())
{
index++;
XNamespace ns = "http://www.w3.org/2005/Atom";
string imageID = (string)entries.ElementAt<XElement>(index).Element(ns + "Title").Value;
getImage(imageID);
}
}
}
I am not seeing any images. Anybody able to get this sample running?
This one? http://msdn.microsoft.com/en-us/magazine/gg232764.aspx
If so, there are some things that had to change to make it work, as the original code was on a preview version of the WP7 tools, as listed in the comments there:
Delete (or comment out) the following lines of code from MainPage.xaml.cs
recDownloader.Headers["$accountKey"] = "<Your account key>";
recDownloader.Headers["$uniqueUserID"] = "<Your user ID>";
imgDownloader.Headers["$accountKey"] = "<Your account key>";
imgDownloader.Headers["$uniqueUserID"] = "<Your user ID>";
Replace the two recDownloader lines of code with:
recDownloader.Credentials = new NetworkCredential("accountKey", "<Your account key>");
Replace the two imgDownloader lines of code with:
imgDownloader.Credentials = new NetworkCredential("accountKey", "<Your account key>");