facebook desktop app C# - c#

I am trying to build a desktop app to use facebook api and get data from friends.
Anyways I am stuck in the log in stage.
I have used some advice and made the log in to facebook with WebBrowser. It works great.
I am stuck at trying to make it give me status = Failed or success
I tried doing it like this at the end of the button_1 method
if (!w.DocumentText.Contains(#"<div class=""linkWrap noCount"">Messages</div>"))
{
w.Navigate(#"http://www.facebook.com/login.php");
MessageBox.Show("Login error. Wrong username or password!");
}
else
{
MessageBox.Show("Logged in successfully");
}
the < div class=""linkWrap noCount"">Messages< /div> is only shown while logged in so thats why I use it to see if a user is logged in
but the problem is it always gives me an error (wrong user and pass) becasue it reads it before the browser finishes to navigate to the page. I tried threads and thread sleep and even timers but it doesnt seem to work
an ideas?
here is the code:
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();
string email = textBox1.Text;
string password = textBox2.Text;
// create a new browser
WebBrowser w = new WebBrowser();
w.Dock = DockStyle.Fill;
this.Controls.Add(w); // you may add the controll to your windows forms if you want to see what is going on
// latter you may not chose to add the browser or you can even set it to invisible...
// navigate to facebook
w.Navigate(#"http://www.facebook.com/login.php");
// wait a little
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
HtmlElement temp=null;
// while we find an element by id named email
while (temp == null)
{
temp = w.Document.GetElementById("email");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once we find it place the value
temp.SetAttribute("value", email);
temp = null;
// wiat till element with id pass exists
while (temp == null)
{
temp = w.Document.GetElementById("pass");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once it exist set its value equal to passowrd
temp.SetAttribute("value", password);
// if you already found the last fields the button should also be there...
var inputs = w.Document.GetElementsByTagName("input");
int counter = 0;
bool enableClick = false;
// iterate through all the inputs in the document
foreach (HtmlElement btn in inputs)
{
try
{
var att = btn.GetAttribute("tabindex");
var name = btn.GetAttribute("id");
if (enableClick)// button to submit always has a differnt id. it should be after password textbox
{
btn.InvokeMember("click");
counter++;
}
if (name.ToUpper().Contains("PASS") || att=="4")
{
enableClick = true; // button should be next to the password input
}
// try a max of 5 times
if (counter > 5)
{
break;
}
}
catch
{
}
}
}

Checkout the facebook-sharp SDK for Windows forms:
https://github.com/facebook-csharp-sdk/facebook-winforms

I recommend you use Facebook C# SDK. It uses the OAuth protocol, for user-authentication.
Down an code example how to get user friends with Facebook-C#-SDK:
using Facebook; //add reference to facebook dll for it work
declare the fields:
private FacebookOAuthResult result;
private FacebookOAuthClient OAuth;
and
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Url.AbsolutePath == "/login.php")
{
// do login..
}
if (FacebookOAuthResult.TryParse(e.Url, out result))
{
if (result.IsSuccess)
{
FacebookClient fbClient = new FacebookClient(result.AccessToken);
dynamic friends = fbClient.Get("/me/friends"); //User friends
// do something..
}
else
{
string errorDescription = result.ErrorDescription;
string errorReason = result.ErrorReason;
string msg = String.Format("{0} ({1})", errorReason, errorDescription);
MessageBox.Show(msg, "User-authentication failed!");
}
}
}
and then for start user-authentication:
//..
OAuth = new FacebookOAuthClient();
OAuth.AppId = appId; // see link above,you can find how to get it
OAuth.AppSecret = appSecret; // see link above,you can find how to get it
Uri loginUrl = OAuth.GetLoginUrl(paramenters);
webBrowser1.Navigate(loginUrl.AbsoluteUri);

Related

Save user messages sent to bot and send finished form to other user

For days I've been trying to solve this problem with my Telegram Bot.
I'm trying to send the user some questions after he "/start"s the bot.
I want to capture all user answers and then send it to some user that I want to see user answers in one message.
I tried to do it by sending inline buttons and couldn't find the way to wait for the next message from the user. I tried to store the answers in a string array, and it doesn't work either.
And at the end of the question, I want to send all user answers to some userid/channel in one message with all user questions.
I use Telegram.Bot library.
Here is my code
static string gotName = "0";
static string gotAge = "0";
static string gotMessage = "0";
static string[] Forminfo = { gotName, gotAge, gotMessage };
async private void Bot_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
{
if (e.Update.Type == UpdateType.Message && e.Update.Message.Text == "/start")
{
var streg = new InlineKeyboardMarkup(new[]
{
new [] // first row
{
InlineKeyboardButton.WithCallbackData("Next Step","start")
}
});
var update = e.Update.Message.Text;
var strmsg = "To Start The Register please send the bot your name and click on Next Step";
await bot.SendTextMessageAsync(e.Update.Message.Chat.Id, strmsg, ParseMode.Html, replyMarkup: streg);
var usermsg = await bot.GetUpdatesAsync();
Forminfo[0] = usermsg.ToString();
}
}
async private void Bot_OnCallbackQuery(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
{
var streg1 = new InlineKeyboardMarkup(new[]
{
new [] // first row
{
InlineKeyboardButton.WithCallbackData("Next","start1")
}
});
if (Forminfo[0] != "0")
{
var startedmsg = "Hello " + Forminfo[0].ToString() + "\n" +
"Please Send us your Age and click Next";
try
{
await bot.SendTextMessageAsync(e.CallbackQuery.Message.Chat.Id, startedmsg, ParseMode.Html, replyMarkup: streg1);
}
catch(HttpRequestException ex)
{
await bot.SendTextMessageAsync(e.CallbackQuery.Message.Chat.Id, "To Many Request Please Try Later.", ParseMode.Html);
}
}
}
There are a couple things to fix:
If all you are handling inside your OnUpdate callback are messages, use OnMessage instead
You are using OnUpdate and then manually call GetUpdates. You can't mix multiple approaches of getting updates - the StartReceiving call already handles calling GetUpdates internally.
By having one string[] as the result, you are assuming only one user will use the bot at the same time. A better approach would be to use a Dictionary<userId, result>.
In your SendTextMessageAsync call, you don't have to set ParseMode if you are sending regular text
I don't see what you are using the buttons for if you're never checking whether the user clicked them
This is a code example that does what you want, but does not validate the input at all:
const long TargetChannelId = 123456;
static readonly ConcurrentDictionary<int, string[]> Answers = new ConcurrentDictionary<int, string[]>();
private static async void Bot_OnMessage(object sender, MessageEventArgs e)
{
Message message = e.Message;
int userId = message.From.Id;
if (message.Type == MessageType.Text)
{
if (Answers.TryGetValue(userId, out string[] answers))
{
if (answers[0] == null)
{
answers[0] = message.Text;
await Bot.SendTextMessageAsync(message.Chat, "Now send me your age");
}
else if (answers[1] == null)
{
answers[1] = message.Text;
await Bot.SendTextMessageAsync(message.Chat, "Now send me your message");
}
else
{
Answers.TryRemove(userId, out string[] _);
await Bot.SendTextMessageAsync(message.Chat, "Thank you, that's all I need from you");
string answersText = $"User {answers[0]}, aged {answers[1]} sent the following message:\n{message.Text}";
await Bot.SendTextMessageAsync(TargetChannelId, answersText);
}
}
else
{
Answers.TryAdd(userId, new string[2]);
await Bot.SendTextMessageAsync(message.Chat, "Please send me your name");
}
}
}

Windows IOT UWP - Relay

Good Evening,
I’m doing some troubleshooting on the beginning of my home automation system. I am trying to toggle a relay using a Raspberry PI 3 and Windows IOT in C#. I’ve been playing with the code and I can see the relay toggle once or twice, but then the app crashes. I’m an IOT Noob, so is there something wrong with this code? (Variable names are defined elsewhere and the weird variable names I have below are for my WIP project... I prefer troubleshooting in English)....
private void BtnTempFan_Click(object sender, RoutedEventArgs e)
{
if (BtnTempFan.IsChecked == true)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.High);
}
else
{
TempFan.Dispose();
}
}
private void TogglePin(GpioPin PinName, int PinNumber, ToggleButton Name, GpioPinValue value)
{
int pinnumber = PinNumber;
GpioPinValue pinvalue;
var gpio = GpioController.GetDefault();
PinName = gpio.OpenPin(pinnumber);
if (gpio == null)
{
PinName = null;
LblError.Text = "We can't find the controller on the device" + PinName;
LblError.Visibility = Visibility.Visible;
return;
}
if (PinName == null)
{
LblError.Text = "We can't find the pin on the device. Pin number " + PinNumber + "does not exist";
LblError.Visibility = Visibility.Visible;
return;
}
if (Name.IsChecked == true)
{
pinvalue = value;
PinName.Write(pinvalue);
PinName.SetDriveMode(GpioPinDriveMode.Output);
}
You don't say what the exception is. However, I believe you are supposed open a GPIO pin only once per app:
var gpio = GpioController.GetDefault();
PinName = gpio.OpenPin(pinnumber);
You have it in a method which is called once per button click. By opening the pin more than once, you are encountering that the pin is already open, and I believe this is what throws an exception and crashes the app.
In my code, I handle pin states in a "driver" class, and have a method called Connect which I call once when starting the application. For example:
public async Task Connect()
{
var gpioController = await GpioController.GetDefaultAsync();
try
{
_openPin = gpioController.OpenPin(_doorMotorOpenPin);
_closePin = gpioController.OpenPin(_doorMotorClosePin);
}
}
This encapsulates the 2 pins: _openPin and _closePin into a class that I can manage the lifecycle of.
Codekaizen is correct. I separated out opening the pin into a method that only gets called once and problem solved.
private void BtnTempFan_Click(object sender, RoutedEventArgs e)
{
if (BtnTempFan.IsChecked == false)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.High);
}
if (BtnTempFan.IsChecked == true)
{
TogglePin(TempFan, TempFan_PIN, BtnTempFan, GpioPinValue.Low);
}
}
private void InitializePins()
{
var gpio = GpioController.GetDefault();
// Show an error if there is no GPIO controller
if (gpio == null)
{
TempFan = null;
LblError.Text = "We can't find the controller on the device";
LblError.Visibility = Visibility.Visible;
return;
}
TempFan = gpio.OpenPin(TempFan_PIN);
TempFan.SetDriveMode(GpioPinDriveMode.Output);
}
private void TogglePin(GpioPin PinName, int PinNumber, ToggleButton Name, GpioPinValue value)
{
int pinnumber = PinNumber;
GpioPinValue pinvalue;
pinvalue = value;
PinName.Write(pinvalue);
}

Making a prettier Facebook Login Screen for Parse.com Server with Xamarin.Android

Im trying to create a login system for Xamarin.Android to be used on a Parse server. I want to login the user with Facebook and save his real name and his small user photo.
My current code of displaying the login system is this:
using Xamarin.Auth;
loginFacebookButton.Click += (sender, e) =>
{
if (CrossConnectivity.Current.IsConnected)
LoginToFacebook();
else
{
DisplayNoConnectivityMessage();
}
};
loginTwitterButton.Click += (sender, e) =>
{
LoginToTwitter();
};
}
void DisplayNoConnectivityMessage()
{
AlertDialog.Builder alert2 = new AlertDialog.Builder(this);
alert2.SetTitle("Network error");
alert2.SetMessage("Connection with the Internet is required. Please check your connectivity and try again.");
alert2.Show();
}
void DisplayLoadingMessage(bool Dismiss)
{
RunOnUiThread(() =>
{
if (!Dismiss)
{
builder = new AlertDialog.Builder(this);
builder.SetTitle("Signing in");
builder.SetMessage("Please wait...");
builder.SetCancelable(false);
alert = builder.Create();
alert.Show();
} else {
if (alert != null)
if (alert.IsShowing)
{
alert.Dismiss();
alert.Dispose();
}
}
});
}
async void LoginToFacebook()
{
var auth = new OAuth2Authenticator(
clientId: "809804315805408",
scope: "user_about_me",
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html")
);
auth.AllowCancel = false;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += LoginComplete;
var intent = auth.GetUI(this);
StartActivity(intent);
}
public async void LoginComplete(object sender, AuthenticatorCompletedEventArgs e)
{
string id = "";
string name = "";
JsonValue obj;
if (!e.IsAuthenticated)
{
var builder = new AlertDialog.Builder(this);
builder.SetMessage("Not Authenticated");
builder.SetPositiveButton("Ok", (o, c) => { });
builder.Create().Show();
return;
}
else {
DisplayLoadingMessage(false);
AccountStore.Create(this) .Save(e.Account, "Facebook");
// Now that we're logged in, make a OAuth2 request to get the user's info.
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, e.Account);
await request.GetResponseAsync().ContinueWith(t =>
{
var builder2 = new AlertDialog.Builder(this);
if (t.IsFaulted)
{
builder2.SetTitle("Error");
builder2.SetMessage(t.Exception.Flatten().InnerException.ToString());
builder2.Show();
}
else if (t.IsCanceled)
{
builder2.SetTitle("Task Canceled");
builder2.Show();
}
else {
obj = JsonValue.Parse(t.Result.GetResponseText());
id = obj["id"];
name = obj["name"];
}
builder.SetPositiveButton("Ok", (o, c) => { });
builder.Create();
}, UIScheduler);
var accessToken = e.Account.Properties["access_token"];
var expiresIn = Convert.ToDouble(e.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var user = await ParseFacebookUtils.LogInAsync(id, accessToken, expiryDate);
try
{
user.Add("Name", name);
}
catch (Exception ex)
{
Console.WriteLine("LoginFragment.cs | LoginComplete() :: user.Add (\"Name\",name); :: " + ex.Message);
}
var webClient = new WebClient();
//var httpClient = new HttpClient(new NativeMessageHandler());
var url = new Uri("http://graph.facebook.com/" + id + "/picture?type=small");
application.currentUserImageUrl = url.ToString();
application.currentUserName = name;
byte[] bytes = null;
//bytes = await httpClient.GetByteArrayAsync(url);
bytes = await webClient.DownloadDataTaskAsync(url);
ParseFile saveImageFile = new ParseFile("profileImage.jpg", bytes);
try
{
user.Add("profile_pic", saveImageFile);
}
catch (Exception ex)
{
Console.WriteLine("LoginFragment.cs | LoginComplete() :: user.Add (\"profile_pic\",saveImageFile); :: " + ex.Message);
}
application.currentUser = user;
await user.SaveAsync();
DisplayLoadingMessage(true);
ChangeScreen();
}
}
The problem with this code is this:
After the login i get a Success message displayed (a simple
success message on a white page) that must be from facebook and
obviously i dont wnat to be displayed on the user.
While the
LoginCompete code is running the app is working on background and the user doesn't see anyhting, its like the app closes and after
the login opens again. I have try to display an AlertDialog with
the function DisplayNoConnectivityMessage but it doesnt be shown
in the user anything i dont know way.
The easiest way to login with Facebook on Parse is the official Parse SDK in combination with the offical Facebook for Android SDK to handle the Single-Sign On Scenario.
With just some small steps you achieve the expected result:
Follow this small guide to setup your app for the Facebook SDK: https://components.xamarin.com/gettingstarted/facebookandroid
Setup the Parse SDK
public App()
{
// App.xaml initialization
ParseClient.Initialize("Your Application ID", "Your .NET Key");
ParseFacebookUtils.Initialize("Your Facebook App Id");
// Other initialization
}
Add a FB Login Button to your View.
<com.facebook.login.widget.LoginButton
android:id="#+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
android:layout_marginBottom="30dp" />
Get the callback and use the token to signin the user with Parse.
public class MainActivity : Activity, IFacebookCallback
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
// SetContentView (Resource.Layout.Main);
var callbackManager = CallbackManagerFactory.Create();
var loginButton = FindViewById<LoginButton>(Resource.Id.login_button);
loginButton.RegisterCallback(callbackManager, this);
}
#region IFacebookCallback
public void OnCancel()
{
// Handle Cancel
}
public void OnError(FacebookException error)
{
// Handle Error
}
public async void OnSuccess(Object result)
{
// We know that this is a LoginResult
var loginResult = (LoginResult) result;
// Convert Java.Util.Date to DateTime
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var expireDate = epoch.AddMilliseconds(loginResult.AccessToken.Expires.Time);
// FB User AccessToken
var accessToken = loginResult.AccessToken.Token;
ParseUser user = await ParseFacebookUtils.LogInAsync("Your Facebook App Id", accessToken, expireDate);
}
#endregion
...
}
(Optional) Interact with the Facebook SDK & ParseUser
// You can simply pass the acquired AccessToken to the GraphRequest
var parameters = new Bundle();
parameters.PutString("fields", "id,email,gender,cover,picture.type(small)");
var request = new GraphRequest(loginResult.AccessToken, "me", parameters, HttpMethod.Get);
// Execute request and Handle response (See FB Android SDK Guide)
// to get image as byte[] from GraphResponse
byte[] data;
// Store the image into the ParseUser
user["image"] = new ParseFile("image.jpg", data);
Instead of using the GraphRequest you can always fallback to the HttpClient / WebClient and pass the AccessToken as URL parameter. Docs
Additional
Here a link to the official docs: http://parseplatform.github.io/docs/dotnet/guide/#facebook-users
Pick SDK from Nuget: https://www.nuget.org/packages/Xamarin.Facebook.Android/
The Xamarin Facebook Android SDK works like the Java SDK so this docs are also worth to look at: https://developers.facebook.com/docs/facebook-login/android#addbutton
My problem finally was:
By disabling secure browsing on facebook login application settings from facebook developers dashboard, i was able to get rib of the success message.
Setting the Activity to "NoHistory = true", makes social login problematic cause the responds from the social platforms to the Activity isn't tracked as it should. Also this was the problem for not showing the AlertDialog (i would never going to guess that).
But the answer of #paul-reichelt is the best approach for native facebook login.

Receiving Notfication when app is running

In fear of asking a question that might have been asked before, but my search skills did not able me to find. Okay, so here goes.
I have Windows Phone 8 App, where I can receive TileUpdates and Notifications, when My app is not running in the foreground. This I did by following http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202940(v=vs.105).aspx
In that link I learned that for getting notifications when app is running I should simply attach an event for the reception case. This I did in my AcquirePushChannel() function, which looks as follows:
public static void AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("MyPushChannel");
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("MyPushChannel");
CurrentChannel.Open();
if (!CurrentChannel.IsShellToastBound)
{
CurrentChannel.BindToShellTile();
}
CurrentChannel.BindToShellToast();
CurrentChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(Push_NotificationRecieved);
}
if (!CurrentChannel.IsShellTileBound)
{
CurrentChannel.BindToShellToast();
CurrentChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(Push_NotificationRecieved);
}
CurrentChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(Push_NotificationChannelChanged);
}
I have implemented CurrentChannel.ChannelUriUpdated, for the case that channelUri changes and I execute some code to also changes my ChannelsTable in the Cloud.
My Push_NotificationRecieved looks like:
private static void Push_NotificationRecieved(object sender, NotificationEventArgs e)
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
// Parse out the information that was part of the message.
foreach (string key in e.Collection.Keys)
{
message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);
if (string.Compare(
key,
"wp:Param",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.CompareOptions.IgnoreCase) == 0)
{
relativeUri = e.Collection[key];
}
}
// Display a dialog of all the fields in the toast.
MessageBox.Show(message.ToString());
//Dispatcher.BeginInvoke((message) => MessageBox.Show(message.ToString()));
}
I cannot see why the notification is not registered. Since in my log in the cloud I receive that the Toast Notification was received?
Any Ideas? Furthermore can I display the toast from the code or something similar, as far as I have read it is not possible?
Extra
Have tried changing the functions to public but did not help with the problem.
Anybody have an Idea to why the event is not firing.
The answer you posted is almost correct. From the previous you have:
public static void AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("MyPushChannel");
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("MyPushChannel");
CurrentChannel.Open();
if (!CurrentChannel.IsShellToastBound)
{
CurrentChannel.BindToShellTile();
}
CurrentChannel.BindToShellToast();
}
if (!CurrentChannel.IsShellTileBound)
{
CurrentChannel.BindToShellToast();
}
CurrentChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(Push_NotificationChannelChanged);
CurrentChannel.ShellToastNotificationReceived += CurrentChannel_ShellToastNotificationReceived;
}
And to that you have to add:
private static void CurrentChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
{
StringBuilder message = new StringBuilder();
string relativeUri = string.Empty;
message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());
// Parse out the information that was part of the message.
foreach (string key in e.Collection.Keys)
{
message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);
if (string.Compare(
key,
"wp:Param",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.CompareOptions.IgnoreCase) == 0)
{
relativeUri = e.Collection[key];
}
}
// Display a dialog of all the fields in the toast.
MessageBox.Show(message.ToString());
}
So all you send is inside the e.collection. So you can from the server send all kind of parameters.
Of course just after I set a bounty to run I got it working. So here is the updated code.
public static void AcquirePushChannel()
{
CurrentChannel = HttpNotificationChannel.Find("MyPushChannel");
if (CurrentChannel == null)
{
CurrentChannel = new HttpNotificationChannel("MyPushChannel");
CurrentChannel.Open();
if (!CurrentChannel.IsShellToastBound)
{
CurrentChannel.BindToShellTile();
}
CurrentChannel.BindToShellToast();
}
if (!CurrentChannel.IsShellTileBound)
{
CurrentChannel.BindToShellToast();
}
CurrentChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(Push_NotificationChannelChanged);
CurrentChannel.ShellToastNotificationReceived += CurrentChannel_ShellToastNotificationReceived;
}
Okay so the reason for this, is that you need to set the events on every startup. Then you will get the wished properties. Then you have to create your own code for getting what you want :)

Sharepoint Sequential Workflow not adding Task into Tasklist

After the deployment of the workflow onto the sharepoint site, I am able to start the workflow by creating new rows of a list. These are also reflected in the field, "no. of workflow in progress". However, I cannot seem to find the tasks created for specific users in the Task list.
As a beginner with Sharepoint development, I am not exactly sure what is wrong. Please kindly advise.
this is my tested code:
private void OnCreateTask_MethodInvoking(object sender, EventArgs e)
{
taskId1 = Guid.NewGuid();
// SPContentTypeId myContentTypeId=new SPContentTypeId("0x01080100e73fd5f172cb40d8a5dca97fad7a58b8");
SPContentType myContentType = SPContext.Current.Web.ContentTypes["Powerfull Approval Workflow Task"];
CreateTaskApproval_ContentTypeID = myContentType.Id.ToString();
#region Enable ContentTypes
if (this.workflowProperties.TaskList.ContentTypesEnabled != true)
{
workflowProperties.TaskList.ContentTypesEnabled = true;
}
bool contenTypeExists = false;
foreach (SPContentType contentType in workflowProperties.TaskList.ContentTypes)
{
if (contentType.Name == myContentType.Name)
{
contenTypeExists = true;
break;
}
}
if (contenTypeExists != true)
{
workflowProperties.TaskList.ContentTypes.Add(myContentType);
}
myContentType.EditFormUrl = "_layouts/SequentialWorkflow/TaskEdit/TaskEditForm.aspx";
myContentType.DisplayFormUrl = "_layouts/SequentialWorkflow/TaskEdit/TaskEditForm.aspx";
myContentType.Update();
#endregion
taskProperties.PercentComplete = (float)0.0;
taskProperties.AssignedTo = myInstantiationData.User;
taskProperties.DueDate = myInstantiationData.DueDate;
taskProperties.Description = myInstantiationData.Request;
taskProperties.StartDate = DateTime.Now;
taskProperties.Title = "Please approve " + this.workflowProperties.Item.DisplayName;
}

Categories