command line c# code works, but winforms code does not - c#

I am working on a Adobe Echosign demo C# winforms application. My code is a direct copy of their command line code (with modifications), however, my code returns an error after it transmits the data.
This is the command line code from EchoSign that works
public static void sendDocument(string apiKey, string fileName, string formFieldLayerTemplateKey, string recipient)
{
FileStream file = getTestPdfFile(fileName);
secure.echosign.com.FileInfo[] fileInfos = new secure.echosign.com.FileInfo[1];
fileInfos[0] = new secure.echosign.com.FileInfo(fileName, null, file);
SenderInfo senderInfo = null;
string[] recipients = new string[1];
recipients[0] = recipient;
DocumentCreationInfo documentInfo = new DocumentCreationInfo(
recipients,
testPrefix + Path.GetFileName(file.Name),
testMessage,
fileInfos,
SignatureType.ESIGN,
SignatureFlow.SENDER_SIGNATURE_NOT_REQUIRED
);
if (formFieldLayerTemplateKey != null)
{
secure.echosign.com.FileInfo[] formFieldLayerTemplates = new secure.echosign.com.FileInfo[1];
formFieldLayerTemplates[0] = new secure.echosign.com.FileInfo(formFieldLayerTemplateKey);
documentInfo.formFieldLayerTemplates = formFieldLayerTemplates;
}
DocumentKey[] documentKeys;
documentKeys = ES.sendDocument(apiKey, senderInfo, documentInfo);
Console.WriteLine("Document key is: " + documentKeys[0].documentKey);
}
This is my code block that returns an error from their system:
public static void sendDocument(string apiKey, string fileName, string formFieldLayerTemplateKey, string recipient)
{
try
{
SenderInfo senderInfo = new SenderInfo();
senderInfo = null;
FileStream FileToSign = getTestPdfFile(fileName);
byte[] bytes = System.IO.File.ReadAllBytes("C:\\PROJECTS\\TestFile.pdf");
secure.echosign.com.FileInfo[] fileInfos = new secure.echosign.com.FileInfo[1];
fileInfos[0] = new EchoSignTest.secure.echosign.com.FileInfo();
fileInfos[0].fileName = fileName;
fileInfos[0].mimeType = null;
fileInfos[0].file = bytes;
RecipientInfo[] docRecipient = new RecipientInfo[1];
docRecipient[0] = new RecipientInfo();
docRecipient[0].email = recipient;
DocumentCreationInfo documentInfo = new DocumentCreationInfo();
documentInfo.recipients = docRecipient;
documentInfo.name = testPrefix + Path.GetFileName(FileToSign.Name);
documentInfo.message = testMessage;
documentInfo.fileInfos = fileInfos;
documentInfo.signatureType = SignatureType.ESIGN;
documentInfo.signatureFlow = SignatureFlow.SENDER_SIGNATURE_NOT_REQUIRED;
if (formFieldLayerTemplateKey != null)
{
secure.echosign.com.FileInfo[] formFieldLayerTemplates = new secure.echosign.com.FileInfo[1];
formFieldLayerTemplates[0] = new secure.echosign.com.FileInfo();
formFieldLayerTemplates[0].formKey = formFieldLayerTemplateKey;
documentInfo.formFieldLayerTemplates = formFieldLayerTemplates;
}
EchoSignDocumentService19PortTypeClient ES = new EchoSignDocumentService19PortTypeClient();
DocumentKey[] documentKeys = new DocumentKey[1];
documentKeys = ES.sendDocument(apiKey, senderInfo, documentInfo);
Console.WriteLine("Document key is: " + documentKeys[0].documentKey);
}
catch (NullReferenceException ex)
{
string errMessage = ex.Message;
}
catch (Exception ex)
{
string errMessage = ex.Message;
}
}
What is different between the two code blocks? The error may reside in the FileInfo[] or DocumentCreationInfo() blocks. I am perhaps not creating the objects as the system requires.
Any suggestions are appreciated.

The error seems to be the direct assignment of the bytes of the document you read to the fileInfos[0].file variable. In the documentation for FileInfo it states that the file parameter has to be the raw file content, encoded using base64, but you assign the raw file content without encoding it. When the constructor is called with a file stream like in your first example (the command-line one), the constructor seems to handle this automatically. You could try to change these lines in your Winforms example:
FileStream FileToSign = getTestPdfFile(fileName);
byte[] bytes = System.IO.File.ReadAllBytes("C:\\PROJECTS\\TestFile.pdf");
secure.echosign.com.FileInfo[] fileInfos = new secure.echosign.com.FileInfo[1];
fileInfos[0] = new EchoSignTest.secure.echosign.com.FileInfo();
fileInfos[0].fileName = fileName;
fileInfos[0].mimeType = null;
fileInfos[0].file = bytes;
into this code and try if this works:
FileStream FileToSign = getTestPdfFile(fileName);
secure.echosign.com.FileInfo[] fileInfos = new secure.echosign.com.FileInfo[1];
fileInfos[0] = new secure.echosign.com.FileInfo(fileName, null, FileToSign);
You should use the provided constructors instead of direct assignment to make sure all variables/parameters are handled properly.
The error you told about in your comments about the constructor that doesn't take 3 arguments could be a result of the EchoSignTest. prefix before your constructor call as it seems this is your own program's namespace and not the right namespace of the provided API.

Related

Failing to cover the code and pass the test

I am a beginner in unit testing. I am trying to write a test script, but I am stuck. I'd like to understand what I am doing wrong.
public ConvertExcelDocumentResponse ConvertExcelDocument(ConvertExcelDocumentRequest request)
{
var logger = Bootstrapper.Resolve<ILogger>();
ConvertExcelDocumentResponse response = new ConvertExcelDocumentResponse();
if (!string.IsNullOrEmpty(request.FileName) &&
System.IO.Path.GetExtension(request.FileName).ToLowerInvariant() == ".xls" &&
request.FileContent != null && request.FileContent.Length > 0)
{
response.FileContent = _httpClient.ConvertExcelDocument(request.FileContent, request.FileName);
response.FileName = System.IO.Path.GetFileNameWithoutExtension(request.FileName) + ".xlsx";
response.Success = true;
}
else
{
logger.LogError("Unable to convert Excel Document '" + request.FileName + "' only .xls files are allowed.");
response.FileContent = new byte[] { };
response.Success = false;
}
return response;
}
Here is my test:
/// <summary>
/// Test to Convert XLS to XLSX
/// </summary>
[TestCategory("DocumentService")]
[TestMethod]
public void Test_ConvertExcelDocumentResponse()
{
byte[] filecontent = new byte[] { };
string filename = "file";
using (ShimsContext.Create())
{
ConvertExcelDocumentRequest excelDocumentRequest1 = new ConvertExcelDocumentRequest()
{
FileName = "filename",
FileContent = new byte[] {},
};
ConvertExcelDocumentRequest excelDocumentRequest2 = new ConvertExcelDocumentRequest()
{
FileName = "",
FileContent = new byte[] {},
};
ShimDocumentService.AllInstances.ConvertExcelDocumentConvertExcelDocumentRequest = ((#this, Success) =>
{
return new ConvertExcelDocumentResponse()
{
FileContent=filecontent,
Success = true,
FileName = filename,
};
});
ShimHttpClientBase.AllInstances.ConvertWordDocumentByteArrayString = ((#this, fileContent, fileName) =>
{
return fileContent;
});
//Act
ILogger logger = Bootstrapper.Resolve<ILogger>();
var docService = new DocumentService();
//IDocumentService DocumentService = Bootstrapper.Resolve<IDocumentService>();
var excelResponse1 = docService.ConvertExcelDocument(excelDocumentRequest1);
var excelResponse2 = docService.ConvertExcelDocument(excelDocumentRequest2);
//Assert
Assert.AreEqual(excelResponse1.FileContent, filecontent );
Assert.AreEqual(excelResponse1.FileName, filename);
Assert.IsTrue(excelResponse1.Success, "Expects true");
Assert.AreEqual(excelResponse2.FileContent, filecontent);
Assert.AreEqual(excelResponse2.FileName, filename);
Assert.IsTrue(excelResponse2.Success, "Expects true");
}
}
This is passing the test but code coverage is 0%. I don't know where I am going wrong. I tried covering filename = null and few other conditions. not sure why it isn't covering my code
It looks like you'll need to also write a test where the filename is null or empty. That way you will cover the code in the else block.
Increasing code coverage often involves making your test exercise pieces of code that are not likely to be normally hit.

Parse WebCacheV01.dat in C#

I'm looking to parse the WebCacheV01.dat file using C# to find the last file location for upload in an Internet browser.
%LocalAppData%\Microsoft\Windows\WebCache\WebCacheV01.dat
I using the Managed Esent nuget package.
Esent.Isam
Esent.Interop
When I try and run the below code it fails at:
Api.JetGetDatabaseFileInfo(filePath, out pageSize, JET_DbInfo.PageSize);
Or if I use
Api.JetSetSystemParameter(instance, JET_SESID.Nil, JET_param.CircularLog, 1, null);
at
Api.JetAttachDatabase(sesid, filePath, AttachDatabaseGrbit.ReadOnly);
I get the following error:
An unhandled exception of type
'Microsoft.Isam.Esent.Interop.EsentFileAccessDeniedException' occurred
in Esent.Interop.dll
Additional information: Cannot access file, the file is locked or in use
string localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string filePathExtra = #"\Microsoft\Windows\WebCache\WebCacheV01.dat";
string filePath = string.Format("{0}{1}", localAppDataPath, filePathExtra);
JET_INSTANCE instance;
JET_SESID sesid;
JET_DBID dbid;
JET_TABLEID tableid;
String connect = "";
JET_SNP snp;
JET_SNT snt;
object data;
int numInstance = 0;
JET_INSTANCE_INFO [] instances;
int pageSize;
JET_COLUMNDEF columndef = new JET_COLUMNDEF();
JET_COLUMNID columnid;
Api.JetCreateInstance(out instance, "instance");
Api.JetGetDatabaseFileInfo(filePath, out pageSize, JET_DbInfo.PageSize);
Api.JetSetSystemParameter(JET_INSTANCE.Nil, JET_SESID.Nil, JET_param.DatabasePageSize, pageSize, null);
//Api.JetSetSystemParameter(instance, JET_SESID.Nil, JET_param.CircularLog, 1, null);
Api.JetInit(ref instance);
Api.JetBeginSession(instance, out sesid, null, null);
//Do stuff in db
Api.JetEndSession(sesid, EndSessionGrbit.None);
Api.JetTerm(instance);
Is it not possible to read this without making modifications?
Viewer
http://www.nirsoft.net/utils/ese_database_view.html
Python
https://jon.glass/attempts-to-parse-webcachev01-dat/
libesedb
impacket
Issue:
The file is probably in use.
Solution:
in order to free the locked file, please stop the Schedule Task -\Microsoft\Windows\Wininet\CacheTask.
The Code
public override IEnumerable<string> GetBrowsingHistoryUrls(FileInfo fileInfo)
{
var fileName = fileInfo.FullName;
var results = new List<string>();
try
{
int pageSize;
Api.JetGetDatabaseFileInfo(fileName, out pageSize, JET_DbInfo.PageSize);
SystemParameters.DatabasePageSize = pageSize;
using (var instance = new Instance("Browsing History"))
{
var param = new InstanceParameters(instance);
param.Recovery = false;
instance.Init();
using (var session = new Session(instance))
{
Api.JetAttachDatabase(session, fileName, AttachDatabaseGrbit.ReadOnly);
JET_DBID dbid;
Api.JetOpenDatabase(session, fileName, null, out dbid, OpenDatabaseGrbit.ReadOnly);
using (var tableContainers = new Table(session, dbid, "Containers", OpenTableGrbit.ReadOnly))
{
IDictionary<string, JET_COLUMNID> containerColumns = Api.GetColumnDictionary(session, tableContainers);
if (Api.TryMoveFirst(session, tableContainers))
{
do
{
var retrieveColumnAsInt32 = Api.RetrieveColumnAsInt32(session, tableContainers, columnIds["ContainerId"]);
if (retrieveColumnAsInt32 != null)
{
var containerId = (int)retrieveColumnAsInt32;
using (var table = new Table(session, dbid, "Container_" + containerId, OpenTableGrbit.ReadOnly))
{
var tableColumns = Api.GetColumnDictionary(session, table);
if (Api.TryMoveFirst(session, table))
{
do
{
var url = Api.RetrieveColumnAsString(
session,
table,
tableColumns["Url"],
Encoding.Unicode);
var downloadedFileName = Api.RetrieveColumnAsString(
session,
table,
columnIds2["Filename"]);
if(string.IsNullOrEmpty(downloadedFileName)) // check for download history only.
continue;
// Order by access Time to find the last uploaded file.
var accessedTime = Api.RetrieveColumnAsInt64(
session,
table,
columnIds2["AccessedTime"]);
var lastVisitTime = accessedTime.HasValue ? DateTime.FromFileTimeUtc(accessedTime.Value) : DateTime.MinValue;
results.Add(url);
}
while (Api.TryMoveNext(session, table.JetTableid));
}
}
}
} while (Api.TryMoveNext(session, tableContainers));
}
}
}
}
}
catch (Exception ex)
{
// log goes here....
}
return results;
}
Utils
Task Scheduler Wrapper
You can use Microsoft.Win32.TaskScheduler.TaskService Wrapper to stop it using c#, just add this Nuget package [nuget]:https://taskscheduler.codeplex.com/
Usage
public static FileInfo CopyLockedFileRtl(DirectoryInfo directory, FileInfo fileInfo, string remoteEndPoint)
{
FileInfo copiedFileInfo = null;
using (var ts = new TaskService(string.Format(#"\\{0}", remoteEndPoint)))
{
var task = ts.GetTask(#"\Microsoft\Windows\Wininet\CacheTask");
task.Stop();
task.Enabled = false;
var byteArray = FileHelper.ReadOnlyAllBytes(fileInfo);
var filePath = Path.Combine(directory.FullName, "unlockedfile.dat");
File.WriteAllBytes(filePath, byteArray);
copiedFileInfo = new FileInfo(filePath);
task.Enabled = true;
task.Run();
task.Dispose();
}
return copiedFileInfo;
}
I was not able to get Adam's answer to work. What worked for me was making a copy with AlphaVSS (a .NET class library that has a managed API for the Volume Shadow Copy Service). The file was in "Dirty Shutdown" state, so I additionally wrote this to handle the exception it threw when I opened it:
catch (EsentErrorException ex)
{ // Usually after the database is copied, it's in Dirty Shutdown state
// This can be verified by running "esentutl.exe /Mh WebCacheV01.dat"
logger.Info(ex.Message);
switch (ex.Error)
{
case JET_err.SecondaryIndexCorrupted:
logger.Info("Secondary Index Corrupted detected, exiting...");
Api.JetTerm2(instance, TermGrbit.Complete);
return false;
case JET_err.DatabaseDirtyShutdown:
logger.Info("Dirty shutdown detected, attempting to recover...");
try
{
Api.JetTerm2(instance, TermGrbit.Complete);
Process.Start("esentutl.exe", "/p /o " + newPath);
Thread.Sleep(5000);
Api.JetInit(ref instance);
Api.JetBeginSession(instance, out sessionId, null, null);
Api.JetAttachDatabase(sessionId, newPath, AttachDatabaseGrbit.None);
}
catch (Exception e2)
{
logger.Info("Could not recover database " + newPath + ", will try opening it one last time. If that doesn't work, try using other esentutl commands", e2);
}
break;
}
}
I'm thinking about using the 'Recent Items' folder as when you select a file to upload an entry is written here:
C:\Users\USER\AppData\Roaming\Microsoft\Windows\Recent
string recent = (Environment.GetFolderPath(Environment.SpecialFolder.Recent));

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

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"

Trying to download file from FileCabinet in NetSuite using C# program

I need to download JPG file from FileCabinet in NetSuite. For that I know the file name, so I searched file and assigned to FileObject. I got the object right, but got NULL content. I am providing here some code. Can anybody point out the error or any missing step here? Thank you.
var result = _service.search(flSearch);
if (result.totalRecords > 0)
{
recordList = result.recordList;
Record[] records = new Record[recordList.Length];
for (int j = 0; j < recordList.Length; j++)
{
if (recordList[j] is File)
{
File itemImage = (File)(recordList[j]);
byte[] data;
data = new Byte[(int)itemImage.fileSize];
data = itemImage.content; //Here getting NULL value
FileStream inFile;
using (inFile = new FileStream("newImage.jpg", FileMode.Create, FileAccess.Write))
{
inFile.Write(data, 0, data.Length);
}
}
}
}
itemImage is just a string - base64.
take that string and do a base64 decode and save that to your local file.
If the search is based on the internal id of the file you want to search, then the following code may help
var service = LoginNetSuite();
Tuple<string, string> fileContent = null;
FileSearch fileSearch = new FileSearch();
FileSearchBasic fileSearchBasic = new FileSearchBasic();
// Specify the folder in which the search is to be done.
SearchMultiSelectField folderFilter = new SearchMultiSelectField();
folderFilter.#operator = SearchMultiSelectFieldOperator.anyOf;
folderFilter.operatorSpecified = true;
RecordRef[] folder = new RecordRef[1];
folder[0] = new RecordRef();
folder[0].internalId = "78990"; // 78990 => Internal id of the folder.
folderFilter.searchValue = folder;
fileSearchBasic.folder = folderFilter;
// Specify the file internal id.
SearchMultiSelectField fileFilter = new SearchMultiSelectField();
fileFilter.#operator = SearchMultiSelectFieldOperator.anyOf;
fileFilter.operatorSpecified = true;
RecordRef[] rec = new RecordRef[1];
rec[0] = new RecordRef();
rec[0].internalId = "345656"; // 345656 => Internal id of the file.
fileFilter.searchValue = rec;
fileSearchBasic.internalId = fileFilter;
fileSearch.basic = fileSearchBasic;
var result = service.search(fileSearch);
var recordList = (Record[])result.recordList;
if (recordList != null && recordList.Length != 0)
{
var file = (File)result.recordList.First();
fileContent = new Tuple<string, string>(file.url, file.name);
}
In this code the folder internal id and the file internal id is given as the search parameters. So the file search will be done in the specified file cabinet with specified file id.
The response from netsuite will consist of the internal id, file name, url, folder name etc. The file can be downloaded from the url location.

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