I am working on a app in which user will search in twitter throw my app. but i could not found any Twitterizer 2.4.2.dll i found only package manager installer every where i have vs 2008 in vs 2008 there is not a pk manager
some of sites tell alternative of pk manager but those are long processess.
i want short solution is there any Twitterizer 2.4.2.dll available ??? so that i connect with twitter
OR there any other way to connect with twitter ??? istead of Twitterizer 2.4.2 ??
at the momnet i am using LinqtoTwitter.dll my code is
static void Main(string[] args)
{
var auth = new ApplicationOnlyAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = "xxxx",
ConsumerSecret = "xxxx"
}
};
var twitterCtx = new TwitterContext(auth);
var queryResults =
from search in twitterCtx.Search
where search.Type == SearchType.Search &&
search.Query == "Linq To Twitter"
select search;
Search srch = queryResults.Single();
srch.Statuses.ForEach(entry =>
Console.WriteLine(
"ID: {0, -15}, Source: {1}\nContent: {2}\n",
entry.StatusID, entry.Source, entry.Text));
Console.ReadKey();
}
but it is giving me `Bad Authentication data
Exception
is there opensource dll availabe so that i connect with twitter not with pk manager ??? `
With the ApplicationOnlyAuthorizer, you must call Authorize(), like this:
var auth = new ApplicationOnlyAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = "xxxx",
ConsumerSecret = "xxxx"
}
};
auth.Authorize();
var twitterCtx = new TwitterContext(auth);
Related
How to validate uploaded ARM Template using azure .net SDK or Fluent API ?
I want to validate my uploaded ARM template like azure portal do using azure .net SDK or Fluent API ?
For reference please see below image azure is showing message if ARM template not valid so same thing i want to implement using any .net API or REST API.
#Jim Below error I am getting:
If you want to validate your arm template, please refer to the following steps
Create a service principal and assign Contributor role to the sp
az ad sp create-for-rbac -n "MyApp"
Install Package
Install-Package Microsoft.Azure.Management.ResourceManager.Fluent -Version 1.34.0
Code
string clientId = "23****9c";
string clientSecret = "?s****/k";
string tenantDomain = "";
string subscription = "";
var creds= SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantDomain, AzureEnvironment.AzureGlobalCloud);
var restClient = RestClient.Configure()
.WithEnvironment(AzureEnvironment.AzureGlobalCloud)
.WithCredentials(creds)
.WithLogLevel(HttpLoggingDelegatingHandler.Level.BodyAndHeaders)
.Build();
ResourceManagementClient managementClient = new ResourceManagementClient(restClient);
managementClient.SubscriptionId = subscription;
//Validates whether the specified template is syntactically correct and will be accepted by Azure Resource Manager..
DeploymentValidateResultInner res = await managementClient.Deployments.ValidateAsync("<groupName>", "<deployName>", new DeploymentInner()
{
Location = "",
Properties = new DeploymentProperties()
{
ParametersLink = new ParametersLink("uri"),
TemplateLink = new TemplateLink("")
}
});
Console.WriteLine(res.Error.Message);
// get changes that will be made by the deployment if executed at the scope of resource group
WhatIfOperationResultInner res1 = await managementClient.Deployments.WhatIfAsync("<groupName>", "<deployName>", new DeploymentWhatIf() {
Location="",
Properties= new DeploymentWhatIfProperties() {
ParametersLink = new ParametersLink("uri"),
TemplateLink = new TemplateLink("")
}
});
foreach (var change in res1.Changes) {
//
}
I like that the accepted answer adds the "what if" to validation. However, Microsoft.Azure.Management.ResourceManager is deprecated, and it took me a bit to figure out a way to validate an ARM template using the replacement library: Azure.ResourceManager.
Here's a code snippet that provides template validation using the new library (it doesn't include the what-if call):
var credential = new DefaultAzureCredential();
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var client = new ArmClient(credential, subscriptionId);
var deploymentContent = new ArmDeploymentContent(new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
{
Template = BinaryData.FromString(templateContent),
Parameters = BinaryData.FromObjectAsJson(new
{
hostingPlanName = new
{
value = hostingPlanName
},
webSiteName = new
{
value = webAppName
},
skuName = new
{
value = webSkuName
},
skuCapacity = new
{
value = webSkuCapacity
},
})
});
var resourceGroupId = ResourceGroupResource.CreateResourceIdentifier(SubscriptionId!, resourceGroupName);
// This ArmDeploymentResource resource may or may not exist, but it doesn't matter - it's just a placeholder for validation
var deploymentResourceId = ArmDeploymentResource.CreateResourceIdentifier(resourceGroupId, deploymentName);
var armDeployment = client.GetArmDeploymentResource(deploymentResourceId);
var validateOperation = await armDeployment.ValidateAsync(WaitUntil.Completed, toValidate, _cancellationToken);
var validateResult = validateOperation.Value;
if (validateResult.Error != null)
{
_logger.LogEndOperation(loggerOpKey, false, validateResult.Error.Message ?? "Validation errored");
_logger.LogError(JsonConvert.SerializeObject(validateResult.Error, Formatting.Indented));
return false;
}
// Log this if you want:
string deploymentDetails = $"Deployment: {deploymentName} ProvisioningState:{validateResult.Properties.ProvisioningState}\n"
+ $" started:{validateResult.Properties.Timestamp} duration:{validateResult.Properties.Duration}\n"
+ $" correlationId:{validateResult.Properties.CorrelationId}\n"
+ $" outputs:{JsonConvert.SerializeObject(validateResult.Properties.Outputs)}";
bool succeeded = validateResult.Properties.ProvisioningState == "Succeeded";
return succeeded;
I am trying to create a domain shared contact in GSuite via the Contacts API in C# but unable to figure out how to POST the atom XML entry to the Feed URL as mentioned here : https://developers.google.com/admin-sdk/domain-shared-contacts/#Creating
I have tried following the older GData way mentioned here https://developers.google.com/gdata/client-cs but I get a "Execution of authentication request returned unexpected result: 404" error.
static void Main(string[] args)
{
Console.WriteLine("Hello !! ");
//Get Auth
OAuth2Parameters p = ContactsAuth();
//Create a domain shared contact
try
{
RequestSettings settings = new RequestSettings("GSuiteAdminApp", p);
ContactsRequest cr = new ContactsRequest(settings);
ContactEntry cn = new ContactEntry();
Name n = new Name();
n.GivenName = "Ice";
n.FamilyName = "Cold001";
n.FullName = "Ice Cold001";
EMail e = new EMail();
e.Rel = "http://schemas.google.com/g/2005#work";
e.Primary = true;
e.Address = "ice.cold001#xyz.com";
cn.Name = n;
cn.Emails.Add(e);
}
catch (Exception e44)
{
Console.WriteLine(e44.Message);
}
}
//Auth for Contacts API
public static OAuth2Parameters ContactsAuth()
{
string clientId = "xxxxxxxxxxxxxx.apps.googleusercontent.com";
string clientSecret = "xxxxxxxxxxxxx";
string[] scopes = new string[] { "https://www.google.com/m8/feeds/" };
try
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
}, scopes, "super-admin#mydomain.com", CancellationToken.None, new FileDataStore("C:\\Temp\\A\\SharedContactsOauth")).Result;
// Translate the Oauth permissions to something the old client libray can read
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.AccessToken = credential.Token.AccessToken;
parameters.RefreshToken = credential.Token.RefreshToken;
return parameters;
}
catch (Exception ex33)
{
Console.WriteLine(ex33.Message);
return null;
}
}
This gives a "request failed" error.
I was finally able to figure it out by stringing along code snippets from few different sources and some modifications of my own. Linda Lawton's https://www.daimto.com/google-contacts-with-c/ for the OAuth2 part using older GData API. Google's documentation on Contacts API v3.0 https://developers.google.com/contacts/v3/ for mechanics of using the .NET client library for contacts and their (bit sketchy) documentation on "domain shared contacts", especially on using the proper FeedUri and Atom entries for new contact https://developers.google.com/admin-sdk/domain-shared-contacts/#Creating.
Basically what it boils down to is this -
Use a GSuite Super Admin account to authrorize to Contacts API using OAuth2.0, then use GData Contacts .NET client library to create the new contact
by suppying your Gsuite domain in the method and you are done.
Here's the full code which I have it working for me now:
using System;
using System.Threading;
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
namespace SharedContactsAPI
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello !! ");
//Get Auth
OAuth2Parameters p = ContactsAuth();
////Create a domain shared contact
try
{
RequestSettings settings = new RequestSettings("GSuiteAdminApp", p);
ContactsRequest contactreq = new ContactsRequest(settings);
Console.WriteLine("Attempting to create a Domain Shared Contact in GSuite");
Console.WriteLine(" ");
CreateContact(contactreq);
}
catch (Exception e44)
{
Console.WriteLine(e44.Message);
}
}
//Create Shared Contact
public static Contact CreateContacttest(ContactsRequest cr)
{
Contact newEntry = new Contact();
// Set the contact's name.
newEntry.Name = new Name()
{
FullName = "Ice Cold005",
GivenName = "Ice",
FamilyName = "Cold005"
};
newEntry.Content = "Notes";
// Set the contact's e-mail addresses.
newEntry.Emails.Add(new EMail()
{
Primary = true,
Rel = ContactsRelationships.IsWork,
Address = "ice.cold005#xyz.com"
});
//Insert the contact
Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("test.com"));
Contact createdEntry = cr.Insert(feedUri, newEntry);
Console.WriteLine("New Contact created successfully with ContactID = " + createdEntry.Id);
return createdEntry;
}
//Auth for Contacts API
public static OAuth2Parameters ContactsAuthtest()
{
string clientId = "xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
string[] scopes = new string[] { "https://www.google.com/m8/feeds/contacts/" };
try
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
}, scopes, "super-admin#test.com", CancellationToken.None, new FileDataStore("C:\\Temp\\A\\SharedContactsOauth")).Result;
// Translate the Oauth permissions to something the old client libray can read
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.AccessToken = credential.Token.AccessToken;
parameters.RefreshToken = credential.Token.RefreshToken;
return parameters;
}
catch (Exception ex33)
{
Console.WriteLine(ex33.Message);
return null;
}
}
}
}
I am trying to get recent 200 tweets using TweetSharp but it is returning 12 for some reason.
var service = new TwitterService(
_consumerKey,
_consumerSecret,
tokenClaim,
tokenSecret
);
IAsyncResult result = service.BeginListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { Count = 200}
IEnumerable<TwitterStatus> tweets = service.EndListTweetsOnUserTimeline(result);
Any ideas why would that be? Thanks
Update
Following How to fetch maximum 800 tweets from ListTweetOnHomeTimeline() method of TweetSharp?
IAsyncResult result =
_twitterService.BeginListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { Count = 200 });
IEnumerable<TwitterStatus> tweets = _twitterService.EndListTweetsOnUserTimeline(result).ToArray();
var tweet2 = _twitterService.ListTweetsOnUserTimeline(new ListTweetsOnUserTimelineOptions { Count = 200, MaxId = tweets.Last().Id });
return tweet2;
tweet2 is empty.
TweetSharp is an old library and no longer maintained. It is known to have authentication problems, but big chance is that you're bumping against an other issue due to Twitter API changes. Just don't waste your time trying to fix it.
I suggest you to use the more up-to-date library Linq2Twitter which is also available on NuGet.
With LinqToTwitter your code would look like:
static async Task<List<Status>> ListTweetsOnUserTimeline(string screenName)
{
var auth = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
AccessToken = accessToken,
AccessTokenSecret = accessTokenSecret
}
};
using (var context = new TwitterContext(auth))
{
var tweets = await (from tweet in context.Status
where tweet.Type == StatusType.User &&
tweet.Count == 200 &&
tweet.ScreenName == screenName
select tweet)
.ToListAsync();
return tweets;
}
}
I am having trouble to Create a contact in google using google api v3.
I can successfully call cr.GetContacts() to get all the contacts (for the user I'm specifying), but cr.Insert is giving me the error:
Execution of request failed: https://www.google.com/m8/feeds/contacts/someuser#mydomain.com/full
Am I missing something?
string serviceAccountEmail = "111111111111-aaaa1a1aa11a1aaaaaaa11aaaa1aaa11#developer.gserviceaccount.com";
X509Certificate2 certificate = new X509Certificate2(#"C:\All\ContactsManager-1aa1bbb1ab11.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[]
{
"https://www.google.com/m8/feeds"
},
User = "someuser#mydomain.com"
}.FromCertificate(certificate));
credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait();
RequestSettings rs = new RequestSettings("ContactsManager", credential.Token.AccessToken);
//rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
//var contacts = cr.GetContacts(); //////THIS LINE WORKS AND GETS ALL THE CONTACTS
Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("someuser#mydomain.com"));
//feedUri will now be https://www.google.com/m8/feeds/contacts/someuser%40mydomain.com/full
Contact createdEntry = cr.Insert(feedUri, newContact);
Console.WriteLine("Contact's ID: " + createdEntry.Id);
EDIT: I figured out the problem, just want to update for anybody else who has the same issue.
If you followed the v3 documentation for creating a contact: they have a section on that contact entity like this:
newEntry.IMs.Add(new IMAddress()
{
Primary = true,
Rel = ContactsRelationships.IsHome,
Protocol = ContactsProtocols.IsGoogleTalk,
});
if you remove this IMAddress, then the contact creates fine.
I need help in uploading images directly to twitter in Windows Phone 7.
I am done with oauth flow of twitter and can also could update tweets but I have not been able to upload image to twitter using wp7?
I have worked out a solution for this, by using the Hammock.WindowsPhone.Mango library.
(TweetSharp internally uses Hammock library for oAuth and other functionalities, but I have never used TweetSharp or Twitterizer)
I have installed the latest version of Hammock from Nuget
And then the following code is used for photo upload to Twitter:
public void uploadPhoto(Stream photoStream, string photoName)
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.consumerKey,
ConsumerSecret = TwitterSettings.consumerKeySecret,
Token = TwitterSettings.accessToken,
TokenSecret = TwitterSettings.accessTokenSecret,
Version = "1.0a"
};
RestClient restClient = new RestClient
{
Authority = "https://upload.twitter.com",
HasElevatedPermissions = true,
Credentials = credentials,
Method = WebMethod.Post
};
RestRequest restRequest = new RestRequest
{
Path = "1/statuses/update_with_media.json"
};
restRequest.AddParameter("status", tbxNewTweet.Text);
restRequest.AddFile("media[]", photoName, photoStream, "image/jpg");
}
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
}
private void PostTweetRequestCallback(RestRequest request, Hammock.RestResponse response, object obj)
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//Success code
}
}
Here,
photoName is the name of the image selected ( "e.OriginalFileName")
photoStream is the "e.ChosenPhoto" from the PhotoChooserTask
and the 4th parameter for .AddFile() should be taken care (I have not considered other formats while doing this sample, you have to take care in your apps)
I hope this helps!!
LINQ to Twitter supports WP7 and has a TweetWithMedia method that works like this:
private void PostButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(TweetTextBox.Text))
MessageBox.Show("Please enter text to tweet.");
ITwitterAuthorizer auth = SharedState.Authorizer;
if (auth == null || !auth.IsAuthorized)
{
NavigationService.Navigate(new Uri("/OAuth.xaml", UriKind.Relative));
}
else
{
var twitterCtx = new TwitterContext(auth);
var media = GetMedia();
twitterCtx.TweetWithMedia(
TweetTextBox.Text, false, StatusExtensions.NoCoordinate, StatusExtensions.NoCoordinate, null, false,
media,
updateResp => Dispatcher.BeginInvoke(() =>
{
HandleResponse(updateResp);
}));
}
}
Joe