I have a code in C# that access TFS Rest API.
When I use the following code:
VssConnection connection = new VssConnection(orgUrl, new VssCredentials());
I get the results I need.
When trying to set the credentials:
VssConnection connection = new VssConnection(orgUrl, credentials);
I get an error.
An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll
The error occurs when the following code line is committed:
WorkItem workitem = witClient.GetWorkItemAsync(workItemId).Result;
Full code:
static void Main(string[] args)
{
Uri orgUrl = new Uri("my uri");
string personalAccessToken = "my token";
int workItemId = 486915;
// Create a connection
VssCredentials credentials = new VssBasicCredential("", personalAccessToken);
VssConnection connection = new VssConnection(orgUrl, credentials);
//VssConnection connection = new VssConnection(orgUrl, new VssCredentials());
// Show details a work item
ShowWorkItemDetails(connection, workItemId);
Console.ReadLine();
}
public static void ShowWorkItemDetails(VssConnection connection, int workItemId)
{
// Get an instance of the work item tracking client
WorkItemTrackingHttpClient witClient = connection.GetClient<WorkItemTrackingHttpClient>();
// Get the specified work item
WorkItem workitem = witClient.GetWorkItemAsync(workItemId).Result;
// Output the work item's field values
foreach (var field in workitem.Fields)
{
Console.WriteLine(" {0}: {1}", field.Key, field.Value);
}
}
Related
I have Generated Microsoft Graph app in ASP.NET MVC platform, that I have downloaded from Microsoft Graph site. I need to access the shared mail folder not sure exactly how can I get that?? In the following code I can access my mailFolder but not shared mailfolder!
public static async Task<IEnumerable<MailFolder>> GetMailFolderAsync()
{
var graphClient = GetAuthenticatedClient();
var mailFolder = await graphClient.Me.MailFolders.Request().GetAsync();
var sharedMailFolder = await graphClient.Users.Request().GetAsync();
return mailFolder;
}
Also, I want to know in above code where I can pass the parameter to access next page or all pages??
private static GraphServiceClient GetAuthenticatedClient()
{
return new GraphServiceClient(
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
string signedInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
SessionTokenStore tokenStore = new SessionTokenStore(signedInUserId,
new HttpContextWrapper(HttpContext.Current));
var idClient = new ConfidentialClientApplication(
appId, redirectUri, new ClientCredential(appSecret),
tokenStore.GetMsalCacheInstance(), null);
var accounts = await idClient.GetAccountsAsync();
var result = await idClient.AcquireTokenSilentAsync(
graphScopes.Split(' '), accounts.FirstOrDefault());
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
}));
I think it is not possible to access shared folders I am investigating as well. In regards to the question of getting pages, as soon as you get the first request
public static async Task<IEnumerable<MailFolder>> GetMailFolderAsync()
{
var graphClient = GetAuthenticatedClient();
var mailFolder = await graphClient.Me.MailFolders.Request().GetAsync();
var sharedMailFolder = await graphClient.Users.Request().GetAsync();
return mailFolder;
}
then you can review for example, mailFolder.NextPageRequest, if it is not null then you can request it by doing mailFolder.NextPageRequest.GetAsync() and you can use it as a loop conditional
while(mailfoldersCollection != null) {
// Do your stuff with items within for(var folder in mailfoldersCollection) {}
// when read all items in CurrentPage then
if (mailFolder.NextPageRequest != null) {
mailfoldersCollection = await mailFolder.NextPageRequest.GetAsync();
}
hope it works for you!
I am following the blog http://www.venkatbaggu.com/signalr-database-update-notifications-asp-net-mvc-usiing-sql-dependency/ to get a signalR push message out to connected clients.
My debugger never hits the onchange event.
my Global.asax.cs:
string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
protected void Application_Start()
{
// basic stuff
SqlDependency.Start(connString);
var repo = new Repositories.MarkerRepository();
repo.GetAllMarkers(); // to register the dependency
}
My MarkerRepository.cs:
readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
private MarkersHub _mh = new MarkersHub(); // my signalr hub class
public IEnumerable<House> GetAllMarkers()
{
var markers = new List<House>();
using (var connection = new SqlConnection(_connString))
{
connection.Open();
using (var command = new SqlCommand(#"SELECT * FROM [dbo].Houses", connection))
{
command.Notification = null;
var dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
markers.Add(item: new House {
ID = (int)reader["ID"],
Name = (string)reader["Name"],
Code = reader["Code"] != DBNull.Value ? (string)reader["Code"] : "",
Latitude = Convert.ToDouble(reader["Latitude"]),
Longitude = Convert.ToDouble(reader["Longitude"])
});
}
}
}
return markers;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
_mh.SendMarkers();
}
}
I have had a hit once but it was no change, only a notification for subscribe. I have read a lot about resubscribe, but when it hit this event the sql:
select * from sys.dm_qn_subscriptions
still returns no rows. Not on my db or master. So I think that there is an error in the blog post with the re-subscribe to the on change event? This sample https://msdn.microsoft.com/en-us/library/a52dhwx7(VS.80).aspx does unregister in the onchange event and calls the method which registers a new event. Can someone verify my assumption?
These were the values for the SqlNotificationEventArgs e in my event and told me that my query to depend on, was invalid.
SqlNotificationEventArgs.Type --> SqlNotificationType.Subscribe
SqlNotificationEventArgs.Info --> SqlNotificationInfo.Invalid
SqlNotificationEventArgs.Source --> SqlNotificationSource.Statement
The statement may not use the asterisk () or table_name. syntax to specify columns.
source https://msdn.microsoft.com/en-us/library/ms181122.aspx
I'm using Signalr .Net Client in my Console application to receive messages from the Signalr Hub which is a separate web application.
My console application is connecting to the hub correctly and receive message from the hub only once. Then the client method in the Signalr .Net client not getting called.
Once I stop the console application and run it, again it receive a message from the hub only once and nothing happens.
Here is my Hub Code
public override Task OnConnected()
{
try
{
var cType = Context.QueryString["type"];
var connectionId = Context.ConnectionId;
var connectedUserList = (from d in Users
where d.ClientType == cType
select d).ToList();
if (connectedUserList.Count > 0)
{
var conUser = connectedUserList.First<ConnectedUsers>();
conUser.ConnectionIds.Add(connectionId);
}
else
{
var newUser = new ConnectedUsers
{
ConnectionIds = new HashSet<string> {connectionId}
,
ClientType = cType
};
Users.Add(newUser);
}
}
catch (Exception ex)
{
).Error(ex);
}
return base.OnConnected();
}
And My .Net Client Connection
static void Main(string[] args)
{
SignalrHandler();
Console.ReadLine();
}
public static async void SignalrHandler()
{
var url = ConfigurationSettings.AppSettings["Url"] ?? #"http://localhost:1010/";
var querystringData = new Dictionary<string, string> { { "type", "WIN" } };
_hubConnection = new HubConnection(url, querystringData);
MarcolinMainProxy = _hubConnection.CreateHubProxy("MainHub");
MarcolinMainProxy.On<string>("sendAlert", type => InvokeMethod(type));
await _hubConnection.Start();
}
Client Method
private static void InvokeMethod(string type)
{
Console.WriteLine(String.Format("Recieved Message From Server On :{0}",System.DateTime.Now.ToString()));
Console.WriteLine("Message Received");
Console.ReadLine();
}
And This happens when I use an Invoke method with following line
MarcolinMainProxy.On<string>("sendAlert", type => InvokeMethod(type));
And when I use following line it works..
MarcolinMainProxy.On<string>("sendAlert", stock => Console.WriteLine("Symbol {0} Price {1}", "sd", "sdde"));
Check the following link
https://damienbod.com/2013/11/13/signalr-messaging-a-complete-client-with-a-console-application/
You have to change your code to
MarcolinMainProxy.On<string>("sendAlert", InvokeMethod);
I'm getting the error "com.google.gdata.client.GoogleService$SessionExpiredException: Unauthorized" when I try to retrieve the worksheets from a particular spreadsheet. I'm using the same code that has been given in "https://developers.google.com/google-apps/spreadsheets/#audience" but still I'm getting the error.
Below is the code:
public class SpreadsheetApiQuickstart {
private static final String SCOPE = "https://spreadsheets.google.com/feeds/spreadsheets/private/full";
private static final String APP_NAME = "S.A.R.A.H";
authorized user.
private static final String USER = "me";
private static final String CLIENT_SECRET_PATH = "C://Users/ahrashid.contractor/Downloads/client_secret_461052169747-ffbpdvcbmu822r2vg2bhrn4ae3lrjri8.apps.googleusercontent.com.json";
private static GoogleClientSecrets clientSecrets;
public static void main(String[] args) throws FileNotFoundException, IOException, ServiceException {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
.setAccessType("offline")
.setApprovalPrompt("force").build();
String url = flow.newAuthorizationUrl().setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
.build();
System.out.println("Please open the following URL in your browser then type"
+ " the authorization code:\n" + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
// Generate Credential using retrieved code.
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory).setClientSecrets(clientSecrets).build().setFromTokenResponse(response);
SpreadsheetService service = new SpreadsheetService(APP_NAME);
service.setOAuth2Credentials(credential);
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
if (spreadsheets.size() == 0) {
// TODO: There were no spreadsheets, act accordingly.
}
// TODO: Choose a spreadsheet more intelligently based on your
// app's needs.
SpreadsheetEntry spreadsheet = spreadsheets.get(0);
System.out.println(spreadsheet.getTitle().getPlainText());
// Make a request to the API to fetch information about all
// worksheets in the spreadsheet.
/* Till here everything is working fine. I'm getting the exception in the below line */
List<WorksheetEntry> worksheets = spreadsheet.getWorksheets(); /* this line gives com.google.gdata.client.GoogleService$SessionExpiredException: Unauthorized exception" */
// Iterate through each worksheet in the spreadsheet.
for (WorksheetEntry worksheet : worksheets) {
// Get the worksheet's title, row count, and column count.
String title = worksheet.getTitle().getPlainText();
int rowCount = worksheet.getRowCount();
int colCount = worksheet.getColCount();
// Print the fetched information to the screen for this worksheet.
System.out.println("\t" + title + "- rows:" + rowCount + " cols: " + colCount);
}
I have console application in which I am doing sqldependency. My problem is when I set commandType as Text, it is working fine. But if I use commandType as StoredProcedure, onchange method is calling infinitely.
Please see the code below:
static DataSet myDataSet;
static SqlConnection connection;
static SqlCommand command;
static void Main(string[] args)
{
// Remove any existing dependency connection, then create a new one.
string connstr = "Data Source=XYZ;Initial Catalog=Dev;Integrated Security=True";
string ssql = #"[dbo].[SchedulerPendingControlRequestIDFetch]";
CanRequestNotifications();
SqlDependency.Stop(connstr);
SqlDependency.Start(connstr);
if (connection == null)
connection = new SqlConnection(connstr);
if (command == null)
command = new SqlCommand(ssql, connection);
command.CommandType = CommandType.StoredProcedure;
if (myDataSet == null)
myDataSet = new DataSet();
GetAdvtData();
System.Console.ReadKey();
connection.Close();
}
private static bool CanRequestNotifications()
{
SqlClientPermission permission =
new SqlClientPermission(
PermissionState.Unrestricted);
try
{
permission.Demand();
return true;
}
catch (System.Exception)
{
return false;
}
}
private static void GetAdvtData()
{
myDataSet.Clear();
// Ensure the command object does not have a notification object.
command.Notification = null;
// Create and bind the SqlDependency object to the command object.
SqlDependency dependency = new SqlDependency(command,null,100);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(myDataSet, "ControlRequest");
}
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency =
(SqlDependency)sender;
dependency.OnChange -= dependency_OnChange;
Console.WriteLine(e.Info.ToString() + e.Source.ToString());
GetAdvtData();
}
My stored Procedure is:
IF OBJECT_ID('SchedulerSirasColcoDetailFetch') IS NOT NULL
DROP PROCEDURE SchedulerSirasColcoDetailFetch
Go
PRINT 'Creating stored procedure SchedulerSirasColcoDetailFetch'
Go
CREATE PROCEDURE [dbo].[SchedulerSirasColcoDetailFetch]
AS
BEGIN
SELECT Colco_Code AS 'CountryCode',Connection_String AS 'Url',Resend_Interval AS 'ResendInterval',
Default_Encoding AS 'Encoding' FROM dbo.SirasColcoDetail
END
If I copy the select statement inside stored procedure as my command text and set the commandType as Text, everything is working fine.
could you please let me know what the issue is????
Thanks a lot in advance.
Mahesh
You're supposed to check the values of the SqlNotificationEventArgs argument. Only if Type is Change and Source is Data where you notified for a data change.
You'll discover that you're not notified for data changes, but for incorrect settings or incorrect query. Your query and connection settings must comply with the requirements specified in Creating a Query for Notifications.