Как реализовать просмотр списка файловых вложений для SCSM 2012 R2
Я здесь новичок, и поэтому мой вопрос может быть не таким ясным, как вы привыкли. Тем не менее, я надеюсь, что вы сможете дать мне подсказку для решения моей проблемы. В настоящее время я разрабатываю настраиваемую форму запроса на изменение для System Center Service Manager 2012 R2 с UR 7 с использованием Visual Studio 2013 с авторскими расширениями. Эта форма основана на пользовательском элементе управления WPF (Visual C#) с.Net-FrameWork 3.5. Моя цель - создать представление списка, в которое я хочу добавить с помощью кнопки добавления более одного вложения в этот вид. Код выглядит так:
Типовая проекция в пакете панажинга:
<TypeProjection ID="TypeProjection.RFCMinor" Accessibility="Public" Type="RFC.Minor.RFCMinor">
<Component Path="$Target/Path[Relationship='WorkItem!System.WorkItemHasFileAttachment']$" Alias="FileAttachments">
<Component Path="$Target/Path[Relationship='SupportingItem!System.FileAttachmentAddedByUser']$" Alias="FileAttachmentAddedBy" />
</Component>
</TypeProjection>
Элемент представления списка в xaml-Code:
<ListView x:Name="lvAttachedRiskRelFiles" MinHeight="70" ItemsSource="{Binding Path=FileAttachments, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
MouseDoubleClick="lvAttachedRiskRelFiles_MouseDoubleClick">
<ListView.View>
<GridView>
<scwpf:SortableGridViewColumn Header="File Name" DisplayMemberBinding="{Binding FileName}" Width="Auto"/>
<scwpf:SortableGridViewColumn Header="Attached By" DisplayMemberBinding="{Binding AttachedBy}" Width="Auto"/>
<scwpf:SortableGridViewColumn Header="File Size (KB)" DisplayMemberBinding="{Binding FileSize}" Width="Auto"/>
<scwpf:SortableGridViewColumn Header="Attached Date" DisplayMemberBinding="{Binding AttachedDate}" Width="Auto"/>
</GridView>
</ListView.View>
<Button Content="Add" Name="btnAddRiskFile" Click="btnAddRiskFile_Click"/>
C#-Code в настоящее время выглядит так:
private void btnAddRiskFile_Click(object sender, System.Windows.RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name
if (result == true)
{
// Open document
string filename = dlg.FileName;
AddFileToListView(filename);
}
}
internal void AddFileToListView(String sFile)
{
//emg: current EnterpriseManagementGroup
//System.SupportingItem.Library; ManagementPack ID: 23e3ae8e-1981-8560-2e55-8730cbc04965
ManagementPack mpSupporting =
emg.ManagementPacks.GetManagementPack(new Guid("23e3ae8e-1981-8560-2e55-8730cbc04965"));
//Get the System.FileAttachment class
ManagementPackClass mpcAttachment = emg.EntityTypes.GetClass("System.FileAttachment", mpSupporting);
//Get attachment details
string sExt = Path.GetExtension(sFile);
string sAttachmentName = Path.GetFileNameWithoutExtension(sFile);
//Create new stream and read file into memory
MemoryStream ms = new MemoryStream();
using (FileStream fs = File.OpenRead(sFile))
{
ms.SetLength(fs.Length);
fs.Read(ms.GetBuffer(), 0, (int)fs.Length);
}
//Did we get any data?
if (ms != null && ms.Length != 0)
{
//Reset stream position
ms.Position = 0;
//Create a new attachment
CreatableEnterpriseManagementObject cemoAttachment = new CreatableEnterpriseManagementObject(emg, mpcAttachment);
//Create a new attachment relationship from SupportingItem -> File Attachment (via "HasFileAttachment: ID =aa8c26dc-3a12-5f88-d9c7-753e5a8a55b4)
//DisplayName : Has File Attachment
//Source : System.WorkItem
//Target : System.FileAttachment
ManagementPackRelationship relAttachment =
emg.EntityTypes.GetRelationshipClass(new Guid("aa8c26dc-3a12-5f88-d9c7-753e5a8a55b4"));
CreatableEnterpriseManagementRelationshipObject cemroAttachment =
new CreatableEnterpriseManagementRelationshipObject(emg, relAttachment);
//Create a new added by user relationship
// ID: ffd71f9e-7346-d12b-85d6-7c39f507b7bb
// DisplayName : Added By User
//Source : System.FileAttachment
//Target : System.User
ManagementPackRelationship relAddedByUser =
emg.EntityTypes.GetRelationshipClass(new Guid("ffd71f9e-7346-d12b-85d6-7c39f507b7bb"));
CreatableEnterpriseManagementRelationshipObject cemroAddedByUser =
new CreatableEnterpriseManagementRelationshipObject(emg, relAddedByUser);
//Set properties of attachment
string sFileName = sAttachmentName;
if (sExt != "") sFileName += "." + sExt;
cemoAttachment[mpcAttachment, "AddedDate"].Value = DateTime.UtcNow;
cemoAttachment[mpcAttachment, "DisplayName"].Value = sFileName;
cemoAttachment[mpcAttachment, "Extension"].Value = sExt;
cemoAttachment[mpcAttachment, "Content"].Value = ms;
cemoAttachment[mpcAttachment, "Size"].Value = ms.Length;
cemoAttachment[mpcAttachment, "Description"].Value = sFileName;
cemoAttachment[mpcAttachment, "Id"].Value = Guid.NewGuid().ToString();
//Set the source and target for the attachment and save (this must be done first)
cemroAttachment.SetSource(emoWorkItem); //Here I do not know how to get the current WorkItem?
cemroAttachment.SetTarget(cemoAttachment);
cemroAttachment.Commit();
//Set the added by user relationship (this must done after the previous relationship)
cemroAddedByUser.SetSource(cemoAttachment);
cemroAddedByUser.SetTarget(emoUser); //Here I do not know how to get the current User?
cemroAddedByUser.Commit();
}
}
C#-Code для процесса прикрепления изначально с этой веб-страницы. Моя проблема в том, что я не знаю, как объявить текущего пользователя и текущий рабочий элемент для отношений. Когда я нажимаю кнопку добавления, диалоговое окно файла закрывается и ничего не появляется. Я думал, что эта проблема вызвана отсутствующей ссылкой на отношения.
У кого-нибудь из вас есть идея, с чего начать исправление этой проблемы? Кроме того, у вас есть идея, что я мог бы сделать, чтобы это исправить?
С наилучшими пожеланиями и спасибо заранее.
1 ответ
Для тех, кто столкнется с той же проблемой: решение было довольно легко найти:
IDataItem idiParentWorkItem = this.DataContext as IDataItem;
EnterpriseManagementObject emoWorkItem = emg.EntityObjects.GetObject<EnterpriseManagementObject>((Guid)idiParentWorkItem["$Id$"], ObjectQueryOptions.Default);
EnterpriseManagementObject emoUser = emg.EntityObjects.GetObject<EnterpriseManagementObject>((Guid)ConsoleContextHelper.Instance.CurrentUser["$Id$"], ObjectQueryOptions.Default);
Кроме того, я искал неправильные привязки пользователей, которые я хотел показать. Поэтому мне нужно было изменить привязку члена.
В целом код, который работает для меня, выглядит так:
C#:
internal void AddFileToListView(String sFile)
{
IDataItem idiParentWorkItem = this.DataContext as IDataItem;
EnterpriseManagementObject emoWorkItem = emg.EntityObjects.GetObject<EnterpriseManagementObject>((Guid)idiParentWorkItem["$Id$"], ObjectQueryOptions.Default);
EnterpriseManagementObject emoUser = emg.EntityObjects.GetObject<EnterpriseManagementObject>((Guid)ConsoleContextHelper.Instance.CurrentUser["$Id$"], ObjectQueryOptions.Default);
//System.SupportingItem.Library; ManagementPack ID: 23e3ae8e-1981-8560-2e55-8730cbc04965
ManagementPack mpSupporting =
emg.ManagementPacks.GetManagementPack(new Guid("23e3ae8e-1981-8560-2e55-8730cbc04965"));
//Get the System.FileAttachment class
ManagementPackClass mpcAttachment = emg.EntityTypes.GetClass("System.FileAttachment", mpSupporting);
//Get attachment details
string sExt = Path.GetExtension(sFile);
string sAttachmentName = Path.GetFileNameWithoutExtension(sFile);
//Create new stream and read file into memory
MemoryStream ms = new MemoryStream();
using (FileStream fs = File.OpenRead(sFile))
{
ms.SetLength(fs.Length);
fs.Read(ms.GetBuffer(), 0, (int)fs.Length);
}
//Did we get any data?
if (ms != null && ms.Length != 0)
{
//Reset stream position
ms.Position = 0;
//Create a new attachment
CreatableEnterpriseManagementObject cemoAttachment = new CreatableEnterpriseManagementObject(emg, mpcAttachment);
//Create a new attachment relationship from SupportingItem -> File Attachment (via "HasFileAttachment: ID =aa8c26dc-3a12-5f88-d9c7-753e5a8a55b4)
//DisplayName : Has File Attachment
//Source : System.WorkItem
//Target : System.FileAttachment
ManagementPackRelationship relAttachment =
emg.EntityTypes.GetRelationshipClass(new Guid("aa8c26dc-3a12-5f88-d9c7-753e5a8a55b4"));
CreatableEnterpriseManagementRelationshipObject cemroAttachment =
new CreatableEnterpriseManagementRelationshipObject(emg, relAttachment);
//Create a new added by user relationship
// ID: ffd71f9e-7346-d12b-85d6-7c39f507b7bb
// DisplayName : Added By User
//Source : System.FileAttachment
//Target : System.User
ManagementPackRelationship relAddedByUser =
emg.EntityTypes.GetRelationshipClass(new Guid("ffd71f9e-7346-d12b-85d6-7c39f507b7bb"));
CreatableEnterpriseManagementRelationshipObject cemroAddedByUser =
new CreatableEnterpriseManagementRelationshipObject(emg, relAddedByUser);
//Set properties of attachment
string sFileName = sAttachmentName;
if (sExt != "") sFileName += sExt;
cemoAttachment[mpcAttachment, "AddedDate"].Value = DateTime.UtcNow;
cemoAttachment[mpcAttachment, "DisplayName"].Value = sFileName;
cemoAttachment[mpcAttachment, "Extension"].Value = sExt;
cemoAttachment[mpcAttachment, "Content"].Value = ms;
cemoAttachment[mpcAttachment, "Size"].Value = ms.Length;
cemoAttachment[mpcAttachment, "Description"].Value = sFileName;
cemoAttachment[mpcAttachment, "Id"].Value = Guid.NewGuid().ToString();
//Set the source and target for the attachment and save (this must be done first)
cemroAttachment.SetSource(emoWorkItem);
cemroAttachment.SetTarget(cemoAttachment);
////Set the added by user relationship (this must done after the previous relationship)
cemroAddedByUser.SetSource(cemoAttachment);
cemroAddedByUser.SetTarget(emoUser);
cemroAttachment.Commit();
cemroAddedByUser.Commit();
EnterpriseManagementObjectDataType emoDataType = new EnterpriseManagementObjectDataType(mpcAttachment);
IDataItem item = emoDataType.CreateProxyInstance(cemoAttachment);
Collection<IDataItem> items = lvAttachedRiskRelFiles.ItemsSource as Collection<IDataItem>;
if (!items.Contains(item))
items.Add(item);
}
}
XAML:
<ListView x:Name="lvAttachedRiskRelFiles" ItemsSource="{Binding Path=FileAttachments, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
MouseDoubleClick="lvAttachedRiskRelFiles_MouseDoubleClick">
<ListView.View>
<GridView>
<scwpf:SortableGridViewColumn Header="Display Name" DisplayMemberBinding="{Binding DisplayName}" Width="Auto"/>
<scwpf:SortableGridViewColumn DisplayMemberBinding="{Binding FileAttachmentAddedBy.DisplayName}" Width="Auto" Header="Added By"/>
<scwpf:SortableGridViewColumn DisplayMemberBinding="{Binding Size}" Width="Auto" Header="Size" />
<scwpf:SortableGridViewColumn DisplayMemberBinding="{Binding AddedDate}" Width="Auto" Header="Added Date"/>
</GridView>
</ListView.View>
</ListView>