Unexpected end of file in C# while reading GeoRSS feed - c#

In my program I fetch GeoRSS from a website every 10th second. As long as no new items are added to the GeoRSS feed, the program works fine (i.e. I can fetch and parse the rss properly - also when the elements of the existing rss items change their value). However, as soon as a new item is added to the rss feed, I get the following error:
Unexpected end of file while parsing Name has occurred. Line 85, position 13.
Stacktrace:
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.ParseQName(Boolean isQName, Int32 startOffset, Int32& colonPos)
at System.Xml.XmlTextReaderImpl.ParseElement()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlReader.MoveToContent()
at System.Xml.XmlReader.IsStartElement()
at System.ServiceModel.Syndication.Rss20FeedFormatter.ReadItemFrom(XmlReader reader, SyndicationItem result, Uri feedBaseUri)
at System.ServiceModel.Syndication.Rss20FeedFormatter.ReadItem(XmlReader reader, SyndicationFeed feed)
at System.ServiceModel.Syndication.Rss20FeedFormatter.ReadItems(XmlReader reader, SyndicationFeed feed, Boolean& areAllItemsRead)
at System.ServiceModel.Syndication.Rss20FeedFormatter.ReadXml(XmlReader reader, SyndicationFeed result)
at System.ServiceModel.Syndication.Rss20FeedFormatter.ReadFrom(XmlReader reader)
at System.ServiceModel.Syndication.SyndicationFeed.Load[TSyndicationFeed](XmlReader reader)
at Master.Model.ResourceManagerService.wc_OpenReadCompleted(Object sender, OpenReadCompletedEventArgs e) in C:\Users\polle\Documents\Visual Studio 2010\Projects\Master(23)\LSCommMaster\Master\Master\Services\ResourceManagerService.cs:line 319
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherOperation operation, CancellationToken cancellationToken, TimeSpan timeout)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run()
at Master.App.Main() in C:\Users\polle\Documents\Visual Studio 2010\Projects\Master(23)\LSCommMaster\Master\Master\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
The code I use to fetch the rss is included below:
public static void FetchRSS(string url)
{
if (url != String.Empty)
{
LoadRSS(url.Trim());
DispatcherTimer UpdateTimer = new System.Windows.Threading.DispatcherTimer();
UpdateTimer.Interval = new TimeSpan(0, 0, 0, 0, 10000);
UpdateTimer.Tick += (evtsender, args) =>
{
LoadRSS(url.Trim());
};
UpdateTimer.Start();
}
}
private static void LoadRSS(string uri)
{
Trace.WriteLine("Fetching rss feed");
WebClient wc = new WebClient();
wc.OpenReadCompleted += wc_OpenReadCompleted;
Uri feedUri = new Uri(uri, UriKind.Absolute);
wc.OpenReadAsync(feedUri);
}
private static void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
Trace.WriteLine("Error in Reading Feed. Try Again later!");
return;
}
using (Stream s = e.Result)
{
SyndicationFeed feed;
List<SyndicationItem> feedItems = new List<SyndicationItem>();
using (XmlReader reader = XmlReader.Create(s))
{
try
{
feed = SyndicationFeed.Load(reader);
foreach (SyndicationItem feedItem in feed.Items)
{
SyndicationElementExtensionCollection ec = feedItem.ElementExtensions;
string title = feedItem.Title.Text;
string x = "";
string y = "";
string state = "not available";
string type = "not available";
string task = "not available";
foreach (SyndicationElementExtension ee in ec)
{
XmlReader xr = ee.GetReader();
switch (ee.OuterName)
{
case ("lat"):
{
y = xr.ReadElementContentAsString();
break;
}
case ("long"):
{
x = xr.ReadElementContentAsString();
break;
}
case ("point"):
{
string p = xr.ReadElementString();
string[] coordinates = p.Split(' ');
y = coordinates[0];
x = coordinates[1];
break;
}
case ("state"):
{
state = xr.ReadElementString();
break;
}
case ("type"):
{
type = xr.ReadElementString();
break;
}
case ("taskDescription"):
{
task = xr.ReadElementString();
break;
}
}
}
if (!string.IsNullOrEmpty(x))
{
Resource resource = new Resource()
{
Geometry = new MapPoint(Convert.ToDouble(x, System.Globalization.CultureInfo.InvariantCulture),
Convert.ToDouble(y, System.Globalization.CultureInfo.InvariantCulture), new SpatialReference(4326))
};
resource.Attributes.Add("TITLE", title);
resource.Attributes.Add("STATE", state);
resource.Attributes.Add("TYPE", type);
resource.Attributes.Add("TASK", task);
resource.Attributes.Add("PENDINGTASK", "none");
resource.Title = title;
resource.TypeDescription = type;
resource.State = state;
resource.TaskDescription = task;
resource.PendingTask = "none";
ResourceDataReceivedMessage msg = new ResourceDataReceivedMessage() { Resource = resource };
Messenger.Default.Send<ResourceDataReceivedMessage>(msg);
}
else
{
Trace.WriteLine("STRING IS NULL OR EMPTY");
}
}
}
catch
{
Trace.WriteLine("Exception occurred while fetching RSS feed" );
}
}
}
}
Does anyone have an idea what's causing the error, and how I can prevent it from happening?

sounds like when you get an update you are just adding it to the end of what you already have, possibly outside of the wrong ending tag?
<root>
<!-- Tags Galore -->
</root>
<addedTags></addedTags>
Like that

Related

Exception has been thrown by the target of an invocation?

I have an exception and I couldn't find a solution for my problem. I think my whole code is valid c#.
namespace YoutubeDownloader2Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
DownloadUrl DownloadUrl = new DownloadUrl();
List<Class1> FinalLiast = DownloadUrl.DownloadUrlMethod(textBox1.Text);
int i = 0;
foreach (var Urls in FinalLiast)
{
string Authorization = Urls.Author;
IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(Urls.Url);
VideoInfo Video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 144);
if (Video.RequiresDecryption)
{
DownloadUrlResolver.DecryptDownloadUrl(Video);
}
string path = Directory.CreateDirectory(#"C:\Youtube\" + Authorization).ToString();
var videoDownloader = new VideoDownloader(Video,
Path.Combine((#"C:\youtube\" + path), Video.Title + Video.VideoExtension));
StreamWriter dosya = File.AppendText((#"C:\youtube\" + path) + i + ".txt");
videoDownloader.Execute();
//Thread.Sleep(60000);
i++;
}
}
}
}
public class DownloadUrl
{
public List<Class1> DownloadUrlMethod(string txtboxDeger)
{
VideoSearch Items = new VideoSearch();
List<Class1> ListClass1 = new List<Class1>();
string searchCount =
txtboxDeger + "&sp=EgIYAVAU";
foreach (var Item in Items.SearchQuery(searchCount, 1))
{
Class1 Video = new Class1();
Video.title = Item.Title;
Video.Author = Item.Author;
Video.Url = Item.Url;
IEnumerable<VideoInfo> videos = DownloadUrlResolver.GetDownloadUrls(Video.Url);
ListClass1.Add(Video);
}
return ListClass1;
}
}
The code works fine for three queries, but I have 20. At 3. step, it throws an exception; here's the stack trace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at YoutubeDownloader2Form.Program.Main() in C:\Users\Ramazan BIYIK\source\repos\YoutubeDownloader2Form\YoutubeDownloader2Form\Program.cs:line 26>>
You can see from picture where the code throws. I tried asynchronously, and it also throws. I checked the InnerException; it says that the given path's format is not supported. But, it downloaded first three videos successfully. It should work fine for other videos too.
Why is this code throwing an exception?
I followed these tutorials to write this code:
https://www.youtube.com/watch?v=kv63n_rfJwk
https://www.youtube.com/watch?v=TnG3urCD_m0

Oracle.DataAccess.Client.OracleException C#

I have this class where I am selecting two values from the database and comparing it to the textbox values provided by the users. Below is my class.
public void Userlogin(TextBox username, TextBox pwd)
{
int _failedAttempt = 0;
OpenConnection();
command = new OracleCommand();
command.CommandText = "SELECT username, user_pwd FROM dinein_system_users WHERE username:usrname AND user_pwd:pwd";
command.Connection = dbconnect;
command.BindByName = true;
try
{
command.Parameters.Add("usrname", username.Text);
command.Parameters.Add("pwd", pwd.Text);
}
catch (NullReferenceException NRE)
{
MessageBox.Show("Please contact your developer about this error. Thank you " + NRE);
}
_reader = command.ExecuteReader();
if (_reader.Read() != true)
{
_failedAttempt = _failedAttempt + 1;
while (_failedAttempt < 3)
{
MessageBox.Show("Incorrect Username or Password. Please try again " + "Attempts: " + _failedAttempt);
username.ResetText();
pwd.ResetText();
}
}
else
{
MessageBox.Show("Welcome");
}
}
my connection string
this._connectionString = "Data Source=xe;Max Pool Size=50;Min Pool Size=1;Connection Lifetime=120;Enlist=true;User Id=hr;Password=hr";
So when the program is executed I am getting this error
An unhandled exception of type 'Oracle.DataAccess.Client.OracleException' occurred in Oracle.DataAccess.dll
Additional information: External component has thrown an exception. I have been at this for the past hour any help would be appreciated.
Update
Open Connection method
public void OpenConnection()
{
try
{
if (dbconnect == null)
{
dbconnect = new OracleConnection(this._connectionString);
dbconnect.Open();
return;
}
switch (dbconnect.State)
{
case ConnectionState.Closed:
case ConnectionState.Broken:
dbconnect.Close();
dbconnect.Dispose();
dbconnect = new OracleConnection(this._connectionString);
dbconnect.Open();
return;
}
}
catch (OracleException oracleException)
{
MessageBox.Show("Database connectionString is null. Contact your developer! " + oracleException);
}
}
Exception Stack Trace
at Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, String procedure, Boolean bCheck)
at Oracle.DataAccess.Client.OracleException.HandleError(Int32 errCode, OracleConnection conn, String procedure, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, Boolean bCheck)
at Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery, Boolean fillRequest, CommandBehavior behavior)
at Oracle.DataAccess.Client.OracleCommand.ExecuteReader()
at DINEIN.OracleDB_Connection.Userlogin(TextBox username, TextBox pwd) in f:\My Documents\Projects\DINEIN\DINEIN\OracleDB_Connection.cs:line 92
at DINEIN.Login.btn_login_Click(Object sender, EventArgs e) in f:\My Documents\Projects\DINEIN\DINEIN\Login.cs:line 31
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.PerformClick()
at System.Windows.Forms.Form.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.ProcessDialogKey(Keys keyData)
at System.Windows.Forms.Control.PreProcessMessage(Message& msg)
at System.Windows.Forms.Control.PreProcessControlMessageInternal(Control target, Message& msg)
at System.Windows.Forms.Application.ThreadContext.PreTranslateMessage(MSG& msg)
at System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FPreTranslateMessage(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at DINEIN.Program.Main() in f:\My Documents\Projects\DINEIN\DINEIN\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Rather than using your separate OpenConnection() method, consider coding with the using() statement. It will ensure that your connection an other database-related objects are always disposed.
For example:
int _failedAttempt = 0;
public void Userlogin(TextBox username, TextBox pwd)
{
try
{
using (var connection = new OracleConnection(_connectionString))
{
connection.Open();
using (var command = new OracleCommand())
{
command.CommandText = "SELECT username, user_pwd FROM dinein_system_users WHERE username= :usrname AND user_pwd= :pwd";
command.Connection = connection;
command.BindByName = true;
command.Parameters.Add("usrname", username.Text);
command.Parameters.Add("pwd", pwd.Text);
using (var reader = command.ExecuteReader())
{
if (reader.Read() != true)
{
_failedAttempt += 1;
if (_failedAttempt < 3)
{
MessageBox.Show("Incorrect Username or Password. " +
"Please try again. " +
$"Attempts: {_failedAttempt}");
username.ResetText();
pwd.ResetText();
}
else
{
// 3 failed attempts
}
}
else
{
_failedAttempt = 0;
MessageBox.Show("Welcome");
}
}
}
}
}
catch(OracleException ex)
{
MessageBox.Show("Error: {ex}");
}
}

String Invoke Issue

I am using a backgroundworker and I think there is a cross thread thing.. But I cant solve it.
my code is here
private void bgworkerGameLoad_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
var arg = e.Argument.ToString();
var liste = webHelper.ShowGame("http://www.abx.com/" + arg);
txtHowToPlay.Invoke(new Action(() => txtHowToPlay.Text = String.Format("Oyun Bilgi: {0}", liste[0])));
txtInfo.Invoke(new Action(() => txtInfo.Text = String.Format("Nasıl Oynanır: {0}", liste[1])));
bgworkerGameLoad.ReportProgress(0,liste[2]);
}
private void bgworkerGameLoad_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (FlashPlayerActive)
UnLoad();
string url="";
Invoke(new MethodInvoker(() =>
{
url= e.UserState.ToString();
Thread.Sleep(2);
}));
axShockwaveFlash1.Movie = url;
LoadFlash();
pbWaitForChannelLoading.Visible = false;
axShockwaveFlash1.Play();
}
the problem is that I cant get the e.UserState.ToString() for my shocwaveplayer. I used a local string variable but its the same result.
it is occured targetofaninvocation exception in program.cs
Application.Run(new FrmMain());;
but that code is in frmMain.cs
this is detail of the exception
System.Reflection.TargetInvocationException was unhandled
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at XXX.Program.Main() in c:\Users..............\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
at System.Windows.Forms.Control.Invoke(Delegate method)
at XXX.FrmMain.bgworkerGameLoad_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e) in c:\Users..........\FrmMain.cs:line 332
at System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
at System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object arg)
InnerException:
what is my mistake? I tried to use delegate but its the same..
It sounds like the problem is as simple as e.UserState being null. You don't even need to use Invoke to get at UserState - you'll see the same problem if you just have:
if (FlashPlayerActive)
UnLoad();
string url = e.UserState.ToString();
Thread.Sleep(2); // This is generally a bad idea anyway, btw...
Where are you setting the UserState? I suspect you're not setting it anywhere, so it's still null, which is why you're getting an exception.
I solved the problem..
I hadnt added axShockwaveFlash1 to my form before set values..
in LoadFlash function, it was
public void LoadFlash()
{
axShockwaveFlash1 = new AxShockwaveFlash();
axShockwaveFlash1.BeginInit();
axShockwaveFlash1.Location = new Point(14, 196);
axShockwaveFlash1.Name = "Test Movie";
axShockwaveFlash1.TabIndex = 0;
axShockwaveFlash1.Movie = liste[2];
axShockwaveFlash1.EmbedMovie = true;
axShockwaveFlash1.AutoSize = true;
axShockwaveFlash1.Size = new Size(640, 480);
axShockwaveFlash1.Visible = true;
axShockwaveFlash1.EndInit();
splitContainerControl.Panel2.Controls.Add(axShockwaveFlash1);
FlashPlayerActive = true;
}
but i changed this code like
public void LoadFlash()
{
axShockwaveFlash1 = new AxShockwaveFlash();
splitContainerControl.Panel2.Controls.Add(axShockwaveFlash1);
axShockwaveFlash1.BeginInit();
axShockwaveFlash1.Location = new Point(14, 196);
...
it works..
if found the solution here
http://forum.fusioncharts.com/topic/2424-how-to-resolve-invalidactivexstateexception-while-loading-chart/#entry8855
thanx

System.UnauthorizedAccess Exception: Access to the path c:\\ is denied

I am uploading and retrieving documents to and from the DB.Uploading works great
But retrieving is what is causing the error
Here's the code for retrieving
DataGridViewRow row = dataGridView1.CurrentRow;
int SelectedplantId = Convert.ToInt32(row.Cells["PId"].Value);
SQLiteConnection conn = new SQLiteConnection(connString);
conn.Open();
string qry = "select Otherdocuments from Plant where PId = #PId";
SQLiteCommand cmd = new SQLiteCommand(qry, conn);
cmd.Parameters.AddWithValue("#PId", SelectedpId);
byte[] buffer = (byte[])cmd.ExecuteScalar();
conn.Close();
//string filename = Application.StartupPath + "\\" + sFileName;
string SaveLocation = "C:" + "\\" + sFileName;
FileStream fs = null;
try
{
fs = new FileStream(SaveLocation,FileMode.Create);
fs.Write(buffer, 0, buffer.Length);
}
finally
{
if (fs != null)
{
((IDisposable)fs).Dispose();
}
}
At fs = new FileStream(SaveLocation,FileMode.Create); is where this exception occurs.
Stack Trace
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at RVEST.frmPlant.btnRetrieveDocs_Click(Object sender, EventArgs e) in C:\D_Drive_Stuff\RVESTV2\RVEST\frmPlant.cs:line 169
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at RVEST.Program.Main() in C:\D_Drive_Stuff\RVESTV2\RVEST\Program.cs:line 26
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Thank you
Sun
The error message seems obvious, the App does not have permission to write in C:\ and probably not in Application.StartupPath either.
//string filename = Application.StartupPath + "\\" + sFileName;
//string SaveLocation = "C:" + "\\" + sFileName;
string SaveLocation = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), sFileName);
There are a few other SpecialFolders that might be applicable.

How to read Exchange 2010 SP 1 public folder using c#

I am trying to read a public folder hosted in ExchangeServer 2010 SP1. Well I am able to connect but when I am trying to read the folder I am getting stragne error. Hope somebody will able to share his/her experience. Below is the code what I am executing doing and after that the error SoapException was Unhandled I am getting.
ExchangeServiceBinding serviceBinding = new ExchangeServiceBinding();
serviceBinding.Credentials = new NetworkCredential("XXXXXXXX", "YYYYYY", "zzzzzzzz");
serviceBinding.RequestServerVersionValue = new RequestServerVersion();
serviceBinding.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010_SP1;
serviceBinding.Url = #"https://the.domain.of.my.work/EWS/exchange.asmx";
DistinguishedFolderIdType publicFolderRoot = new DistinguishedFolderIdType();
publicFolderRoot.Id = DistinguishedFolderIdNameType.publicfoldersroot;
FindFolder(serviceBinding, publicFolderRoot, #"All Public Folders");
private static FolderIdType FindFolder(ExchangeServiceBinding esb, BaseFolderIdType folderId, string folderName)
{
//FindPublicFolderType request = new FindPublicFolderType();
FindFolderType request = new FindFolderType();
request.Traversal = FolderQueryTraversalType.Shallow;
request.FolderShape = new FolderResponseShapeType();
request.FolderShape.BaseShape = DefaultShapeNamesType.AllProperties;
request.ParentFolderIds = new BaseFolderIdType[] { folderId };
//Giving error at this below
FindFolderResponseType response = esb.FindFolder(request);
foreach (ResponseMessageType rmt in response.ResponseMessages.Items)
{
if (rmt.ResponseClass == ResponseClassType.Success)
{
FindFolderResponseMessageType ffResponse = (FindFolderResponseMessageType)rmt;
if (ffResponse.RootFolder.TotalItemsInView > 0)
{
foreach (BaseFolderType subFolder in ffResponse.RootFolder.Folders)
if (subFolder.DisplayName == folderName)
return subFolder.FolderId;
return null;
}
Console.WriteLine("Can't find '" + folderName + "'.");
}
else
{
//Console.WriteLine("Response was: " + rmt.ResponseClass + Environment.NewLine + rmt.MessageText);
MessageBox.Show("Response was: " + rmt.ResponseClass + Environment.NewLine + rmt.MessageText);
}
}
return null;
}
After executing the above code I am facing error mentioned below
System.Web.Services.Protocols.SoapException
System.Web.Services.Protocols.SoapException
was unhandled Message="The mailbox
that was requested doesn't support the
specified RequestServerVersion."
Source="System.Web.Services"
Actor="" Lang="en-US" Node=""
Role="" StackTrace:
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage
message, WebResponse response, Stream
responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String
methodName, Object[] parameters)
at RnDExchangePublicFolder.ExchangeWebServices.ExchangeServiceBinding.FindFolder(FindFolderType
FindFolder1) in
E:\Data\VS2008\RnDExchangePublicFolder\RnDExchangePublicFolder\Web
References\ExchangeWebServices\Reference.cs:line
547
at RnDExchangePublicFolder.Form1.FindFolder(ExchangeServiceBinding
esb, BaseFolderIdType folderId, String
folderName) in
E:\Data\VS2008\RnDExchangePublicFolder\RnDExchangePublicFolder\Form1.cs:line
51
at RnDExchangePublicFolder.Form1.btnConnect_Click(Object
sender, EventArgs e) in
E:\Data\VS2008\RnDExchangePublicFolder\RnDExchangePublicFolder\Form1.cs:line
39
at System.Windows.Forms.Control.OnClick(EventArgs
e)
at System.Windows.Forms.Button.OnClick(EventArgs
e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs
mevent)
at System.Windows.Forms.Control.WmMouseUp(Message&
m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message&
m)
at System.Windows.Forms.ButtonBase.WndProc(Message&
m)
at System.Windows.Forms.Button.WndProc(Message&
m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&
m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr
hWnd, Int32 msg, IntPtr wparam, IntPtr
lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&
msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32
dwComponentID, Int32 reason, Int32
pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32
reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32
reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form
mainForm)
at RnDExchangePublicFolder.Program.Main()
in
E:\Data\VS2008\RnDExchangePublicFolder\RnDExchangePublicFolder\Program.cs:line
18
at System.AppDomain._nExecuteAssembly(Assembly
assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String
assemblyFile, Evidence
assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object
state)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback
callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Can somebody share their experience what is causing the issue or to further proceed.?
Thanks

Categories