How to reference my added web service - visual-studio-2010

This is my first time dealing with Web Services. I have successfully Added a Web Service to one that I have created in VS 2010. What I'm trying to do is access the functions of the added web service in this .asmx file This is what I see now along with all the auto added code.
Service1.asmx.vb
Public Class Service1
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function HelloWorld() As String
Return "Hello World"
End Function
The added web service that I have added is called blahService. So I'm just curious as how do I access the functions that are in the added web service? Do I have to do something like this...?
Dim foo as new blahService()
Then when I go to access a function just do
foo.function()

1) From within your Solution Explorer of your project, right-click on “Service References”, then click on “Add Service Reference”
2) The dialog box which appears allows you to put in the URL of your web service. Enter it, then press the “Go” Button”
3) You can see that the name of the web service appears in the Services pane. Give your webservice a namespace (anything you like) that will be used to refer to it from within your project. Press the OK button. That namespace will now appear in the list of Service References
A web service is considered to have anonymous authentication if no specific permission is required to access it. The server is allowed to fulfill every request without regard to the entity who is requesting the information. This is the case for many web services on the internet.
For reference, this is the source code for the method which I will be calling from my application:
[WebMethod]
public List<string> GetStrings(int StartNumber, int EndNumber)
{
List<string> MyList = new List<string>();
for (int i = StartNumber; i <= EndNumber; i++)
{
MyList.Add("AuthASMXService String #" + i.ToString());
}
return MyList;
}
and here’s the code that will call the method in the web service instantiated above:
private void ASMXWebServiceInvoke_Click_1(object sender, RoutedEventArgs e)
{
ASMXWebServiceReference.WebService1SoapClient MyASMXWebServiceClient
= new ASMXWebServiceReference.WebService1SoapClient();
ASMXWebServiceReference.GetStringsResponse MyStringsResponse =
MyASMXWebServiceClient.GetStrings(10, 20);
ASMXWebServiceReference.ArrayOfString MyStrings =
MyStringsResponse.Body.GetStringsResult;
ASMXGridView.ItemsSource = MyStrings;
}
How do I connect to an ASMX web service?

Related

CRM Plugin for Publish and Publish All messages

I was wondering if we can write plugins that get executed for messages like "publish" and "publish all" in Dynamics CRM (any version). if so can you share any sample references for the same or code snippets.
This is a plugin that works for Publish and PublishAll messages and it will log the event using an entity that I created for this purpose (you can change to do whatever you want).
When the event is Publish, the plugin uses the ParameterXml parameter (MSDN) to log which components are being published. In the case of the PublishAll message, this parameter is not present so there's no detail (which makes sense because you're publishing all).
public class PublishPlugin : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
if (context.MessageName != "Publish" && context.MessageName != "PublishAll")
return;
string parameterXml = string.Empty;
if (context.MessageName == "Publish")
{
if (context.InputParameters.Contains("ParameterXml"))
{
parameterXml = (string)context.InputParameters["ParameterXml"];
}
}
CreatePublishAuditRecord(service, context.MessageName, context.InitiatingUserId, parameterXml);
}
private void CreatePublishAuditRecord(IOrganizationService service, string messageName, Guid userId, string parameterXml)
{
Entity auditRecord = new Entity("fjo_publishaudit");
auditRecord["fjo_message"] = messageName;
auditRecord["fjo_publishbyid"] = new EntityReference("systemuser", userId);
auditRecord["fjo_publishon"] = DateTime.Now;
auditRecord["fjo_parameterxml"] = parameterXml;
service.Create(auditRecord);
}
}
This is how it looks in CRM:
You can download the plugin project and CRM solution from my GitHub.
See here for a list of valid Dynamics CRM messages. Publish and PublishAll are both listed. They're also valid in all version of CRM from 2011 onward.
https://msdn.microsoft.com/en-us/library/gg328576.aspx
Just register your plugin like any other but use Publish or PublishAll for the message and leave the Entity as blank.
In the case of Publish, it seems by looking at the documentation that you can't narrow down which entity is being published. You'll have to take a look at what the Input Parameters give you to see if you can work out which entity you're dealing with, if you need it.

How to authenticate against Sharepoint Online with user credentials?

I am trying to customize some lists for SharePoint Online and since I am new to the subject I do not know how to connect to the service.
When I use NAPA and from the cloud use the option "Edit in Visual Studio", I am prompted for credentials automatically when the project opens.
However, when I start from bottom-up, i.e. open a new project in Visual Studio, add all necessary dlls, this part of code throws an error (it is an authentication issue):
ClientContext context = new ClientContext("https://MYURL.sharepoint.com/n/");
context.ExecuteQuery();
I am using Microsoft.SharePoint.Client;
The error message:
An unhandled exception of type 'System.Net.WebException' occurred in Microsoft.SharePoint.Client.dll
Additional information: The remote server returned an error: (403) Forbidden.
I think I am missing part of the code which is responsible for authentication and which in case of NAPA app is hard-coded.
How can I authenticate to SharePoint Online? (it is enough if my code runs just once, it's not an app, I don't want to package it and publish)
I am guessing it has something to do with http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.sharepoint.remote.authentication.aspx, but that's as far as I got.
How to authenticate against SharePoint Online using the managed CSOM
The CSOM for SharePoint 2013 introduces the SharePointOnlineCredentials class that allows to perform an active authentication to SharePoint Online.
Example
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the URL of the SharePoint Online site:");
string webUrl = Console.ReadLine();
Console.WriteLine("Enter your user name (format: username#tenant.onmicrosoft.com)");
string userName = Console.ReadLine();
Console.WriteLine("Enter your password.");
SecureString password = GetPasswordFromConsoleInput();
using (var context = new ClientContext(webUrl))
{
context.Credentials = new SharePointOnlineCredentials(userName,password);
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
Console.WriteLine("Your site title is: " + context.Web.Title);
}
}
private static SecureString GetPasswordFromConsoleInput()
{
ConsoleKeyInfo info;
//Get the user's password as a SecureString
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey(true);
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
}

WebApi Odata Windows Store App EndSaveChanges exception

I am trying to create a Windows Store App using a WebApi Odata controller. After some effort I have all the Get requests working, I am now moving onto the CRUD methods, and am getting the following Exception on the EndSaveChanges of the Data Service Context.
<?xml version="1.0" encoding="utf-8"?>
<m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<m:code />
<m:message xml:lang="en-US">No HTTP resource was found that matches the request URI 'http://localhost:56317/odata/ESFClients(guid'f04ad636-f896-4de4-816c-388106cd39ce')'.</m:message>
<m:innererror>
<m:message>No routing convention was found to select an action for the OData path with template '~/entityset/key'.</m:message>
<m:type></m:type>
<m:stacktrace></m:stacktrace>
</m:innererror>
</m:error>
Now I think this is a bug in WebApi from this http://aspnetwebstack.codeplex.com/workitem/822 and its hiding the actual error. To make sure it wasn't my Odata Endpoint I created a quick console app to get an entry, update it and Patch it back, which worked all ok. My WebApi Odata Controller derives from ODataController with
public HttpResponseMessage Patch([FromODataUri] Guid key, Delta<ESFClient> patch)
As the method.
In my windows application I have a extension method on the DataServiceContext for the Save Changes.
public static async Task<DataServiceResponse> SaveChangesAsync(this DataServiceContext context, SaveChangesOptions options)
{
var queryTask = Task.Factory.FromAsync<DataServiceResponse>(context.BeginSaveChanges(options, null, null),
queryAsyncResult =>
{
var results = context.EndSaveChanges(queryAsyncResult);
return results;
});
return await queryTask;
}
And calling the update like so from a blank Windows Store XAML page.
public async Task UpdateWeekNo()
{
var container = new ESFOdataService.Container(new Uri("http://localhost:56317/odata/"));
var clients = (DataServiceQuery<ESFClient>)from p in container.ESFClients where p.UserID == new Guid("f04ad636-f896-4de4-816c-388106cd39ce") select p;
var result = await clients.ExecuteAsync();
var updatedClient = result.Single();
if (updatedClient != null)
{
updatedClient.WeekNo = 19;
container.UpdateObject(updatedClient);
await container.SaveChangesAsync(SaveChangesOptions.PatchOnUpdate); // Use PATCH not MERGE.
}
}
So does anyone come across the same issue, or know how I can find out the actual error. One interesting point is that if I debug the controller while running the Windows App, the patch method does not get called.
Ok, so I have finally solved this. Just a recap for those who could experience the same issue. I have an Odata WebApi controller, Windows 8 Store Application using WCF Client Library, with the reference created from Add Service Reference. When trying to update (patch) a record an exception was being thrown at the EndSaveChanges. This is because for some reason Post Tunneling is enabled by default on my context. Setting this to false allowed everything to work.
Context.UsePostTunneling = false;
Context.IgnoreResourceNotFoundException = true;

Create a Windows Session from a service via the Win32 API

I have a windows service that can create an executable in the users windows session, via calling the "CreateProcessAsUser" function. This works fine as long as there is a windows session already there. In the case that there isn't one already I'd like to be able to create one programmatically. Is this is possible? Can't seem to find a function to do it.
This isn't quite the solution for the question I asked, but it was the solution that helped achieve what I was trying to achieve by asking this question, if you see what I mean.
Rather than have having a windows services that creates a server session you can configure windows to automatically logon at boot time. This still means someone could accenditally log off, but cures the main reason for sessions disappearing: the server being rebooted. Use the following steps to activate auto-logon:
Press the Windows key + R on your keyboard to launch the “Run” dialog box.
Type regedit and hit enter to open the Registry Editor
Then browse to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\Winlogon\
Set AutoAdminLogon = 1 (create it if doesn't exist its a string variable)
Set DefaultUserName = your username (create it if doesn't exist its a string variable)
Set DefaultPassword = your password (create it if doesn't exist its a string variable)
Instructions were taken from this post:
http://channel9.msdn.com/Blogs/coolstuff/Tip-Auto-Login-Your-Windows-7-User-Account
You cannot create a new session from a service. Sessions are managed by the OS. New ones get created when users logon interactively.
#Robert, I know this is an old question and that you've already found something that works for you but in my case I was looking for something similar to your original question and I did finally figure it out so I thought I'd share. My solution uses only .NET and a COM reference not the Win32 API mentioned in your title, but I'm guessing that wasn't really a requirement for you.
I've written a simple utility to using the Remote Desktop ActiveX control (COM Reference). If you paste this code into a Class Library you can then call it by simply passing in the server, username, domain, and password and everything is done for you without any other interaction required. Once the method is complete you can then call your "CreateProcessAsUser" Code. I've written this utility in a way so that you could call it every time but initiating an RDP session takes several seconds so for performance sake I'd suggest you write another method to enumerate the sessions and see if your user is logged in and only call this utility when you determine that your user isn't logged in (That's what I did in my actual project). If you feel you need help with that post in the comments and I'll share how I did that but It's not really part of this question so for now I'm leaving it out.
Here's a link back to my question that has a few more requirements/details than this question.
Create Windows Session programmatically from Console or Windows Service
And here's my RDP utility. After you put this code in a class library you can then call it from a console app, winForms app, or from a windows service running on the same machine or from a remote machine.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using AxMSTSCLib;
namespace Utility.RemoteDesktop
{
public class Client
{
private int LogonErrorCode { get; set; }
public void CreateRdpConnection(string server, string user, string domain, string password)
{
void ProcessTaskThread()
{
var form = new Form();
form.Load += (sender, args) =>
{
var rdpConnection = new AxMSTSCLib.AxMsRdpClient9NotSafeForScripting();
form.Controls.Add(rdpConnection);
rdpConnection.Server = server;
rdpConnection.Domain = domain;
rdpConnection.UserName = user;
rdpConnection.AdvancedSettings9.ClearTextPassword = password;
rdpConnection.AdvancedSettings9.EnableCredSspSupport = true;
if (true)
{
rdpConnection.OnDisconnected += RdpConnectionOnOnDisconnected;
rdpConnection.OnLoginComplete += RdpConnectionOnOnLoginComplete;
rdpConnection.OnLogonError += RdpConnectionOnOnLogonError;
}
rdpConnection.Connect();
rdpConnection.Enabled = false;
rdpConnection.Dock = DockStyle.Fill;
Application.Run(form);
};
form.Show();
}
var rdpClientThread = new Thread(ProcessTaskThread) { IsBackground = true };
rdpClientThread.SetApartmentState(ApartmentState.STA);
rdpClientThread.Start();
while (rdpClientThread.IsAlive)
{
Task.Delay(500).GetAwaiter().GetResult();
}
}
private void RdpConnectionOnOnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
{
LogonErrorCode = e.lError;
}
private void RdpConnectionOnOnLoginComplete(object sender, EventArgs e)
{
if (LogonErrorCode == -2)
{
Debug.WriteLine($" ## New Session Detected ##");
Task.Delay(10000).GetAwaiter().GetResult();
}
var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
rdpSession.Disconnect();
}
private void RdpConnectionOnOnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e)
{
Environment.Exit(0);
}
}
}
What about the LogonUser function?
http://winapi.freetechsecrets.com/win32/WIN32LogonUser.htm

Accessing particular service method from metro app?

i have a web services which i am accessing in my client application(metro app) , but i want to access a particular method inside those many methods i have how should i do it ,
as of now , i am doing it in this way to accessing the web services from my metro app:-
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
string responseBodyAsText;
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://182.134.34.99/OE/examplewebservices.svc");
response.EnsureSuccessStatusCode();
StatusText.Text = response.StatusCode.ToString();
responseBodyAsText = await response.Content.ReadAsStringAsync();
}
my requirement is :- there are many methods inside that examplewebservices , so i want to access one of the method inside that , pass input parameters to that method and get the result.
1)How to access one a particular method inside those many methods ( from metro app) ?
2)how to pass input to that service method (from metro app)?
Question might be very basic to you , pls help out. i am new to metro application development.
Thanks in advance.
The code you have does not call a service, it downloads service definition page. You will need to add a service reference to your project (right click on project node, choose Add Service Reference from context menu). Then you will be able to call methods of your service. In WinRT app, you will only be able to call web service asynchronously, so all methods will have 'Async' suffix and you will have to use async/await pattern when calling it.
To call an operation on the service you can use this pattern:
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://182.134.34.99/OE/examplewebservices.svc");
HttpResponseMessage response = await client.GetAsync("MyOperation");
...
}
To send values in this simplistic example you can send them as QueryStrings appended to the MyOperation string as follows: MyOperation?myvalue=1 etc.
Other than that #Seva Titov gave a good response to the dynamic aspect.

Resources