Programatically add document to Hummingbird/OpenText eDocs database - database

I am working with the the (formerly Hummingbird Enterprise) OpenText eDocs document management system.
http://www.opentext.com/2/global/products/products-opentext-edocs-products/products-opentext-edocs-document-management.htm
We are still using Hummingbird 5.1.0.5.
I have been reviewing the API docs for this software, but some areas are slightly vague.
So far, I can create my Profile form, populate some values.
DOCSObjects.Application docApp = null;
DOCSObjects.IProfile profile = null;
Type fType = Type.GetTypeFromProgID("DOCSObjects.Application");
docApp = (DOCSObjects.Application)Activator.CreateInstance(fType);
try { profile = docApp.CurrentLibrary.CreateProfile("DEF_PROF"); }
catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); }
if (profile != null)
{
try
{
profile.Columns["DOCNAME"].Value = "New PDF Document";
profile.Columns["APP_ID"].Value = "ACROBAT";
profile.ShowProfile(1);
// not sure how to set a document here
profile.SetDocument(docApp.CurrentLibrary.Name, document);
profile.Save(); // requires a short flag, but what?
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
else
{
MessageBox.Show("Profile is null");
}
Where I am having trouble is how to save a document with the profile.
I am using C# and the API docs and intellisense simply ask for on object for the document.
Does that mean the path or do I need to load the PDF into some specific DOCSObjects type?
Also, the API docs references a Constant such as OF_NORMAL when saving the document. I assume this is 0, but are there others I should know about? There are many Constants referenced in the docs that have no values defined. (All examples are in C++/VB).
I know it's a long shot anyone is using this software, but thought I would give it a try.
Thank you and any assistance is appreciated.

I have done it in VB - using an API wrapper that I created. You should use the PCDClient under DM API folder instead of the DOCSObjects.
This code here probably won't work right away for you because it is heavily customized, but play around with it and you can probably figure it out. Good Luck!
Public Sub CreateProfile(ByRef Doc As Profile)
Try
'SET THE STATIC META DATA
Doc.objDoc.SetProperty("TYPE_ID", "DOCS") ' DOCUMENT TYPE IS ALWAYS DOCS
Doc.objDoc.SetProperty("TYPIST_ID", RDIMSAPI._UserID)
Doc.objDoc.SetProperty("APP_ID", RDIMSData.GetApp(Doc.FileToImport)) ' FILE TO IMPORT
'CREATE THE DOCUMENT
Doc.objDoc.Create()
If Doc.objDoc.ErrNumber <> 0 Then
Throw New Exception(Doc.objDoc.ErrNumber & " - " & Doc.objDoc.ErrDescription)
End If
'RETRIEVE THE NEW DOCUMENT PROFILE
Dim DocNumber As Integer = Doc.objDoc.GetReturnProperty("%OBJECT_IDENTIFIER")
Dim VersionID As Integer = Doc.objDoc.GetReturnProperty("%VERSION_ID")
'ADD THE DOCUMENT TO THE PROFILE
Dim objPutDoc As New PCDClient.PCDPutDoc
objPutDoc.SetDST(RDIMSAPI._sDST)
objPutDoc.AddSearchCriteria("%TARGET_LIBRARY", RDIMSAPI._Library)
objPutDoc.AddSearchCriteria("%DOCUMENT_NUMBER", DocNumber)
objPutDoc.AddSearchCriteria("%VERSION_ID", VersionID)
objPutDoc.Execute()
If objPutDoc.ErrNumber <> 0 Then
Throw New Exception(Doc.objDoc.ErrNumber & " - " & Doc.objDoc.ErrDescription)
End If
objPutDoc.NextRow()
'UPLOAD THE DOCUMENT
Dim objPutStream As PCDClient.PCDPutStream = objPutDoc.GetPropertyValue("%CONTENT")
Dim fs As FileStream = System.IO.File.OpenRead(Doc.FileToImport)
Dim fi As FileInfo = New System.IO.FileInfo(Doc.FileToImport)
Dim br As BinaryReader = New BinaryReader(fs)
Dim addDocBytes As Byte() = br.ReadBytes(CInt(fs.Length))
br.Read(addDocBytes, 0, addDocBytes.Length)
br.Close()
Dim bytesWritten As Integer = 0
objPutStream.Write(addDocBytes, addDocBytes.Length, bytesWritten)
objPutStream.SetComplete()
'UNLOCK THE DOCUMENT
Dim objDoc As New PCDClient.PCDDocObject
objDoc.SetDST(RDIMSAPI._sDST)
objDoc.SetObjectType("0_RDIMSPROF_SYS")
objDoc.SetProperty("%TARGET_LIBRARY", RDIMSAPI._Library)
objDoc.SetProperty("%OBJECT_IDENTIFIER", DocNumber)
objDoc.SetProperty("%VERSION_ID", VersionID)
objDoc.SetProperty("%STATUS", "%UNLOCK")
objDoc.Update()
objDoc.Fetch()
objDoc = Nothing
If Doc.objDoc.ErrNumber <> 0 Then
Throw New Exception(Doc.objDoc.ErrNumber & " - " & Doc.objDoc.ErrDescription)
End If
'RELEASE ALL OBJECTS AND RETURN DOCUMENT NUMBER
objPutDoc = Nothing
Catch ex As Exception
'IF EXCEPTION, LOG ERROR AND DISPLAY MESSAGE
Throw New Exception("(" & Me.GetType().FullName & "." & New StackTrace(0).GetFrame(0).GetMethod.Name & ") " & ex.Message)
Exit Sub
End Try
End Sub

I don't know if you're still trying. But here's my C# code for this. It's part of a larger module, so it won't work immediately. The profile parameter would be for example "DEF_PROF".
This also uses the PCDClientLib. My understanding is that these are serverside libraries, wich you should use only on the server. And that you should use the lib you've already used for clientside code.
// All variable prepended with an underscore are class fields etc...
// DMImportException is a custom exception, nothing special really
/// <summary>
/// Import a file into the library previously logged in to.
/// </summary>
/// <param name="profile">The name of the used profile.</param>
/// <param name="profileNameValues">A dictionary of strings containing the profile values wich should be saved for the document.</param>
/// <param name="FileName">The path and filename of the file to import.</param>
public virtual void ImportFile(string profile, Dictionary<string, string> profileNameValues, string FileName)
{
if (!_isLoggedIn)
{
throw new DMImportException("Trying to import a file while not logged in into DM.");
}
int totalbyteswritten;
byte[] bdata;
bdata = file.readallbytes(filename);
pcddocobject objdoc = new pcddocobject();
objdoc.setproperty("%target_library", _library);
objdoc.setdst(_dst);
objdoc.setobjecttype(profile);
foreach(var profilenamevaluepair in profilenamevalues)
{
objdoc.setproperty(profilenamevaluepair.key, profilenamevaluepair.value);
}
objdoc.create();
if (objdoc.errnumber != 0)
{
throw new dmimportexception("error while creating a new objdoc. check the inner error.", objdoc.errnumber, objdoc.errdescription);
}
_docnumber = objDoc.GetReturnProperty("%OBJECT_IDENTIFIER").ToString();
_versionID = objDoc.GetReturnProperty("%VERSION_ID").ToString();
PCDPutDoc objPutDoc = new PCDPutDoc();
objPutDoc.SetDST(_dst);
objPutDoc.AddSearchCriteria("%TARGET_LIBRARY", _library);
objPutDoc.AddSearchCriteria("%DOCUMENT_NUMBER", _docNumber);
objPutDoc.AddSearchCriteria("%VERSION_ID", _versionID);
objPutDoc.Execute();
if (objPutDoc.ErrNumber != 0)
{
throw new DMImportException("RecentEdit Failure on Execute: Error while trying to get a handle to the newly created doc. Check the inner error.", objPutDoc.ErrNumber, objPutDoc.ErrDescription);
}
objPutDoc.NextRow();
PCDPutStream objPutStream = (PCDPutStream)objPutDoc.GetPropertyValue("%CONTENT");
objPutStream.Write((object)bdata, (int)bdata.Length, out TotalBytesWritten);
objPutStream.SetComplete();
objPutStream = null;
objDoc = null;
objDoc = new PCDDocObject();
objDoc.SetDST(_dst);
objDoc.SetObjectType(profile);
objDoc.SetProperty("%TARGET_LIBRARY", _library);
objDoc.SetProperty("%OBJECT_IDENTIFIER", _docNumber);
objDoc.SetProperty("%VERSION_ID", _versionID);
objDoc.SetProperty("%STATUS", "%UNLOCK");
objDoc.Update();
if (objDoc.ErrNumber != 0)
{
throw new DMImportException("Error while trying to unlock the just imported file. Check the inner error.", objDoc.ErrNumber, objDoc.ErrDescription);
}
objPutDoc = null;
objDoc = null;
return;
}
P.S. I'd recommend you update to a later version of eDocs (we're upgrading from 5.1.0.5 to 5.2.1 end of this week ;-D)
--- EDIT ---
I think you need
Application.CurrentLibrary.CreateProfile("PROF_DEF").CreateVersionFromFile( /* filePath is one of the params */);
if you really need to do this with the DM Ext. API instead of the DM API

Related

How to update value of a "usercert" property in LDAP AD

I have a requirement where I need to update the value saved in the property ("usercert") of a computer present in active directory.
// Retrieving properties value from AD
DirectoryEntry entry = new DirectoryEntry(LDAPPath, LDAPUser, DecryptPwd(LDAPPwd, LDAPKey));
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = string.Format("(&(objectCategory=computer)(Name=" + MachineName + "))");
result = searcher.FindOne();
byte[] text= (byte[])result.GetDirectoryEntry().Properties["usercert"].Value;
// Updateing new value to AD string updatedText= "New Text";
if (result.GetDirectoryEntry().Properties["usercert"] != null &&
result.GetDirectoryEntry().Properties["usercert"].Value != null)
{
byte[] updatedTextByte = Encoding.ASCII.GetBytes(updatedText);
result.GetDirectoryEntry().InvokeSet("usercert", updatedPassByte);
//(result.GetDirectoryEntry().Properties["usercert"]).Value = Encoding.ASCII.GetBytes(updatedText);
//result.GetDirectoryEntry().Properties["usercert"].Add(Encoding.ASCII.GetBytes(updatedText));
//result.GetDirectoryEntry().Properties["usercert"][0] = Encoding.ASCII.GetBytes(updatedText);
result.GetDirectoryEntry().CommitChanges();
}
I tried with all of the above commented code but nothing works for me. Can you please help me to solve this issue.
Calling GetDirectoryEntry() creates a new DirectoryEntry object each time you call it, which you can see in the source code here.
So when you do this:
result.GetDirectoryEntry().CommitChanges();
It's creating a brand new DirectoryEntry object and calling CommitChanges() on that. So nothing is changed.
You will need to call GetDirectoryEntry() only once and make changes to that object. For example:
var resultDe = result.GetDirectoryEntry();
resultDe.Properties["usercert"]).Value = whatever;
resuleDe.CommitChanges();

How to load multiple sheets of an Excel File in SSIS with header information in the sheets

I have a file with 2 sheets in it. It has the header information in it. I tried foreach loop container to load the data
Error i got is:
[SSIS.Pipeline] Error: "Excel Source" failed validation and returned validation status "VS_NEEDSNEWMETADATA".
I tried removing the header row manually from the sheets and ran foreach loop container and it worked perfectly fine.
But in my requirement i will be getting the header row followed by blank row in each sheet.
How do i do in this case.
I believe we need to use script task to to eliminate header and followed null row from the file and read the rest of the records.
My problem is i am bad at c# code logic.
Your help is much appreciated.
Thank you,
swathi
The following Script Task will delete the top 2 rows from every worksheet in the file (you'll need to create the variable 'ExcelFilePath' in SSIS and pass that in to the task, along with 'System::TaskName'):
public void Main()
{
MainTask();
GC.Collect();
GC.WaitForPendingFinalizers();
}
private void MainTask()
{
xl.Application xlApp = null;
xl.Workbook excelFile = null;
string excelFilePath = Dts.Variables["User::ExcelFilePath"].Value.ToString();
string thisTask = Dts.Variables["System::TaskName"].Value.ToString();
try
{
xlApp = new xl.Application();
excelFile = xlApp.Workbooks.Open(excelFilePath);
xlApp.DisplayAlerts = false;
foreach (xl.Worksheet ws in excelFile.Worksheets)
{
ws.Rows["1:2"].EntireRow.Delete();
}
xlApp.DisplayAlerts = true;
excelFile.Save();
excelFile.Close();
xlApp.Quit();
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
Dts.Events.FireError(0, thisTask, ex.Message, String.Empty, 0);
if (excelFile != null) excelFile.Close(SaveChanges:false);
if (xlApp != null) xlApp.Quit();
}
}
You will need to add references to 'COM' > 'Microsoft Excel [version number] Object Library' (whichever version you have) and '.NET' > 'Microsoft.CSharp'. You'll then need to declare using xl = Microsoft.Office.Interop.Excel; in your 'Namespaces' region.

What is the most efficient way to extract information from a text file formatted like this

Consider a text file stored in an online location that looks like this:
;aiu;
[MyEditor45]
Name = MyEditor 4.5
URL = http://www.myeditor.com/download/myeditor.msi
Size = 3023788
Description = This is the latest version of MyEditor
Feature = Support for other file types
Feature1 = Support for different encodings
BugFix = Fix bug with file open
BugFix1 = Fix crash when opening large files
BugFix2 = Fix bug with search in file feature
FilePath = %ProgramFiles%\MyEditor\MyEditor.exe
Version = 4.5
Which details information about a possible update to an application which a user could download. I want to load this into a stream reader, parse it and then build up a list of Features, BugFixes etc to display to the end user in a wpf list box.
I have the following piece of code that essentially gets my text file (first extracting its location from a local ini file and loads it into a streamReader. This at least works although I know that there is no error checking at present, I just want to establish the most efficient way to parse this first. One of these files is unlikely to ever exceed more than about 250 - 400 lines of text.
Dim UpdateUrl As String = GetUrl()
Dim client As New WebClient()
Using myStreamReader As New StreamReader(client.OpenRead($"{UpdateUrl}"))
While Not myStreamReader.EndOfStream
Dim line As String = myStreamReader.ReadLine
If line.Contains("=") Then
Dim p As String() = line.Split(New Char() {"="c})
If p(0).Contains("BugFix") Then
MessageBox.Show($" {p(1)}")
End If
End If
End While
End Using
Specifically I'm looking To collate the information about Features, BugFixes and Enhancements. Whilst I could construct what would in effect be a rather messy if statement I feel sure that there must be a more efficient way to do this , possibly involving linq. I'd welcome any suggestions.
I have added the wpf tag on the off chance that someone reading this with more experience of displaying information in wpf listboxes than I have might just spot a way to effectively define the info I'm after in such a way that it could then be easily displayed in a wpf list box in three sections (Features, Enhancements and BugFixes).
Dom, Here is an answer in C#. I will try to convert it to VB.Net momentarily. First, since the file is small, read all of it into a list of strings. Then select the strings that contain an "=" and parse them into data items that can be used. This code will return a set of data items that you can then display as you like. If you have LinqPad, you can test thecode below, or I have the code here: dotnetfiddle
Here is the VB.Net version: VB.Net dotnetfiddle
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Class Program
Public Sub Main()
Dim fileContent As List(Of String) = GetFileContent()
Dim dataItems = fileContent.Where(Function(c) c.Contains("=")).[Select](Function(c) GetDataItem(c))
dataItems.Dump()
End Sub
Public Function GetFileContent() As List(Of String)
Dim contentList As New List(Of String)()
contentList.Add("sb.app; aiu;")
contentList.Add("")
contentList.Add("[MyEditor45]")
contentList.Add("Name = MyEditor 4.5")
contentList.Add("URL = http://www.myeditor.com/download/myeditor.msi")
contentList.Add("Size = 3023788")
contentList.Add("Description = This is the latest version of MyEditor")
contentList.Add("Feature = Support for other file types")
contentList.Add("Feature1 = Support for different encodings")
contentList.Add("BugFix = Fix bug with file open")
contentList.Add("BugFix1 = Fix crash when opening large files")
contentList.Add("BugFix2 = Fix bug with search in file feature")
contentList.Add("FilePath = % ProgramFiles %\MyEditor\MyEditor.exe")
contentList.Add("Version = 4.5")
Return contentList
End Function
Public Function GetDataItem(value As String) As DataItem
Dim parts = value.Split("=", 2, StringSplitOptions.None)
Dim dataItem = New DataItem()
dataItem.DataType = parts(0).Trim()
dataItem.Data = parts(1).Trim()
Return dataItem
End Function
End Class
Public Class DataItem
Public DataType As String
Public Data As String
End Class
Or, in C#:
void Main()
{
List<string> fileContent = GetFileContent();
var dataItems = fileContent.Where(c => c.Contains("="))
.Select(c => GetDataItem(c));
dataItems.Dump();
}
public List<string> GetFileContent()
{
List<string> contentList = new List<string>();
contentList.Add("sb.app; aiu;");
contentList.Add("");
contentList.Add("[MyEditor45]");
contentList.Add("Name = MyEditor 4.5");
contentList.Add("URL = http://www.myeditor.com/download/myeditor.msi");
contentList.Add("Size = 3023788");
contentList.Add("Description = This is the latest version of MyEditor");
contentList.Add("Feature = Support for other file types");
contentList.Add("Feature1 = Support for different encodings");
contentList.Add("BugFix = Fix bug with file open");
contentList.Add("BugFix1 = Fix crash when opening large files");
contentList.Add("BugFix2 = Fix bug with search in file feature");
contentList.Add("FilePath = % ProgramFiles %\\MyEditor\\MyEditor.exe");
contentList.Add("Version = 4.5");
return contentList;
}
public DataItem GetDataItem(string value)
{
var parts = value.Split('=');
var dataItem = new DataItem()
{
DataType = parts[0],
Data = parts[1]
};
return dataItem;
}
public class DataItem
{
public string DataType;
public string Data;
}
The given answer only focuses on the first part, converting the data to a structure that can be shaped for display. But I think you main question is how to do the actual shaping.
I used a somewhat different way to collect the file data, using Microsoft.VisualBasic.FileIO.TextFieldParser because I think that makes coding just al little bit easier:
Iterator Function GetTwoItemLines(fileName As String, delimiter As String) _
As IEnumerable(Of Tuple(Of String, String))
Using tfp = New TextFieldParser(fileName)
tfp.TextFieldType = FieldType.Delimited
tfp.Delimiters = {delimiter}
tfp.HasFieldsEnclosedInQuotes = False
tfp.TrimWhiteSpace = False
While Not tfp.EndOfData
Dim arr = tfp.ReadFields()
If arr.Length >= 2 Then
Yield Tuple.Create(arr(0).Trim(), String.Join(delimiter, arr.Skip(1)).Trim())
End If
End While
End Using
End Function
Effectively the same thing happens as in your code, but taking into account Andrew's keen caution about data loss: a line is split by = characters, but the second field of a line consists of all parts after the first part with the delimiter re-inserted: String.Join(delimiter, arr.Skip(1)).Trim().
You can use this function as follows:
Dim fileContent = GetTwoItemLines(file, "=")
For display, I think the best approach (most efficient in terms of lines of code) is to group the lines by their first items, removing the numeric part at the end:
Dim grouping = fileContent.GroupBy(Function(c) c.Item1.TrimEnd("0123456789".ToCharArray())) _
.Where(Function(k) k.Key = "Feature" OrElse k.Key = "BugFix" OrElse k.Key = "Enhancement")
Here's a Linqpad dump (in which I took the liberty to change one item a bit to demonstrate the correct dealing with multiple = characters:
You could do it with Regular Expressions:
Imports System.Text.RegularExpressions
Private Function InfoReader(ByVal sourceText As String) As List(Of Dictionary(Of String, String()))
'1) make array of fragments for each product info
Dim products = Regex.Split(sourceText, "(?=\[\s*\w+\s*])")
'2) declare variables needed ahead
Dim productProperties As Dictionary(Of String, String)
Dim propertyNames As String()
Dim productGroupedProperties As Dictionary(Of String, String())
Dim result As New List(Of Dictionary(Of String, String()))
'2) iterate along fragments
For Each product In products
'3) work only in significant fragments ([Product]...)
If Regex.IsMatch(product, "\A\[\s*\w+\s*]") Then
'4) make array of property lines and extract dictionary of property/description
productProperties = Regex.Split(product, "(?=^\w+\s*=)", RegexOptions.Multiline).Where(
Function(s) s.Contains("="c)
).ToDictionary(
Function(s) Regex.Match(s, "^\w+(?=\s*=)").Value,
Function(s) Regex.Match(s, "(?<==\s+).*(?=\s+)").Value)
'5) extract distinct property names, ignoring numbered repetitions
propertyNames = productProperties.Keys.Select(Function(s) s.TrimEnd("0123456789".ToCharArray)).Distinct.ToArray
'6) make dictionary of distinctProperty/Array(Of String){description, description1, ...}
productGroupedProperties = propertyNames.ToDictionary(
Function(s) s,
Function(s) productProperties.Where(
Function(kvp) kvp.Key.StartsWith(s)
).Select(
Function(kvp) kvp.Value).ToArray)
'7) enlist dictionary to result
result.Add(productGroupedProperties)
End If
Next
Return result
End Function

my combo box is duplicating the strings

help, combobox just keep adding items, i tried using removeallitems but after that i cant put anything on the first combobox
public class Function {
public void combofillsect(JComboBox section, String year){
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String query;
try{
query = "Select Section from asd where Year=?";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
pst = conn.prepareStatement(query);
pst.setString(1, year);
rs = pst.executeQuery();
while(rs.next()){
section.addItem(rs.getString("Section"));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
section.addItem(e.toString());
};
}
Function funct= new Function();
{funct.combofillsect(jComboBox1,String.valueOf(jComboBox2.getSelectedItem())); }
why cant I post image?
Are you programming in C# ? If it's the case then you can use the function Clear like that : yourComboBox.Items.Clear() to delete all the current items. I don't know if it will solve your problem but your technique of getting the data from your database seems weird to me, if you used a dataset you could have done dataset.Tables(0).Rows.Count() to get the number of entries and then set the exit condition of your loop like this -> counter < dataset.Tables(0).Rows.Count(), and set a counter++ at the end of your while (maybe that's why you say your combobox won't stop filling, but I don't know what do the next() function).
I don't know the C# code but there is my VB.NET function :
Public Function getAll() As DataSet
ConnectionDB()
Dim cmd As SqlClient.SqlCommand
cmd = New SqlClient.SqlCommand("SELECT * FROM table", Connect)//Connect is a System.Data.SqlClient.SqlConnection, or my connection string
Dim adapter As New Data.SqlClient.SqlDataAdapter
Dim dataset As New DataSet
adapter.SelectCommand = cmd
adapter.Fill(dataset)
adapter.Dispose()
cmd.Dispose()
Connect.Close()
Return dataset
End Function
I don't know if I helped you but I didn't really understood what your problem was and you didn't even mentioned the language you use ^^ Good luck
Edit : and if you can't post images, that's because you don't have yet 10 points of reputation, you can get informations about reputation here : https://stackoverflow.com/help/whats-reputation, but you still can post the link of a picture it will allow users to click on it

Object reference not set to an instance of an object during xml serialization and problem with selection of combobox item upon loading

question 1. I have this issue of "Object reference not set to an instance of an object" when my Majorlabel is empty and this occurs after i try to do a save button click on xml serialization. How can i fix this?
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string savepath;
SaveFileDialog DialogSave = new SaveFileDialog();
// Default file extension
DialogSave.DefaultExt = "txt";
// Available file extensions
DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
// Adds a extension if the user does not
DialogSave.AddExtension = true;
// Restores the selected directory, next time
DialogSave.RestoreDirectory = true;
// Dialog title
DialogSave.Title = "Where do you want to save the file?";
// Startup directory
DialogSave.InitialDirectory = #"C:/";
DialogSave.ShowDialog();
savepath = DialogSave.FileName;
DialogSave.Dispose();
DialogSave = null;
FormSaving abc = new FormSaving();
if (!string.IsNullOrEmpty(MajorversionresultLabel.Content.ToString()))
{
abc.Majorversion = MajorversionresultLabel.Content.ToString();
}
abc.Startzbuildfrom = StartzbuildcomboBox.SelectedItem.ToString();
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, abc);
}
}
As recommended,
here is the line of error:
if (!string.IsNullOrEmpty(MajorversionresultLabel.Content.ToString()))
{
abc.Majorversion = MajorversionresultLabel.Content.ToString();
}
Question 2. I used this line to save my combo box selection:
abc.Startzbuildfrom = StartzbuildcomboBox.SelectedItem.ToString();
and in my load i have this line:
StartzbuildcomboBox.SelectedItem = abc.Startzbuildfrom
why wont it select the combobox selection previously?
As a first note, I'd recommend only putting one question into a single query here. Makes it easier.
For your second question, my guess is that you're running into a reference variable problem. I think that calling the ToString() method on the SelectedItem actually creates an entirely new string variable. Then, when you try to set the selected item later, it can't find the new string as a possible item to select because, even though the two strings have the same value, they are different objects. I would maybe recommend that you either:
1) Set the selected item by searching through your combo box contents to find a string whose value matches the one you've saved
or
2) Save the actual reference by saying abc.Startzbuildfrom = StartzbuildcomboBox.SelectedItem. Then set the selected item from that reference.
I suspect that MajorversionresultLabel is null, or MajorversionresultLabel.Content is null. Thus your statement
if (!string.IsNullOrEmpty(MajorversionresultLabel.Content.ToString()))
will throw a NullReferenceException. Try this instead:
if (MajorversionresultLabel != null && MajorversionresultLabel.Content != null && MajorversionLabel.Content.ToString() != string.Empty)
I bet your NullReferenceException will go away.

Resources