How can I put the code block into a function in c#? - c#

I would want to use a function in the place of the if/else-clause.
public void CopyPasteFiles(string modelInfoFilePath, string definitionFilePath, string pedName)
{
string messageBoxText = "Looks like a ped with this name already Exists. Please try a new Name.";
if (this.IsMale)
{
modelInfoFilePath = Tokenizer.Detokenize(modelInfoFilePath);
this.NewModelInfoPath = modelInfoFilePath.Replace("Z_Z_ProxyPed_MR1_000_Dummy", pedName);
if (!File.Exists(this.NewModelInfoPath))
{
File.Copy(modelInfoFilePath, this.NewModelInfoPath, false);
FileInfo fileInfo = new FileInfo(this.NewModelInfoPath);
fileInfo.IsReadOnly = false;
}
else
{
RsMessageBox.Show(messageBoxText);
}
definitionFilePath = Tokenizer.Detokenize(definitionFilePath);
this.NewDefinitionPath = definitionFilePath.Replace("Z_Z_ProxyPed_MR1_000_Dummy", pedName);
if (!File.Exists(this.NewDefinitionPath))
{
File.Copy(definitionFilePath, this.NewDefinitionPath, false);
FileInfo fileInfo = new FileInfo(this.NewDefinitionPath);
fileInfo.IsReadOnly = false;
}
else
{
RsMessageBox.Show(messageBoxText);
}
}
else if (this.IsFemale)
{
modelInfoFilePath = Tokenizer.Detokenize(modelInfoFilePath);
this.NewModelInfoPath = modelInfoFilePath.Replace("Z_Z_ProxyPed_FR1_000_Dummy", pedName);
if (!File.Exists(this.NewModelInfoPath))
{
File.Copy(modelInfoFilePath, this.NewModelInfoPath, false);
FileInfo fileInfo = new FileInfo(this.NewModelInfoPath);
fileInfo.IsReadOnly = false;
}
else
{
RsMessageBox.Show(messageBoxText);
}
definitionFilePath = Tokenizer.Detokenize(definitionFilePath);
this.NewDefinitionPath = definitionFilePath.Replace("Z_Z_ProxyPed_FR1_000_Dummy", pedName);
if (!File.Exists(this.NewDefinitionPath))
{
File.Copy(definitionFilePath, this.NewDefinitionPath, false);
FileInfo fileInfo = new FileInfo(this.NewDefinitionPath);
fileInfo.IsReadOnly = false;
}
else
{
RsMessageBox.Show(messageBoxText);
}
}
}

Let's see: you have the following piece of code which comes back constantly:
if (!File.Exists(New_Information))
{
File.Copy(Existing_Information, New_Information, false);
FileInfo fileInfo = new FileInfo(New_Information);
fileInfo.IsReadOnly = false;
}
else
{
RsMessageBox.Show(messageBoxText);
}
This means that you need to write a function, using the two parameters Existing_Information and New_Information, something like:
void Do_Something(var Existing_Information, var New_Information)
{
if (!File.Exists(New_Information))
{
File.Copy(Existing_Information, New_Information, false);
FileInfo fileInfo = new FileInfo(New_Information);
fileInfo.IsReadOnly = false;
}
else
{
RsMessageBox.Show(messageBoxText);
}
}
Inside your code, you just replace your if-loop by that function, using the correct parameters:
Do_Something(modelInfoFilePath, this.NewmodelInfoFilePath);
...
Do_Something(definitionFilePath, this.DefinitionFilePath);
...

First you should analyze what parts of your code are the same, and which variables can be substituted for parameters.
Looking at your code, I see 4 parts that are somewhat similar.
2 of them are for this.IsMale, and two of them are this.IsFemale (which could also be !this.IsMale considering a binary biological standpoint). We can use this to change the string itself, instead of using two if statements.
2 of them use modelInfoFilePath, while the other 2 use definitionFilePath.
If we declare these first, we can use them as parameters for a CopyFile method.
Take a look at this code below, you might see what I mean.
public void CopyPasteFiles(string modelInfoFilePath, string definitionFilePath, string pedName)
{
modelInfoFilePath = Tokenizer.Detokenize(modelInfoFilePath);
definitionFilePath = Tokenizer.Detokenize(definitionFilePath);
string pedReplaceName = this.IsMale : "Z_Z_ProxyPed_MR1_000_Dummy" ? "Z_Z_ProxyPed_FR1_000_Dummy";
// replace names
this.NewModelInfoPath =
modelInfoFilePath.Replace(pedReplaceName, pedName);
this.NewDefinitionPath =
definitionFilePath.Replace(pedReplaceName, pedName);
// copy files
CopyFile(modelInfoFilePath, this.NewModelInfoPath);
CopyFile(definitionFilePath, this.NewDefinitionPath);
}
public void CopyFile(filePath, newFilePath) {
if (!File.Exists(newFilePath))
{
File.Copy(filePath, newFilePath, false);
FileInfo fileInfo = new FileInfo(newFilePath);
fileInfo.IsReadOnly = false;
}
else {
RsMessageBox.Show("Looks like a ped with this name already exists. Please try a new Name.");
}
}

Related

Creating a folder under Inbox using Mocrosoft.Graph 2.0.14

I'm trying to create a folder under my Inbox in Office 365 using MS Graph 2.0, but I'm finding surprisingly little information on the topic anywhere on the internet. The authentication works fine, and I was able to read the existing test folder. My method for doing this is below:
private void SetupMailBoxes()
{
SmartLog.EnterMethod("SetupMailBoxes()");
MailFolder inbox = null;
try
{
bool dbErrorFolder = false;
bool exchangeErrorFolder = false;
inbox = _journalMailbox.MailFolders.Inbox.Request().GetAsync().GetAwaiter().GetResult();
if (inbox.ChildFolderCount > 0)
{
inbox.ChildFolders = _journalMailbox.MailFolders.Inbox.ChildFolders.Request().GetAsync().GetAwaiter().GetResult();
}
if (inbox.ChildFolders != null)
{
for (int i = 0; i < inbox.ChildFolders.Count && (!dbErrorFolder || !exchangeErrorFolder); i++)
{
if (inbox.ChildFolders[i].DisplayName.ToLower() == "db-error-items")
{
dbErrorFolder = true;
}
else if (inbox.ChildFolders[i].DisplayName.ToLower() == "exchange-error-items")
{
exchangeErrorFolder = true;
}
}
}
if (!dbErrorFolder)
{
try
{
//inbox.ODataType = "post";
var folder = _journalMailbox.MailFolders.Inbox.Request().CreateAsync(
new MailFolder()
{
DisplayName = "DB-Error_Items",
}).GetAwaiter().GetResult();
//inbox.ChildFolders.Add(folder);
}
catch (Exception ex)
{
throw;
}
}
}
catch (Exception exp)
{
SmartLog.LeaveMethod("SetupMailBoxes()");
throw;
}
finally
{
}
SmartLog.LeaveMethod("SetupMailBoxes()");
}
Where _clientSecretCredential is created like this:
_graphServiceClient = null;
_options = new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud };
_clientSecretCredential = new ClientSecretCredential(
this.FindString(config.TenentID)
, this.FindString(config.AppID)
, this.FindString(config.Secret)
, _options);
string[] apiScope = new string[] { this.FindString(config.Scope) };
_token = _clientSecretCredential.GetToken(new Azure.Core.TokenRequestContext(apiScope));
graphServiceClient = new GraphServiceClient(_clientSecretCredential, apiScope);
IUserRequestBuilder _journalMailbox = _graphServiceClient.Users["journal#mycompany.com"];
The code seems correct, but everytime I execute "_journalMailbox.MailFolders.Inbox.Request().CreateAsync", I get the following error:
Code: ErrorInvalidRequest
Message: The OData request is not supported.
ClientRequestId:Some Guid.
From what I could figure out by searching on the internet, it has to do with the method using the wrong method to access the API. I mean like, its using "GET" in stead of "POST" or something like that, but that would mean its a bug in the MS code, and that would an unimaginably big oversight on Microsoft's part, so I can't think its that.
I've tried searching documentation on how to create subfolders, but of the preciously few results I'm getting, almost none has C# code samples, and of those, all are of the previous version of Microsoft Graph.
I'm really stumped here, I'm amazed at how hard it is to find any documentation to do something that is supposed to be simple and straight forward.
Ok, so it turned out that I was blind again. Here is the correct code for what I was trying to do:
private void SetupMailBoxes()
{
SmartLog.EnterMethod("SetupMailBoxes()");
MailFolder inbox = null;
try
{
bool dbErrorFolder = false;
bool exchangeErrorFolder = false;
inbox = _journalMailbox.MailFolders.Inbox.Request().GetAsync().GetAwaiter().GetResult();
if (inbox.ChildFolderCount > 0)
{
inbox.ChildFolders = _journalMailbox.MailFolders.Inbox.ChildFolders.Request().GetAsync().GetAwaiter().GetResult();
}
if (inbox.ChildFolders != null)
{
for (int i = 0; i < inbox.ChildFolders.Count && (!dbErrorFolder || !exchangeErrorFolder); i++)
{
if (inbox.ChildFolders[i].DisplayName.ToLower() == "db-error-items")
{
dbErrorFolder = true;
}
else if (inbox.ChildFolders[i].DisplayName.ToLower() == "exchange-error-items")
{
exchangeErrorFolder = true;
}
}
}
else
{
inbox.ChildFolders = new MailFolderChildFoldersCollectionPage();
}
if (!dbErrorFolder)
{
try
{
var folder = new MailFolder()
{
DisplayName = "DB-Error-Items",
IsHidden = false,
ParentFolderId = inbox.Id
};
folder = _journalMailbox.MailFolders[inbox.Id].ChildFolders.Request().AddAsync(folder).GetAwaiter().GetResult();
inbox.ChildFolders.Add(folder);
}
catch (Exception ex)
{
throw;
}
}
}
catch (Exception exp)
{
SmartLog.LeaveMethod("SetupMailBoxes()");
throw;
}
finally
{
}
SmartLog.LeaveMethod("SetupMailBoxes()");
}

How to have an AWS Lambda/Rekognition Function return an array of object keys

This feels like a simple question and I feel like I am overthinking it. I am doing an AWS project that will compare face(s) on an image to a database (s3bucket) of other faces. So far, I have a lambda function for the comparefacerequest, a class library which invokes the function, and an UWP that inputs the image file and outputs a result. It has worked so far being based on boolean (true or false) functions, but now I want it to instead return what face(s) are recognized via an array. I struggling at implementing this.
Below is my lambda function. I have adjusted the task to be an Array instead of a bool and changed the return to be an array. At the bottom, I have created a global variable class with a testing array so I could attempt to reference the array elsewhere.
public class Function
{
//Function
public async Task<Array> FunctionHandler(string input, ILambdaContext context)
{
//number of matched faces
int matched = 0;
//Client setup
var rekognitionclient = new AmazonRekognitionClient();
var s3client = new AmazonS3Client();
//Create list of target images
ListObjectsRequest list = new ListObjectsRequest
{
BucketName = "bucket2"
};
ListObjectsResponse listre = await s3client.ListObjectsAsync(list);
//loop of list
foreach (Amazon.S3.Model.S3Object obj in listre.S3Objects)
{
//face request with input and obj.key images
var comparefacesrequest = new CompareFacesRequest
{
SourceImage = new Image
{
S3Object = new S3Objects
{
Bucket = "bucket1",
Name = input
}
},
TargetImage = new Image
{
S3Object = new S3Objects
{
Bucket = "bucket2",
Name = obj.Key
}
},
};
//compare with confidence of 95 (subject to change) to current target image
var detectresponse = await rekognitionclient.CompareFacesAsync(comparefacesrequest);
detectresponse.FaceMatches.ForEach(match =>
{
ComparedFace face = match.Face;
if (match.Similarity > 95)
{
//if face detected, raise matched
matched++;
for(int i = 0; i < Globaltest.testingarray.Length; i++)
{
if (Globaltest.testingarray[i] == "test")
{
Globaltest.testingarray[i] = obj.Key;
}
}
}
});
}
//Return true or false depending on if it is matched
if (matched > 0)
{
return Globaltest.testingarray;
}
return Globaltest.testingarray;
}
}
public static class Globaltest
{
public static string[] testingarray = { "test", "test", "test" };
}
Next, is my invoke request in my class library. It has so far been based on the lambda outputting a boolean result, but I thought, "hey, it is parsing the result, it should be fine, right"? I do convert the result to a string, as there is no GetArray, from what I know.
public async Task<bool> IsFace(string filePath, string fileName)
{
await UploadS3(filePath, fileName);
AmazonLambdaClient client = new AmazonLambdaClient(accessKey, secretKey, Amazon.RegionEndpoint.USWest2);
InvokeRequest ir = new InvokeRequest();
ir.InvocationType = InvocationType.RequestResponse;
ir.FunctionName = "ImageTesting";
ir.Payload = "\"" + fileName + "\"";
var result = await client.InvokeAsync(ir);
var strResponse = Encoding.ASCII.GetString(result.Payload.ToArray());
if (bool.TryParse(strResponse, out bool result2))
{
return result2;
}
return false;
}
Finally, here is the section of my UWP where I perform the function. I am referencing the lambda client via "using Lambdaclienttest" (name of lamda project, and this is its only instance I use the reference though). When I run my project, I do still get a face detected when it should, but the Globaltest.testingarray[0] is still equal to "test".
var Facedetector = new FaceDetector(Credentials.accesskey, Credentials.secretkey);
try
{
var result = await Facedetector.IsFace(filepath, filename);
if (result)
{
textBox1.Text = "There is a face detected";
textBox2.Text = Globaltest.testingarray[0];
}
else
{
textBox1.Text = "Try Again";
}
}
catch
{
textBox1.Text = "Please use a photo";
}
Does anyone have any suggestions?

accept multi line string in Process.Start

i am parsing a path from a directory location:
assuming that InitialPath = #"C:\Users\username\Documents\Visual Studio 2015\Projects"
and i have a loop of:
var list = new List<string>();
foreach(var folder in Directory.GetDirectories(InitialPath) {
var folder = Path.GetFileName(folder);
var file = Path.GetFileName(Directory.GetFiles(folder, "*.sln").Single());
list.Add(InitialPath + "\\" + folder + "\\" + file); //would then result something like "C:\Users\username\Documents\Visual Studio 2015\Projects\Folder1\Project1inFolder1.sln"
}
if i try a path from the list and assign it to a richbox as its .text value, it returns a single line text.
but when i'm displaying it on a MessageBox, the string is being broken into two lines as below:
i need to force it not to be broken into several lines. i mean, i need it to be a single line string only no matter the length of the string because Process.Start() wont accept the string because it gets cut into lines. see below for reference:
PS: sorry for not being able to explain my question eligibly, english is not my natural language
just in case, here is my code snippet:
using MaterialSkin;
using MaterialSkin.Controls;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Principal;
namespace The_Projects {
public partial class MainForm : MaterialForm {
public MainForm() {
InitializeComponent();
var materialSkinManager = MaterialSkinManager.Instance;
materialSkinManager.AddFormToManage(this);
materialSkinManager.Theme = MaterialSkinManager.Themes.LIGHT;
materialSkinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
public class DirectoryInformation {
private string _FolderName;
private string _Solution;
private DateTime _Created;
private DateTime _Accessed;
private DateTime _Modified;
private string _SecIdentity;
private string _NTAccount;
private double _FileSize;
private int _FileCount;
public string FolderName {
get { return _FolderName; }
set { _FolderName = value; }
}
public string Solution {
get { return _Solution; }
set { _Solution = value; }
}
public DateTime Created {
get { return _Created; }
set { _Created = value; }
}
public DateTime Accessed {
get { return _Accessed; }
set { _Accessed = value; }
}
public DateTime Modified {
get { return _Modified; }
set { _Modified = value; }
}
public string SecIdentity {
get { return _SecIdentity; }
set { _SecIdentity = value; }
}
public string NTAccount {
get { return _NTAccount; }
set { _NTAccount = value; }
}
public double FileSize {
get { return _FileSize; }
set { _FileSize = value; }
}
public int FileCount {
get { return _FileCount; }
set { _FileCount = value; }
}
}
public string InitialPath = #"X:\_\Document\Visual Studio 2015\Projects\";
public string FolderPath = string.Empty;
public string Solution = string.Empty;
private void MainForm_Load(object sender, EventArgs e) {
var projectList = new List<DirectoryInformation>();
foreach(var dirs in Directory.GetDirectories(InitialPath)) {
var ac = File.GetAccessControl(dirs);
var di = new DirectoryInfo(dirs);
var dirInf = new DirectoryInformation() {
FolderName = Path.GetFileName(dirs),
Solution = Path.GetFileName(Directory.GetFiles(dirs, "*.sln").Single()),
Created = Directory.GetCreationTime(dirs),
Accessed = Directory.GetLastAccessTime(dirs),
Modified = Directory.GetLastWriteTime(dirs),
SecIdentity = ac.GetOwner(typeof(SecurityIdentifier)).ToString(),
NTAccount = ac.GetOwner(typeof(SecurityIdentifier)).Translate(typeof(NTAccount)).ToString(),
FileSize = (double) di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(x => x.Length) / 1024000,
FileCount = Directory.GetFiles(dirs, "*.*", SearchOption.AllDirectories).Count()
};
projectList.Add(dirInf);
}
lstProjectList.DataSource = projectList;
lstProjectList.DisplayMember = "FolderName";
}
private void lstProjectList_SelectedIndexChanged(object sender, EventArgs e) {
var project = lstProjectList.SelectedValue as DirectoryInformation;
lblFolder.Text = project.FolderName;
lblCreated.Text = project.Created.ToString();
lblAccess.Text = project.Accessed.ToString();
lblModified.Text = project.Modified.ToString();
lblIdentifier.Text = project.SecIdentity;
lblOwner.Text = project.NTAccount;
lblSize.Text = project.FileSize.ToString("F2") + " MB";
lblCount.Text = project.FileCount.ToString();
FolderPath = InitialPath + project.FolderName;
Solution = FolderPath + "\\" + project.Solution;
}
private void btnOpenProject_Click(object sender, EventArgs e) {
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", Solution);
//Clipboard.SetText(Solution);
}
private void btnOpenFolder_Click(object sender, EventArgs e) {
Process.Start("explorer.exe", FolderPath);
}
}
}
It's just the way your MessageBox is wrapping text. You've got two options here:
Create a custom Forms class
Create a form dialog just for showing messages
EDIT:
Change this:
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", Solution);
to
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", "\"" + Solution + "\"");
What's happening here is the second parameter to the Process.Start method is treated as argument(s) for the executable given by the first parameter. So what process.start does is the equivalent (but not quite the same) of opening the command prompt and typing out:
"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe" X:\_\Document\Visual Studio 2015\.....
and the command prompt treats (space) as a parameter separator, so it treats X:\_\Document\Visual as one parameter, Studio as the next and so on. When you use "\"" around the string you're telling Process.Start that the whole thing (including spaces) is a single parameter.
Your sample had some bugs in it, for me this worked and I got all *.sln files
//this is just to show that you can get short file name if you need FileInfo
var list = new Dictionary<string, string>();
var files = Directory.GetFiles(InitialPath, "*.sln", SearchOption.AllDirectories);
foreach (var file in files)
{
FileInfo fileInfo = new FileInfo(file);
list.Add(fileInfo.Name, file);
}
Process.Start(list.FirstOrDefault().Value);
On my computer starts with no problems.
But if you want a devenv.exe start with a solution open you do it like so
Process.Start(#"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe", #"devenv/""" + fullFilePath + #"""");
you need the command in arguments devenv/ and you must you must enclose paths in double quotation marks ("fullFilePath").

Save progress to a text file C#

I have a problem here...so that's what I wanna do:
I have a program that saves information about user progress, ex: Calls, Answered Calls... and the user run this program every day and save the iformation to the text file. So the problem is that when the user hit's the Save button it add's a new stat's for that day. But I want those data to be modified if user save's in that day 2 times.
What I wanna do is to create a new file where to save the last time saved, and if the date are not diferent Append to file, else modify existing for that day saves.
What I did so far is:
string input3 = string.Format("{0:yyyy-MM-dd}", DateTime.Now);
StreamWriter t,tw;
if(File.Exists(filename))
{
tw=File.AppendText(filename);
t = new StreamWriter("lasttimesaved.txt");
t.WriteLine(input3);
}
else
{
tw=new StreamWriter(filename);
t = new StreamWriter("lasttimesaved.txt");
t.WriteLine(input3);
}
tw.WriteLine();
tw.Write("Stats for Name ");
tw.Write(input);
tw.Write("_");
tw.WriteLine(input3);
tw.WriteLine();
tw.Write("Total Calls: "); tw.WriteLine(calls);
tw.Write("Total Answered: "); tw.WriteLine(answ);
tw.Close();
the only thing now that I don't know ho to do is how to add above all that a check instance to see if the user allready saved today info and to modify existing data.
it's like:
try
{
using (StreamReader sr = new StreamReader("lasttimesaved.txt"))
{
String line = sr.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
if(String.Compare(input3,line) == 0)
{
// that's where I need to modify the existing data.
}
else
{
// do the code above
}
Can anyone help me to modify curent recorded data without losing previous records.
in text file is:
Stats for Name_2013-11-26
Total Calls: 25
Total Answered: 17
Stats for Name_2013-11-27
Total Calls: 32
Total Answered: 15
Stats for Name_2013-11-28
Total Calls: 27
Total Answered: 13
I would say use XML, it will still be readable and modifiable without code and you have some neat way to modify the file with code.
With XML you can easily query the file to see if the date of today is already mentioned in the file, if so you could edit that node if not you could easily append a node.
To append nodes to an xml file i would look at this link:
C#, XML, adding new nodes
Hope this helps, use it like here:
void main()
{
var uw = new UserInformationWriter(#"C:\temp\stats.txt");
var user = new UserInfomration { Calls = "111", Answered = "110" };
uw.Save(user);
}
Here the class(es):
public class UserInformationWriter
{
public string CentralFile { get; set; }
public UserInformationWriter(string centraFile)
{
CentralFile = centraFile;
}
public void Save(UserInfomration newUserInformation)
{
try
{
var streamReader = new StreamReader(CentralFile);
var sourceInformation = streamReader.ReadToEnd();
streamReader.Close();
var userCollection = (List<UserInfomration>)(sourceInformation.ToUserInfomation());
var checkItem = ShouldModify(userCollection);
if (checkItem.Item1)
userCollection.Remove(checkItem.Item2);
newUserInformation.DateTime = DateTime.Today;
userCollection.Add(newUserInformation);
File.Delete(CentralFile);
foreach (var userInfomration in userCollection)
WriteToFile(userInfomration);
}
catch (Exception) { }
}
private Tuple<bool, UserInfomration> ShouldModify(IEnumerable<UserInfomration> userInfomations)
{
try
{
foreach (var userInfomration in userInfomations)
if (userInfomration.DateTime == DateTime.Today)
return new Tuple<bool, UserInfomration>(true, userInfomration);
}
catch (Exception) { }
return new Tuple<bool, UserInfomration>(false, null);
}
private void WriteToFile(UserInfomration newUserInformation)
{
using (var tw = new StreamWriter(CentralFile, true))
{
tw.WriteLine("*Stats for Name_{0}", newUserInformation.DateTime.ToShortDateString());
tw.WriteLine();
tw.WriteLine("*Total Calls: {0}", newUserInformation.Calls);
tw.WriteLine("*Total Answered: {0}#", newUserInformation.Answered);
tw.WriteLine();
}
}
}
public class UserInfomration
{
public DateTime DateTime { get; set; }
public string Calls { get; set; }
public string Answered { get; set; }
}
public static class StringExtension
{
private const string CallText = "TotalCalls:";
private const string AnsweredText = "TotalAnswered:";
private const string StatsForName = "StatsforName_";
private const char ClassSeperator = '#';
private const char ItemSeperator = '*';
public static IEnumerable<UserInfomration> ToUserInfomation(this string input)
{
var splited = input.RemoveUnneededStuff().Split(ClassSeperator);
splited = splited.Where(x => !string.IsNullOrEmpty(x)).ToArray();
var userInformationResult = new List<UserInfomration>();
foreach (var item in splited)
{
if (string.IsNullOrEmpty(item)) continue;
var splitedInformation = item.Split(ItemSeperator);
splitedInformation = splitedInformation.Where(x => !string.IsNullOrEmpty(x)).ToArray();
var userInformation = new UserInfomration
{
DateTime = ConvertStringToDateTime(splitedInformation[0]),
Calls = splitedInformation[1].Substring(CallText.Length),
Answered = splitedInformation[2].Substring(AnsweredText.Length)
};
userInformationResult.Add(userInformation);
}
return userInformationResult;
}
private static DateTime ConvertStringToDateTime(string input)
{
var date = input.Substring(StatsForName.Length);
return DateTime.ParseExact(date, "dd.MM.yyyy", CultureInfo.InvariantCulture);
}
private static string RemoveUnneededStuff(this string input)
{
input = input.Replace("\n", String.Empty);
input = input.Replace("\r", String.Empty);
input = input.Replace("\t", String.Empty);
return input.Replace(" ", string.Empty);
}
}
Let me know If you need help or I understood you wrong.

You don't have permission to post in a group

I've finished a program in C# which integrates with Facebook and posts to more than one group in a click
but I am facing a problem right now when there is a group that you don't have a permission to post to I can't complete posting to the rest
here's the post function
I put it in other Class
public static bool PostImage(Frm form,string AccessToken, string Status, string ImagePath)
{
try
{
if (form.listBox2 .SelectedItems .Count > 0)
{
string item;
foreach (int i in form. listBox2.SelectedIndices)
{
item = form.listBox2.Items[i].ToString();
groupid = item;
FacebookClient fbpost = new FacebookClient(AccessToken);
var imgstream = File.OpenRead(ImagePath);
dynamic res = fbpost.Post("/" + groupid + "/photos", new
{
message = Status,
File = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(ImagePath)
}.SetValue(imgstream)
});
result = true;
}
}
return result;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return false;
}
}
You need to put a try catch block inside the loop. Then, in the catch block you log the error (or do whatever you want with it) then continue the loop:
foreach (int i in form. listBox2.SelectedIndices)
{
try
{
item = form.listBox2.Items[i].ToString();
groupid = item;
FacebookClient fbpost = new FacebookClient(AccessToken);
var imgstream = File.OpenRead(ImagePath);
dynamic res = fbpost.Post("/" + groupid + "/photos", new
{
message = Status,
File = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(ImagePath)
}.SetValue(imgstream)
});
result = true;
}
catch(exception excp)
{
//Do something with the exception
}
}
Now I don't know exactly how your code works, but this should give you a rough idea.

Categories