1467 lines
52 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Provider;
using Intel.Management.Wsman;
using Microsoft.PowerShell.Commands;
namespace Intel.Management.PSModule.Amt
{
class StorageManager : DriveContainer
{
// private data
IManagedReference _storageRef;
string SessionHandle;
uint AppHandle;
static uint _retryThreshold = 5;
Session SessionItem;
Application[] Apps;
string Enterprise;
static string[] _propNames = { "Mtu", "WriteEraseLimit", "RegistrationTimeout", "LockTimeout", "RetryThreshold" };
public StorageManager(DriveItem parent)
: base("3PDStorage",parent)
{
IWsmanConnection conn = ((AmtRootService)GetRoot()).Connection;
_storageRef = conn.NewReference("AMT_ThirdPartyDataStorageService");
AppHandle = uint.MaxValue;
}
public override string[] Properties
{
get { return _propNames; }
}
public override DriveItem NewItem(string name, string type, object newItem, DriveProvider provider)
{
SessionDynamicParameters sessionParams = provider.GetDynamicParameters() as SessionDynamicParameters;
StorageManager stgManager = new StorageManager(this);
string vendorName, applicationName, enterpriseName;
GetStorageParamaters(sessionParams.StoragePath,
out vendorName, out applicationName, out enterpriseName);
stgManager.Enterprise = enterpriseName;
stgManager.RegisterApplication(sessionParams.UUID,
vendorName,
applicationName,
enterpriseName);
List<DriveItem> list = new List<DriveItem>(_items);
DriveItem itemToAdd = new Session(stgManager,name,this);
list.Add(itemToAdd);
_items = list.ToArray();
stgManager.SessionItem = itemToAdd as Session;
return (DriveItem)itemToAdd;
}
public override object NewItemDynamicParameters(string itemTypeName, object newItemValue)
{
return new SessionDynamicParameters();
}
public void GetStorageParamaters(string path,out string vendor, out string appName, out string entName)
{
vendor = string.Empty;
appName = string.Empty;
entName = string.Empty;
string pathPart=string.Empty;
char[] pathSplits = { '\\', '/' };
string[] pathItems = path.Split(pathSplits,StringSplitOptions.RemoveEmptyEntries);
// /\ :*?" <> |
if (pathItems.Length == 1)
{
appName = pathItems[0];
}
else if (pathItems.Length == 2)
{
vendor = pathItems[0];
appName = pathItems[1];
}
else if (pathItems.Length > 2)
{
entName = pathItems[0];
vendor = pathItems[1];
appName = pathItems[2];
}
}
public uint Mtu
{
get { return GetMtu(); }
}
public uint WriteEraseLimit
{
get { return GetWriteEraseLimit(); }
}
public uint LockTimeout
{
get
{
uint lockTime, regTime;
GetTimeoutValues(out regTime, out lockTime);
return lockTime;
}
}
public uint RegistrationTimeout
{
get
{
uint lockTime, regTime;
GetTimeoutValues(out regTime, out lockTime);
return regTime;
}
}
public uint RetryThreshold
{
get { return _retryThreshold; }
set { _retryThreshold =value; }
}
/* // copy constuctor
public StorageManager(StorageManager stgManager)
{
_storageRef = stgManager._storageRef;
AppHandle = stgManager.AppHandle;
SessionHandle = stgManager.SessionHandle;
RootContainer = stgManager.RootContainer;
SessionItem = stgManager.SessionItem;
Apps = stgManager.Apps;
Enterprise = stgManager.Enterprise;
}*/
class Application
{
uint _handle;
string _vendor;
string _name;
public Application(uint handle, string vendor, string name)
{
_handle = handle;
_vendor = vendor;
_name = name;
}
public uint Handle
{
get { return _handle; }
}
public string Name
{
get { return _name; }
}
public string VendorName
{
get { return _vendor; }
}
}
class SessionDynamicParameters
{
public SessionDynamicParameters()
{
_uuid = Guid.Empty;
}
[Parameter(Mandatory = true, Position = 0, HelpMessage = "The StoragePath in 'Enterprise:\\Vendor\\Application' format")]
public string StoragePath
{
get { return _storagePath; }
set { _storagePath = value; }
}
[Parameter(Mandatory = false, Position = 3, HelpMessage = "UUID of the comupter accessing storage")]
public Guid UUID
{
get { return _uuid; }
set { _uuid = value; }
}
string _storagePath;
Guid _uuid;
}
class GetContentDynamicParameters
{
public GetContentDynamicParameters()
{
_encoding = Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.String;
_blockHandle = uint.MaxValue;
_blockName = string.Empty;
_delimeter = Environment.NewLine;
_storagePath=string.Empty;
}
[Parameter(Mandatory = false, HelpMessage = "The handle to a storage Block")]
public uint BlockHandle
{
get { return _blockHandle; }
set { _blockHandle = value; }
}
[Parameter(Mandatory = false, HelpMessage = "The name of a storage block")]
public string BlockName
{
get { return _blockName; }
set { _blockName = value; }
}
[Parameter(Mandatory = false, HelpMessage = "The application block to read from")]
public string Delimiter
{
get { return _delimeter; }
set { _delimeter = value; }
}
[Parameter(Mandatory = false, HelpMessage = "The vendor block to read from")]
public string StoragePath
{
get { return _storagePath; }
set { _storagePath = value; }
}
[Parameter(Mandatory = false, HelpMessage = "Encoding type of the content")]
public Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding Encoding
{
get { return _encoding; }
set { _encoding = value; }
}
FileSystemCmdletProviderEncoding _encoding;
uint _blockHandle;
string _blockName;
string _storagePath;
string _delimeter;
}
class SetContentDynamicParameters
{
public SetContentDynamicParameters()
{
_encoding = Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.Unknown;
_allocationSize = 0;
_blockHandle = uint.MaxValue;
_blockName = string.Empty;
_delimeter = Environment.NewLine;
_storagePath = string.Empty;
}
[Parameter(Mandatory = false, HelpMessage = "The handle to a pre existing Block")]
public uint BlockHandle
{
get { return _blockHandle; }
set { _blockHandle = value; }
}
[Parameter(Mandatory = false, HelpMessage = "The name of the block")]
public string BlockName
{
get { return _blockName; }
set { _blockName = value; }
}
[Parameter(Mandatory = false, HelpMessage = "The vendor to read from")]
public string StoragePath
{
get { return _storagePath; }
set { _storagePath = value; }
}
[Parameter(Mandatory = false, HelpMessage = "Encoding type of the content")]
public Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding Encoding
{
get { return _encoding; }
set { _encoding = value; }
}
[Parameter(Mandatory = false, HelpMessage = "The Allocation size of a new partition block")]
public uint AllocationSize
{
get
{ return _allocationSize;
}
set
{
_allocationSize = GetAllocationSize(value);
}
}
[Parameter(Mandatory = false, HelpMessage = "The application block to read from")]
public string Delimiter
{
get { return _delimeter; }
set { _delimeter = value; }
}
FileSystemCmdletProviderEncoding _encoding;
uint _blockHandle;
string _delimeter;
string _blockName;
string _storagePath;
uint _allocationSize;
}
/*
class ClearContentDynamicParameters
{
public ClearContentDynamicParameters()
{
}
[Parameter(Mandatory = false, HelpMessage = "The handle to a pre existing Block")]
public uint BlockHandle
{
get { return _blockHandle; }
set { _blockHandle = value; }
}
[Parameter(Mandatory = false, HelpMessage = "The name of the block to clear")]
public string BlockName
{
get { return _blockName; }
set { _blockName = value; }
}
[Parameter(Mandatory = false, HelpMessage = "The application that owns the block")]
public string ApplicationName
{
get { return _appName; }
set { _appName = value; }
}
[Parameter(Mandatory = false, HelpMessage = "The vendor that owns the block")]
public string VendorName
{
get { return _vendorName; }
set { _vendorName = value; }
}
uint _blockHandle;
string _blockName;
string _appName;
string _vendorName;
}*/
class StorageBlock {
StorageManager _stgManager;
uint _handle;
uint _size;
uint _owner;
bool _hidden;
string _blockName;
public StorageBlock( StorageManager stgManager,
uint handle,uint size, bool hidden, string blockName, uint owner)
{
_stgManager = stgManager;
_handle = handle;
_size = size;
_hidden = hidden;
_blockName = blockName;
_owner = owner;
}
public void Remove()
{
IManagedInstance outObj= _stgManager.DeallocateBlock(Handle);
if (outObj.GetProperty("ReturnValue").Equals("0"))
{
_stgManager.SessionItem.DeAllocateBlock(this);
}
}
public uint Handle
{
get { return _handle; }
}
public string BlockName
{
get { return _blockName; }
}
public uint BlockSize
{
get { return _size; }
}
public uint Owner
{
get { return _owner; }
}
public string StoragePath
{
get
{
StringBuilder builder = new StringBuilder();
string appName, vendorName;
_stgManager.GetApplicationAttributes(
_stgManager.GetCurrentApplicationHandle(),
out appName, out vendorName);
builder.Append(".\\");
builder.Append(EncodeName(vendorName));
builder.Append("\\");
builder.Append(EncodeName(appName));
return builder.ToString();
}
}
public override string ToString()
{
if (string.IsNullOrEmpty(_blockName))
return _handle.ToString();
return _blockName;
}
}
class BlockReader : IContentReader
{
StorageManager _stgManager;
MemoryStream _stream;
GetContentDynamicParameters _params;
string[] _stringLines;
int _lineIndex;
string _vendorBlock;
string _applicationBlock;
public BlockReader(StorageManager stgManager,GetContentDynamicParameters dynamicParams)
{
_stgManager = stgManager;
_params = dynamicParams;
string entName;
stgManager.GetStorageParamaters(_params.StoragePath,
out entName, out _vendorBlock, out _applicationBlock);
Application curApp = _stgManager.SessionItem.GetCurrentStorageApplication();
if (_vendorBlock.Equals(string.Empty)) _vendorBlock = curApp.VendorName;
if (_applicationBlock.Equals(string.Empty)) _applicationBlock = curApp.Name;
}
private int GetWideNullTerminatorLength()
{
int i;
int hitCount = 0;
byte[] data = _stream.GetBuffer();
for (i = 0; i < _stream.Length; i++)
{
if (data[i] == 0)
hitCount++;
else
hitCount = 0;
if (hitCount > 1)
{
break;
}
}
if (hitCount < 2) hitCount = 0;
return i-hitCount;
}
private int GetNullTerminatorLength()
{
int i;
int hitCount = 0;
byte[] data = _stream.GetBuffer();
for (i = 0; i < _stream.Length; i++)
{
if (data[i] == 0)
hitCount++;
else
hitCount = 0;
if (hitCount > 0)
break;
}
return i-hitCount;
}
private void SplitLines(long lines, string data, System.Collections.IList content)
{
long hitCount=lines;
if (lines>0)
{
_stringLines = data.Split(_params.Delimiter.ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
List<string> stringList = new List<string>();
}
else
{
content.Add(new PSObject(data));
}
}
private void EncodeContent(long lines, System.Collections.IList content)
{
byte[] data = null;
int bytesRead = 0;
switch (_params.Encoding)
{
case FileSystemCmdletProviderEncoding.Byte:
case FileSystemCmdletProviderEncoding.Unknown:
/*data = new byte[_stream.Length];
bytesRead = _stream.Read(data, 0, data.Length);
if (bytesRead > 0)
content.Add(data);*/
break;
case FileSystemCmdletProviderEncoding.UTF8:
data = new byte[GetNullTerminatorLength()];
bytesRead = _stream.Read(data, 0, data.Length);
if (bytesRead > 0)
{
string result = Encoding.UTF8.GetString(data, 0, bytesRead);
SplitLines(lines, result, content);
}
break;
case FileSystemCmdletProviderEncoding.Ascii:
data = new byte[GetNullTerminatorLength()];
bytesRead = _stream.Read(data, 0, data.Length);
if (bytesRead > 0)
{
string result = Encoding.ASCII.GetString(data, 0, bytesRead);
SplitLines(lines, result, content);
}
break;
case FileSystemCmdletProviderEncoding.UTF7:
data = new byte[GetNullTerminatorLength()];
bytesRead = _stream.Read(data, 0, data.Length);
if (bytesRead > 0)
{
string result = Encoding.UTF7.GetString(data, 0, bytesRead);
SplitLines(lines, result, content);
}
break;
case FileSystemCmdletProviderEncoding.BigEndianUnicode:
data = new byte[GetWideNullTerminatorLength()];
bytesRead = _stream.Read(data, 0, data.Length);
if (bytesRead > 0)
{
string result = Encoding.BigEndianUnicode.GetString(data, 0, bytesRead);
SplitLines(lines, result, content);
}
break;
case FileSystemCmdletProviderEncoding.Unicode:
case FileSystemCmdletProviderEncoding.String:
data = new byte[GetWideNullTerminatorLength()];
bytesRead = _stream.Read(data, 0, data.Length);
if (bytesRead > 0)
{
string result = Encoding.Unicode.GetString(data, 0, bytesRead);
SplitLines(lines, result, content);
}
break;
}
}
public void Dispose()
{
}
public void Close()
{
if (_stream != null)
_stream.Close();
_stream = null;
}
public void Seek(long offset, System.IO.SeekOrigin origin)
{
}
public System.Collections.IList Read(long size)
{
System.Collections.IList list = new System.Collections.ArrayList();
if (_stream == null)
{
_stream = new MemoryStream();
uint blockHandle = uint.MaxValue;//_params.BlockHandle;
uint blockSize = 4096;
// find a block by name
if (blockHandle == uint.MaxValue)
{
StorageBlock item = _stgManager.SessionItem.FindBlock(
_params.BlockName, _applicationBlock, _vendorBlock);
blockHandle = item.Handle;
blockSize = item.BlockSize;
}
else
{
StorageBlock item = _stgManager.SessionItem.FindBlock(blockHandle);
blockSize = item.BlockSize;
}
_stgManager.LockBlock(blockHandle);
try
{
uint offset = 0;
bool reading = true;
while (reading)
{
IManagedInstance outObj = _stgManager.ReadBlock(blockHandle, offset, 4096);
byte[] data = new byte[0];
string dataString = outObj.GetProperty("Data").ToString();
if (!dataString.Equals(string.Empty))
data = Convert.FromBase64String(dataString);
_stream.Write(data, 0, data.Length);
offset += (uint)data.Length;
if (offset >= blockSize)
reading = false;
}
}
finally
{
_stgManager.UnlockBlock(blockHandle);
}
_stream.Seek(0, SeekOrigin.Begin);
EncodeContent(size,list);
}
if (_stringLines != null)
{
if (_lineIndex < _stringLines.Length)
list.Add(new PSObject(_stringLines[_lineIndex]));
}
else
{
if (_lineIndex < _stream.Length)
list.Add(new PSObject(_stream.GetBuffer()[_lineIndex]));
}
_lineIndex++;
return list;
}
}
class BlockWriter : IContentWriter
{
StorageManager _stgManager;
SetContentDynamicParameters _params;
MemoryStream _stream;
string _vendorBlock;
string _applicationBlock;
public BlockWriter(StorageManager stgManager,SetContentDynamicParameters dynamicParams)
{
_stgManager = stgManager;
_params = dynamicParams;
string entName;
stgManager.GetStorageParamaters(_params.StoragePath,
out entName, out _vendorBlock, out _applicationBlock);
Application curApp = _stgManager.SessionItem.GetCurrentStorageApplication();
if (_vendorBlock.Equals(string.Empty)) _vendorBlock = curApp.VendorName;
if (_applicationBlock.Equals(string.Empty)) _applicationBlock = curApp.Name;
}
private Stream GetEncodedContent(System.Collections.IList content)
{
_stream = new MemoryStream();
byte[] newLineData = null;
if (_params.Encoding == FileSystemCmdletProviderEncoding.Unknown)
{
//detect the content type
foreach (Object item in content)
{
if (item is PSObject)
{
if (PSObject.AsPSObject(item).BaseObject is string)
{
_params.Encoding = FileSystemCmdletProviderEncoding.String;
break;
}
}
else if (item is string)
{
_params.Encoding = FileSystemCmdletProviderEncoding.String;
break;
}
}
}
switch (_params.Encoding)
{
case FileSystemCmdletProviderEncoding.Byte:
case FileSystemCmdletProviderEncoding.Unknown:
foreach (byte item in content)
_stream.WriteByte(item);
break;
case FileSystemCmdletProviderEncoding.UTF8:
newLineData = Encoding.UTF8.GetBytes(_params.Delimiter);
foreach (PSObject item in content)
{
byte[] itemData = Encoding.UTF8.GetBytes(item.BaseObject.ToString());
_stream.Write(itemData, 0, itemData.Length);
_stream.Write(newLineData, 0, newLineData.Length);
}
_stream.WriteByte(0);
break;
case FileSystemCmdletProviderEncoding.Ascii:
newLineData = Encoding.ASCII.GetBytes(_params.Delimiter);
foreach (PSObject item in content)
{
byte[] itemData = Encoding.ASCII.GetBytes(item.BaseObject.ToString());
_stream.Write(itemData, 0, itemData.Length);
_stream.Write(newLineData,0,newLineData.Length);
}
_stream.WriteByte(0);
break;
case FileSystemCmdletProviderEncoding.UTF7:
newLineData = Encoding.UTF7.GetBytes(_params.Delimiter);
foreach (PSObject item in content)
{
byte[] itemData = Encoding.UTF7.GetBytes(item.BaseObject.ToString());
_stream.Write(itemData, 0, itemData.Length);
_stream.Write(newLineData, 0, newLineData.Length);
}
_stream.WriteByte(0);
break;
case FileSystemCmdletProviderEncoding.BigEndianUnicode:
newLineData = Encoding.BigEndianUnicode.GetBytes(_params.Delimiter);
foreach (PSObject item in content)
{
byte[] itemData = Encoding.BigEndianUnicode.GetBytes(item.BaseObject.ToString());
_stream.Write(itemData, 0, itemData.Length);
_stream.Write(newLineData, 0, newLineData.Length);
}
_stream.WriteByte(0);
_stream.WriteByte(0);
break;
case FileSystemCmdletProviderEncoding.String:
newLineData = Encoding.Unicode.GetBytes(_params.Delimiter);
foreach (string item in content)
{
byte[] itemData = Encoding.Unicode.GetBytes(item);
_stream.Write(itemData, 0, itemData.Length);
_stream.Write(newLineData, 0, newLineData.Length);
}
_stream.WriteByte(0);
_stream.WriteByte(0);
break;
case FileSystemCmdletProviderEncoding.Unicode:
newLineData = Encoding.Unicode.GetBytes(_params.Delimiter);
foreach (PSObject item in content)
{
byte[] itemData = Encoding.Unicode.GetBytes(item.BaseObject.ToString());
_stream.Write(itemData, 0, itemData.Length);
_stream.Write(newLineData, 0, newLineData.Length);
}
_stream.WriteByte(0);
_stream.WriteByte(0);
break;
}
_stream.Seek(0, SeekOrigin.Begin);
return _stream;
}
public void Dispose()
{
}
public void Close()
{
if (_stream != null)
_stream.Close();
}
public void Seek(long offset, System.IO.SeekOrigin origin)
{
}
public System.Collections.IList Write(System.Collections.IList content)
{
uint blockHandle = _params.BlockHandle;
// find a block by name
if (blockHandle == uint.MaxValue)
{
StorageBlock item = _stgManager.SessionItem.FindBlock(
_params.BlockName,_applicationBlock,_vendorBlock);
if (item != null)
blockHandle = item.Handle;
}
Stream stream=GetEncodedContent(content);
uint blocksize = _params.AllocationSize;
if (blocksize < stream.Length)
{
blocksize = StorageManager.GetAllocationSize((uint)stream.Length);
}
//if we don't have a block handle create one
if (blockHandle == uint.MaxValue)
{
StorageBlock item =_stgManager.SessionItem.AllocateBlock(_params.BlockName, blocksize);
blockHandle = item.Handle;
}
_stgManager.LockBlock(blockHandle);
try
{
uint offset = 0;
bool writing = stream.Length>0;
byte[] data = new byte[4096];
while (writing)
{
int br = stream.Read(data, 0, data.Length);
if (br > 0)
{
uint bw = _stgManager.WriteBlock(blockHandle, offset,
Convert.ToBase64String(data, 0, br));
offset += bw;
if (bw != br)
writing = false;
}
else
writing = false;
}
}
finally
{
_stgManager.UnlockBlock(blockHandle);
}
return content;
}
}
class Session : DriveItem
{
StorageManager _stgManager;
bool _sharedCached;
bool _ownedCached;
List<StorageBlock> _items;
static string[] _propKeys = { "BytesAvailable", "SessionHandle", "ApplicationHandle" , "StoragePath","Blocks" };
public Session(StorageManager stgManager, string name, DriveItem parent)
: base(name,new Content(),parent)
{
_stgManager = stgManager;
_items = null;
_stgManager.Apps = new Application[0];
LoadOwnedBlocks();
LoadSharedBlocks();
}
public override object GetReturnObject()
{
return new NameValuePairItem(Name, Value);
}
public override string[] Properties
{
get { return _propKeys; }
}
public override void RemoveItem( DriveProvider provider)
{
if (provider !=null && provider.Force.IsPresent)
{
_stgManager.RemoveChildItem(this);
_stgManager.UnregisterApplication();
//_stgManager.RemoveApplication();
}
else
{
_stgManager.UnregisterApplication();
_stgManager.RemoveChildItem(this);
}
}
public override object GetContentWriterDynamicParameters()
{
return new SetContentDynamicParameters();
}
public override IContentWriter GetContentWriter( DriveProvider provider)
{
return new BlockWriter(_stgManager,provider.GetDynamicParameters() as SetContentDynamicParameters);
}
public override object GetContentReaderDynamicParameters()
{
return new GetContentDynamicParameters();
}
public override IContentReader GetContentReader( DriveProvider provider)
{
return new BlockReader(_stgManager, provider.GetDynamicParameters() as GetContentDynamicParameters);
}
public override void ClearContent(DriveProvider provider)
{
}
public void DeAllocateBlock(StorageBlock block)
{
_items.Remove(block);
}
public StorageBlock AllocateBlock(string name, uint size)
{
IManagedInstance outObj = _stgManager.AllocateBlock(size, false, name);
StorageOperationException.CheckResult(outObj);
uint handle = uint.Parse(outObj.GetProperty("BlockHandle").ToString());
StorageBlock newItem = new StorageBlock(_stgManager,
handle, size, false, name,
_stgManager.AppHandle);
_items.Add(newItem);
return newItem;
}
public Application GetCurrentStorageApplication()
{
Application result = null;
foreach (Application stgApp in _stgManager.Apps)
{
if (stgApp.Handle==_stgManager.AppHandle)
{
result = stgApp;
break;
}
}
return result;
}
public Application FindStorageApplication(string appName, string vendorName)
{
Application result = null;
foreach (Application stgApp in _stgManager.Apps)
{
if (string.Compare(stgApp.Name, appName, true) == 0 &&
string.Compare(stgApp.VendorName, vendorName, true) == 0)
{
result = stgApp;
break;
}
}
if (result == null)
throw new StorageOperationException(
Intel.Management.PSModule.Properties.Resources.BLOCK_NOT_FOUND);
return result;
}
public StorageBlock FindBlock(string blockName,string appName,string vendorName)
{
StorageBlock result = null;
uint appId = FindStorageApplication(appName, vendorName).Handle;
foreach (StorageBlock block in _items)
{
if (block.Owner == appId && block.BlockName.Equals(blockName))
{
result = block;
break;
}
}
return result;
}
public StorageBlock FindBlock(uint handle)
{
StorageBlock result = null;
foreach (StorageBlock block in _items)
{
if (block.Handle==handle)
{
result = block;
break;
}
}
if (result == null)
throw new StorageOperationException(
Intel.Management.PSModule.Properties.Resources.APPLICATION_NOT_FOUND);
return result;
}
private void LoadSharedBlocks()
{
List<StorageBlock> list = null;
if (_items!=null)
list = new List<StorageBlock>(_items);
else
list = new List<StorageBlock>();
if (!_sharedCached)
{
//you should always get the current app
IManagedInstance outObj = _stgManager.GetRegisteredApplications();
IWsmanItem handles = outObj.GetProperty("AppHandles");
foreach (IWsmanItem handle in handles)
{
uint appHandle = uint.Parse(handle.ToString());
//load the application into the cached (if not already)
string vendorName, appName;
_stgManager.GetApplicationAttributes(appHandle,out vendorName,out appName);
//skip loading owned blocks
if (appHandle == _stgManager.GetCurrentApplicationHandle())
break;
LoadBocks(appHandle, list);
}
_sharedCached = true;
_items = list;
}
}
private void LoadOwnedBlocks()
{
List<StorageBlock> list = null;
if (_items!=null)
list = new List<StorageBlock>(_items);
else
list = new List<StorageBlock>();
if (!_ownedCached)
{
LoadBocks(_stgManager.GetCurrentApplicationHandle(), list);
_ownedCached = true;
_items = list;
}
}
private void LoadBocks(uint appHandle, List<StorageBlock> list)
{
IManagedInstance outObj = _stgManager.GetAllocatedBlocks(appHandle);
IWsmanItem handles = outObj.GetProperty("BlockHandles");
if (handles != null)
{
foreach (IWsmanItem handle in handles)
{
uint blockHandle = uint.Parse(handle.ToString());
IManagedInstance attrObj = _stgManager.GetBlockAttributes(blockHandle);
list.Add(
new StorageBlock(_stgManager,
blockHandle,
uint.Parse(attrObj.GetProperty("BlockSize").ToString()),
bool.Parse(attrObj.GetProperty("BlockHidden").ToString()),
attrObj.GetProperty("BlockName").ToString(),
_stgManager.AppHandle)
);
} //End for each BLock
} // end Handles not NULL
}//end LoadBlocks
public string SessionHandle
{
get
{
return _stgManager.SessionHandle;
}
}
public uint ApplicationHandle
{
get
{
return _stgManager.GetCurrentApplicationHandle();
}
}
public StorageBlock[] Blocks
{
get { return _items.ToArray(); }
}
public string StoragePath
{
get
{
string appName, vendorName;
_stgManager.GetApplicationAttributes(
_stgManager.GetCurrentApplicationHandle(),
out vendorName,out appName );
StringBuilder builder = new StringBuilder();
builder.Append("\\\\");
builder.Append(EncodeName(_stgManager.Enterprise));
builder.Append("\\");
builder.Append(EncodeName(vendorName));
builder.Append("\\");
builder.Append(EncodeName(appName));
return builder.ToString();
}
}
public uint BytesAvailable
{
get
{
return _stgManager.GetBytesAvailable();
}
}
public override object GetProperty(Collection<string> propList, DriveProvider provider)
{
//if (provider != null && provider.Force.IsPresent) _isCached = false;
return base.GetProperty(propList, provider);
}
} // End SessionContainer
public class StorageOperationException : AmtException
{
public StorageOperationException(string message) : base(message) { }
/*public static void CheckResult(IManagedInstance resultObj)
{
string returnValue = resultObj.GetProperty("ReturnValue").ToString();
if (!returnValue.Equals("0"))
{
throw new StorageOperationException(resultObj.SimpleName + ".ReturnValue=" + returnValue);
}
}*/
}
private bool RemoveItem(DriveItem item)
{
return RemoveChildItem(item, true);
}
public static uint GetAllocationSize(uint size)
{
uint blocksize = (size / (4 * 1024));
blocksize = blocksize * (4 * 1024);
if (size > blocksize)
blocksize = blocksize + (4 * 1024);
return blocksize;
}
private uint GetMtu()
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("GetMTU");
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return uint.Parse( outObj.GetProperty("Mtu").ToString());
}
void RegisterApplication(Guid uuid,string vendorName,string appName ,string entName)
{
string uuidString = BitConverter.ToString(uuid.ToByteArray());
uuidString = uuidString.Replace("-", "");
IManagedInstance inputObj = _storageRef.CreateMethodInput("RegisterApplication");
inputObj.SetProperty("CallerUUID",uuidString );
inputObj.SetProperty("VendorName", vendorName);
inputObj.SetProperty("ApplicationName", appName);
inputObj.SetProperty("EnterpriseName", entName);
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
SessionHandle= outObj.GetProperty("SessionHandle").ToString();
GetCurrentApplicationHandle();
}
void RemoveApplication()
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("RemoveApplication");
inputObj.SetProperty("SessionHandle", SessionHandle);
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
}
void UnregisterApplication()
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("UnregisterApplication");
inputObj.SetProperty("SessionHandle", SessionHandle);
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
}
private uint GetWriteEraseLimit()
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("GetWriteEraseLimit");
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return uint.Parse(outObj.GetProperty("WriteEraseLimit").ToString());
}
private void GetTimeoutValues(out uint regTimeout, out uint lockTimeout)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("GetTimeoutValues");
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
regTimeout = uint.Parse(outObj.GetProperty("RegistrationTimeout").ToString());
lockTimeout = uint.Parse(outObj.GetProperty("LockTimeout").ToString());
}
private uint GetBytesAvailable()
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("GetBytesAvailable");
inputObj.SetProperty("SessionHandle", SessionHandle);
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return uint.Parse(outObj.GetProperty("BytesAvailable").ToString());
}
private IManagedInstance AllocateBlock(uint size,bool hidden,string name)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("AllocateBlock");
inputObj.SetProperty("SessionHandle", SessionHandle);
inputObj.SetProperty("BytesRequested", size.ToString());
inputObj.SetProperty("BlockHidden", hidden.ToString().ToLower());
if (!name.Equals(string.Empty))
inputObj.SetProperty("BlockName", name);
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return outObj;
}
private IManagedInstance GetAllocatedBlocks(uint owner)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("GetAllocatedBlocks");
inputObj.SetProperty("SessionHandle",SessionHandle);
inputObj.SetProperty("BlockOwnerApplication", owner.ToString());
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return outObj;
}
private IManagedInstance GetBlockAttributes(uint handle)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("GetBlockAttributes");
inputObj.SetProperty("SessionHandle", SessionHandle);
inputObj.SetProperty("BlockHandle", handle.ToString());
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return outObj;
}
private uint WriteBlock(uint handle,uint offset,string data)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("WriteBlock");
inputObj.SetProperty("SessionHandle", SessionHandle);
inputObj.SetProperty("BlockHandle", handle.ToString());
inputObj.SetProperty("ByteOffset", offset.ToString());
inputObj.SetProperty("Data", data);
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return uint.Parse(outObj.GetProperty("BytesWritten").ToString());
}
private IManagedInstance ReadBlock(uint handle, uint offset, uint count)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("ReadBlock");
inputObj.SetProperty("SessionHandle", SessionHandle);
inputObj.SetProperty("BlockHandle", handle.ToString());
inputObj.SetProperty("ByteOffset", offset.ToString());
inputObj.SetProperty("ByteCount", count.ToString());
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return outObj;
}
public void LockBlock(uint handle)
{
if (_retryThreshold > 0)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("LockBlock");
inputObj.SetProperty("SessionHandle", SessionHandle);
inputObj.SetProperty("BlockHandle", handle.ToString());
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
string result = outObj.GetProperty("ReturnValue").ToString();
for (int i = 0; i < _retryThreshold && result.Equals("18"); i++)
{
System.Threading.Thread.Sleep(200);
outObj = _storageRef.InvokeMethod(inputObj);
result = outObj.GetProperty("ReturnValue").ToString();
}
StorageOperationException.CheckResult(outObj);
}
}
public void UnlockBlock(uint handle)
{
if (_retryThreshold > 0)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("UnlockBlock");
inputObj.SetProperty("SessionHandle", SessionHandle);
inputObj.SetProperty("BlockHandle", handle.ToString());
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
}
}
private IManagedInstance DeallocateBlock(uint handle)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("DeallocateBlock");
inputObj.SetProperty("SessionHandle", SessionHandle);
inputObj.SetProperty("BlockHandle", handle.ToString());
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return outObj;
}
private uint GetCurrentApplicationHandle()
{
if (AppHandle == uint.MaxValue)
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("GetCurrentApplicationHandle");
inputObj.SetProperty("SessionHandle", SessionHandle);
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
AppHandle = uint.Parse(outObj.GetProperty("ApplicationHandle").ToString());
}
return AppHandle;
}
private IManagedInstance GetRegisteredApplications()
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("GetRegisteredApplications");
inputObj.SetProperty("SessionHandle", SessionHandle);
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
return outObj;
}
private void GetApplicationAttributes(uint handle,out string vendorName,out string appName )
{
vendorName = string.Empty;
appName = string.Empty;
//find in cache
foreach (Application app in Apps)
{
if (app.Handle.Equals(handle))
{
vendorName = app.VendorName;
appName = app.Name;
break;
}
}
//not found in cache
if (appName.Equals(string.Empty))
{
IManagedInstance inputObj = _storageRef.CreateMethodInput("GetApplicationAttributes");
inputObj.SetProperty("SessionHandle", SessionHandle);
inputObj.SetProperty("ApplicationBeingRequested", AppHandle.ToString());
IManagedInstance outObj = _storageRef.InvokeMethod(inputObj);
StorageOperationException.CheckResult(outObj);
vendorName = outObj.GetProperty("VendorName").ToString();
appName = outObj.GetProperty("ApplicationName").ToString();
//addto cache
List<Application> list = new List<Application>(Apps);
list.Add(new Application(handle,vendorName,appName));
Apps=list.ToArray();
}
}
}
}