how to use application/x-rtp binding with gstreamer-sharp? - c#

I am wondering how/if it's possible to use the follwing gstreamer bindings using gstreamer-sharp/C# for Windows?
udpsrc port=1234 ! application/x-rtp, payload=127 ! rtph264depay ! avdec_h264 ! videoconvert ! autovideosink
I am not sure how to do the "application/x-rtp, payload=127" part and I think that's all I am missing, but I am not 100% sure about this. The videosink I am trying to use is dshowvideosink.
Here is relavent parts of my code so far. The variable videoDisplay is just a WinForms Panel control on my form.
internal enum videosinktype { glimagesink, d3dvideosink, dshowvideosink, directdrawsink}
static Element mVideoConv, mUdpcSrc, mDemux, mAvDecH264, mAVSink;
static Gst.App.AppSink mAppSink;
static System.Threading.Thread mMainGlibThread;
static GLib.MainLoop mMainLoop; // GLib's Main Loop
private const videosinktype mCfgVideosinkType = videosinktype.dshowvideosink;
private ulong mHandle;
private Gst.Video.VideoSink mGlImageSink;
private Gst.Pipeline mCurrentPipeline = null;
private void InitGStreamerPipeline()
{
//Assign Handle to prevent Cross-Threading Access
mHandle = (ulong)videoDisplay.Handle;
//Init Gstreamer
Gst.Application.Init();
GtkSharp.GstreamerSharp.ObjectManager.Initialize();
mMainLoop = new GLib.MainLoop();
mMainGlibThread = new System.Threading.Thread(mMainLoop.Run);
mMainGlibThread.Start();
#region BuildPipeline
switch (mCfgVideosinkType)
{
case videosinktype.glimagesink:
mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("glimagesink", "glimagesink");
break;
case videosinktype.d3dvideosink:
mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("d3dvideosink", "d3dvideosink");
//mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("dshowvideosink", "dshowvideosink");
break;
case videosinktype.dshowvideosink:
mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("dshowvideosink", "dshowvideosink");
break;
case videosinktype.directdrawsink:
mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("directdrawsink", "directdrawsink");
break;
default:
break;
}
//what's the gstreamer-sharp equivalent of:
//application/x-rtp, payload=127
//??
mUdpcSrc = ElementFactory.Make("udpsrc", "sink0");
mUdpcSrc["port"] = 1234;
mDemux = ElementFactory.Make("rtph264depay", "depay0");
mAvDecH264 = ElementFactory.Make("avdec_h264", "avdech2640");
mVideoConv = ElementFactory.Make("videoconvert", "vidconvert0");
mAVSink = ElementFactory.Make("autovideosink", "video_sink");
mCurrentPipeline = new Gst.Pipeline("pipeline");
mCurrentPipeline.Add(mUdpcSrc, mDemux, mAvDecH264, mVideoConv, mAVSink);
if (!mVideoTestSource.Link(mVideoSink))
if (mUdpcSrc.Link(mVideoSink))
{
System.Diagnostics.Debug.WriteLine("Elements could not be linked");
}
#endregion
//subscribe to bus & bussync msgs
Bus bus = mCurrentPipeline.Bus;
bus.AddSignalWatch();
bus.Message += HandleMessage;
Bus bus = mCurrentPipeline.Bus;
bus.EnableSyncMessageEmission();
bus.SyncMessage += new SyncMessageHandler(bus_SyncMessage);
//play the stream
var setStateRet = mCurrentPipeline.SetState(State.Null);
System.Diagnostics.Debug.WriteLine("SetStateNULL returned: " + setStateRet.ToString());
setStateRet = mCurrentPipeline.SetState(State.Ready);
System.Diagnostics.Debug.WriteLine("SetStateReady returned: " + setStateRet.ToString());
setStateRet = mCurrentPipeline.SetState(Gst.State.Playing);
}
/// <summary>
///
/// </summary>
/// <remarks>
/// Indeed the application needs to set its Window identifier at the right time to avoid internal Window creation
/// from the video sink element. To solve this issue a GstMessage is posted on the bus to inform the application
/// that it should set the Window identifier immediately.
///
/// API: http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-libs/html/gst-plugins-base-libs-gstvideooverlay.html
/// </remarks>
/// <param name="o"></param>
/// <param name="args"></param>
private void bus_SyncMessage(object o, SyncMessageArgs args)
{
//Convenience function to check if the given message is a "prepare-window-handle" message from a GstVideoOverlay.
System.Diagnostics.Debug.WriteLine("bus_SyncMessage: " + args.Message.Type.ToString());
if (Gst.Video.Global.IsVideoOverlayPrepareWindowHandleMessage(args.Message))
{
Element src = (Gst.Element)args.Message.Src;
#if DEBUG
System.Diagnostics.Debug.WriteLine("Message'prepare-window-handle' received by: " + src.Name + " " + src.ToString());
#endif
if (src != null && (src is Gst.Video.VideoSink | src is Gst.Bin))
{
// Try to set Aspect Ratio
try
{
src["force-aspect-ratio"] = true;
}
catch (PropertyNotFoundException) { }
// Try to set Overlay
try
{
Gst.Video.VideoOverlayAdapter overlay_ = new Gst.Video.VideoOverlayAdapter(src.Handle);
overlay_.WindowHandle = mHandle;
overlay_.HandleEvents(true);
}
catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception thrown: " + ex.Message); }
}
}
}
private void HandleMessage (object o, MessageArgs args)
{
var msg = args.Message;
//System.Diagnostics.Debug.WriteLine("HandleMessage received msg of type: {0}", msg.Type);
switch (msg.Type)
{
case MessageType.Error:
//
GLib.GException err;
string debug;
System.Diagnostics.Debug.WriteLine("Error received: " + msg.ToString());
//msg.ParseError (out err, out debug);
//if(debug == null) { debug = "none"; }
//System.Diagnostics.Debug.WriteLine ("Error received from element {0}: {1}", msg.Src, err.Message);
//System.Diagnostics.Debug.WriteLine ("Debugging information: "+ debug);
break;
case MessageType.StreamStatus:
Gst.StreamStatusType status;
Element theOwner;
msg.ParseStreamStatus(out status, out theOwner);
System.Diagnostics.Debug.WriteLine("Case SteamingStatus: status is: " + status + " ; Ownder is: " + theOwner.Name);
break;
case MessageType.StateChanged:
//System.Diagnostics.Debug.WriteLine("Case StateChanged: " + args.Message.ToString());
State oldState, newState, pendingState;
msg.ParseStateChanged(out oldState, out newState, out pendingState);
if (newState == State.Paused)
args.RetVal = false;
System.Diagnostics.Debug.WriteLine("Pipeline state changed from {0} to {1}: ; Pending: {2}", Element.StateGetName(oldState), Element.StateGetName(newState), Element.StateGetName(pendingState));
break;
case MessageType.Element:
System.Diagnostics.Debug.WriteLine("Element message: {0}", args.Message.ToString());
break;
default:
System.Diagnostics.Debug.WriteLine("HandleMessage received msg of type: {0}", msg.Type);
break;
}
args.RetVal = true;
}

application/x-rtp, payload=127 is just the GstCaps for the udpsrc element. You can listen on the pad-added signal and add the caps once a pad is created.
new Caps("application/x-rtp, payload=(int)127");

Related

Multithreaded Selenium Bot does not work correctly

I wrote a bot in C#, I used Selenium.
Problem: When I start more threads at same time, the bot does the work in the first window. All of the e-mail addresses are being added to the "E-mail" textbox in the same window instead of one e-mail address per window.
But it should look like:
Start function: DivisionStart()
private void DivisionStart() {
foreach(var account in BotConfig.AccountList) {
while (CurrentBotThreads >= BotConfig.MaxLoginsAtSameTime) {
Thread.Sleep(1000);
}
StartedBotThreads++;
CurrentBotThreads++;
int startIndex = (StartedBotThreads * BotConfig.AdsPerAccount + 1) - BotConfig.AdsPerAccount - 1;
int stopIndex = BotConfig.AdsPerAccount * CurrentBotThreads;
if (stopIndex > BotConfig.ProductList.Count) {
stopIndex = BotConfig.ProductList.Count;
}
Debug.Print("Thread: " + StartedBotThreads);
var adList = GetAdListBy(startIndex, stopIndex);
foreach(var ad in adList) {
Debug.Print("Für thread: " + StartedBotThreads + " | Anzeige: " + ad.AdTitle);
}
Debug.Print("Parallel");
var ebayBotThread = new Thread(() => {
var botOptions = new IBotOptionsModel() {
CaptchaSolverApiKey = CaptchaSolverApiKey,
ReCaptchaSiteKey = "6LcZlE0UAAAAAFQKM6e6WA2XynMyr6WFd5z1l1Nr",
StartPageUrl = "https://www.ebay-kleinanzeigen.de/m-einloggen.html?targetUrl=/",
EbayLoginEmail = account.AccountEmail,
EbayLoginPassword = account.AccountPassword,
Ads = adList,
};
var ebayBot = new EbayBot(this, botOptions);
ebayBot.Start(StartedBotThreads);
Thread.Sleep(5000);
});
ebayBotThread.Start();
}
}
The class with function which will be executed in each thread:
using OpenQA.Selenium;
using Selenium.WebDriver.UndetectedChromeDriver;
using System.Diagnostics;
using TwoCaptcha.Captcha;
using System.Drawing;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Chrome.ChromeDriverExtensions;
namespace EbayBot
{
class EbayBot
{
public Selenium.Extensions.SlDriver Driver;
private WebDriverHelper DriverHelper;
private Bot Sender;
private bool CaptchaSolved = false;
public IBotOptionsModel Options;
public EbayBot(Bot sender, IBotOptionsModel options)
{
Sender = sender;
Options = options;
}
public void Start(int threadIndex)
{
var chromeOptions = new ChromeOptions();
/*if (Sender.BotConfig.EnableProxy)
{
chromeOptions.AddHttpProxy(
Options.Proxy.IpAddress,
Options.Proxy.Port,
Options.Proxy.Username,
Options.Proxy.Password
);
}*/
Driver = UndetectedChromeDriver.Instance(null, chromeOptions);
DriverHelper = new WebDriverHelper(Driver);
string status = "";
Debug.Print("Bot-Thread: " + threadIndex);
Driver.Url = Options.StartPageUrl + Options.EbayLoginEmail;
PressAcceptCookiesButton();
Login();
if (!CaptchaSolved) return;
Driver.Wait(3);
if (LoginError() || !IsLoggedIn())
{
status = "Login für '" + Options.EbayLoginEmail + "' fehlgeschlagen!";
Debug.Print(status);
Sender.ProcessStatus = new IStatusModel(status, Color.Red);
return;
}
else
{
status = "Login für '" + Options.EbayLoginEmail + "' war erfolgreich!";
Debug.Print(status);
Sender.ProcessStatus = new IStatusModel(status, Color.Green);
}
Driver.Wait(5);
BeginFillFormular();
}
private bool CookiesAccepted()
{
try
{
var btnAcceptCookies = Driver.FindElement(By.Id(Config.PageElements["id_banner"]));
return btnAcceptCookies == null;
}
catch (Exception)
{
return true;
}
}
private void PressAcceptCookiesButton()
{
DriverHelper.WaitForElement(Config.PageElements["id_banner"], "", 10);
if (CookiesAccepted()) return;
var btnAcceptCookies = Driver.FindElement(By.Id(Config.PageElements["id_banner"]));
btnAcceptCookies.Click();
}
private bool IsLoggedIn()
{
Debug.Print("Check if logged in already");
try
{
var userEmail = Driver.FindElement(By.Id("user-email")).Text;
return userEmail.ToLower().Contains(Options.EbayLoginEmail);
}
catch (Exception)
{
return false;
}
}
private bool LoginError()
{
try
{
var loginErrorH1 = Driver.FindElements(By.TagName("h1"));
return loginErrorH1[0].Text.Contains("ungültig");
}
catch (Exception)
{
return false;
}
}
private void Login()
{
if (IsLoggedIn()) return;
string status = "Anmelden bei " + Options.EbayLoginEmail + "...";
Debug.Print(status);
Sender.ProcessStatus = Sender.ProcessStatus = new IStatusModel(status, Color.DimGray);
Driver.Wait(5);
var fieldEmail = Driver.FindElement(By.Id(Config.PageElements["id_login_email"]));
var fieldPassword = Driver.FindElement(By.Id(Config.PageElements["id_login_password"]));
var btnLoginSubmit = Driver.FindElement(By.Id(Config.PageElements["id_login_button"]));
fieldEmail.SendKeys(Options.EbayLoginEmail);
Driver.Wait(4);
fieldPassword.SendKeys(Options.EbayLoginPassword);
SolveCaptcha();
if (!CaptchaSolved)
{
return;
}
Debug.Print("Clicking login button");
btnLoginSubmit.Click();
}
public void BeginFillFormular()
{
Debug.Print("Formular setup, Inserate: " + Options.Ads.Count);
foreach (var adData in Options.Ads)
{
Debug.Print("Setting up formular for " + adData.AdTitle);
var adFormular = new AdFormular(Driver, adData, Options);
adFormular._EbayBot = this;
adFormular.CreateAd(Sender);
// 10 seconds
Debug.Print("Nächstes Insert für " + adData.AdTitle);
}
}
public string GetSolvedCaptchaAnswer(string captchaUrl = "")
{
string code = string.Empty;
var solver = new TwoCaptcha.TwoCaptcha(Options.CaptchaSolverApiKey);
var captcha = new ReCaptcha();
captcha.SetSiteKey(Options.ReCaptchaSiteKey);
captcha.SetUrl(captchaUrl == "" ? Options.StartPageUrl : captchaUrl);
try
{
solver.Solve(captcha).Wait();
code = captcha.Code;
}
catch (AggregateException e)
{
Sender.ProcessStatus = new IStatusModel("Captcha Api-Fehler: " + e.InnerExceptions.First().Message, Color.Red);
Driver.Wait(10);
}
return code;
}
public void SolveCaptcha(string captchaUrl = "")
{
Debug.Print("Solving captcha...");
var solvedCaptchaAnswer = GetSolvedCaptchaAnswer(captchaUrl);
if (solvedCaptchaAnswer == string.Empty)
{
Debug.Print("Captcha konnte nicht gelöst werden");
Sender.ProcessStatus = new IStatusModel("Captcha konnte nicht gelöst werden", Color.Red);
CaptchaSolved = false;
Driver.Wait(10);
return;
}
CaptchaSolved = true;
Debug.Print("Captcha answer: " + solvedCaptchaAnswer);
Driver.ExecuteScript("document.getElementById('g-recaptcha-response').innerHTML = '" + solvedCaptchaAnswer + "'");
Debug.Print("Captcha solved!");
Driver.Wait(2);
}
}
}
If I remove the Thread.Sleep(5000); in the DivisionStart function it will work, but I need it I actually want to wait for a found proxy but I simulated it with Thread.Sleep
How can I solve my problem?
Thanks for any answer!
I fixed it.
I used UndetectedChromeDriver wich does not use different ports.
I use another Undetected driver now.
Thank you all

Microsoft.Synchronization code crashing in Unity but works in Visual C#

So i modified a sample code from here https://code.msdn.microsoft.com/windowsdesktop/File-Synchronization-516e3ad7 a little to fit my needs. This is a console application that takes in 2 arguments, first is the source, second is destination. It's a one way sync source to destination folders.
// <copyright file="SyncMain.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>Sample code for using the MSF File Sync Provider</summary>
using System;
using System.IO;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Files;
public class FileSyncProviderSample
{
public static void Main(string[] args)
{
if (args.Length < 2 ||
string.IsNullOrEmpty(args[0]) || string.IsNullOrEmpty(args[1]) ||
!Directory.Exists(args[0]) || !Directory.Exists(args[1]))
{
Console.WriteLine(
"Usage: FileSyncSample [valid directory path 1] [valid directory path 2]");
return;
}
string replica1RootPath = args[0];
string replica2RootPath = args[1];
try
{
// Set options for the sync operation
FileSyncOptions options =
FileSyncOptions.ExplicitDetectChanges |
FileSyncOptions.RecycleDeletedFiles |
FileSyncOptions.RecyclePreviousFileOnUpdates |
FileSyncOptions.RecycleConflictLoserFiles;
FileSyncScopeFilter filter = new FileSyncScopeFilter();
filter.FileNameExcludes.Add("*.lnk"); // Exclude all *.lnk files
// Explicitly detect changes on both replicas upfront, to avoid two change
// detection passes for the two-way sync
DetectChangesOnFileSystemReplica(
replica1RootPath, filter, options);
DetectChangesOnFileSystemReplica(
replica2RootPath, filter, options);
// Sync in both directions
SyncFileSystemReplicasOneWay(replica1RootPath, replica2RootPath, null, options);
//SyncFileSystemReplicasOneWay(replica2RootPath, replica1RootPath, null, options);
}
catch (Exception e)
{
Console.WriteLine("\nException from File Sync Provider:\n" + e.ToString());
}
}
public static void DetectChangesOnFileSystemReplica(
string replicaRootPath,
FileSyncScopeFilter filter, FileSyncOptions options)
{
FileSyncProvider provider = null;
try
{
provider = new FileSyncProvider(replicaRootPath, filter, options);
provider.DetectChanges();
}
finally
{
// Release resources
if (provider != null)
provider.Dispose();
}
}
public static void SyncFileSystemReplicasOneWay(
string sourceReplicaRootPath, string destinationReplicaRootPath,
FileSyncScopeFilter filter, FileSyncOptions options)
{
FileSyncProvider sourceProvider = null;
FileSyncProvider destinationProvider = null;
try
{
sourceProvider = new FileSyncProvider(
sourceReplicaRootPath, filter, options);
destinationProvider = new FileSyncProvider(
destinationReplicaRootPath, filter, options);
destinationProvider.AppliedChange +=
new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);
destinationProvider.SkippedChange +=
new EventHandler<SkippedChangeEventArgs>(OnSkippedChange);
SyncOrchestrator agent = new SyncOrchestrator();
agent.LocalProvider = sourceProvider;
agent.RemoteProvider = destinationProvider;
agent.Direction = SyncDirectionOrder.Upload; // Sync source to destination
Console.WriteLine("Synchronizing changes to replica: " +
destinationProvider.RootDirectoryPath);
agent.Synchronize();
}
finally
{
// Release resources
if (sourceProvider != null) sourceProvider.Dispose();
if (destinationProvider != null) destinationProvider.Dispose();
}
}
public static void OnAppliedChange(object sender, AppliedChangeEventArgs args)
{
switch(args.ChangeType)
{
case ChangeType.Create:
Console.WriteLine("-- Applied CREATE for file " + args.NewFilePath);
break;
case ChangeType.Delete:
Console.WriteLine("-- Applied DELETE for file " + args.OldFilePath);
break;
case ChangeType.Update:
Console.WriteLine("-- Applied OVERWRITE for file " + args.OldFilePath);
break;
case ChangeType.Rename:
Console.WriteLine("-- Applied RENAME for file " + args.OldFilePath +
" as " + args.NewFilePath);
break;
}
}
public static void OnSkippedChange(object sender, SkippedChangeEventArgs args)
{
Console.WriteLine("-- Skipped applying " + args.ChangeType.ToString().ToUpper()
+ " for " + (!string.IsNullOrEmpty(args.CurrentFilePath) ?
args.CurrentFilePath : args.NewFilePath) + " due to error");
if (args.Exception != null)
Console.WriteLine(" [" + args.Exception.Message + "]");
}
}
It works just as expected, but when i modified the code and uses it in Unity, it crashes in editor playmode and does nothing when running the build. The crash seems to originate from agent.Synchronize();
Script in Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Microsoft.Synchronization;
using Microsoft.Synchronization.Files;
using System;
using System.IO;
public class FileSyncTest : MonoBehaviour
{
[SerializeField] private string replica1RootPath;
[SerializeField] private string replica2RootPath;
[SerializeField] private KeyCode activateSyncKey = KeyCode.Keypad5;
private void Update()
{
if (Input.GetKeyDown(activateSyncKey))
{
if (Directory.Exists(replica1RootPath) || Directory.Exists(replica2RootPath))
{
try
{
// Set options for the sync operation
FileSyncOptions options =
FileSyncOptions.ExplicitDetectChanges |
FileSyncOptions.RecycleDeletedFiles |
FileSyncOptions.RecyclePreviousFileOnUpdates |
FileSyncOptions.RecycleConflictLoserFiles;
FileSyncScopeFilter filter = new FileSyncScopeFilter();
filter.FileNameExcludes.Add("*.lnk"); // Exclude all *.lnk files
// Explicitly detect changes on both replicas upfront, to avoid two change
// detection passes for the two-way sync
DetectChangesOnFileSystemReplica(
replica1RootPath, filter, options);
DetectChangesOnFileSystemReplica(
replica2RootPath, filter, options);
// Sync in both directions
SyncFileSystemReplicasOneWay(replica1RootPath, replica2RootPath, null, options);
//SyncFileSystemReplicasOneWay(replica2RootPath, replica1RootPath, null, options);
}
catch (Exception e)
{
Debug.Log("\nException from File Sync Provider:\n" + e.ToString());
}
}
else
{
Debug.Log("One of the dir doesn't exist");
}
}
}
public void DetectChangesOnFileSystemReplica(
string replicaRootPath,
FileSyncScopeFilter filter, FileSyncOptions options)
{
FileSyncProvider provider = null;
try
{
provider = new FileSyncProvider(replicaRootPath, filter, options);
provider.DetectChanges();
}
finally
{
// Release resources
if (provider != null)
provider.Dispose();
}
}
private void SyncFileSystemReplicasOneWay(
string sourceReplicaRootPath, string destinationReplicaRootPath,
FileSyncScopeFilter filter, FileSyncOptions options)
{
FileSyncProvider sourceProvider = null;
FileSyncProvider destinationProvider = null;
try
{
sourceProvider = new FileSyncProvider(
sourceReplicaRootPath, filter, options);
destinationProvider = new FileSyncProvider(
destinationReplicaRootPath, filter, options);
destinationProvider.AppliedChange +=
new EventHandler<AppliedChangeEventArgs>(OnAppliedChange);
destinationProvider.SkippedChange +=
new EventHandler<SkippedChangeEventArgs>(OnSkippedChange);
SyncOrchestrator agent = new SyncOrchestrator();
agent.LocalProvider = sourceProvider;
agent.RemoteProvider = destinationProvider;
agent.Direction = SyncDirectionOrder.Upload; // Sync source to destination
Debug.Log("Synchronizing changes to replica: " +
destinationProvider.RootDirectoryPath);
agent.Synchronize();
}
finally
{
// Release resources
if (sourceProvider != null) sourceProvider.Dispose();
if (destinationProvider != null) destinationProvider.Dispose();
}
}
private void OnAppliedChange(object sender, AppliedChangeEventArgs args)
{
switch (args.ChangeType)
{
case ChangeType.Create:
Debug.Log("-- Applied CREATE for file " + args.NewFilePath);
break;
case ChangeType.Delete:
Debug.Log("-- Applied DELETE for file " + args.OldFilePath);
break;
case ChangeType.Update:
Debug.Log("-- Applied OVERWRITE for file " + args.OldFilePath);
break;
case ChangeType.Rename:
Debug.Log("-- Applied RENAME for file " + args.OldFilePath +
" as " + args.NewFilePath);
break;
}
}
private void OnSkippedChange(object sender, SkippedChangeEventArgs args)
{
Debug.Log("-- Skipped applying " + args.ChangeType.ToString().ToUpper()
+ " for " + (!string.IsNullOrEmpty(args.CurrentFilePath) ?
args.CurrentFilePath : args.NewFilePath) + " due to error");
if (args.Exception != null)
Debug.Log(" [" + args.Exception.Message + "]");
}
}
I have copied the required DLLs into the project folders, below are the DLLs i copied.
FeedSync.21.dll
FileSyncProvider21.dll
MetaStore21.dll
Microsoft.Synchronization.dll
Microsoft.Synchronization.Files.dll
Microsoft.Synchronization.MetadataStorage.dll
Microsoft.Synchronization.SimpleProviders.dll
Msfdb.dll
Msfdbqp.dll
Msfdbse.dll
-SimpleProviders21.dll
-Synchronization21.dll
Editor.log
- https://pastebin.com/3MnNFY4z
Any help will be appreciated!

Display gstreamer-sharp video stream in WinForms

I am looking for an example/help for displaying a gstreamer-sharp feed in a WinForms application.
I am using VS 2012 and have the "glue" project built for this version of VS. I also have glib-sharp, gstreamer-sharp installed and referenced by my project. I have the gstreamer bin directory set as my project's working directory.
If have the following code in a button click handler I get the GStreamer D3D video sink test Window which pops-up on top of my Form.
Gst.Application.Init();
var pipeline = Parse.Launch(#"videotestsrc ! videoconvert ! autovideosink");
pipeline.SetState(State.Playing);
I would like to get the stream displaying within my application on a Panel or PictureBox I'm thinking.
Thanks!
The code below will get the test stream to display on a WinForm's panel control.
internal enum videosinktype { glimagesink, d3dvideosink, dshowvideosink, directdrawsink}
static Element mVideoTestSource, mVideoCaps, mVideoSink, mAppQueue, mVideoConv;
static Gst.App.AppSink mAppSink;
static System.Threading.Thread mMainGlibThread;
static GLib.MainLoop mMainLoop; // GLib's Main Loop
private const videosinktype mCfgVideosinkType = videosinktype.dshowvideosink;
private ulong mHandle;
private Gst.Video.VideoSink mGlImageSink;
private Gst.Pipeline mCurrentPipeline = null;
private void InitGStreamerPipeline()
{
//Assign Handle to prevent Cross-Threading Access
mHandle = (ulong)videoDisplay.Handle;
//Init Gstreamer
Gst.Application.Init();
GtkSharp.GstreamerSharp.ObjectManager.Initialize();
mMainLoop = new GLib.MainLoop();
mMainGlibThread = new System.Threading.Thread(mMainLoop.Run);
mMainGlibThread.Start();
#region BuildPipeline
switch (mCfgVideosinkType)
{
case videosinktype.glimagesink:
mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("glimagesink", "glimagesink");
break;
case videosinktype.d3dvideosink:
mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("d3dvideosink", "d3dvideosink");
//mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("dshowvideosink", "dshowvideosink");
break;
case videosinktype.dshowvideosink:
mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("dshowvideosink", "dshowvideosink");
break;
case videosinktype.directdrawsink:
mGlImageSink = (Gst.Video.VideoSink)Gst.ElementFactory.Make("directdrawsink", "directdrawsink");
break;
default:
break;
}
mVideoTestSource = ElementFactory.Make("videotestsrc", "videotestsrc0");
mVideoConv = ElementFactory.Make("videoconvert", "vidconvert0");
mVideoSink = ElementFactory.Make("autovideosink", "sink0");
mCurrentPipeline = new Gst.Pipeline("pipeline");
mCurrentPipeline.Add(mVideoTestSource, mVideoConv, mVideoSink, mGlImageSink);
if (!mVideoTestSource.Link(mVideoSink))
if (mUdpcSrc.Link(mVideoSink))
{
System.Diagnostics.Debug.WriteLine("Elements could not be linked");
}
#endregion
//subscribe to bus & bussync msgs
Bus bus = mCurrentPipeline.Bus;
bus.AddSignalWatch();
bus.Message += HandleMessage;
Bus bus = mCurrentPipeline.Bus;
bus.EnableSyncMessageEmission();
bus.SyncMessage += new SyncMessageHandler(bus_SyncMessage);
//play the stream
var setStateRet = mCurrentPipeline.SetState(State.Null);
System.Diagnostics.Debug.WriteLine("SetStateNULL returned: " + setStateRet.ToString());
setStateRet = mCurrentPipeline.SetState(State.Ready);
System.Diagnostics.Debug.WriteLine("SetStateReady returned: " + setStateRet.ToString());
setStateRet = mCurrentPipeline.SetState(Gst.State.Playing);
}
/// <summary>
///
/// </summary>
/// <remarks>
/// Indeed the application needs to set its Window identifier at the right time to avoid internal Window creation
/// from the video sink element. To solve this issue a GstMessage is posted on the bus to inform the application
/// that it should set the Window identifier immediately.
///
/// API: http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-base-libs/html/gst-plugins-base-libs-gstvideooverlay.html
/// </remarks>
/// <param name="o"></param>
/// <param name="args"></param>
private void bus_SyncMessage(object o, SyncMessageArgs args)
{
//Convenience function to check if the given message is a "prepare-window-handle" message from a GstVideoOverlay.
System.Diagnostics.Debug.WriteLine("bus_SyncMessage: " + args.Message.Type.ToString());
if (Gst.Video.Global.IsVideoOverlayPrepareWindowHandleMessage(args.Message))
{
Element src = (Gst.Element)args.Message.Src;
#if DEBUG
System.Diagnostics.Debug.WriteLine("Message'prepare-window-handle' received by: " + src.Name + " " + src.ToString());
#endif
if (src != null && (src is Gst.Video.VideoSink | src is Gst.Bin))
{
// Try to set Aspect Ratio
try
{
src["force-aspect-ratio"] = true;
}
catch (PropertyNotFoundException) { }
// Try to set Overlay
try
{
Gst.Video.VideoOverlayAdapter overlay_ = new Gst.Video.VideoOverlayAdapter(src.Handle);
overlay_.WindowHandle = mHandle;
overlay_.HandleEvents(true);
}
catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception thrown: " + ex.Message); }
}
}
}
private void HandleMessage (object o, MessageArgs args)
{
var msg = args.Message;
//System.Diagnostics.Debug.WriteLine("HandleMessage received msg of type: {0}", msg.Type);
switch (msg.Type)
{
case MessageType.Error:
//
GLib.GException err;
string debug;
System.Diagnostics.Debug.WriteLine("Error received: " + msg.ToString());
//msg.ParseError (out err, out debug);
//if(debug == null) { debug = "none"; }
//System.Diagnostics.Debug.WriteLine ("Error received from element {0}: {1}", msg.Src, err.Message);
//System.Diagnostics.Debug.WriteLine ("Debugging information: "+ debug);
break;
case MessageType.StreamStatus:
Gst.StreamStatusType status;
Element theOwner;
msg.ParseStreamStatus(out status, out theOwner);
System.Diagnostics.Debug.WriteLine("Case SteamingStatus: status is: " + status + " ; Ownder is: " + theOwner.Name);
break;
case MessageType.StateChanged:
//System.Diagnostics.Debug.WriteLine("Case StateChanged: " + args.Message.ToString());
State oldState, newState, pendingState;
msg.ParseStateChanged(out oldState, out newState, out pendingState);
if (newState == State.Paused)
args.RetVal = false;
System.Diagnostics.Debug.WriteLine("Pipeline state changed from {0} to {1}: ; Pending: {2}", Element.StateGetName(oldState), Element.StateGetName(newState), Element.StateGetName(pendingState));
break;
case MessageType.Element:
System.Diagnostics.Debug.WriteLine("Element message: {0}", args.Message.ToString());
break;
default:
System.Diagnostics.Debug.WriteLine("HandleMessage received msg of type: {0}", msg.Type);
break;
}
args.RetVal = true;
}
Have a look at the GstVideoOverlay interface here:
https://developer.gnome.org/gst-plugins-libs/stable/gst-plugins-base-libs-gstvideooverlay.html
You will have to adapt to the C# syntax I guess, but there is a good amount of explaination and code samples for this.
You can have a look at https://cgit.freedesktop.org/gstreamer/gstreamer-sharp/tree/samples/VideoOverlay.cs You need to adapt this code to use the window Handle of WinForms.

sending SIP messages with C#

I am trying to send a predefined message to our SIP phones which will trigger an event(reboot) in C#. I found some scripts in other languages (perl/python) which do exactly what i am trying to do but have never done this before. I have most of if ported over but really don't know if i have all of right elements. Here is script i am trying to port:
#!/usr/bin/perl -w
use Net::Ping;
use Socket;
my $phone_ip = $ARGV[0];
sub reboot_sip_phone { # Send the phone a check-sync to reboot it
$local_ip = $phone_ip;
$sip_to = $phone_ip;
$sip_from = "0";
$tm = time();
$call_id = $tm . "msgto$sip_to";
$httptime = `date -R`;
$MESG = "NOTIFY sip:$sip_to\#$phone_ip:5060 SIP/2.0
Via: SIP/2.0/UDP $local_ip
From: <sip:$sip_from\#$local_ip>
To: <sip:$sip_to\#$phone_ip>
Event: check-sync
Date: $httptime
Call-ID: $call_id\#$local_ip
CSeq: 1300 NOTIFY
Contact: <sip:$sip_from\#$local_ip>
Content-Length: 0 ";
$proto = getprotobyname('udp');
socket( SOCKET, PF_INET, SOCK_DGRAM, $proto );
$iaddr = inet_aton("$phone_ip");
$paddr = sockaddr_in( 5060, $iaddr );
bind( SOCKET, $paddr );
$port = 5060;
$hisiaddr = inet_aton($phone_ip);
$hispaddr = sockaddr_in( $port, $hisiaddr );
if ( send( SOCKET, $MESG, 0, $hispaddr ) ) {
print "reboot of phone ", "$phone_ip", " was successful", "\n";
}
else { print "reboot of phone ", "$phone_ip", " failed", "\n"; }
}
exit;
this is my code so far:
class Driver
{
static void Main(string[] args)
{
if (!String.IsNullOrEmpty(args[0]))
{
var phone_ip = args[0];
SipMessage newMsg = new SipMessage(phone_ip);
IPAddress addr = IPAddress.Parse(phone_ip);
IPEndPoint end_point = new IPEndPoint(addr, 5060);
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp);
byte[] send_buffer = Encoding.ASCII.GetBytes(newMsg.ToString());
Console.WriteLine("sending message: " + newMsg.ToString());
socket.SendTo(send_buffer, end_point);
Console.WriteLine("Sent message to " + phone_ip);
}
else Console.WriteLine("Message did not send");
}
}
class SipMessage
{
private string _to, _from, _call_id, _msg;
private DateTime _time;
public SipMessage(string p_ip = "")
{
_to = p_ip;
_from = "<sip:test>";
_time = DateTime.Now;
_call_id = _time.ToString() + "msgto" + _to;
_msg = String.Format("NOTIFY sip:" + _to + ":5060 SIP/2.0" +
"\nVia: SIP/2.0/UDP " + _to +
"\nFrom: {0};tag=1530231855-106746376154 " +
"\nTo: <sip:{1}:5060> " +
"\nEvent: check-sync " +
"\nDate: {2} " +
"\nCall-ID: {3} " +
"\nCSeq: 1 NOTIFY " +
"\nContact: {0} " +
"\nContent-Length: 0 ", _from, _to, _time, _call_id);
}
public override string ToString()
{
return _msg;
}
}
}
i have run the code and tested on a phone but it won't kick start the event. Am I on the right track? Am i missing something?
As an alternative you could use my C# sipsorcery nuget package.
using System;
using System.Net;
using System.Threading;
using SIPSorcery.SIP;
using SIPSorcery.SIP.App;
using SIPSorcery.Sys;
using SIPSorcery.Sys.Net;
namespace SipSendNotify
{
class Program
{
private const int _defaultSIPUdpPort = SIPConstants.DEFAULT_SIP_PORT; // The default UDP SIP port.
private static SIPTransport _sipTransport;
static void Main(string[] args)
{
try
{
// Configure the SIP transport layer.
_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine());
// Use default options to set up a SIP channel.
var localIP = LocalIPConfig.GetDefaultIPv4Address(); // Set this manually if needed.
int port = FreePort.FindNextAvailableUDPPort(_defaultSIPUdpPort);
var sipChannel = new SIPUDPChannel(new IPEndPoint(localIP, port));
_sipTransport.AddSIPChannel(sipChannel);
SIPCallDescriptor callDescriptor = new SIPCallDescriptor("test", null, "sip:500#67.222.131.147", "sip:you#somewhere.com", null, null, null, null, SIPCallDirection.Out, null, null, null);
SIPNonInviteClientUserAgent notifyUac = new SIPNonInviteClientUserAgent(_sipTransport, null, callDescriptor, null, null, (monitorEvent) => { Console.WriteLine("Debug: " + monitorEvent.Message); });
notifyUac.ResponseReceived += (resp) => { Console.WriteLine(resp.ToString()); };
notifyUac.SendRequest(SIPMethodsEnum.NOTIFY);
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne();
}
catch (Exception excp)
{
Console.WriteLine("Exception Main. " + excp);
}
finally
{
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
}
}

Switch-case statement not working as expected

I have written a small program that basically works on a SWITCH statement. It reads each case within the switch statement and calls and executes the appropriate functions. But, I am facing a problem that, all the functions are getting executed when the first case of the switch statement is getting called. It should not be the case because only that function which is called by a particular switch-case statement should be executed. Can some one suggest me what is wrong with my code? Posting my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Drawing;
using System.ComponentModel;
using System.ServiceModel.Security;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using Excel1.MWMClient.MWMServiceProxy;
namespace Excel1
{
class WebServiceFunctions
{
private string siteID = "INDIA";
static TemplateClient templateClient;
static TaskClient taskClient;
public WebServiceFunctions()
{
templateClient = new Excel1.MWMClient.MWMServiceProxy.TemplateClient();
templateClient.ClientCredentials.UserName.UserName = "admin";
templateClient.ClientCredentials.UserName.Password = "admin";
templateClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
taskClient = new Excel1.MWMClient.MWMServiceProxy.TaskClient();
taskClient.ClientCredentials.UserName.UserName = "admin";
taskClient.ClientCredentials.UserName.Password = "admin";
taskClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
}
public void GetAllTemplateNames(String strSite, String strRetVal)
{
//GetAllTemplateNames
Console.WriteLine("Invoking GetAllTemplate method");
Console.WriteLine("List of all templates with details");
Console.WriteLine("-----------------------------------");
List<Excel1.MWMClient.MWMServiceProxy.TemplateData> tData = templateClient.GetAllTemplate(strSite).ToList();
foreach (Excel1.MWMClient.MWMServiceProxy.TemplateData data in tData)
{
Console.WriteLine("TemplateName:" + data.name);
Console.WriteLine("TemplateDescription:" + data.description);
Console.WriteLine("SiteName:" + data.site_name);
Console.WriteLine("-----------------------------------");
}
Console.WriteLine("-----------------------------------");
}
public List<TemplateData> ReturnAllTemplateNames()
{
// Console.WriteLine("Invoking GetAllTemplate method");
// Console.WriteLine("List of all templates with details");
// Console.WriteLine("-----------------------------------");
List<Excel1.MWMClient.MWMServiceProxy.TemplateData> tData = templateClient.GetAllTemplate(siteID).ToList();
foreach (Excel1.MWMClient.MWMServiceProxy.TemplateData data in tData)
{
Console.WriteLine("TemplateName:" + data.name);
Console.WriteLine("TemplateDescription:" + data.description);
Console.WriteLine("SiteName:" + data.site_name);
Console.WriteLine("-----------------------------------");
}
Console.WriteLine("-----------------------------------");
return tData;
}
public void GetTaskInstanceFromTemplate(Excel1.MWMClient.MWMServiceProxy.TemplateData data)
{
Console.WriteLine("Invoking GetTaskInstanceFromTemplate method");
Console.WriteLine("-----------------------------------");
Excel1.MWMClient.MWMServiceProxy.TaskInstance tInstance = taskClient.GetTaskInstanceFromTemplate(siteID, data);
if (tInstance != null)
{
Console.WriteLine("TaskName: " + tInstance.name);
Console.WriteLine("TaskDescription :" + tInstance.description);
}
Console.WriteLine("-----------------------------------");
}
public TaskInstance ReturnTaskInstanceFromTemplate(Excel1.MWMClient.MWMServiceProxy.TemplateData data)
{
Console.WriteLine("Invoking GetTaskInstanceFromTemplate method");
Console.WriteLine("-----------------------------------");
Excel1.MWMClient.MWMServiceProxy.TaskInstance tInstance = taskClient.GetTaskInstanceFromTemplate(siteID, data);
if (tInstance != null)
{
Console.WriteLine("TaskName: " + tInstance.name);
Console.WriteLine("TaskDescription :" + tInstance.description);
}
Console.WriteLine("----------------------" + tInstance.name + "-------------");
return tInstance;
}
public int CreateTask(Excel1.MWMClient.MWMServiceProxy.TaskInstance instance)
{
Console.WriteLine("Invoking CreateTask method");
Console.WriteLine("-----------------------------------");
int retVal = taskClient.CreateTask(instance);
Console.WriteLine("Task create successfully:ID=" + retVal.ToString());
Console.WriteLine("-----------------------------------");
return retVal;
}
public void GetTaskStatus(int taskId)
{
Console.WriteLine("Invoking GetTaskStatus method");
Console.WriteLine("------------------****-----------------");
Excel1.MWMClient.MWMServiceProxy.TaskStatus taskStatus = new Excel1.MWMClient.MWMServiceProxy.TaskStatus();
taskStatus = taskClient.GetTaskStatus(taskId);
Console.WriteLine("Task status : " + taskStatus.taskStatus.ToString());
Console.WriteLine("-----------------------------------");
}
public void PerformTaskOperation(int taskId, string operation, String reason)
{
Console.WriteLine("PerformTaskOperation method");
Console.WriteLine("-----------------------------------");
int operationStatusCode = 0;
operationStatusCode = taskClient.PerformTaskOperation(taskId, operation, reason);
String updateSuccess = operationStatusCode == 1 ? "update success" : "update failed";
Console.WriteLine("Returned Operation Status Code = " + operationStatusCode + "|| Updation status message:" + updateSuccess);
}
//public void GetTaskHistory(int taskId, int detailLevel)
//{
// Console.WriteLine("Invoking GetTaskHistory method");
// Console.WriteLine("------------------*****-----------------");
// Excel1.MWMClient.MWMServiceProxy.TaskHistory taskHistory = new Excel1.MWMClient.MWMServiceProxy.TaskHistory();
// taskHistory = taskClient.GetTaskHistory(taskId, detailLevel);
// if (taskHistory.listOfAllowedActions != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskAllowedAction allowedAction in taskHistory.listOfAllowedActions)
// {
// Console.WriteLine("Task History - allowedAction : " + allowedAction.actionName);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.listOfCustomAttributes != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskCustomAttributes customAttribute in taskHistory.listOfCustomAttributes)
// {
// Console.WriteLine("Custom Attribute : " + customAttribute.key + " | Value:" + customAttribute.value);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskinstanceEscalations != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskEscaltion taskEscaltion in taskHistory.taskinstanceEscalations)
// {
// Console.WriteLine("Task Escaltion : " + taskEscaltion.escalationLevel + " | escalationType : " + taskEscaltion.escalationType);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskInstanceUsers != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskUser taskUser in taskHistory.taskInstanceUsers)
// {
// Console.WriteLine("Task User : " + taskUser.firstName + " , " + taskUser.lastName);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskInstanceGroups != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskGroup group in taskHistory.taskInstanceGroups)
// {
// Console.WriteLine("Group : " + group.groupName + "| escalationLevel : " + group.escalationLevel);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskInstanceSkills != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskSkill skill in taskHistory.taskInstanceSkills)
// {
// Console.WriteLine("Skill : " + skill.skillName + "| description : " + skill.description);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.taskStatusList != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.TaskStatus taskStatus in taskHistory.taskStatusList)
// {
// Console.WriteLine("TaskStatus : " + taskStatus.taskStatus);
// Console.WriteLine("-----------------------------------");
// }
// if (taskHistory.userTaskInstanceList != null)
// foreach (Excel1.MWMClient.MWMServiceProxy.UserTaskInstance userTaskInstance in taskHistory.userTaskInstanceList)
// {
// Console.WriteLine("UserTaskInstance status: " + userTaskInstance.status);
// Console.WriteLine("-----------------------------------");
// }
// //taskHistory.listOfAllowedActions
//}
public void CreateTaskFromTemplate(Excel1.MWMClient.MWMServiceProxy.TemplateData data)
{
//taskClient.ClientCredentials.UserName.UserName = "USR";
//taskClient.ClientCredentials.UserName.Password = "PWD";
//taskClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
Console.WriteLine("Invoking CreateTaskFromTemplate method");
Console.WriteLine("------------------***-----------------");
int taskId = taskClient.CreateTaskFromTemplate(siteID, data);
Console.WriteLine("Created task from template with TaskId: " + taskId);
Console.WriteLine("-----------------------------------");
}
};
class Program
{
static WebServiceFunctions wsf = new WebServiceFunctions();
public static void Main(string[] args)
{
//
//Initializing the excel sheet
//
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#"D:/WebServiceTemplate.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
//
//Getting row count, column count and the number of sheets
//
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
int numSheets = xlWorkbook.Sheets.Count;
//
// Iterate through the sheets. They are indexed starting at 1.
//
for (int row = 2; row <= rowCount; row++)
{
//
// Do something with the data in the array with a custom method.
//
String strRetVal = xlRange.Cells[row, 3].Value;
String strFunctionName = xlRange.Cells[row, 4].Value;
String strParam1 = xlRange.Cells[row, 6].Value;
String strParam2 = xlRange.Cells[row, 7].Value;
String strParam3 = xlRange.Cells[row, 8].Value;
String strParam4 = xlRange.Cells[row, 9].Value;
TemplateData tData = new TemplateData();
TaskInstance tInstance = new TaskInstance();
int tID = 0;
ProcessInput(strRetVal, strFunctionName, strParam1, strParam2, strParam3, strParam4, tData, tInstance, tID);
//creating a task from templates in one flow
//1)Get all templates.
List<Excel1.MWMClient.MWMServiceProxy.TemplateData> templateDataList = new List<TemplateData>();
//bool createTaskFromTemplate_Flag = false;
templateDataList = wsf.ReturnAllTemplateNames();
//if (createTaskFromTemplate_Flag)
//{
// foreach (TemplateData templateDataInst in templateDataList)
// {
// //We are not using the method CreateTaskFromTemplate for this application
// //WebServiceFunctions.CreateTaskFromTemplate(templateDataInst);
// }
//}
bool createTaskForAll = false;
if (createTaskForAll)
{
foreach (TemplateData templateDataInst in templateDataList)
{
//2)Get task instance
TaskInstance taskInstance = new TaskInstance();
taskInstance = wsf.ReturnTaskInstanceFromTemplate(templateDataInst);
taskInstance.scheduleActivity = new ScheduleActivity();
taskInstance.scheduleActivity.nextRun = new DateTime();
taskInstance.scheduleActivity.isRecurring = 0;
//over riding taskType in task
taskInstance.taskType = "pull";
//3)Create task.
wsf.CreateTask(taskInstance);
}
}
else
{
int numberOfTemplatesReturned = templateDataList.Count();
Random random = new Random();
int randomTemplateInList = random.Next(0, numberOfTemplatesReturned);
Console.WriteLine("Random number from template list:" + randomTemplateInList);
TemplateData templateDataInstance = new TemplateData();
templateDataInstance = templateDataList.ElementAt(randomTemplateInList);
//2)Get task instance
TaskInstance taskInstance = new TaskInstance();
taskInstance = wsf.ReturnTaskInstanceFromTemplate(templateDataInstance);
// 3)Create task.
tID = wsf.CreateTask(taskInstance);
wsf.GetTaskStatus(tID);
//int detailLevel = 2;
// Console.WriteLine("Task History for a newly created task would contain minimal details.");
// Console.WriteLine("Run method with taskId of a task which has gone through various phases to see detailed history.");
// wsf.GetTaskHistory(tID, detailLevel);
}
// Console.WriteLine("Updating status via update task status");
//wsf.PerformTaskOperation(tID, "DELETE", "trying pauseeee");
// Console.WriteLine("Press Enter To Exit Client Application.");
Console.ReadLine();
}
}
public static void ProcessInput(String strRetVal, String strFunctionName, /*String strParamCount,*/ String strParam1, String strParam2, String strParam3, String strParam4, TemplateData tData, TaskInstance tInstance, int tID)
{
switch (strFunctionName)
{
case "ITemplate.GetAllTemplate":
{
//ITemplate.GetAllTemplate code
MessageBox.Show("ITemplate.GetAllTemplate");
wsf.GetAllTemplateNames(strParam1, strRetVal);
break;
}
case "ITask.GetTaskInstanceFromTemplate":
{
//ITask.GetTaskInstanceFromTemplate code
MessageBox.Show("ITask.GetTaskInstanceFromTemplate");
wsf.GetTaskInstanceFromTemplate(tData);
break;
}
case "CreateTask":
{
//CreateTask code
MessageBox.Show("CreateTask");
wsf.CreateTask(tInstance);
break;
}
case "UpdateDatabase":
{
//UpdateDatabase code
MessageBox.Show("UpdateDatabase");
break;
}
case "GetTaskStatus":
{
//GetTaskStatus code
MessageBox.Show("GetTaskStatus");
wsf.GetTaskStatus(tID);
break;
}
case "VerifyValue":
{
//VerifyValue code
MessageBox.Show("VerifyValue");
}
break;
}
}
};
}
The call to ProcessInput() is in a loop. Have you run this in debug? That switch should work. Are you sure a SINGLE call to ProcessInput runs all the case conditions?

Categories