Perforce Api - How to command "get revision [changelist number]" - c#

I would like to implement the Perforce command "Get Revision [Changelist Number]" using the Perforce .NET API (C#). I currently have code that will "Get Latest Revision", but I need to modify it to get a specific changelist.
To sync the data with a changelist number, what should I do?
Source
// --------Connenct----------------
Perforce.P4.Server server = new Perforce.P4.Server(
new Perforce.P4.ServerAddress("127.0.0.1:9999"));
Perforce.P4.Repository rep = new Perforce.P4.Repository(server);
Perforce.P4.Connection con = rep.Connection;
con.UserName = m_P4ID;
string password = m_P4PASS;
Perforce.P4.Options opconnect = new Perforce.P4.Options();
opconnect.Add("-p", password);
con.Connect(opconnect);
if (con.Credential == null)
con.Login(password);
//----------Download----------
string clientPath = #"C:\P4V\";
string ws_client = clientPath;
Perforce.P4.Client client = new Perforce.P4.Client();
client.Name = ws_client;
client.Initialize(con);
con.CommandTimeout = new TimeSpan(0);
IList<Perforce.P4.FileSpec> fileList = client.SyncFiles(new Perforce.P4.Options());
//----------Disconnect------------
con.Disconnect();
con.Dispose();
Edit: Attempt 1
Perforce.P4.DepotPath depot = new Perforce.P4.DepotPath("//P4V//");
Perforce.P4.LocalPath local = new Perforce.P4.LocalPath(ws_client);
Perforce.P4.FileSpec fs = new Perforce.P4.FileSpec(depot, null, local,
Perforce.P4.VersionSpec.Head);
IList<Perforce.P4.FileSpec> listFiles = new List<Perforce.P4.FileSpec>();
listFiles.Add(fs);
IList<Perforce.P4.FileSpec> foundFiles = rep.GetDepotFiles(listFiles,
new Perforce.P4.Options(1234)); // 1234 = Changelist number
client.SyncFiles(foundFiles, null);
Error Message
Usage: files/print [-o localFile -q] files...Invalid option: -c.
I do not know the problem of any argument.
Or there will not be related to this reference source?
Edit 2
I tried to solve this problem. However, it does not solve the problem yet.
Perforce.P4.Changelist changelist = rep.GetChangelist(1234);
IList<Perforce.P4.FileMetaData> fileMeta = changelist.Files;
In this case, I could get only the files in the changelist. I would like to synchronize all files of the client at the moment of changelist 1234.

SyncFiles takes an optional FileSpec arg. You can specify a file path and a revision specifier with that FileSpec arg. Here are the relevant docs:
FileSpec object docs
SyncFiles method docs
You don't need to run GetDepotFiles() to get the FileSpec object; you can just create one directly as shown in the FileSpec object docs. The error you are getting with GetDepotFiles() is because it expects the change number to be specified as part of the FileSpec object passed into as the first argument to GetDepotFiles().
To expand further, GetDepotFiles() calls the 'p4 files' command when it talks to Perforce. new Perforce.P4.Options(1234) generates an option of '-c 1234' which 'p4 files' doesn't accept. That's why the error message is 'Usage: files/print [-o localFile -q] files...Invalid option: -c.'

I struggled with the same problem as well. Finally based on Matt's answer I got it working. Please see simple example below.
using (Connection con = rep.Connection)
{
//setting up client object with viewmap
Client client = new Client();
client.Name = "p4apinet_solution_builder_sample_application_client";
client.OwnerName = "p4username";
client.Root = "c:\\clientRootPath";
client.Options = ClientOption.AllWrite;
client.LineEnd = LineEnd.Local;
client.SubmitOptions = new ClientSubmitOptions(false, SubmitType.RevertUnchanged);
client.ViewMap = new ViewMap();
client.ViewMap.Add("//depotpath/to/your/file.txt", "//" + client.Name + "/clientpath/to/your/file.txt", MapType.Include);
//connecting to p4 and creating client on p4 server
Options options = new Options();
options["Password"] = "p4password";
con.UserName = "p4username";
con.Client = new Client();
con.Connect(options);
con.Client = rep.CreateClient(client);
//syncing all files (in this case 1) defined in client's viewmap to the changelist level of 12345
Options syncFlags = new Options(SyncFilesCmdFlags.Force, 100);
VersionSpec changeListLevel = new ChangelistIdVersion(12345);
List<FileSpec> filesToBeSynced = con.Client.ViewMap.Select<MapEntry, FileSpec>(me => new FileSpec(me.Left, changeListLevel)).ToList();
IList<FileSpec> results = con.Client.SyncFiles(filesToBeSynced, syncFlags);
}

The following code should allow you to sync a depot to a particular revision (changelist number).
string uri = "...";
string user = "...";
string workspace = "...";
string pass = "...";
int id = 12345; // the actual changelist number
string depotPath = "//depot/foo/main/...";
int maxItemsToSync = 10000;
Server server = new Server(new ServerAddress(uri));
Repository rep = new Repository(server);
server = new Server(new ServerAddress(uri));
rep = new Repository(server);
Connection con = rep.Connection;
con.UserName = user;
con.Client = new Client();
con.Client.Name = workspace;
// connect
bool connected = con.Connect(null);
if (connected)
{
try
{
// attempt a login
Perforce.P4.Credential cred = con.Login(pass);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
con.Disconnect();
connected = false;
}
if (connected)
{
// get p4 info and show successful connection
ServerMetaData info = rep.GetServerMetaData(null);
Console.WriteLine("CONNECTED TO " + info.Address.Uri);
Console.WriteLine("");
try
{
Options opts = new Options();
// uncomment below lines to only get a preview of the sync w/o updating the workspace
//SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.Preview, maxItemsToSync);
SyncFilesCmdOptions syncOpts = new SyncFilesCmdOptions(SyncFilesCmdFlags.None, maxItemsToSync);
VersionSpec version = new ChangelistIdVersion(id);
PathSpec path = new DepotPath(depotPath);
FileSpec depotFile = new FileSpec(path, version);
IList<FileSpec> syncedFiles = rep.Connection.Client.SyncFiles(syncOpts, depotFile);
//foreach (var file in syncedFiles)
//{
// Console.WriteLine(file.ToString());
//}
Console.WriteLine($"{syncedFiles.Count} files got synced!");
}
catch (Exception ex)
{
Console.WriteLine("");
Console.WriteLine(ex.Message);
Console.WriteLine("");
}
finally
{
con.Disconnect();
}
}
}
If you are looking for other ways to build the file spec, like for example sync only a specific list of files to "head", etc, visit this link and search for "Building a FileSpec"

Related

SAS Provider for OLE DB (SAS.IOMProvider) doesn't work with ObjectPool

I'm using the SAS Integration Technologies COM components to connect to SAS Server from a C# .NET project. I want to submit statements to a SAS Workspace then load the output dataset from SAS using the OLE DB provider (SAS.IOMProvider). I am able to do this successfully using code like this:
static int Main(string[] args)
{
var keeper = new ObjectKeeper();
var factory = new ObjectFactoryMulti2();
var server = new ServerDef()
{
MachineDNSName = "sas.server.com",
Protocol = Protocols.ProtocolBridge,
Port = 8591,
BridgeSecurityPackage = "Negotiate",
};
var workspace = (IWorkspace)factory.CreateObjectByServer("Workspace1", true, server, null, null);
keeper.AddObject(1, workspace.UniqueIdentifier, workspace);
try
{
using (var conn = new OleDbConnection("Provider=SAS.IOMProvider.1; Data Source=iom-id://" + workspace.UniqueIdentifier))
{
// success
conn.Open();
}
}
catch (Exception ex)
{
System.Console.Error.WriteLine(ex.ToString());
return 1;
}
finally
{
keeper.RemoveObject(workspace);
workspace.Close();
}
return 0;
}
However, when I try using the ObjectPool feature of ObjectFactoryMulti2, the OLE DB connection doesn't work. It always throws "The object could not be found; make sure it was previously added to the object keeper." Here is the code that does not work:
static int Main(string[] args)
{
var keeper = new ObjectKeeper();
var factory = new ObjectFactoryMulti2();
var server = new ServerDef()
{
MachineDNSName = "sas.server.com`",
Protocol = Protocols.ProtocolBridge,
Port = 8591,
BridgeSecurityPackage = "Negotiate",
MaxPerObjectPool = Environment.ProcessorCount,
RunForever = true,
RecycleActivationLimit = 100,
};
var login = new LoginDef();
var pool = factory.ObjectPools.CreatePoolByServer("Pool1", server, login);
var lease = pool.GetPooledObject(null, null, 5000);
var workspace = (IWorkspace)lease.SASObject;
keeper.AddObject(1, workspace.UniqueIdentifier, workspace);
try
{
using (var conn = new OleDbConnection("Provider=SAS.IOMProvider.1; Data Source=iom-id://" + workspace.UniqueIdentifier))
{
// throws System.Data.OleDb.OleDbException: 'The object 1EFCE532-99BA-4A27-AF37-574EAE1CD04C could not be found; make sure it was previously added to the object keeper.'
conn.Open();
}
}
catch (Exception ex)
{
System.Console.Error.WriteLine(ex.ToString());
return 1;
}
finally
{
keeper.RemoveObject(workspace);
lease.ReturnToPool();
pool.Shutdown();
}
return 0;
}
Is there a way to use SAS connection pooling with the SAS OLE DB provider?
Got a good answer to this question from SAS Support. When using a connection pool, you have to cast the workspace to IServerStatus and connect using its ServerStatusUniqueID property instead of IWorkspace.UniqueIdentifier.
var pool = factory.ObjectPools.CreatePoolByServer("Pool1", server, login);
var lease = pool.GetPooledObject(null, null, 5000);
var workspace = (IWorkspace)lease.SASObject;
var status = (IServerStatus)lease.SASObject;
keeper.AddObject(1, workspace.UniqueIdentifier, workspace);
using (var conn = new OleDbConnection("Provider=SAS.IOMProvider.1; Data Source=iom-id://" + status.ServerStatusUniqueID))
{
// success
conn.Open();
}
keeper.RemoveObject(workspace);
lease.ReturnToPool();

SSRS Create Subscription via C#

I am trying to create subscriptions for reports via C# code using Web Reference CreateSubscription method. I have tried:
Using Web Reference and Service Reference. Both give error that is below.
Connecting to 2 different SSRS servers (localbox and on another server on the network)
On the local machine I tweaked permission of the user account to have admin level access.
Tried different parameters in web.config from examples on internet
The error that I get is:
"System.Web.Services.Protocols.SoapException: The report server
cannot open a connection to the report server database".
I am a bit stuck at this point. I am not sure if the SSRS is not configured correctly or I need to pass in a certain credentials via C# when I make the call. Any ideas?
Resources Used:
https://ssrstutorials.blogspot.com/2012/10/lesson-12-using-ssrs-web-services.html
https://msdn.microsoft.com/en-us/library/reportservice2005.reportingservice2005.createsubscription.aspx
https://jaliyaudagedara.blogspot.com/2012/05/accessing-report-server-using-report.html
Web Reference URL:
http://localhost:80/ReportServer/ReportService2005.asmx
Code:
ReportingService2005 rs = new ReportingService2005();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
string report = "/Demo/DemoReport";
string desc = "Send email";
string eventType = "TimedSubscription";
string scheduleXml = #"<ScheduleDefinition><StartDateTime>2017-11-
24T09:00:00-08:00</StartDateTime><WeeklyRecurrence>
<WeeksInterval>1</WeeksInterval><DaysOfWeek><Monday>True</Monday>
</DaysOfWeek></WeeklyRecurrence></ScheduleDefinition>";
ParameterValue[] extensionParams = new ParameterValue[8];
extensionParams[0] = new ParameterValue();
extensionParams[0].Name = "TO";
extensionParams[0].Value = "demo#demo.com";
extensionParams[1] = new ParameterValue();
extensionParams[1].Name = "ReplyTo";
extensionParams[1].Value = "demo#demo.com";
extensionParams[2] = new ParameterValue();
extensionParams[2].Name = "IncludeReport";
extensionParams[2].Value = "True";
extensionParams[3] = new ParameterValue();
extensionParams[3].Name = "RenderFormat";
extensionParams[3].Value = "MHTML";
extensionParams[4] = new ParameterValue();
extensionParams[4].Name = "Subject";
extensionParams[4].Value = "#ReportName was executed at
#ExecutionTime";
extensionParams[5] = new ParameterValue();
extensionParams[5].Name = "Comment";
extensionParams[5].Value = "Demo";
extensionParams[6] = new ParameterValue();
extensionParams[6].Name = "IncludeLink";
extensionParams[6].Value = "True";
extensionParams[7] = new ParameterValue();
extensionParams[7].Name = "Priority";
extensionParams[7].Value = "NORMAL";
ParameterValue parameter = new ParameterValue();
parameter.Name = "";
parameter.Value = "";
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = parameter;
string matchData = scheduleXml;
ExtensionSettings extSettings = new ExtensionSettings();
extSettings.ParameterValues = extensionParams;
extSettings.Extension = "Report Server Email";
try
{
rs.CreateSubscription(report, extSettings, desc, eventType,
matchData, parameters);
}
catch (SoapException e)
{
Console.WriteLine(e.Detail.InnerXml.ToString());
}
Error:
System.Web.Services.Protocols.SoapException: The report server cannot
open a connection to the report server database. A connection to the
database is required for all requests and processing. --->
Microsoft.ReportingServices.Library.ReportServerDatabaseUnavailableException:
The report server cannot open a connection to the report server
database. A connection to the database is required for all requests
and processing. at
Microsoft.ReportingServices.Library.Global.EnsureModeFromCatalog()
at Microsoft.ReportingServices.Library.Global.EnsureRSNativeMode()
at Microsoft.ReportingServices.WebServer.ReportingService2005..ctor()

Amazon Order API or Report API to get SKU number and total quantity sold?

I want a list of all SKU for which there were any sales between the From Date and To Date with the quantity sold. I am all confused what to do - should I use Amazon MWS Order API for this or Report API for this? Does anyone have a c# code which shows how a report is requested and downloaded at my end for further processing i.e. saving the data in databases.
Any help would be much appreciated.
p.s. I have a large volume of data
UPDATE: Meanwhile I have written this code to get the report type and save the data. Now the error is "Access to path denied"
private const string targetRptType = "_GET_CONVERGED_FLAT_FILE_ORDER_REPORT_DATA_";
try
{
RequestReportRequest reportRequestRequest = new RequestReportRequest();
reportRequestRequest.Merchant = merchantId;
reportRequestRequest.ReportType = targetRptType;
reportRequestRequest.StartDate = DateTime.Now.AddDays(-3);
reportRequestRequest.EndDate = DateTime.Now;
MarketplaceWebServiceConfig config = new MarketplaceWebServiceConfig();
config.ServiceURL = "https://mws.amazonservices.com";
MarketplaceWebService.MarketplaceWebService service = new MarketplaceWebServiceClient(accessKeyId, secretAccessKey, applicationName, applicationVersion, config);
RequestReportResponse requestResponse = service.RequestReport(reportRequestRequest);
Thread.Sleep(15000);
Response.Write(requestResponse.RequestReportResult.ReportRequestInfo.ReportProcessingStatus);
GetReportRequestListRequest reportRequestListRequest = new GetReportRequestListRequest();
reportRequestListRequest.Merchant = merchantId;
List<ReportRequestInfo> myListzz = new List<ReportRequestInfo>();
GetReportRequestListResponse reportRequestListResponse = new GetReportRequestListResponse();
reportRequestListResponse = service.GetReportRequestList(reportRequestListRequest);
GetReportRequestListResult reportRequestListResult = new GetReportRequestListResult();
reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
while (myListzz[0].ReportProcessingStatus.ToString() != "_DONE_")
{
Thread.Sleep(20000);
reportRequestListResponse = service.GetReportRequestList(reportRequestListRequest);
reportRequestListResult = reportRequestListResponse.GetReportRequestListResult;
myListzz = reportRequestListResult.ReportRequestInfo;
}
GetReportListRequest listRequest = new GetReportListRequest();
listRequest.Merchant = merchantId;
listRequest.ReportRequestIdList = new IdList();
listRequest.ReportRequestIdList.Id.Add(requestResponse.RequestReportResult.ReportRequestInfo.ReportRequestId);
GetReportListResponse listResponse = service.GetReportList(listRequest);
//MessageBox.Show(listResponse.GetReportListResult.ReportInfo.ToString());
GetReportListResult getReportListResult = listResponse.GetReportListResult;
GetReportRequest reportRequest = new GetReportRequest();
reportRequest.Merchant = merchantId;
reportRequest.WithReportId(getReportListResult.ReportInfo[0].ReportId);
GetReportResponse reportResponse = new GetReportResponse();
try
{
reportRequest.Report = File.Open("C:\\AmazonReport.csv", FileMode.OpenOrCreate, FileAccess.ReadWrite); // Getting error access to path denied
reportResponse = service.GetReport(reportRequest);
}
catch (MarketplaceWebServiceException exe)
{
Response.Write(exe);
}
StreamReader sr = new StreamReader(reportRequest.Report);
Response.Write(sr.ReadToEnd());
sr.Close();
}
catch (MarketplaceWebServiceException ex)
{
Response.Write(ex.Message);
}
Can anyone please check my code and suggest if this is the correct way to get data from a report? I am still not able to save the report.
UPDATE 2
I have changed the path and now the error is gone and the file is created but it is just a 1 kb file with 2 records.. looks like it is not fetching full data. Not sure if the code is correct or not. Checking this on scratchpad https://mws.amazonservices.com/scratchpad/index.html
I would save the report in your current working directory. Access to C:\ is usually locked down unless you are running as an admin. Use the following if you want to be explicit (if you provide just a file name and not a fully justified path, it will also save in your current working directory)
reportRequest.Report = File.Open(Path.Combine(Directory.GetCurrentDirectory(), "AmazonReport.csv"), FileMode.OpenOrCreate, FileAccess.ReadWrite);
The Orders API would make this much easier in my opinion. You can request Orders using a Date range and get everything you need.

I am getting An Error with c# and Docusign How Do i resolve this error

I am getting the error
Unable to load template. Unable to load template from TemplateReference(0). Error: Data at the root level is invalid. Line 1, position 1.
below is a simplified version of the code i am using...
If i don't use the template reference type of the code everything works fine. But when i start using a template reference.. Nothing works and i get this error. Anyone have a suggestion?
TemplateReference _tempRef = new TemplateReference();
TemplateReference[] _tempRefs = new TemplateReference[] { };
TemplateReferenceRoleAssignment[] _roleAssignmentArray = new TemplateReferenceRoleAssignment[] { };
Recipient[] _recipientsArray = new Recipient[] { };
EnvelopeInformation envelope = new EnvelopeInformation();
Recipient recipient = new Recipient();
recipient.ID = "1";
recipient.Email = "someemail#somewhere.com";
recipient.UserName = "Some Person";
recipient.Type = RecipientTypeCode.Signer;
recipient.RequireIDLookup = false;
Array.Resize(ref _roleAssignmentArray, 1);
Array.Resize(ref _recipientsArray, 1);
_recipientsArray[0] = recipient;
var saRoleAssignment = new TemplateReferenceRoleAssignment
{
RecipientID = "1",
RoleName = "SA"
};
_roleAssignmentArray[0] = saRoleAssignment;
var reference = new Docusign.TemplateReference();
reference.Template = "49C0BE2B-48F7-4F38-B44A-19EB8E6A1A38";
reference.Document = new Docusign.Document();
reference.Document.PDFBytes = new byte[0];
reference.Document.ID = Convert.ToString(1);
reference.Document.Name = "please work";
reference.RoleAssignments = _roleAssignmentArray;
Array.Resize(ref _tempRefs, 1);
_tempRefs[1 - 1] = reference;
//.NET
//.NET
envelope.AccountId = "accountID";
envelope.Subject = "Sample Application";
envelope.EmailBlurb = "You can add a personal message here.";
APIServiceSoapClient apiService = new APIServiceSoapClient();
apiService.ClientCredentials.UserName.UserName = "userhere";
apiService.ClientCredentials.UserName.Password = "pass";
var status = apiService.CreateEnvelopeFromTemplates(_tempRefs, _recipientsArray, envelope, true);
If you're using DocuSign's SOAP api instead of REST then you should definitely familiarize yourself with the SOAP SDK on GitHub:
https://github.com/docusign/DocuSign-eSignature-SDK
There's an MS.NET (C#) version which has sample code that works out of the box, you only need to enter your api credentials. I suggest you use that as your project base, especially since it was updated recently.
Since you have not identified which line the error is stemming from it's a little hard to debug, but if you look at SendTemplate.aspx.cs in the SDK you'll see that the template reference is instantiated like this:
// Construct the template reference
var templateReference = new DocuSignAPI.TemplateReference
{
TemplateLocation = DocuSignAPI.TemplateLocationCode.Server,
Template = TemplateTable.Value,
RoleAssignments = CreateFinalRoleAssignments(recipients)
};
where CreateFinalRoleAssignments() is defined as:
protected DocuSignAPI.TemplateReferenceRoleAssignment[] CreateFinalRoleAssignments(DocuSignAPI.Recipient[] recipients)
{
// Match up all the recipients to the roles on the template
return recipients.Select(recipient => new DocuSignAPI.TemplateReferenceRoleAssignment
{
RecipientID = recipient.ID, RoleName = recipient.RoleName
}).ToArray();
}

System.ServiceModel.Channels.MessageHeader Error

I'm trying to get the following to work on my machine but I get an error (Cannot create an instance of the abstract class or interface 'System.ServiceModel.Channels.MessageHeader')
using System;
using System.IO;
using System.Reflection;
namespace com.companyname.business
{
/// <summary>
/// Summary description for SessionCreateRQClient.
/// </summary>
class SessionCreateRQClient
{
/// <summary>
/// The main entry point.
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{
// Set user information, including security credentials and the IPCC.
string username = "user";
string password = "password";
string ipcc = "IPCC";
string domain = "DEFAULT";
string temp = Environment.GetEnvironmentVariable("tmp"); // Get temp directory
string PropsFileName = temp + "/session.properties"; // Define dir and file name
DateTime dt = DateTime.UtcNow;
string tstamp = dt.ToString("s") + "Z";
//Create the message header and provide the conversation ID.
MessageHeader msgHeader = new MessageHeader();
msgHeader.ConversationId = "TestSession"; // Set the ConversationId
From from = new From();
PartyId fromPartyId = new PartyId();
PartyId[] fromPartyIdArr = new PartyId[1];
fromPartyId.Value = "WebServiceClient";
fromPartyIdArr[0] = fromPartyId;
from.PartyId = fromPartyIdArr;
msgHeader.From = from;
To to = new To();
PartyId toPartyId = new PartyId();
PartyId[] toPartyIdArr = new PartyId[1];
toPartyId.Value = "WebServiceSupplier";
toPartyIdArr[0] = toPartyId;
to.PartyId = toPartyIdArr;
msgHeader.To = to;
//Add the value for eb:CPAId, which is the IPCC.
//Add the value for the action code of this Web service, SessionCreateRQ.
msgHeader.CPAId = ipcc;
msgHeader.Action = "SessionCreateRQ";
Service service = new Service();
service.Value = "SessionCreate";
msgHeader.Service = service;
MessageData msgData = new MessageData();
msgData.MessageId = "mid:20001209-133003-2333#clientofsabre.com1";
msgData.Timestamp = tstamp;
msgHeader.MessageData = msgData;
Security security = new Security();
SecurityUsernameToken securityUserToken = new SecurityUsernameToken();
securityUserToken.Username = username;
securityUserToken.Password = password;
securityUserToken.Organization = ipcc;
securityUserToken.Domain = domain;
security.UsernameToken = securityUserToken;
SessionCreateRQ req = new SessionCreateRQ();
SessionCreateRQPOS pos = new SessionCreateRQPOS();
SessionCreateRQPOSSource source = new SessionCreateRQPOSSource();
source.PseudoCityCode = ipcc;
pos.Source = source;
req.POS = pos;
SessionCreateRQService serviceObj = new SessionCreateRQService();
serviceObj.MessageHeaderValue = msgHeader;
serviceObj.SecurityValue = security;
SessionCreateRS resp = serviceObj.SessionCreateRQ(req); // Send the request
if (resp.Errors != null && resp.Errors.Error != null)
{
Console.WriteLine("Error : " + resp.Errors.Error.ErrorInfo.Message);
}
else
{
msgHeader = serviceObj.MessageHeaderValue;
security = serviceObj.SecurityValue;
Console.WriteLine("**********************************************");
Console.WriteLine("Response of SessionCreateRQ service");
Console.WriteLine("BinarySecurityToken returned : " + security.BinarySecurityToken);
Console.WriteLine("**********************************************");
string ConvIdLine = "convid="+msgHeader.ConversationId; // ConversationId to a string
string TokenLine = "securitytoken="+security.BinarySecurityToken; // BinarySecurityToken to a string
string ipccLine = "ipcc="+ipcc; // IPCC to a string
File.Delete(PropsFileName); // Clean up
TextWriter tw = new StreamWriter(PropsFileName); // Create & open the file
tw.WriteLine(DateTime.Now); // Write the date for reference
tw.WriteLine(TokenLine); // Write the BinarySecurityToken
tw.WriteLine(ConvIdLine); // Write the ConversationId
tw.WriteLine(ipccLine); // Write the IPCC
tw.Close();
//Console.Read();
}
}
catch(Exception e)
{
Console.WriteLine("Exception Message : " + e.Message );
Console.WriteLine("Exception Stack Trace : " + e.StackTrace);
Console.Read();
}
}
}
}
I have added the reference System.ServiceModel and the lines:
using System.ServiceModel;
using System.ServiceModel.Channels;
but I continue to get that error when trying to compile --
Cannot create an instance of the abstract class or interface 'System.ServiceModel.Channels.MessageHeader'
I am using Microsoft Visual Studio 2008
Version 9.0.21022.8 RTM
Microsoft .NET Framework
Version 3.5 SP1
Professional Edition
Is there another reference I have to add? Or a dll to move over?
I wonder was the code above written for Framework 2.0 only?
Thanks for your help.
The error message is correct, you cannot create an instance of that class, it is declared abstract.
http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.messageheader.aspx
See if the static method MessageHeader.CreateHeader will work for you. Note there is several overloads, so pick the best one for you.

Categories

Resources