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.
Related
I Have to Upload the file to my teamdrive, the file has been created to team drive but I can not upload the file chunks to it. So, please help to solve it.
On Writing a Chunk I am facing the Error of "The remote server returned an error: (404) Not Found."
I am getting the Teamdrive ID and the File ID which has been created.
/*** Creation of a File to Team Drive ***/
f_ObjFile.TeamDriveId = "/*TeamDrive ID*/";
try
{
f_ObjNewFile.Parents = f_ObjFile.Parents; // f_ObjFile = <Team Driv ID>
f_ObjNewFile.Name = f_ObjFile.Name;
f_ObjNewFile.MimeType = f_ObjFile.MimeType;
f_ObjNewFile.TeamDriveId = f_ObjFile.TeamDriveId;
f_CreateRequest = GoogleHelper.InvokeApiCall(() => { return this.DriveServiceObj.Files.Create(f_ObjNewFile); }, this);
if (f_CreateRequest != null)
{
f_CreateRequest.SupportsTeamDrives = true;
f_CreateRequest.Fields = "*";
f_ObjNewFile = GoogleHelper.InvokeApiCall(() => { return f_CreateRequest.Execute(); }, this);
}
f_ObjDocumentItem = new DocumentItem(UserEmailID, f_ObjNewFile);
f_ObjDocumentItem.ItemID = f_ObjNewFile.Id;
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
f_ObjDocumentItem.ChunkUploadURL = InitiateResumeRequest(f_Url, f_ObjNewFile.Id);
}
catch(Exception ex) { }
finally
{
f_ObjNewFile = null;
f_CreateRequest = null;
}
/* Writing the chunks to the file in TeamDrive */
try
{
httpRequest = GoogleHelper.CreateHttpWebRequestObj(f_ObjChunkData.ChunkUploadURL,true);
httpRequest.Method = GoogleConstant.PATCH;
httpRequest.ContentLength = f_ObjChunkData.FileData.Length;
httpRequest.SendChunked = true;
httpRequest.Headers["Content-Range"] = "bytes " + f_ObjChunkData.StartOffset +
"-" +
f_ObjChunkData.EndOffset + "/" +
f_ObjChunkData.FileSize.ToString();
using (System.IO.Stream f_ObjHttpStream = GoogleHelper.InvokeApiCall(() => { return httpRequest.GetRequestStream(); }, this))
{
if (f_ObjHttpStream != null)
{
System.IO.MemoryStream f_ChunkStream = null;
f_ChunkStream = new System.IO.MemoryStream(f_ObjChunkData.FileData);
f_ChunkStream.CopyTo(f_ObjHttpStream);
f_ObjHttpStream.Flush();
f_ObjHttpStream.Close();
f_ChunkStream.Close();
f_ChunkStream = null;
}
}
using (HttpWebResponse httpResponse = GoogleHelper.InvokeApiCall(() => { return (HttpWebResponse)(httpRequest.GetResponse()); }, this))
{
if (httpResponse != null)
{
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
httpResponse.Close();
}
}
}
}
catch (Exception ex) { }
In Followin Line :
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
Insted Of
"https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable"
Use following URL :
https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable&supportsTeamDrives=true
and its Done...
Now you can upload the chunks...
I use the following code to upload a file and form data asynchronous. What do I need to change in order to detect if the transfer has been cancelled or interrupted and then take proper action?
[HttpPost]
public async Task<object> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Temp/"));
try
{
var filesReadToProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);
var paramName = "formInput";
var formStreamToRead = filesReadToProvider.Contents.First(x => x.Headers.ContentDisposition.Name == $"\"{formInput}\"");
var formInput = await formStreamToRead.ReadAsStringAsync();
foreach (var fileData in streamProvider.FileData)
{
var fileName = "";
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
fileName = Guid.NewGuid().ToString();
}
fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(#"/") || fileName.Contains(#"\"))
{
fileName = Path.GetFileName(fileName);
}
File.Move(fileData.LocalFileName, Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), Path.GetDirectoryName(fileName) + Guid.NewGuid() + Path.GetExtension(fileName)));
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
I'm a newbie using c# and i need to create an extension that goes to a directory and retrieves info about the users like username, name and email.
This is the login validation method that i created and it's working.
public void MssValidateUserLDAP(string ssHostname, string ssBaseDN, string ssUsername, string ssPassword, out bool ssOk, out string ssErrorMessage) {
ssOk = false;
ssErrorMessage = string.Empty;
String ssBaseRDN = string.Empty; // stores user RDN for authentication
LdapConnection connection = new LdapConnection(ssHostname);
connection.AuthType = AuthType.Basic;
try
{
SearchRequest searchRequest = new SearchRequest();
// Search parameters
searchRequest.Scope = System.DirectoryServices.Protocols.SearchScope.OneLevel;
searchRequest.DistinguishedName = ssBaseDN;
searchRequest.Filter = ssUsername;
// cast the returned directory response as a SearchResponse object
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
// enumerate the entries in the search response
foreach (SearchResultEntry entry in searchResponse.Entries)
{
ssBaseRDN = entry.DistinguishedName;
ssOk = true;
}
if (ssBaseRDN != "")
{
connection.Bind(new NetworkCredential(ssBaseRDN, ssPassword));
}
else { ssOk = false; ssErrorMessage = "User not found"; }
}
catch (Exception e)
{
ssErrorMessage = e.GetType().Name + " " + e.Message;
ssOk = false;
}
}
This is what i was able to do, but it's not working and i can't find the reason behind that. Any help would be appreciated!
public void MssSearch(string ssUsername, string ssPassword, string ssPath, out RLUserRecordList ssUsers, out string ssErrorMessage) {
ssErrorMessage = "";
ssUsers = new RLUserRecordList(null);
try
{
RLUserRecordList aux = new RLUserRecordList();
DirectoryEntry rootEntry = new DirectoryEntry(ssPath,ssUsername,ssPassword);
DirectorySearcher searcher = new DirectorySearcher(rootEntry);
foreach(SearchResult result in searcher.FindAll())
{
RCUserRecord u = new RCUserRecord(Convert.ToString(result.Properties["cn"][0]));
aux.Append(u);
}
ssUsers = aux;
}
catch (Exception e){
ssErrorMessage = e.GetType().Name + " " + e.Message;
}
} // MssSearch
I'am posting an image from a console application to a asp.net web api. I'am getting a file in the folder but the image is black (no image). Do I have something wrong in my code?
public class UploadController : ApiController
{
[System.Web.Mvc.HttpPost]
public string Upload()
{
var request = HttpContext.Current.Request;
var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads/"), request.Headers["filename"]);
try
{
using (var fs = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
{
request.InputStream.CopyTo(fs);
}
}
catch (Exception e)
{
return e.Message;
}
return "uploaded";
}
}
Edit
My console app
http://pastebin.com/VsnDMYpb
try this. This works for me. I used this for multiple file upload
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Uploads/" + postedFile.FileName);
postedFile.SaveAs(filePath);
}
Use Request.Content.ReadAsMultipartAsync
public Task<IQueryable<HDFile>> Post()
{
try
{
var uploadFolderPath = HostingEnvironment.MapPath("~/App_Data/" + UploadFolder);
log.Debug(uploadFolderPath);
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IQueryable<HDFile>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
return new HDFile(info.Name, Request.RequestUri.AbsoluteUri + "?filename=" + info.Name, (info.Length / 1024).ToString());
});
return fileInfo.AsQueryable();
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
catch (Exception ex)
{
log.Error(ex);
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message));
}
}
The code I get from this post
EDIT: I've posted the solution below.
I know you don't like these type of questions, but i've been struggling with this issue for half a day now.
I've written a C# code that fetches user attributes from our Active Directory using LDAP, the code works well.
The code is as follows:
DirectoryEntry dirEnt = new DirectoryEntry("LDAP://dc=dom,dc=int");
DirectorySearcher adSearch = new DirectorySearcher(dirEnt);
adSearch.SearchScope = SearchScope.Subtree;
adSearch.PageSize = 10000;
adSearch.Filter = "(&(objectClass=user))";
SearchResultCollection sColl = adSearch.FindAll();
foreach (SearchResult sResult in sColl)
{
string sConn = sResult.Properties["distinguishedName"][0].ToString();
DirectoryEntry dirEnt2 = new DirectoryEntry("LDAP://" + sConn);
...
// dirEnt2 contains ALL attributes for the user
}
I'm trying to port this code to Java, but it seems like that the technique I used in C# does not work too well in Java.
Using the following code
DirContext context;
ArrayList<String> nList = new ArrayList<String>();
Hashtable env = new Hashtable();
String username = ...;
String password = ...;
try {
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUri);
try {
context = new InitialDirContext(env);
} catch (NamingException e) {
throw new RuntimeException(e);
}
SearchControls ctrl = new SearchControls();
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration enumeration = context.search("", "(objectClass=user)",
ctrl);
while (enumeration.hasMore()) {
SearchResult result = (SearchResult) enumeration.next();
Attributes attribs = result.getAttributes();
NamingEnumeration values = ((BasicAttribute)
attribs.get("distinguishedName")).getAll();
while (values.hasMore()) {
nList.add(values.next().toString());
}
}
} catch (NamingException e) {
e.printStackTrace();
}
for (String sVar : nList ){
Hashtable env2 = new Hashtable();
env2.put(Context.SECURITY_PRINCIPAL, username);
env2.put(Context.SECURITY_CREDENTIALS, password);
env2.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env2.put(Context.PROVIDER_URL, "ldap://DOM/" + sVar);
Attributes attrs = null;
try {
context = new InitialDirContext(env2);
attrs = context.getAttributes(sVar);
} catch (NamingException e) {
System.out.println(e.toString());
continue;
}
System.out.println(attrs.toString());
}
Yields that attrs only contains BASIC attributes regarding the user (such as samaccountname, displayname, etc)
and no 'email', 'telephone' or any other similar attributes.
Any help on the issue is blessed!
Here's the solution, sorry for the messy code/formatting
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import javax.naming.ldap.*;
public class UserFetch {
public static void main(String[] args) {
try{
// Activate paged results
byte[] cookie = null;
int count=0;
int total;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.REFERRAL, "follow");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
env.put(Context.SECURITY_PRINCIPAL, "USERNAME#DOM.COM");
env.put(Context.SECURITY_CREDENTIALS, "PASSWORD");
env.put(Context.PROVIDER_URL, "ldap://DOM.COM:389");
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(new Control[]{
new PagedResultsControl(10000, Control.CRITICAL) });
do {
// Perform the search
NamingEnumeration results =
ctx.search("dc=DOM,dc=COM", "(&(objectclass=user)(employeeNumber=*))", getSimpleSearchControls());
// Iterate over a batch of search results
while (results != null && results.hasMore()) {
// Display an entry
SearchResult entry = (SearchResult)results.next();
Attributes attrs = entry.getAttributes ();
System.out.println(attrs.get("SAMAccountName")); // Username
System.out.println("Firstname: " +
attrs.get("givenname")); // firstname
System.out.println("Lastname: " + attrs.get("sn")); // lastname
System.out.println("EmployeeID " + attrs.get("employeeID"));
System.out.println("EmployeeNumber: " +
attrs.get("employeeNumber"));
// Handle the entry's response controls (if any)
}
// Examine the paged results control response
Control[] controls = ctx.getResponseControls();
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc =
(PagedResultsResponseControl)controls[i];
total = prrc.getResultSize();
cookie = prrc.getCookie();
} else {
// Handle other response controls (if any)
}
}
}
// Re-activate paged results
ctx.setRequestControls(new Control[]{
new PagedResultsControl(10000, cookie, Control.CRITICAL) });
} while (cookie != null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SearchControls getSimpleSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
String[] attrIDs =
{ "SAMAccountName", "sn", "givenname", "employeeID",
"employeeNumber" };
searchControls.setReturningAttributes(attrIDs);
return searchControls;
}
}
Try setting the returned attributes on your SearchControls
ctrl.setReturningAttributes(new String[] {"email", "telephone"});