Why do i get this exception when calling the google calendar event? - webforms

This code is export event to google calendar, it is working fine in local but after upload the service in IIS server,i am getting this exception occurred.System.ServiceModel.ProtocolException: 'The content type text/html; charset=utf-8 of the response message does not match the content type of the binding (text/XML; charset=utf-8).
public partial class UNGCCalendarEvent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button 1_Click(object sender, EventArgs e)
{
// WCFServiceClient client = new WCFServiceClient();
using (UNGCCalenderSoapClient uNGC = new UNGCCalenderSoapClient())
{
uNGC.Endpoint.Binding.SendTimeout = new TimeSpan(0, 2, 30);
// EntityExtractionClient nlp = new EntityExtractionClient();
uNGC.InnerChannel.OperationTimeout = new TimeSpan(0, 50, 0);
string EventSummary = TextSumary.Text.ToString();
string EventLocation = TextLocation.Text.ToString();
string EventDescription = TextDescription.Text.ToString();
string EventStartDateTime = TextStartDate.Text.ToString();
string EventEndDateTime = TextEndDate.Text.ToString();
string CustomCalenderName = TextCustomCalenderName.Text.ToString();
string StartDatetimeZone = TextStartDatetimeZone.Text.ToString();
string EndDatetimeZone = TextEndDatetimeZone.Text.ToString();
string[] attendees = Textattendees.Text.Split(',');
var a = new ArrayOfString { Textattendees.Text };
string attachmentsfileUrl = TextattachmentsfileUrl.Text.ToString();
//string s = new string(attendees);
//string a = uNGC.UNGCCalenderService(EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime));
string calendar = uNGC.ExportGoogleEvents(EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime), CustomCalenderName, StartDatetimeZone, EndDatetimeZone, attachmentsfileUrl, a);
uNGC.Close();
}
}
protected void BtnUpdate_Click(object sender, EventArgs e)
{
UNGCCalenderSoapClient uNGC = new UNGCCalenderSoapClient();
// UNGCCalender arrString = UNGCCalenderSoapClient.ArrayOfString();
string EventID = TextEventID.Text.ToString();
string EventSummary = TextSumary.Text.ToString();
string EventLocation = TextLocation.Text.ToString();
string EventDescription = TextDescription.Text.ToString();
string EventStartDateTime = TextStartDate.Text.ToString();
string EventEndDateTime = TextEndDate.Text.ToString();
string CustomCalenderName = TextCustomCalenderName.Text.ToString();
string StartDatetimeZone = TextStartDatetimeZone.Text.ToString();
string EndDatetimeZone = TextEndDatetimeZone.Text.ToString();
string[] attendees = Textattendees.Text.Split(',');
string attachmentsfileUrl = TextattachmentsfileUrl.Text.ToString();
//string s = new string(attendees);
//string a = uNGC.UNGCCalenderService(EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime));
// string calendar = uNGC.UpdateGoogleEvents(EventID,EventSummary, EventLocation, EventDescription, Convert.ToDateTime(EventStartDateTime), Convert.ToDateTime(EventEndDateTime), CustomCalenderName, StartDatetimeZone, EndDatetimeZone, attachmentsfileUrl, arrString.AddRange(attendees));
}
}

Related

Issue while Playing, the recorded audio in WP7

Hi Developers,
If we save the recorded voice as a mp3 file. we get the error while opening the file as Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.
Please Give a Solution to overcome this Issue ....
Here is My Source code
namespace Windows_Phone_Audio_Recorder
{
public partial class MainPage : PhoneApplicationPage
{
MemoryStream m_msAudio = new MemoryStream();
Microphone m_micDevice = Microphone.Default;
byte[] m_baBuffer;
SoundEffect m_sePlayBack;
ViewModel vm = new ViewModel();
long m_lDuration = 0;
bool m_bStart = false;
bool m_bPlay = false;
private DispatcherTimer m_dispatcherTimer;
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
DataContext = vm;
m_dispatcherTimer = new DispatcherTimer();
m_dispatcherTimer.Interval = TimeSpan.FromTicks(10000);
m_dispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
m_dispatcherTimer.Start();
FrameworkDispatcher.Update();
//icBar.ItemsSource = vm.AudioData;
}
void frameworkDispatcherTimer_Tick(object sender, EventArgs e)
{
FrameworkDispatcher.Update();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
m_bStart = true;
tbData.Text = "00:00:00";
m_lDuration = 0;
m_micDevice.BufferDuration = TimeSpan.FromMilliseconds(1000);
m_baBuffer = new byte[m_micDevice.GetSampleSizeInBytes(m_micDevice.BufferDuration)];
//m_micDevice.BufferReady += new EventHandler(m_Microphone_BufferReady);
m_micDevice.BufferReady += new EventHandler<EventArgs>(m_Microphone_BufferReady);
m_micDevice.Start();
}
void m_Microphone_BufferReady(object sender, EventArgs e)
{
m_micDevice.GetData(m_baBuffer);
Dispatcher.BeginInvoke(()=>
{
vm.LoadAudioData(m_baBuffer);
m_lDuration++;
TimeSpan tsTemp = new TimeSpan(m_lDuration * 10000000);
tbData.Text = tsTemp.Hours.ToString().PadLeft(2, '0') + ":" + tsTemp.Minutes.ToString().PadLeft(2, '0') + ":" + tsTemp.Seconds.ToString().PadLeft(2, '0');
}
);
//this.Dispatcher.BeginInvoke(new Action(() => vm.LoadAudioData(m_baBuffer)));
//this.Dispatcher.BeginInvoke(new Action(() => tbData.Text = m_baBuffer[0].ToString() + m_baBuffer[1].ToString() + m_baBuffer[2].ToString() + m_baBuffer[3].ToString()));
m_msAudio.Write(m_baBuffer,0, m_baBuffer.Length);
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (m_bStart)
{
m_bStart = false;
m_micDevice.Stop();
ProgressPopup.IsOpen = true;
}
if (m_bPlay)
{
m_bPlay = false;
m_sePlayBack.Dispose();
}
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
m_bPlay = true;
m_sePlayBack = new SoundEffect(m_msAudio.ToArray(), m_micDevice.SampleRate, AudioChannels.Mono);
m_sePlayBack.Play();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAudio.Text != "")
{
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
string strSource = txtAudio.Text + ".wav";
int nIndex = 0;
while (isfData.FileExists(txtAudio.Text))
{
strSource = txtAudio.Text + nIndex.ToString().PadLeft(2, '0') + ".wav";
}
IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strSource, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Write(m_msAudio.ToArray(), 0, m_msAudio.ToArray().Length);
isfStream.Close();
}
this.Dispatcher.BeginInvoke(new Action(() => ProgressPopup.IsOpen = false));
}
}
}
DotNet Weblineindia
my Source Code For UPLOADING A AUDIO TO PHP SERVER:
public void UploadAudio()
{
try
{
if (m_msAudio != null)
{
var fileUploadUrl = "uploadurl";
var client = new HttpClient();
m_msAudio.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(m_msAudio), "uploaded_file", strFileName);
// upload the file sending the form info and ensure a result.it will throw an exception if the service doesn't return a valid successful status code
client.PostAsync(fileUploadUrl, content)
.ContinueWith((postTask) =>
{
try
{
postTask.Result.EnsureSuccessStatusCode();
var respo = postTask.Result.Content.ReadAsStringAsync();
string[] splitChar = respo.Result.Split('"');
FilePath = splitChar[3].ToString();
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/VoiceSlider.xaml?FName=" + strFileName, UriKind.Relative)));
}
catch (Exception ex)
{
// Logger.Log.WriteToLogger(ex.Message);
MessageBox.Show("voice not uploaded" + ex.Message);
}
});
}
}
catch (Exception ex)
{
//Logger.Log.WriteToLogger(ex.Message + "Error occured while uploading image to server");
}
}
First of all Windows Phone does not allow to record .mp3 files. So, the .mp3 file that you are saving will not be played by Windows Phone player.
Have a look at this. This demo is working fine for recording .wav file.
If you wish to save other formats like .aac,.amr then user AudioVideoCaptureDevice class.

How to upload images to facebook which is selected by using photoChooserTask in windows phone 8?

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.

DownloadStrinAsync error during parsing in Windows Phone

i've an issue... I would create an app that scraping the result of a google search.. but when I try to use downloadstringasync the debug return me an error "Impossible to assign 'void' to a local variable ..."
You say how I can resolve it?
This is the code
public class SearchResult
{
public string url;
public string title;
public string content;
public FindingEngine engine;
public enum FindingEngine { google, bing, google_and_bing };
public SearchResult(string url, string title, string content, FindingEngine engine)
{
this.url = url;
this.title = title;
this.content = content;
this.engine = engine;
}
}
public static List<SearchResult> GoogleSearch(string search_expression,
Dictionary<string, object> stats_dict)
{
var url_template = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&safe=active&q={0}&start={1}";
Uri search_url;
var results_list = new List<SearchResult>();
int[] offsets = { 0, 8, 16, 24, 32, 40, 48 };
foreach (var offset in offsets)
{
var searchUrl = new Uri(string.Format(url_template, search_expression, offset));
var page = new WebClient().DownloadStringAsync(searchUrl);
var o = (JObject)JsonConvert.DeserializeObject(page);
var results_query =
from result in o["responseData"]["results"].Children()
select new SearchResult(
url: result.Value<string>("url").ToString(),
title: result.Value<string>("title").ToString(),
content: result.Value<string>("content").ToString(),
engine: SearchResult.FindingEngine.google
);
foreach (var result in results_query)
results_list.Add(result);
}
return results_list;
}
Thanks!
DownloadStringAsync doesn't return anything i.e. a void so you cannot simply assign a variable to it.
You need to add an event handler to DownloadStringCompleted which will be fired when DownloadStringAsync completes.
var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(searchUrl);
static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
// e.Result will contain the returned JSON. Move the code that parse the result to here.
}

Unauthorizedaccessexception{"Invalid cross-thread access."}...is occur

i want to short my url with bitly but an exception is occur when i want to set out string to my text block
private void button1_Click(object sender, RoutedEventArgs e)
{
ShortenUrl(textBox1.Text);
}
enum Format
{
XML,
JSON,
TXT
}
enum Domain
{
BITLY,
JMP
}
void ShortenUrl(string longURL)
{
Format format = Format.XML;
Domain domain = Domain.BITLY;
string _domain;
//string output;
// Build the domain string depending on the selected domain type
if (domain == Domain.BITLY)
_domain = "bit.ly";
else
_domain = "j.mp";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
string.Format(#"http://api.bit.ly/v3/shorten?login={0}&apiKey={1}&longUrl={2}&format={3}&domain={4}",
"username", "appkey", HttpUtility.UrlEncode(longURL), format.ToString().ToLower(), _domain));
request.BeginGetResponse(new AsyncCallback(GetResponse), request);
}
void GetResponse(IAsyncResult result)
{
XDocument doc;
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string responseString = reader.ReadToEnd();
doc = XDocument.Load(reader.BaseStream);
}
//// var x = from c in doc.Root.Element("data").Elements()
// where c.Name == "url"
// select c;
//XElement n = ((IEnumerable<XElement>)x).ElementAt(0);
// textBox2.Text = ((IEnumerable<String>)x).ElementAt(0);
lista = (from Born_rich in doc.Descendants("url")
select new a()
{
shrtenurl = Born_rich.Value
}).ToList();
output = lista.ElementAt(0).shrtenurl;
textBox2.Text = output;
//
//
// textBox2.Text = s;
}
List<a> lista = new List<a>();
String output;
}
public class a
{
public String shrtenurl { set; get; }
}
The calback from HttpWebRequest occurs on a non-UI thread. If you want to change soemthing in the UI you must do it on the UI thread. Fortunatley there is an easy way to do this. You simply use the dispatcher to invoke the code in question on the UI.
Dispatcher.BeginInvoke(() => textBox2.Text = output);

I am trying to run Mars Image Viewer Sample from OCT 2010 MSDN Magazine but running into some errors?

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>");

Resources