InvalidCastException was unhandled for C# to use in VB6 - c#

What I'm trying to achieve is slowly modularizing old VB6 code to C#.
I am creating a test in VB6 to press a button and execute my c# form and pass back a string value.
I had it working yesterday and something somehow changed and it no longer works. Below is my C# code that I'm having the issue.
#define USE_COM
using System;
using System.Linq;
using System.Windows.Forms;
namespace CMS_DB_Operator_Input
{
static class Program
{
/// <summary>
/// Open the OperatorInput Form
///
/// Note: Will output the result to console out on success
/// </summary>
/// <param name="args">0: The Default Filter to Use</param>
/// <returns>
/// 0: Failure to Select
/// 1: Successfully Selected an Item
/// </returns>
[STAThread]
static int Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string displayName = (args.Length > 1) ? args[1] : null;
string result = "";
displayName = "CBU35PN42";
//displayName = "";
#if USE_COM
CMS_DB_GateKeeper.IGateKeeperUI api = new MS_DB_GateKeeper.GateKeeperUI();
result = api.AskOperatorInput(displayName); // <- INVALID CAST EXCEPTION was unhandled
#else
CMS_DB_GateKeeper.CMS_DB_GateKeeper_OperatorInput op = new CMS_DB_GateKeeper.CMS_DB_GateKeeper_OperatorInput(displayName);
if (displayName == null)
{
Application.Run(op);
if (op.SelectedDisplayName != null)
{
result = op.GetXmlResult(op.SelectedDisplayName); // Success
}
}
else
{
result = op.GetXmlResult(displayName);
}
#endif
Console.WriteLine(result);
return 0;
}
}
}

Related

How can i modify registry via c# on win7?

I modify my WIN7 computer's registry via c#,but it dosen't work.
my code likes below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32; //添加针对操作注册表的应用
namespace operateToolWPF.Utils
{
class RegisterHelper
{
public static string GetRegistryData(RegistryKey root, string subKey,
string name)
{
string registData = string.Empty;
RegistryKey myKey = root.OpenSubKey(subKey, true);
if (myKey != null)
{
registData = myKey.GetValue(name).ToString();
}
return registData;
}
/// <summary>
/// 向注册表中写数据
/// </summary>
/// <param name="root"></param>
/// <param name="subKey"></param>
/// <param name="keyName"></param>
/// <param name="keyValue"></param>
public static void SetRegistryData(RegistryKey root, string subKey, string keyName, Int32 keyValue)
{
RegistryKey aimDir = root.CreateSubKey(subKey);
aimDir.SetValue(keyName, keyValue, RegistryValueKind.DWord);
}
/// <summary>
/// 删除注册表中指定的注册项
/// </summary>
/// <param name="root"></param>
/// <param name="subKey"></param>
/// <param name="keyName"></param>
public static void DeleteRegist(RegistryKey root, string subKey, string keyName)
{
string[] subkeyNames;
RegistryKey myKey = root.OpenSubKey(subKey, true);
subkeyNames = myKey.GetSubKeyNames();
foreach (string aimKey in subkeyNames)
{
if (aimKey == keyName)
myKey.DeleteSubKeyTree(keyName);
}
}
/// <summary>
/// 判断指定注册表项是否存在
/// </summary>
/// <param name="root"></param>
/// <param name="subKey"></param>
/// <param name="keyName"></param>
/// <returns></returns>
public static bool IsRegistryExits(RegistryKey root, string subKey, string keyName)
{
bool result = false;
string[] subKeyNames;
RegistryKey myKey = root.OpenSubKey(subKey, true);
subKeyNames = myKey.GetValueNames();
foreach (string name in subKeyNames)
{
if (name == keyName)
{
result = true;
return result;
}
}
return result;
}
}
}
and then call it like this:
//获取当前Windows用户
WindowsIdentity curUser = WindowsIdentity.GetCurrent();
//用户SID
SecurityIdentifier sid = curUser.User;
//用户全称
NTAccount ntacc = (NTAccount)sid.Translate(typeof(NTAccount));
Console.WriteLine("Windows SID:" + sid.Value);
Console.WriteLine("用户全称:" + ntacc.Value);
Int32 tempInt = 0; //预先定义一个有符号32位数
//unchecked语句块内的转换,不做溢出检查
unchecked
{
tempInt = Convert.ToInt32("00000000", 16); //强制转换成有符号32位数
}
//读取Display Inline Images
string displayImgPath = sid.Value + #"\Software\Microsoft\Windows\CurrentVersion\Internet Settings";
string ProxyEnable = RegisterHelper.GetRegistryData(Registry.Users, displayImgPath, "ProxyEnable");
//此时的tempInt已经是有符号32位数,可以直接写入注册表
RegisterHelper.SetRegistryData(Registry.Users, displayImgPath, "ProxyEnable", tempInt);
Thread.Sleep(3000);
RegisterHelper.DeleteRegist(Registry.Users, displayImgPath, "ProxyServer");
RegisterHelper.DeleteRegist(Registry.Users, displayImgPath, "ProxyOverride");
Registry.Users.Close();
Process[] MyProcess = Process.GetProcessesByName("explorer");
MyProcess[0].Kill();
by all this ,i want modify ProxyEnable and delete ProxyOverride,ProxyServer,which was cancel IE proxy setting.
I have tried several methodes,but have no one can cancel IE proxy setting.
Can you help me? Thanks!
Here is an example of how I would implement registry IO as you have tried to do. Depending on which part of the registry you are trying to read/write from may use different keys:
public class MyReg{
public RegistryKey Foriegnkey {
get => forignKey;
set => forignKey = value;
}
private RegistryKey forignKey;
public object Read(string Path, string Name) => (Registry.CurrentUser.OpenSubKey(Path, false).GetValue(Name));
public void Write(string Path, string Name, object Data) {
Foriegnkey = Registry.CurrentUser.CreateSubKey(Path, RegistryKeyPermissionCheck.Default);
Foriegnkey.SetValue(Name, Data);
Foriegnkey.Close();
}
}
The example above will read / write at Current User level, but there are other levels which can be used, and you will see these as available options within IntelliSense
You can use this in your application by assigning an instance of your registry class to an object and just calling registry.read/write etc …
This can be checked for nulls using :
if (Registry.GetValue(#"HKEY_CURRENT_USER\Software\MyApp", "SomeValue", null) == null)
And when you come to write data you can use:
myregobject.Write(#"\software\MyApp", "SomeValue", "hello world!");
In your case this enables you to do the following:
if (!Registry.GetValue(#"\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyEnable", null) == null) {
myregobject.Write(#"\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyEnable", "your data here")
}
I cant tell if your delete method works or not from looking at it so i'll throw in my input there as well:
public void RemoveKey(string FolderName) {
Registry.CurrentUser.DeleteSubKeyTree(FolderName);
}
Hope this helps!

C# - Odd Null Reference Exception during testing, why does this happen?

This references my last question which appears to have been abandoned. I am experiencing an odd "bug" if you will with C# and MS VS 2015. To reproduce the error, follow the steps:
Open console app project and copy paste code below.
Set a break point here:
First run code past break point, it works! :D
Then run code again but this time STOP at the break point and DRAG the executing statement cursor INTO the if statement from here:
to here:
Hit Continue and an NRE exception is thrown. Why does this happen? Is it just me? What is the technical explination for this?
CODE:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testapp
{
class Program
{
static void Main(string[] args)
{
FILECollection randomCollection = new FILECollection();
// Fill with junk test data:
for(int i = 0; i<10; i++)
{
FILE junkfile = new FILE() { fileName = i.ToString(), folderName = i.ToString(), fileHashDigest = new byte[1] };
randomCollection.Add(junkfile);
}
if (true)
{
Console.WriteLine("testing this weird exception issue...");
FILE test;
test = new FILE();
test.fileName = "3";
test.folderName = "3";
test.fileHashDigest = new byte[1];
FILE exists = randomCollection.Where(f => f.fileName == test.fileName &&
f.fileHashDigest.SequenceEqual(test.fileHashDigest)).First();
}
}
}
public class FILE
{
public FILE() { _fileName = "";}
private string _fileName;
public string fileName
{
get
{
if (false)
return this._fileName.ToUpper();
else
return this._fileName;
}
set
{
if (false)
this._fileName = value.ToUpper();
else
this._fileName = value;
}
}
public string folderName { get; set; }
public byte[] fileHashDigest { get; set; }
}
public class FILECollection : IEnumerable<FILE>, ICollection<FILE>
{
private HashSet<FILE> svgHash;
private static List<FILE> PreallocationList;
public string FileName = "N/A";
/// <summary>
/// Default Constructor, will not
/// preallocate memory.
/// </summary>
/// <param name="PreallocationSize"></param>
public FILECollection()
{
this.svgHash = new HashSet<FILE>();
this.svgHash.Clear();
}
/// <summary>
/// Overload Constructor Preallocates
/// memory to be used for the new
/// FILE Collection.
/// </summary>
public FILECollection(int PreallocationSize, string fileName = "N/A", int fileHashDigestSize = 32)
{
FileName = fileName;
PreallocationList = new List<FILE>(PreallocationSize);
for (int i = 0; i <= PreallocationSize; i++)
{
byte[] buffer = new byte[fileHashDigestSize];
FILE preallocationSVG = new FILE()
{
fileName = "",
folderName = "",
fileHashDigest = buffer
};
PreallocationList.Add(preallocationSVG);
}
this.svgHash = new HashSet<FILE>(PreallocationList);
this.svgHash.Clear(); // Capacity remains unchanged until a call to TrimExcess is made.
}
/// <summary>
/// Add an FILE file to
/// the FILE Collection.
/// </summary>
/// <param name="svg"></param>
public void Add(FILE svg)
{
this.svgHash.Add(svg);
}
/// <summary>
/// Removes all elements
/// from the FILE Collection
/// </summary>
public void Clear()
{
svgHash.Clear();
}
/// <summary>
/// Determine if the FILE collection
/// contains the EXACT FILE file, folder,
/// and byte[] sequence. This guarantees
/// that the collection contains the EXACT
/// file you are looking for.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(FILE item)
{
return svgHash.Any(f => f.fileHashDigest.SequenceEqual(item.fileHashDigest) &&
f.fileName == item.fileName &&
f.folderName == item.folderName);
}
/// <summary>
/// Determine if the FILE collection
/// contains the same file and folder name,
/// byte[] sequence is not compared. The file and folder
/// name may be the same but this does not guarantee the
/// file contents are exactly the same. Use Contains() instead.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool ContainsPartially(FILE item)
{
return svgHash.Any(f => f.fileName == item.fileName &&
f.folderName == item.folderName);
}
/// <summary>
/// Returns the total number
/// of FILE files in the Collection.
/// </summary>
public int Count
{ get { return svgHash.Count(); } }
public bool IsReadOnly
{ get { return true; } }
public void CopyTo(FILE[] array, int arrayIndex)
{
svgHash.CopyTo(array, arrayIndex);
}
public bool Remove(FILE item)
{
return svgHash.Remove(item);
}
public IEnumerator<FILE> GetEnumerator()
{
return svgHash.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return svgHash.GetEnumerator();
}
}
}
I think either I am debugging in a terribly wrong way, or Microsoft should take a look at this. It's like future code is breaking current code...which is impossible!
OK here's my best guess..
First, as I mentioned in the comments, the exception doesn't occur if you comment out the line FILE exists = randomCollection.Where(f => f.fileName == test.fileName && f.fileHashDigest.SequenceEqual(test.fileHashDigest)).First()‌​;
Second, I noticed the same behavior can be reproduced with the following code:
if (true)
{
object o;
o = new object();
Func<bool> m = () => o == null;
}
i.e. the cause seems to be related to the variable being used in a lambda expression. So, looking at the same code snippet above in ILSpy I get the following:
Program.<>c__DisplayClass0_0 <>c__DisplayClass0_ = new Program.<>c__DisplayClass0_0();
<>c__DisplayClass0_.o = new object();
Func<bool> func = new Func<bool>(<>c__DisplayClass0_.<Main>b__0);
so my best guess is that the NullReferenceException refers to <>c__DisplayClass0_ intance being null - and I'm therefore inclined to believe that the stepping through the if(true) actually skipped the first line where <>c__DisplayClass0_ is instantiated

Facebook login Integration in windows phone 8.1 silverlight

I am new windows phone 8.1 development, i want to integrate facebook login page and update status in through my app in windows phone 8.1 silverlight application. I search alot but nothing found for silverlight app. i add Facebook reference from Nuget package and add three classes here is my code
FacebookHelper.cs
using Facebook;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Security.Authentication.Web;
namespace FaceBookWp8._1.Helpers
{
public class FaceBookHelper
{
FacebookClient _fb = new FacebookClient();
readonly Uri _callbackUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
readonly Uri _loginUrl;
private const string FacebookAppId = "1085047434841730";//Enter your FaceBook App ID here
//private const string FacebookPermissions = "user_about_me,read_stream,publish_stream";
private const string FacebookPermissions = "user_about_me,publish_actions";
public string AccessToken
{
get { return _fb.AccessToken; }
}
public FaceBookHelper()
{
_loginUrl = _fb.GetLoginUrl(new
{
client_id = FacebookAppId,
redirect_uri = _callbackUri.AbsoluteUri,
scope = FacebookPermissions,
display = "popup",
response_type = "token"
});
Debug.WriteLine(_callbackUri);//This is useful for fill Windows Store ID in Facebook WebSite
}
private void ValidateAndProccessResult(WebAuthenticationResult result)
{
if (result.ResponseStatus == WebAuthenticationStatus.Success)
{
var responseUri = new Uri(result.ResponseData.ToString());
var facebookOAuthResult = _fb.ParseOAuthCallbackUrl(responseUri);
if (string.IsNullOrWhiteSpace(facebookOAuthResult.Error))
_fb.AccessToken = facebookOAuthResult.AccessToken;
else
{//error de acceso denegado por cancelación en página
}
}
else if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{// error de http
}
else
{
_fb.AccessToken = null;//Keep null when user signout from facebook
}
}
public void LoginAndContinue()
{
WebAuthenticationBroker.AuthenticateAndContinue(_loginUrl);
}
public void ContinueAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
{
ValidateAndProccessResult(args.WebAuthenticationResult);
}
}
}
ContinuationManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using Windows.ApplicationModel.Activation;
namespace FacebookAppSL
{
class ContinuationManager
{
public void ContinueWith(IActivatedEventArgs args)
{
var rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
return;
switch (args.Kind)
{
case ActivationKind.PickFileContinuation:
break;
case ActivationKind.PickFolderContinuation:
break;
case ActivationKind.PickSaveFileContinuation:
break;
case ActivationKind.WebAuthenticationBrokerContinuation:
var continuator = rootFrame.Content as IWebAuthenticationBrokerContinuable;
if (continuator != null)
continuator.ContinueWithWebAuthenticationBroker((WebAuthenticationBrokerContinuationEventArgs)args);
break;
default:
break;
}
}
}
interface IWebAuthenticationBrokerContinuable
{
void ContinueWithWebAuthenticationBroker(WebAuthenticationBrokerContinuationEventArgs args);
}
}
SuspensionManager.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Windows.ApplicationModel;
using Windows.Storage;
using Windows.Storage.Streams;
namespace FacebookAppSL
{
/// <summary>
/// SuspensionManager captures global session state to simplify process lifetime management
/// for an application. Note that session state will be automatically cleared under a variety
/// of conditions and should only be used to store information that would be convenient to
/// carry across sessions, but that should be discarded when an application crashes or is
/// upgraded.
/// </summary>
internal sealed class SuspensionManager
{
private static Dictionary<string, object> _sessionState = new Dictionary<string, object>();
private static List<Type> _knownTypes = new List<Type>();
private const string sessionStateFilename = "_sessionState.xml";
/// <summary>
/// Provides access to global session state for the current session. This state is
/// serialized by <see cref="SaveAsync"/> and restored by
/// <see cref="RestoreAsync"/>, so values must be serializable by
/// <see cref="DataContractSerializer"/> and should be as compact as possible. Strings
/// and other self-contained data types are strongly recommended.
/// </summary>
public static Dictionary<string, object> SessionState
{
get { return _sessionState; }
}
/// <summary>
/// List of custom types provided to the <see cref="DataContractSerializer"/> when
/// reading and writing session state. Initially empty, additional types may be
/// added to customize the serialization process.
/// </summary>
public static List<Type> KnownTypes
{
get { return _knownTypes; }
}
/// <summary>
/// Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances
/// registered with <see cref="RegisterFrame"/> will also preserve their current
/// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
/// to save its state.
/// </summary>
/// <returns>An asynchronous task that reflects when session state has been saved.</returns>
public static async Task SaveAsync()
{
try
{
// Save the navigation state for all registered frames
foreach (var weakFrameReference in _registeredFrames)
{
Frame frame;
if (weakFrameReference.TryGetTarget(out frame))
{
SaveFrameNavigationState(frame);
}
}
// Serialize the session state synchronously to avoid asynchronous access to shared
// state
MemoryStream sessionData = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
serializer.WriteObject(sessionData, _sessionState);
// Get an output stream for the SessionState file and write the state asynchronously
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
using (Stream fileStream = await file.OpenStreamForWriteAsync())
{
sessionData.Seek(0, SeekOrigin.Begin);
await sessionData.CopyToAsync(fileStream);
}
}
catch (Exception e)
{
throw new SuspensionManagerException(e);
}
}
/// <summary>
/// Restores previously saved <see cref="SessionState"/>. Any <see cref="Frame"/> instances
/// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
/// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
/// state.
/// </summary>
/// <param name="sessionBaseKey">An optional key that identifies the type of session.
/// This can be used to distinguish between multiple application launch scenarios.</param>
/// <returns>An asynchronous task that reflects when session state has been read. The
/// content of <see cref="SessionState"/> should not be relied upon until this task
/// completes.</returns>
public static async Task RestoreAsync(String sessionBaseKey = null)
{
_sessionState = new Dictionary<String, Object>();
try
{
// Get the input stream for the SessionState file
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename);
using (IInputStream inStream = await file.OpenSequentialReadAsync())
{
// Deserialize the Session State
DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), _knownTypes);
_sessionState = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
}
// Restore any registered frames to their saved state
foreach (var weakFrameReference in _registeredFrames)
{
Frame frame;
if (weakFrameReference.TryGetTarget(out frame) && (string)frame.GetValue(FrameSessionBaseKeyProperty) == sessionBaseKey)
{
frame.ClearValue(FrameSessionStateProperty);
RestoreFrameNavigationState(frame);
}
}
}
catch (Exception e)
{
throw new SuspensionManagerException(e);
}
}
private static DependencyProperty FrameSessionStateKeyProperty =
DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null);
private static DependencyProperty FrameSessionBaseKeyProperty =
DependencyProperty.RegisterAttached("_FrameSessionBaseKeyParams", typeof(String), typeof(SuspensionManager), null);
private static DependencyProperty FrameSessionStateProperty =
DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary<String, Object>), typeof(SuspensionManager), null);
private static List<WeakReference<Frame>> _registeredFrames = new List<WeakReference<Frame>>();
/// <summary>
/// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
/// and restored from <see cref="SessionState"/>. Frames should be registered once
/// immediately after creation if they will participate in session state management. Upon
/// registration if state has already been restored for the specified key
/// the navigation history will immediately be restored. Subsequent invocations of
/// <see cref="RestoreAsync"/> will also restore navigation history.
/// </summary>
/// <param name="frame">An instance whose navigation history should be managed by
/// <see cref="SuspensionManager"/></param>
/// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
/// store navigation-related information.</param>
/// <param name="sessionBaseKey">An optional key that identifies the type of session.
/// This can be used to distinguish between multiple application launch scenarios.</param>
public static void RegisterFrame(Frame frame, String sessionStateKey, String sessionBaseKey = null)
{
if (frame.GetValue(FrameSessionStateKeyProperty) != null)
{
throw new InvalidOperationException("Frames can only be registered to one session state key");
}
if (frame.GetValue(FrameSessionStateProperty) != null)
{
throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all");
}
if (!string.IsNullOrEmpty(sessionBaseKey))
{
frame.SetValue(FrameSessionBaseKeyProperty, sessionBaseKey);
sessionStateKey = sessionBaseKey + "_" + sessionStateKey;
}
// Use a dependency property to associate the session key with a frame, and keep a list of frames whose
// navigation state should be managed
frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey);
_registeredFrames.Add(new WeakReference<Frame>(frame));
// Check to see if navigation state can be restored
RestoreFrameNavigationState(frame);
}
/// <summary>
/// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
/// from <see cref="SessionState"/>. Any navigation state previously captured will be
/// removed.
/// </summary>
/// <param name="frame">An instance whose navigation history should no longer be
/// managed.</param>
public static void UnregisterFrame(Frame frame)
{
// Remove session state and remove the frame from the list of frames whose navigation
// state will be saved (along with any weak references that are no longer reachable)
SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty));
_registeredFrames.RemoveAll((weakFrameReference) =>
{
Frame testFrame;
return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame;
});
}
/// <summary>
/// Provides storage for session state associated with the specified <see cref="Frame"/>.
/// Frames that have been previously registered with <see cref="RegisterFrame"/> have
/// their session state saved and restored automatically as a part of the global
/// <see cref="SessionState"/>. Frames that are not registered have transient state
/// that can still be useful when restoring pages that have been discarded from the
/// navigation cache.
/// </summary>
/// <remarks>Apps may choose to rely on <see cref="NavigationHelper"/> to manage
/// page-specific state instead of working with frame session state directly.</remarks>
/// <param name="frame">The instance for which session state is desired.</param>
/// <returns>A collection of state subject to the same serialization mechanism as
/// <see cref="SessionState"/>.</returns>
public static Dictionary<String, Object> SessionStateForFrame(Frame frame)
{
var frameState = (Dictionary<String, Object>)frame.GetValue(FrameSessionStateProperty);
if (frameState == null)
{
var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty);
if (frameSessionKey != null)
{
// Registered frames reflect the corresponding session state
if (!_sessionState.ContainsKey(frameSessionKey))
{
_sessionState[frameSessionKey] = new Dictionary<String, Object>();
}
frameState = (Dictionary<String, Object>)_sessionState[frameSessionKey];
}
else
{
// Frames that aren't registered have transient state
frameState = new Dictionary<String, Object>();
}
frame.SetValue(FrameSessionStateProperty, frameState);
}
return frameState;
}
private static void RestoreFrameNavigationState(Frame frame)
{
var frameState = SessionStateForFrame(frame);
if (frameState.ContainsKey("Navigation"))
{
frame.SetNavigationState((String)frameState["Navigation"]);
}
}
private static void SaveFrameNavigationState(Frame frame)
{
var frameState = SessionStateForFrame(frame);
frameState["Navigation"] = frame.GetNavigationState();
}
}
public class SuspensionManagerException : Exception
{
public SuspensionManagerException()
{
}
public SuspensionManagerException(Exception e)
: base("SuspensionManager failed", e)
{
}
}
}
MainPage.xaml.cs
using Facebook;
using FaceBookWp8._1.Helpers;
using Microsoft.Phone.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Security.Authentication.Web;
using Windows.UI.Popups;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace FacebookAppSL
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : PhoneApplicationPage, IWebAuthenticationBrokerContinuable
{
readonly Uri _loginUrl;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
FaceBookHelper ObjFBHelper = new FaceBookHelper();
private void BtnFaceBookLogin_Click(object sender, RoutedEventArgs e)
{
ObjFBHelper.LoginAndContinue();
}
FacebookClient fbclient = new FacebookClient();
public async void ContinueWithWebAuthenticationBroker(WebAuthenticationBrokerContinuationEventArgs args)
{
ObjFBHelper.ContinueAuthentication(args);
if (ObjFBHelper.AccessToken != null)
{
fbclient = new Facebook.FacebookClient(ObjFBHelper.AccessToken);
//Fetch facebook UserProfile:
dynamic result = await fbclient.GetTaskAsync("me");
string id = result.id;
string email = result.email;
string FBName = result.name;
//Format UserProfile:
GetUserProfilePicture(id);
TxtUserProfile.Text = FBName;
StckPnlProfile_Layout.Visibility = Visibility.Visible;
BtnLogin.Visibility = Visibility.Collapsed;
BtnLogout.Visibility = Visibility.Visible;
}
else
{
StckPnlProfile_Layout.Visibility = Visibility.Collapsed;
}
}
private void GetUserProfilePicture(string UserID)
{
string profilePictureUrl = string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", UserID, "square", ObjFBHelper.AccessToken);
picProfile.Source = new BitmapImage(new Uri(profilePictureUrl));
}
private async void BtnFaceBookPost_Click(object sender, RoutedEventArgs e)
{
var postParams = new
{
name = "Facebook Post Testing from FsdSolutions.",
caption = "WindowsPhone 8.1 FaceBook Integration.",
link = "http://www.fsdsolutions.com/",
description = TxtStatusMsg.Text,
//picture = "http://facebooksdk.net/assets/img/logo75x75.png"
};
try
{
dynamic fbPostTaskResult = await fbclient.PostTaskAsync("/me/feed", postParams);
var responseresult = (IDictionary<string, object>)fbPostTaskResult;
//MessageDialog SuccessMsg = new MessageDialog("Message posted sucessfully on facebook wall");
//await SuccessMsg.ShowAsync();
MessageBox.Show("Message posted sucessfully on facebook wall");
}
catch (Exception ex)
{
//MessageDialog ErrMsg = new MessageDialog("Error Ocuured!");
}
}
Uri _logoutUrl;
private async void BtnFaceBookLogout_Click(object sender, RoutedEventArgs e)
{
_logoutUrl = fbclient.GetLogoutUrl(new
{
next = "https://www.facebook.com/connect/login_success.html",
access_token = ObjFBHelper.AccessToken
});
WebAuthenticationBroker.AuthenticateAndContinue(_logoutUrl);
BtnLogin.Visibility = Visibility.Visible;
BtnLogout.Visibility = Visibility.Collapsed;
}
}
}
I found a problem in these lines in windows phone 8.1 silverlight in ContinuationManager.cs
var rootFrame = Window.Current.Content as Frame;
in SuspensionManager.cs
frame.SetNavigationState((String)frameState["Navigation"]);
frameState["Navigation"] = frame.GetNavigationState();
and In MainPage.xaml.cs
this.NavigationCacheMode = NavigationCacheMode.Required;
Please tell me the alternative of these lines to remove errors.

redirecting output to the text file c#

This is my code:
Process pr2 = new Process();
pr2.StartInfo.FileName = "show-snps";
pr2.StartInfo.Arguments = #"-Clr -x 2 out.delta > out.snps";
pr2.Start();
pr2.WaitForExit();
show-snps writes an error. when I delete the part "> out.snps" everything is ok and it writes the result into the terminal, but I need to redirect it to the text file.
How can I do this?
You can't redirect like that when you are starting the program like that. It requires a shell such as CMD.EXE to do that.
Instead, you need to set ProcessStartInfo.RedirectStandardOutput to a stream that you manage yourself.
There's an example here.
That example shows how to get the data that the console process creates via a StreamReader. For your requirement, you would read from that StreamReader and write to a FileStream output.
In case it's any help, here's a utility class I wrote years ago (for .Net 2) which might be instructive:
using System;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
namespace ProcessUtilities
{
/// <summary>
/// Encapsulates an executable program.
/// This class makes it easy to run a console app and have that app's output appear
/// in the parent console's window, and to redirect input and output from/to files.
/// </summary>
/// <remarks>
/// To use this class:
/// (1) Create an instance.
/// (2) Set the ProgramFileName property if a filename wasn't specified in the constructor.
/// (3) Set other properties if required.
/// (4) Call Run().
/// </remarks>
public class Executable
{
#region Constructor
/// <summary>Runs the specified program file name.</summary>
/// <param name="programFileName">Name of the program file to run.</param>
public Executable(string programFileName)
{
ProgramFileName = programFileName;
_processStartInfo.ErrorDialog = false;
_processStartInfo.CreateNoWindow = false;
_processStartInfo.UseShellExecute = false;
_processStartInfo.RedirectStandardOutput = false;
_processStartInfo.RedirectStandardError = false;
_processStartInfo.RedirectStandardInput = false;
_processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
_processStartInfo.Arguments = "";
}
/// <summary>Constructor.</summary>
public Executable(): this(string.Empty)
{
}
#endregion // Constructor
#region Public Properties
/// <summary>The filename (full pathname) of the executable.</summary>
public string ProgramFileName
{
get
{
return _processStartInfo.FileName;
}
set
{
_processStartInfo.FileName = value;
}
}
/// <summary>The command-line arguments passed to the executable when run. </summary>
public string Arguments
{
get
{
return _processStartInfo.Arguments;
}
set
{
_processStartInfo.Arguments = value;
}
}
/// <summary>The working directory set for the executable when run.</summary>
public string WorkingDirectory
{
get
{
return _processStartInfo.WorkingDirectory;
}
set
{
_processStartInfo.WorkingDirectory = value;
}
}
/// <summary>
/// The file to be used if standard input is redirected,
/// or null or string.Empty to not redirect standard input.
/// </summary>
public string StandardInputFileName
{
set
{
_standardInputFileName = value;
_processStartInfo.RedirectStandardInput = !string.IsNullOrEmpty(value);
}
get
{
return _standardInputFileName;
}
}
/// <summary>
/// The file to be used if standard output is redirected,
/// or null or string.Empty to not redirect standard output.
/// </summary>
public string StandardOutputFileName
{
set
{
_standardOutputFileName = value;
_processStartInfo.RedirectStandardOutput = !string.IsNullOrEmpty(value);
}
get
{
return _standardOutputFileName;
}
}
/// <summary>
/// The file to be used if standard error is redirected,
/// or null or string.Empty to not redirect standard error.
/// </summary>
public string StandardErrorFileName
{
set
{
_standardErrorFileName = value;
_processStartInfo.RedirectStandardError = !string.IsNullOrEmpty(value);
}
get
{
return _standardErrorFileName;
}
}
#endregion // Public Properties
#region Public Methods
/// <summary>Add a set of name-value pairs into the set of environment variables available to the executable.</summary>
/// <param name="variables">The name-value pairs to add.</param>
public void AddEnvironmentVariables(StringDictionary variables)
{
if (variables == null)
throw new ArgumentNullException("variables");
StringDictionary environmentVariables = _processStartInfo.EnvironmentVariables;
foreach (DictionaryEntry e in variables)
environmentVariables[(string)e.Key] = (string)e.Value;
}
/// <summary>Run the executable and wait until the it has terminated.</summary>
/// <returns>The exit code returned from the executable.</returns>
public int Run()
{
Thread standardInputThread = null;
Thread standardOutputThread = null;
Thread standardErrorThread = null;
_standardInput = null;
_standardError = null;
_standardOutput = null;
int exitCode = -1;
try
{
using (Process process = new Process())
{
process.StartInfo = _processStartInfo;
process.Start();
if (process.StartInfo.RedirectStandardInput)
{
_standardInput = process.StandardInput;
standardInputThread = startThread(new ThreadStart(supplyStandardInput), "StandardInput");
}
if (process.StartInfo.RedirectStandardError)
{
_standardError = process.StandardError;
standardErrorThread = startThread(new ThreadStart(writeStandardError), "StandardError");
}
if (process.StartInfo.RedirectStandardOutput)
{
_standardOutput = process.StandardOutput;
standardOutputThread = startThread(new ThreadStart(writeStandardOutput), "StandardOutput");
}
process.WaitForExit();
exitCode = process.ExitCode;
}
}
finally // Ensure that the threads do not persist beyond the process being run
{
if (standardInputThread != null)
standardInputThread.Join();
if (standardOutputThread != null)
standardOutputThread.Join();
if (standardErrorThread != null)
standardErrorThread.Join();
}
return exitCode;
}
#endregion // Public Methods
#region Private Methods
/// <summary>Start a thread.</summary>
/// <param name="startInfo">start information for this thread</param>
/// <param name="name">name of the thread</param>
/// <returns>thread object</returns>
private static Thread startThread(ThreadStart startInfo, string name)
{
Thread t = new Thread(startInfo);
t.IsBackground = true ;
t.Name = name;
t.Start();
return t;
}
/// <summary>Thread which supplies standard input from the appropriate file to the running executable.</summary>
private void supplyStandardInput()
{
// feed text from the file a line at a time into the standard input stream
using (StreamReader reader = File.OpenText(_standardInputFileName))
using (StreamWriter writer = _standardInput)
{
writer.AutoFlush = true;
for (;;)
{
string textLine = reader.ReadLine();
if (textLine == null)
break;
writer.WriteLine(textLine);
}
}
}
/// <summary>Thread which outputs standard output from the running executable to the appropriate file.</summary>
private void writeStandardOutput()
{
using (StreamWriter writer = File.CreateText(_standardOutputFileName))
using (StreamReader reader = _standardOutput)
{
writer.AutoFlush = true;
for (;;)
{
string textLine = reader.ReadLine();
if (textLine == null)
break;
writer.WriteLine(textLine);
}
}
if (File.Exists(_standardOutputFileName))
{
FileInfo info = new FileInfo(_standardOutputFileName);
// if the error info is empty or just contains eof etc.
if (info.Length < 4)
info.Delete();
}
}
/// <summary>Thread which outputs standard error output from the running executable to the appropriate file.</summary>
private void writeStandardError()
{
using (StreamWriter writer = File.CreateText(_standardErrorFileName))
using (StreamReader reader = _standardError)
{
writer.AutoFlush = true;
for (;;)
{
string textLine = reader.ReadLine();
if (textLine == null)
break;
writer.WriteLine(textLine);
}
}
if (File.Exists(_standardErrorFileName))
{
FileInfo info = new FileInfo(_standardErrorFileName);
// if the error info is empty or just contains eof etc.
if (info.Length < 4)
info.Delete();
}
}
#endregion // Private Methods
#region Private Fields
private StreamReader _standardError ;
private StreamReader _standardOutput ;
private StreamWriter _standardInput ;
private string _standardInputFileName;
private string _standardOutputFileName;
private string _standardErrorFileName;
ProcessStartInfo _processStartInfo = new ProcessStartInfo();
#endregion // Private Fields
}
}
This is an old question, but it came up on the first google link for searching for how to redirect the standard output of a launched Process to a file.
The answer I think works well is to add a OutputDataReceived event and write to the file there.
Here is a complete working example.
using System;
using System.IO;
using System.Diagnostics;
using System.Text;
class StandardAsyncOutputExample
{
public static void Main()
{
var outputStream = new StreamWriter("output.txt");
Process process = new Process();
process.StartInfo.FileName = "ipconfig.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
outputStream.WriteLine(e.Data);
}
});
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.Close();
outputStream.Close();
Console.WriteLine("\n\nPress any key to exit.");
Console.ReadLine();
}
}
It didn't work because > redirect was supported by cmd.exe shell. Try the following code instead.
Process pr2 = new Process();
pr2.StartInfo.FileName = #"c:\windows\system32\cmd.exe";
pr2.StartInfo.Arguments = #"/k \"show-snps -Clr -x 2 out.delta > out.snps\"";
pr2.Start();
pr2.WaitForExit();

The best overloaded method match for has some invalid arguments

I am using VS 2010 C#. My code is as follows:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using MarketplaceWebServiceOrders;
using MarketplaceWebServiceOrders.Model;
namespace FetchNewOrdersJob
{
public class MarketplaceWebServiceOrders
{
private volatile bool isRunning;
private OrderFetcher orderFetcher;
private TimeSpan _checkOrdersInterval = TimeSpan.FromMinutes(15.0);
/// <summary>
/// Gets or sets the order check interval. Defaults to 15 minutes.
/// </summary>
public TimeSpan CheckOrdersInterval
{
get { return _checkOrdersInterval; }
set { _checkOrdersInterval = value; }
}
/// <summary>
/// Internal method to handle an order.
/// </summary>
protected virtual void HandleOrder(Order order)
{
Console.WriteLine("Processing Order:");
Console.WriteLine("---------------------------------------------------");
Console.WriteLine(order.ToString());
// Fetch the order items in each order
orderFetcher.FetchOrderItems(order.AmazonOrderId, delegate(OrderItem item)
{
Console.WriteLine("\tProcessing Order Item");
Console.WriteLine("\t---------------------------------------------------"); // Process order item here.
Console.WriteLine("\t" + item.ToString().Replace("\n", "\n\t"));
});
Console.WriteLine("=================================================");
Console.WriteLine();
}
/// <summary>
/// Method to continuously check orders over an interval, and list OrderItems for those Orders.
/// </summary>
private void OrdersJobThread(object obj)
{
orderFetcher.ProcessOrder += HandleOrder;
if (this.CheckOrdersInterval == TimeSpan.MinValue)
{
throw new ArgumentException("The CheckOrdersInterval TimeSpan cannot be zero.", "CheckOrdersInterval");
}
DateTime startCheckInterval = DateTime.Now.Subtract(CheckOrdersInterval);
// Continue forever until the isRunning flag is cleared.
while (isRunning)
{
try
{
// Check the orders for this interval.
DateTime checkInterval = startCheckInterval;
startCheckInterval = DateTime.Now.Subtract(TimeSpan.FromMinutes(3.0));
Console.WriteLine("Fetching orders from " + checkInterval.ToString() + " to " + startCheckInterval.ToString());
orderFetcher.FetchOrders(checkInterval, startCheckInterval);
// Wait for the next interval.
Console.WriteLine("Fetch complete. Sleeping until next interval.");
while (isRunning && DateTime.Now.Subtract(startCheckInterval) < CheckOrdersInterval)
{
Thread.Sleep(1000);
}
}
catch(Exception err)
{
Console.WriteLine("Error: " + err.Message + ". Orders job thread is exiting.");
isRunning = false;
}
}
}
/// <summary>
/// Sample code to invoke the OrderFetcher.
/// </summary>
/// <param name="service">MarketplaceWebServiceOrders object.</param>
/// <param name="sellerId">The seller Id.</param>
/// <param name="marketplaceIdList">List of marketplaces passed in to the GetOrders call.</param>
public static void InvokeOrderFetcherSample(
MarketplaceWebServiceOrders service,
string sellerId,
string [] marketplaceIdList
)
{
// Create a FetchOrderUpdates job with the default time span.
MarketplaceWebServiceOrders job = new MarketplaceWebServiceOrders();
job.isRunning = true;
job.orderFetcher = new OrderFetcher(service, sellerId, marketplaceIdList);
Thread jobThread = new Thread(job.OrdersJobThread);
jobThread.IsBackground = true;
jobThread.Start();
// Pause on the main thread for one hour or until the thread exits, then end the job.
jobThread.Join(1000 * 60 * 60);
job.isRunning = false;
// Block until the thread terminates to prevent any requests in progress from being aborted.
while (jobThread.IsAlive)
{
Thread.Sleep(1000);
}
}
}
}
I get two errors and can't seem to figure this out
Argument 1: cannot convert from 'FetchNewOrdersJob.MarketplaceWebServiceOrders' to 'MarketplaceWebServiceOrders.MarketplaceWebServiceOrders'
The best overloaded method match for 'MarketplaceWebServiceOrders.OrderFetcher.OrderFetcher(MarketplaceWebServiceOrders.MarketplaceWebServiceOrders, string, string[])' has some invalid arguments
The Line number of the error is 112: job.orderFetcher = new OrderFetcher(service, sellerId, marketplaceIdList);
OrderFetcher.cs
using System;
using System.Collections.Generic;
using System.Text;
using MarketplaceWebServiceOrders.Model;
namespace MarketplaceWebServiceOrders
{
/// <summary>
/// Sample helper class to Fetch Orders and OrderItems using the Amazon MWS Orders API.
/// </summary>
public class OrderFetcher
{
public delegate void RetriableMethodCall();
public delegate void ProcessOrderHandler(Order order);
public delegate void ProcessOrderItemHandler(OrderItem orderItem);
/// <summary>
/// Default amount of time, in milliseconds, to sleep if a request is throttled; default to 1 per 10 minutes.
/// </summary>
public const int DEFAULT_THROTTLED_WAIT_TIMEOUT = 10 * 60 * 1000;
/// <summary>
/// Default throttling limit for ListOrders calls; default to 1 per 12 seconds.
/// </summary>
private const int LIST_ORDERS_DEFAULT_THROTTLE_LIMIT = 12 * 1000;
/// <summary>
/// Default throttling limit for ListOrderItems calls; default to 1 per 100 minutes.
/// </summary>
private const int LIST_ORDER_ITEMS_DEFAULT_THROTTLE_LIMIT = 10 * 60 * 1000;
private MarketplaceWebServiceOrders mwsService;
private string mwsSellerId;
private string[] mwsMarketplaceIdList;
private DateTime lastServiceCall = DateTime.MinValue;
private ProcessOrderHandler _processOrder;
/// <summary>
/// Event called when an order is received for processing.
/// </summary>
public event ProcessOrderHandler ProcessOrder
{
add { _processOrder += value; }
remove { _processOrder -= value; }
}
/// <summary>
/// Creates a new instance of the OrderFetcherSample class.
/// </summary>
/// <param name="service"></param>
public OrderFetcher(MarketplaceWebServiceOrders service, string sellerId, string[] marketplaceIdList)
{
mwsService = service;
mwsSellerId = sellerId;
mwsMarketplaceIdList = marketplaceIdList;
}
/// <summary>
/// Fetches all orders created between the starting time and the server's
/// local system time minus two minutes.
/// <param name="startTime">The starting time period of orders to fetch.</param>
public void FetchOrders(DateTime startTime)
{
FetchOrders(startTime, DateTime.MinValue);
}
/// <summary>
/// Fetches all orders created in the given time period and processes them locally.
/// <param name="startTime">The starting time period of orders to fetch.</param>
/// <param name="endTime">The ending time period of orders to fetch.</param>
public void FetchOrders(DateTime startTime, DateTime endTime)
{
ListOrdersRequest request = new ListOrdersRequest();
request.CreatedAfter = startTime;
if (endTime != DateTime.MinValue)
{
request.CreatedBefore = endTime;
}
request.SellerId = mwsSellerId;
request.MarketplaceId = new MarketplaceIdList();
request.MarketplaceId.Id = new List<string>();
foreach (string marketplaceId in mwsMarketplaceIdList)
{
request.MarketplaceId.Id.Add(marketplaceId);
}
List<Order> orderList = new List<Order>();
ListOrdersResponse response = null;
OrderFetcher.InvokeRetriable(LIST_ORDERS_DEFAULT_THROTTLE_LIMIT, delegate()
{
response = mwsService.ListOrders(request);
ProcessOrders(response.ListOrdersResult.Orders.Order);
});
String nextTokenString = response.ListOrdersResult.NextToken;
while (!string.IsNullOrEmpty(nextTokenString))
{
// If NextToken is set, continue looping through the orders.
ListOrdersByNextTokenRequest nextRequest = new ListOrdersByNextTokenRequest();
nextRequest.NextToken = nextTokenString;
nextRequest.SellerId = mwsSellerId;
ListOrdersByNextTokenResponse nextResponse = null;
OrderFetcher.InvokeRetriable(LIST_ORDERS_DEFAULT_THROTTLE_LIMIT, delegate()
{
nextResponse = mwsService.ListOrdersByNextToken(nextRequest);
ProcessOrders(nextResponse.ListOrdersByNextTokenResult.Orders.Order);
});
nextTokenString = nextResponse.ListOrdersByNextTokenResult.NextToken;
}
}
/// <summary>
/// Method called by the FetchOrders method to process the orders.
/// </summary>
/// <param name="orders">List of orders returned by FetchOrders</param>
protected virtual void ProcessOrders(List<Order> orders)
{
foreach (Order order in orders)
{
if (_processOrder != null)
{
_processOrder(order);
}
}
}
/// <summary>
/// Fetches the OrderItems for the specified orderId.
/// </summary>
public void FetchOrderItems(string orderId, ProcessOrderItemHandler handler)
{
if (handler == null) throw new ArgumentNullException("handler");
ListOrderItemsRequest request = new ListOrderItemsRequest();
request.SellerId = mwsSellerId;
request.AmazonOrderId = orderId;
ListOrderItemsResponse response = null;
OrderFetcher.InvokeRetriable(LIST_ORDER_ITEMS_DEFAULT_THROTTLE_LIMIT, delegate()
{
response = mwsService.ListOrderItems(request);
foreach (OrderItem orderItem in response.ListOrderItemsResult.OrderItems.OrderItem)
{
handler(orderItem);
}
});
String nextTokenString = response.ListOrderItemsResult.NextToken;
while (!string.IsNullOrEmpty(nextTokenString))
{
// If NextToken is set, continue looping through the orders.
ListOrderItemsByNextTokenRequest nextRequest = new ListOrderItemsByNextTokenRequest();
nextRequest.NextToken = nextTokenString;
nextRequest.SellerId = mwsSellerId;
ListOrderItemsByNextTokenResponse nextResponse = null;
OrderFetcher.InvokeRetriable(LIST_ORDER_ITEMS_DEFAULT_THROTTLE_LIMIT, delegate()
{
nextResponse = mwsService.ListOrderItemsByNextToken(nextRequest);
foreach (OrderItem orderItem in nextResponse.ListOrderItemsByNextTokenResult.OrderItems.OrderItem)
{
handler(orderItem);
}
});
nextTokenString = nextResponse.ListOrderItemsByNextTokenResult.NextToken;
}
}
/// <summary>
/// Invokes a method in a retriable fashion.
/// </summary>
/// <param name="throttledWaitTime">The amount of time to wait if the request is throttled.</param>
/// <param name="method">The method to invoke.</param>
public static void InvokeRetriable(RetriableMethodCall method)
{
InvokeRetriable(DEFAULT_THROTTLED_WAIT_TIMEOUT, method);
}
/// <summary>
/// Invokes a method in a retriable fashion.
/// </summary>
/// <param name="throttledWaitTime">The amount of time to wait if the request is throttled.</param>
/// <param name="method">The method to invoke.</param>
public static void InvokeRetriable(int throttledWaitTime, RetriableMethodCall method)
{
bool retryRequest = false;
do
{
retryRequest = false;
try
{
// Perform some action
method.Invoke();
}
catch (MarketplaceWebServiceOrdersException ordersErr)
{
// If the request is throttled, wait and try again.
if (ordersErr.ErrorCode == "RequestThrottled")
{
Console.WriteLine("Request is throttled; waiting...");
retryRequest = true;
System.Threading.Thread.Sleep(throttledWaitTime);
}
else
{
// On any other error, re-throw the exception to be handled by the caller
throw;
}
}
} while (retryRequest);
}
}
}
I think this may have to do with the way in which you imported (I assume) your web service objects. If it's a WCF service, make sure your "Model" is referenced along the different projects, and when adding the service reference, make sure to check the option "Reuse existing Types".
You have classes MarketplaceWebServiceOrders both in current FetchNewOrdersJob and in MarketplaceWebServiceOrders namespaces (also last namespace have same name as your class). Looks like your OrderFetcher class is declared in MarketplaceWebServiceOrders namespace. And it expects as argument MarketplaceWebServiceOrders which is also declared in that namespace. But you are trying to pass MarketplaceWebServiceOrders class, which is declared in current FetchNewOrdersJob namespace.
Rename your FetchNewOrdersJob.MarketplaceWebServiceOrders class to avoid these conflicts.

Categories