GIT: perform LF normalization

This commit is contained in:
Gary Sharp
2013-02-28 17:15:46 +11:00
parent 989f08a24d
commit 7d9be5620d
729 changed files with 300734 additions and 300712 deletions
+22
View File
@@ -0,0 +1,22 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
+5 -5
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<solution> <solution>
<add key="disableSourceControlIntegration" value="true" /> <add key="disableSourceControlIntegration" value="true" />
</solution> </solution>
</configuration> </configuration>
+152 -152
View File
@@ -1,153 +1,153 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir> <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir>
<!-- Enable the restore command to run before builds --> <!-- Enable the restore command to run before builds -->
<RestorePackages Condition=" '$(RestorePackages)' == '' ">false</RestorePackages> <RestorePackages Condition=" '$(RestorePackages)' == '' ">false</RestorePackages>
<!-- Property that enables building a package from a project --> <!-- Property that enables building a package from a project -->
<BuildPackage Condition=" '$(BuildPackage)' == '' ">false</BuildPackage> <BuildPackage Condition=" '$(BuildPackage)' == '' ">false</BuildPackage>
<!-- Determines if package restore consent is required to restore packages --> <!-- Determines if package restore consent is required to restore packages -->
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent> <RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent>
<!-- Download NuGet.exe if it does not already exist --> <!-- Download NuGet.exe if it does not already exist -->
<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">false</DownloadNuGetExe> <DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">false</DownloadNuGetExe>
</PropertyGroup> </PropertyGroup>
<ItemGroup Condition=" '$(PackageSources)' == '' "> <ItemGroup Condition=" '$(PackageSources)' == '' ">
<!-- Package sources used to restore packages. By default, registered sources under %APPDATA%\NuGet\NuGet.Config will be used --> <!-- Package sources used to restore packages. By default, registered sources under %APPDATA%\NuGet\NuGet.Config will be used -->
<!-- The official NuGet package source (https://nuget.org/api/v2/) will be excluded if package sources are specified and it does not appear in the list --> <!-- The official NuGet package source (https://nuget.org/api/v2/) will be excluded if package sources are specified and it does not appear in the list -->
<!-- <!--
<PackageSource Include="https://nuget.org/api/v2/" /> <PackageSource Include="https://nuget.org/api/v2/" />
<PackageSource Include="https://my-nuget-source/nuget/" /> <PackageSource Include="https://my-nuget-source/nuget/" />
--> -->
</ItemGroup> </ItemGroup>
<PropertyGroup Condition=" '$(OS)' == 'Windows_NT'"> <PropertyGroup Condition=" '$(OS)' == 'Windows_NT'">
<!-- Windows specific commands --> <!-- Windows specific commands -->
<NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath> <NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath>
<PackagesConfig>$([System.IO.Path]::Combine($(ProjectDir), "packages.config"))</PackagesConfig> <PackagesConfig>$([System.IO.Path]::Combine($(ProjectDir), "packages.config"))</PackagesConfig>
<PackagesDir>$([System.IO.Path]::Combine($(SolutionDir), "packages"))</PackagesDir> <PackagesDir>$([System.IO.Path]::Combine($(SolutionDir), "packages"))</PackagesDir>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(OS)' != 'Windows_NT'"> <PropertyGroup Condition=" '$(OS)' != 'Windows_NT'">
<!-- We need to launch nuget.exe with the mono command if we're not on windows --> <!-- We need to launch nuget.exe with the mono command if we're not on windows -->
<NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath> <NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath>
<PackagesConfig>packages.config</PackagesConfig> <PackagesConfig>packages.config</PackagesConfig>
<PackagesDir>$(SolutionDir)packages</PackagesDir> <PackagesDir>$(SolutionDir)packages</PackagesDir>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<!-- NuGet command --> <!-- NuGet command -->
<NuGetExePath Condition=" '$(NuGetExePath)' == '' ">$(NuGetToolsPath)\nuget.exe</NuGetExePath> <NuGetExePath Condition=" '$(NuGetExePath)' == '' ">$(NuGetToolsPath)\nuget.exe</NuGetExePath>
<PackageSources Condition=" $(PackageSources) == '' ">@(PackageSource)</PackageSources> <PackageSources Condition=" $(PackageSources) == '' ">@(PackageSource)</PackageSources>
<NuGetCommand Condition=" '$(OS)' == 'Windows_NT'">"$(NuGetExePath)"</NuGetCommand> <NuGetCommand Condition=" '$(OS)' == 'Windows_NT'">"$(NuGetExePath)"</NuGetCommand>
<NuGetCommand Condition=" '$(OS)' != 'Windows_NT' ">mono --runtime=v4.0.30319 $(NuGetExePath)</NuGetCommand> <NuGetCommand Condition=" '$(OS)' != 'Windows_NT' ">mono --runtime=v4.0.30319 $(NuGetExePath)</NuGetCommand>
<PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir> <PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>
<RequireConsentSwitch Condition=" $(RequireRestoreConsent) == 'true' ">-RequireConsent</RequireConsentSwitch> <RequireConsentSwitch Condition=" $(RequireRestoreConsent) == 'true' ">-RequireConsent</RequireConsentSwitch>
<!-- Commands --> <!-- Commands -->
<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(RequireConsentSwitch) -o "$(PackagesDir)"</RestoreCommand> <RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(RequireConsentSwitch) -o "$(PackagesDir)"</RestoreCommand>
<BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -p Configuration=$(Configuration) -o "$(PackageOutputDir)" -symbols</BuildCommand> <BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -p Configuration=$(Configuration) -o "$(PackageOutputDir)" -symbols</BuildCommand>
<!-- We need to ensure packages are restored prior to assembly resolve --> <!-- We need to ensure packages are restored prior to assembly resolve -->
<ResolveReferencesDependsOn Condition="$(RestorePackages) == 'true'"> <ResolveReferencesDependsOn Condition="$(RestorePackages) == 'true'">
RestorePackages; RestorePackages;
$(ResolveReferencesDependsOn); $(ResolveReferencesDependsOn);
</ResolveReferencesDependsOn> </ResolveReferencesDependsOn>
<!-- Make the build depend on restore packages --> <!-- Make the build depend on restore packages -->
<BuildDependsOn Condition="$(BuildPackage) == 'true'"> <BuildDependsOn Condition="$(BuildPackage) == 'true'">
$(BuildDependsOn); $(BuildDependsOn);
BuildPackage; BuildPackage;
</BuildDependsOn> </BuildDependsOn>
</PropertyGroup> </PropertyGroup>
<Target Name="CheckPrerequisites"> <Target Name="CheckPrerequisites">
<!-- Raise an error if we're unable to locate nuget.exe --> <!-- Raise an error if we're unable to locate nuget.exe -->
<Error Condition="'$(DownloadNuGetExe)' != 'true' AND !Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" /> <Error Condition="'$(DownloadNuGetExe)' != 'true' AND !Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" />
<SetEnvironmentVariable EnvKey="VisualStudioVersion" EnvValue="$(VisualStudioVersion)" Condition=" '$(VisualStudioVersion)' != '' AND '$(OS)' == 'Windows_NT' " /> <SetEnvironmentVariable EnvKey="VisualStudioVersion" EnvValue="$(VisualStudioVersion)" Condition=" '$(VisualStudioVersion)' != '' AND '$(OS)' == 'Windows_NT' " />
<!-- <!--
Take advantage of MsBuild's build dependency tracking to make sure that we only ever download nuget.exe once. Take advantage of MsBuild's build dependency tracking to make sure that we only ever download nuget.exe once.
This effectively acts as a lock that makes sure that the download operation will only happen once and all This effectively acts as a lock that makes sure that the download operation will only happen once and all
parallel builds will have to wait for it to complete. parallel builds will have to wait for it to complete.
--> -->
<MsBuild Targets="_DownloadNuGet" Projects="$(MSBuildThisFileFullPath)" Properties="Configuration=NOT_IMPORTANT" /> <MsBuild Targets="_DownloadNuGet" Projects="$(MSBuildThisFileFullPath)" Properties="Configuration=NOT_IMPORTANT" />
</Target> </Target>
<Target Name="_DownloadNuGet"> <Target Name="_DownloadNuGet">
<DownloadNuGet OutputFilename="$(NuGetExePath)" Condition=" '$(DownloadNuGetExe)' == 'true' AND !Exists('$(NuGetExePath)')" /> <DownloadNuGet OutputFilename="$(NuGetExePath)" Condition=" '$(DownloadNuGetExe)' == 'true' AND !Exists('$(NuGetExePath)')" />
</Target> </Target>
<Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites"> <Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(RestoreCommand)" <Exec Command="$(RestoreCommand)"
Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" /> Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />
<Exec Command="$(RestoreCommand)" <Exec Command="$(RestoreCommand)"
LogStandardErrorAsError="true" LogStandardErrorAsError="true"
Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" /> Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
</Target> </Target>
<Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites"> <Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(BuildCommand)" <Exec Command="$(BuildCommand)"
Condition=" '$(OS)' != 'Windows_NT' " /> Condition=" '$(OS)' != 'Windows_NT' " />
<Exec Command="$(BuildCommand)" <Exec Command="$(BuildCommand)"
LogStandardErrorAsError="true" LogStandardErrorAsError="true"
Condition=" '$(OS)' == 'Windows_NT' " /> Condition=" '$(OS)' == 'Windows_NT' " />
</Target> </Target>
<UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll"> <UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup> <ParameterGroup>
<OutputFilename ParameterType="System.String" Required="true" /> <OutputFilename ParameterType="System.String" Required="true" />
</ParameterGroup> </ParameterGroup>
<Task> <Task>
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Using Namespace="System" /> <Using Namespace="System" />
<Using Namespace="System.IO" /> <Using Namespace="System.IO" />
<Using Namespace="System.Net" /> <Using Namespace="System.Net" />
<Using Namespace="Microsoft.Build.Framework" /> <Using Namespace="Microsoft.Build.Framework" />
<Using Namespace="Microsoft.Build.Utilities" /> <Using Namespace="Microsoft.Build.Utilities" />
<Code Type="Fragment" Language="cs"> <Code Type="Fragment" Language="cs">
<![CDATA[ <![CDATA[
try { try {
OutputFilename = Path.GetFullPath(OutputFilename); OutputFilename = Path.GetFullPath(OutputFilename);
Log.LogMessage("Downloading latest version of NuGet.exe..."); Log.LogMessage("Downloading latest version of NuGet.exe...");
WebClient webClient = new WebClient(); WebClient webClient = new WebClient();
webClient.DownloadFile("https://nuget.org/nuget.exe", OutputFilename); webClient.DownloadFile("https://nuget.org/nuget.exe", OutputFilename);
return true; return true;
} }
catch (Exception ex) { catch (Exception ex) {
Log.LogErrorFromException(ex); Log.LogErrorFromException(ex);
return false; return false;
} }
]]> ]]>
</Code> </Code>
</Task> </Task>
</UsingTask> </UsingTask>
<UsingTask TaskName="SetEnvironmentVariable" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll"> <UsingTask TaskName="SetEnvironmentVariable" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup> <ParameterGroup>
<EnvKey ParameterType="System.String" Required="true" /> <EnvKey ParameterType="System.String" Required="true" />
<EnvValue ParameterType="System.String" Required="true" /> <EnvValue ParameterType="System.String" Required="true" />
</ParameterGroup> </ParameterGroup>
<Task> <Task>
<Using Namespace="System" /> <Using Namespace="System" />
<Code Type="Fragment" Language="cs"> <Code Type="Fragment" Language="cs">
<![CDATA[ <![CDATA[
try { try {
Environment.SetEnvironmentVariable(EnvKey, EnvValue, System.EnvironmentVariableTarget.Process); Environment.SetEnvironmentVariable(EnvKey, EnvValue, System.EnvironmentVariableTarget.Process);
} }
catch { catch {
} }
]]> ]]>
</Code> </Code>
</Task> </Task>
</UsingTask> </UsingTask>
</Project> </Project>
+96 -96
View File
@@ -1,96 +1,96 @@
using System; using System;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using iTextSharp.text.pdf; using iTextSharp.text.pdf;
namespace Disco.BI.AttachmentBI namespace Disco.BI.AttachmentBI
{ {
public static class Utilities public static class Utilities
{ {
public static bool GenerateThumbnail(Stream Source, string SourceMimeType, Stream OutStream) public static bool GenerateThumbnail(Stream Source, string SourceMimeType, Stream OutStream)
{ {
if (Source != null) if (Source != null)
{ {
// GDI+ (jpg, png, gif, bmp) // GDI+ (jpg, png, gif, bmp)
if (SourceMimeType.Equals("image/jpeg", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("jpg") || if (SourceMimeType.Equals("image/jpeg", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("jpg") ||
SourceMimeType.Equals("image/png", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("png") || SourceMimeType.Equals("image/png", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("png") ||
SourceMimeType.Equals("image/gif", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("gif") || SourceMimeType.Equals("image/gif", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("gif") ||
SourceMimeType.Equals("image/bmp", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("bmp")) SourceMimeType.Equals("image/bmp", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("bmp"))
{ {
try try
{ {
using (Image sourceImage = Image.FromStream(Source)) using (Image sourceImage = Image.FromStream(Source))
{ {
using (Image thumbImage = sourceImage.ResizeImage(48, 48)) using (Image thumbImage = sourceImage.ResizeImage(48, 48))
{ {
using (Image mimeTypeIcon = Disco.Properties.Resources.MimeType_img16) using (Image mimeTypeIcon = Disco.Properties.Resources.MimeType_img16)
thumbImage.EmbedIconOverlay(mimeTypeIcon); thumbImage.EmbedIconOverlay(mimeTypeIcon);
thumbImage.SaveJpg(90, OutStream); thumbImage.SaveJpg(90, OutStream);
return true; return true;
} }
} }
} }
catch (Exception) catch (Exception)
{ {
// Ignore Thumbnail Generation exceptions for images // Ignore Thumbnail Generation exceptions for images
//throw; //throw;
} }
} }
// PDF // PDF
if (SourceMimeType.Equals("application/pdf", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("pdf")) if (SourceMimeType.Equals("application/pdf", StringComparison.InvariantCultureIgnoreCase) || SourceMimeType.Contains("pdf"))
{ {
PdfReader pdfReader = new PdfReader(Source); PdfReader pdfReader = new PdfReader(Source);
try try
{ {
using (DisposableImageCollection pdfPageImages = pdfReader.PdfPageImages(1)) using (DisposableImageCollection pdfPageImages = pdfReader.PdfPageImages(1))
{ {
if (pdfPageImages.Count() > 0) if (pdfPageImages.Count() > 0)
{ {
// Find Biggest Image on Page // Find Biggest Image on Page
Image biggestImage = pdfPageImages.OrderByDescending(i => i.Height * i.Width).First(); Image biggestImage = pdfPageImages.OrderByDescending(i => i.Height * i.Width).First();
using (Image thumbImage = biggestImage.ResizeImage(48, 48, Brushes.White)) using (Image thumbImage = biggestImage.ResizeImage(48, 48, Brushes.White))
{ {
using (Image mimeTypeIcon = Disco.Properties.Resources.MimeType_pdf16) using (Image mimeTypeIcon = Disco.Properties.Resources.MimeType_pdf16)
thumbImage.EmbedIconOverlay(mimeTypeIcon); thumbImage.EmbedIconOverlay(mimeTypeIcon);
thumbImage.SaveJpg(90, OutStream); thumbImage.SaveJpg(90, OutStream);
return true; return true;
} }
} }
} }
} }
finally finally
{ {
if (pdfReader != null) if (pdfReader != null)
pdfReader.Close(); pdfReader.Close();
} }
} }
} }
return false; return false;
} }
public static bool GenerateThumbnail(string SourceFilename, string SourceMimeType, string DestinationFilename) public static bool GenerateThumbnail(string SourceFilename, string SourceMimeType, string DestinationFilename)
{ {
using (FileStream sourceStream = new FileStream(SourceFilename, FileMode.Open, FileAccess.Read)) using (FileStream sourceStream = new FileStream(SourceFilename, FileMode.Open, FileAccess.Read))
{ {
return GenerateThumbnail(sourceStream, SourceMimeType, DestinationFilename); return GenerateThumbnail(sourceStream, SourceMimeType, DestinationFilename);
} }
} }
public static bool GenerateThumbnail(Stream Source, string SourceMimeType, string DestinationFilename) public static bool GenerateThumbnail(Stream Source, string SourceMimeType, string DestinationFilename)
{ {
bool result; bool result;
using (FileStream destinationStream = new FileStream(DestinationFilename, FileMode.Create, FileAccess.Write, FileShare.None)) using (FileStream destinationStream = new FileStream(DestinationFilename, FileMode.Create, FileAccess.Write, FileShare.None))
{ {
result = GenerateThumbnail(Source, SourceMimeType, destinationStream); result = GenerateThumbnail(Source, SourceMimeType, destinationStream);
} }
if (!result && File.Exists(DestinationFilename)) if (!result && File.Exists(DestinationFilename))
File.Delete(DestinationFilename); File.Delete(DestinationFilename);
return result; return result;
} }
} }
} }
+31 -31
View File
@@ -1,31 +1,31 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Data.Configuration; using Disco.Data.Configuration;
namespace Disco.BI namespace Disco.BI
{ {
public static class DataStore public static class DataStore
{ {
public static string CreateLocation(DiscoDataContext dbContext, string SubLocation, DateTime? SubSubLocationTimestamp = null) public static string CreateLocation(DiscoDataContext dbContext, string SubLocation, DateTime? SubSubLocationTimestamp = null)
{ {
return CreateLocation(dbContext.DiscoConfiguration, SubLocation, SubSubLocationTimestamp); return CreateLocation(dbContext.DiscoConfiguration, SubLocation, SubSubLocationTimestamp);
} }
public static string CreateLocation(ConfigurationContext DiscoConfiguration, string SubLocation, DateTime? SubSubLocationTimestamp = null) public static string CreateLocation(ConfigurationContext DiscoConfiguration, string SubLocation, DateTime? SubSubLocationTimestamp = null)
{ {
string SubSubLocation = string.Empty; string SubSubLocation = string.Empty;
if (SubSubLocationTimestamp.HasValue) if (SubSubLocationTimestamp.HasValue)
SubSubLocation = SubSubLocationTimestamp.Value.ToString(@"yyyy\\MM"); SubSubLocation = SubSubLocationTimestamp.Value.ToString(@"yyyy\\MM");
string storeDirectory = System.IO.Path.Combine(DiscoConfiguration.DataStoreLocation, SubLocation, SubSubLocation); string storeDirectory = System.IO.Path.Combine(DiscoConfiguration.DataStoreLocation, SubLocation, SubSubLocation);
if (!System.IO.Directory.Exists(storeDirectory)) if (!System.IO.Directory.Exists(storeDirectory))
System.IO.Directory.CreateDirectory(storeDirectory); System.IO.Directory.CreateDirectory(storeDirectory);
return storeDirectory; return storeDirectory;
} }
} }
} }
+21 -21
View File
@@ -1,21 +1,21 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
namespace Disco.BI.DeviceBI namespace Disco.BI.DeviceBI
{ {
public static class BatchUtilities public static class BatchUtilities
{ {
public static DeviceBatch DefaultNewDeviceBatch(DiscoDataContext dbContext) public static DeviceBatch DefaultNewDeviceBatch(DiscoDataContext dbContext)
{ {
return new DeviceBatch() return new DeviceBatch()
{ {
PurchaseDate = DateTime.Today PurchaseDate = DateTime.Today
}; };
} }
} }
} }
+14 -14
View File
@@ -1,14 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Threading; using System.Threading;
namespace Disco.BI namespace Disco.BI
{ {
public class EnrolSafeException : System.Exception public class EnrolSafeException : System.Exception
{ {
public EnrolSafeException(string Message) : base(Message) public EnrolSafeException(string Message) : base(Message)
{ {
} }
} }
} }
+482 -482
View File
@@ -1,482 +1,482 @@
using Disco.Services.Logging; using Disco.Services.Logging;
using Disco.Services.Logging.Models; using Disco.Services.Logging.Models;
using Disco.Models.ClientServices; using Disco.Models.ClientServices;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
namespace Disco.BI.DeviceBI namespace Disco.BI.DeviceBI
{ {
public class EnrolmentLog : LogBase public class EnrolmentLog : LogBase
{ {
public enum EventTypeIds public enum EventTypeIds
{ {
SessionStarting = 10, SessionStarting = 10,
SessionProgress, SessionProgress,
SessionDevice, SessionDevice,
SessionDeviceInfo, SessionDeviceInfo,
SessionFinished = 20, SessionFinished = 20,
SessionDiagnosticInformation, SessionDiagnosticInformation,
SessionWarning, SessionWarning,
SessionError, SessionError,
SessionErrorWithInner, SessionErrorWithInner,
SessionClientError, SessionClientError,
SessionTaskAddedDevice = 50, SessionTaskAddedDevice = 50,
SessionTaskUpdatingDevice, SessionTaskUpdatingDevice,
SessionTaskCreatedDeviceModel = 56, SessionTaskCreatedDeviceModel = 56,
SessionTaskProvisioningADAccount = 58, SessionTaskProvisioningADAccount = 58,
SessionTaskAssigningUser = 60, SessionTaskAssigningUser = 60,
SessionTaskProvisioningWirelessCertificate = 62, SessionTaskProvisioningWirelessCertificate = 62,
SessionTaskRenamingDevice = 64, SessionTaskRenamingDevice = 64,
SessionTaskMovingDeviceOrganisationUnit = 66, SessionTaskMovingDeviceOrganisationUnit = 66,
ClientError = 400 ClientError = 400
} }
private const int _ModuleId = 50; private const int _ModuleId = 50;
public static EnrolmentLog Current public static EnrolmentLog Current
{ {
get get
{ {
return (EnrolmentLog)LogContext.LogModules[50]; return (EnrolmentLog)LogContext.LogModules[50];
} }
} }
public override string ModuleDescription public override string ModuleDescription
{ {
get get
{ {
return "Device Enrolment"; return "Device Enrolment";
} }
} }
public override int ModuleId public override int ModuleId
{ {
get get
{ {
return 50; return 50;
} }
} }
public override string ModuleName public override string ModuleName
{ {
get get
{ {
return "DeviceEnrolment"; return "DeviceEnrolment";
} }
} }
[System.Diagnostics.DebuggerNonUserCode] [System.Diagnostics.DebuggerNonUserCode]
public EnrolmentLog() public EnrolmentLog()
{ {
} }
private static void Log(EnrolmentLog.EventTypeIds EventTypeId, params object[] Args) private static void Log(EnrolmentLog.EventTypeIds EventTypeId, params object[] Args)
{ {
EnrolmentLog.Current.Log((int)EventTypeId, Args); EnrolmentLog.Current.Log((int)EventTypeId, Args);
} }
public static void LogSessionStarting(string SessionId, string HostId, DeviceEnrol.EnrolmentTypes EnrolmentType) public static void LogSessionStarting(string SessionId, string HostId, DeviceEnrol.EnrolmentTypes EnrolmentType)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionStarting, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionStarting, new object[]
{ {
SessionId, SessionId,
HostId, HostId,
System.Enum.GetName(EnrolmentType.GetType(), EnrolmentType) System.Enum.GetName(EnrolmentType.GetType(), EnrolmentType)
}); });
} }
public static void LogSessionDevice(string SessionId, string DeviceSerialNumber, int? DeviceModelId) public static void LogSessionDevice(string SessionId, string DeviceSerialNumber, int? DeviceModelId)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionDevice, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionDevice, new object[]
{ {
SessionId, SessionId,
DeviceSerialNumber, DeviceSerialNumber,
DeviceModelId DeviceModelId
}); });
} }
public static void LogSessionDeviceInfo(string SessionId, string SerialNumber, string UUID, string ComputerName, string LanMacAddress, string WlanMacAddress, string Manufacturer, string Model, string ModelType) public static void LogSessionDeviceInfo(string SessionId, string SerialNumber, string UUID, string ComputerName, string LanMacAddress, string WlanMacAddress, string Manufacturer, string Model, string ModelType)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionDeviceInfo, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionDeviceInfo, new object[]
{ {
SessionId, SessionId,
SerialNumber, SerialNumber,
UUID, UUID,
ComputerName, ComputerName,
LanMacAddress, LanMacAddress,
WlanMacAddress, WlanMacAddress,
Manufacturer, Manufacturer,
Model, Model,
ModelType ModelType
}); });
} }
public static void LogSessionDeviceInfo(string SessionId, MacEnrol Request) public static void LogSessionDeviceInfo(string SessionId, MacEnrol Request)
{ {
EnrolmentLog.LogSessionDeviceInfo(SessionId, Request.DeviceSerialNumber, Request.DeviceUUID, Request.DeviceComputerName, Request.DeviceLanMacAddress, Request.DeviceWlanMacAddress, Request.DeviceManufacturer, Request.DeviceModel, Request.DeviceModelType); EnrolmentLog.LogSessionDeviceInfo(SessionId, Request.DeviceSerialNumber, Request.DeviceUUID, Request.DeviceComputerName, Request.DeviceLanMacAddress, Request.DeviceWlanMacAddress, Request.DeviceManufacturer, Request.DeviceModel, Request.DeviceModelType);
} }
public static void LogSessionDeviceInfo(string SessionId, Models.ClientServices.Enrol Request) public static void LogSessionDeviceInfo(string SessionId, Models.ClientServices.Enrol Request)
{ {
EnrolmentLog.LogSessionDeviceInfo(SessionId, Request.DeviceSerialNumber, Request.DeviceUUID, Request.DeviceComputerName, Request.DeviceLanMacAddress, Request.DeviceWlanMacAddress, Request.DeviceManufacturer, Request.DeviceModel, Request.DeviceModelType); EnrolmentLog.LogSessionDeviceInfo(SessionId, Request.DeviceSerialNumber, Request.DeviceUUID, Request.DeviceComputerName, Request.DeviceLanMacAddress, Request.DeviceWlanMacAddress, Request.DeviceManufacturer, Request.DeviceModel, Request.DeviceModelType);
} }
public static void LogSessionProgress(string SessionId, int Progress, string Status) public static void LogSessionProgress(string SessionId, int Progress, string Status)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionProgress, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionProgress, new object[]
{ {
SessionId, SessionId,
Progress, Progress,
Status Status
}); });
} }
public static void LogSessionFinished(string SessionId) public static void LogSessionFinished(string SessionId)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionFinished, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionFinished, new object[]
{ {
SessionId SessionId
}); });
} }
public static void LogSessionDiagnosticInformation(string SessionId, string Message) public static void LogSessionDiagnosticInformation(string SessionId, string Message)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionDiagnosticInformation, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionDiagnosticInformation, new object[]
{ {
SessionId, SessionId,
Message Message
}); });
} }
public static void LogSessionWarning(string SessionId, string Message) public static void LogSessionWarning(string SessionId, string Message)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionWarning, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionWarning, new object[]
{ {
SessionId, SessionId,
Message Message
}); });
} }
public static void LogSessionError(string SessionId, System.Exception Ex) public static void LogSessionError(string SessionId, System.Exception Ex)
{ {
if (Ex.InnerException == null) if (Ex.InnerException == null)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionError, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionError, new object[]
{ {
SessionId, SessionId,
Ex.GetType().Name, Ex.GetType().Name,
Ex.Message, Ex.Message,
Ex.StackTrace Ex.StackTrace
}); });
} }
else else
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionErrorWithInner, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionErrorWithInner, new object[]
{ {
SessionId, SessionId,
Ex.GetType().Name, Ex.GetType().Name,
Ex.Message, Ex.Message,
Ex.InnerException.GetType().Name, Ex.InnerException.GetType().Name,
Ex.InnerException.Message, Ex.InnerException.Message,
Ex.StackTrace, Ex.StackTrace,
Ex.InnerException.StackTrace Ex.InnerException.StackTrace
}); });
} }
} }
public static void LogSessionClientError(string SessionId, string ClientIP, string ClientIdentifier, string ClientVersion, string Error, string RawError) public static void LogSessionClientError(string SessionId, string ClientIP, string ClientIdentifier, string ClientVersion, string Error, string RawError)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionClientError, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionClientError, new object[]
{ {
SessionId, SessionId,
ClientIP, ClientIP,
ClientIdentifier, ClientIdentifier,
ClientVersion, ClientVersion,
Error, Error,
RawError RawError
}); });
} }
public static void LogSessionTaskAddedDevice(string SessionId, string DeviceSerialNumber) public static void LogSessionTaskAddedDevice(string SessionId, string DeviceSerialNumber)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskAddedDevice, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskAddedDevice, new object[]
{ {
SessionId, SessionId,
DeviceSerialNumber DeviceSerialNumber
}); });
} }
public static void LogSessionTaskUpdatingDevice(string SessionId, string DeviceSerialNumber) public static void LogSessionTaskUpdatingDevice(string SessionId, string DeviceSerialNumber)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskUpdatingDevice, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskUpdatingDevice, new object[]
{ {
SessionId, SessionId,
DeviceSerialNumber DeviceSerialNumber
}); });
} }
public static void LogSessionTaskCreatedDeviceModel(string SessionId, string DeviceSerialNumber, string Manufacturer, string Model) public static void LogSessionTaskCreatedDeviceModel(string SessionId, string DeviceSerialNumber, string Manufacturer, string Model)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskCreatedDeviceModel, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskCreatedDeviceModel, new object[]
{ {
SessionId, SessionId,
DeviceSerialNumber, DeviceSerialNumber,
Manufacturer, Manufacturer,
Model Model
}); });
} }
public static void LogSessionTaskProvisioningADAccount(string SessionId, string DeviceSerialNumber, string ADAccountName) public static void LogSessionTaskProvisioningADAccount(string SessionId, string DeviceSerialNumber, string ADAccountName)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskProvisioningADAccount, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskProvisioningADAccount, new object[]
{ {
SessionId, SessionId,
DeviceSerialNumber, DeviceSerialNumber,
ADAccountName ADAccountName
}); });
} }
public static void LogSessionTaskAssigningUser(string SessionId, string DeviceSerialNumber, string UserDisplayName, string UserUsername, string UserDomain, string UserSID) public static void LogSessionTaskAssigningUser(string SessionId, string DeviceSerialNumber, string UserDisplayName, string UserUsername, string UserDomain, string UserSID)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskAssigningUser, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskAssigningUser, new object[]
{ {
SessionId, SessionId,
DeviceSerialNumber, DeviceSerialNumber,
UserDisplayName, UserDisplayName,
UserUsername, UserUsername,
UserDomain, UserDomain,
UserSID UserSID
}); });
} }
public static void LogSessionTaskProvisioningWirelessCertificate(string SessionId, string DeviceSerialNumber, string CertificateName) public static void LogSessionTaskProvisioningWirelessCertificate(string SessionId, string DeviceSerialNumber, string CertificateName)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskProvisioningWirelessCertificate, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskProvisioningWirelessCertificate, new object[]
{ {
SessionId, SessionId,
DeviceSerialNumber, DeviceSerialNumber,
CertificateName CertificateName
}); });
} }
public static void LogSessionTaskRenamingDevice(string SessionId, string OldComputerName, string NewComputerName) public static void LogSessionTaskRenamingDevice(string SessionId, string OldComputerName, string NewComputerName)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskRenamingDevice, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskRenamingDevice, new object[]
{ {
SessionId, SessionId,
OldComputerName, OldComputerName,
NewComputerName NewComputerName
}); });
} }
public static void LogSessionTaskMovingDeviceOrganisationUnit(string SessionId, string OldOrganisationUnit, string NewOrganisationUnit) public static void LogSessionTaskMovingDeviceOrganisationUnit(string SessionId, string OldOrganisationUnit, string NewOrganisationUnit)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskMovingDeviceOrganisationUnit, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.SessionTaskMovingDeviceOrganisationUnit, new object[]
{ {
SessionId, SessionId,
OldOrganisationUnit, OldOrganisationUnit,
NewOrganisationUnit NewOrganisationUnit
}); });
} }
public static void LogClientError(string ClientIP, string ClientIdentifier, string ClientVersion, string Error, string RawError) public static void LogClientError(string ClientIP, string ClientIdentifier, string ClientVersion, string Error, string RawError)
{ {
EnrolmentLog.Log(EnrolmentLog.EventTypeIds.ClientError, new object[] EnrolmentLog.Log(EnrolmentLog.EventTypeIds.ClientError, new object[]
{ {
ClientIP, ClientIP,
ClientIdentifier, ClientIdentifier,
ClientVersion, ClientVersion,
Error, Error,
RawError RawError
}); });
} }
protected override System.Collections.Generic.List<LogEventType> LoadEventTypes() protected override System.Collections.Generic.List<LogEventType> LoadEventTypes()
{ {
return new System.Collections.Generic.List<LogEventType> return new System.Collections.Generic.List<LogEventType>
{ {
new LogEventType new LogEventType
{ {
Id = 10, Id = 10,
ModuleId = 50, ModuleId = 50,
Name = "Session Starting", Name = "Session Starting",
Format = "Starting '{2}' Enrolment for {1} (Session# {0})", Format = "Starting '{2}' Enrolment for {1} (Session# {0})",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 12, Id = 12,
ModuleId = 50, ModuleId = 50,
Name = "Session Device", Name = "Session Device",
Format = null, Format = null,
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = false UseDisplay = false
}, },
new LogEventType new LogEventType
{ {
Id = 11, Id = 11,
ModuleId = 50, ModuleId = 50,
Name = "Session Progress", Name = "Session Progress",
Format = "Processing Session# {0}; {1}% Complete; Status: {2}", Format = "Processing Session# {0}; {1}% Complete; Status: {2}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = false, UsePersist = false,
UseDisplay = false UseDisplay = false
}, },
new LogEventType new LogEventType
{ {
Id = 13, Id = 13,
ModuleId = 50, ModuleId = 50,
Name = "Session Device Info", Name = "Session Device Info",
Format = null, Format = null,
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 20, Id = 20,
ModuleId = 50, ModuleId = 50,
Name = "Session Finished", Name = "Session Finished",
Format = "Finished Session# {0}", Format = "Finished Session# {0}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 21, Id = 21,
ModuleId = 50, ModuleId = 50,
Name = "Session Diagnostic Information", Name = "Session Diagnostic Information",
Format = null, Format = null,
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = false, UsePersist = false,
UseDisplay = false UseDisplay = false
}, },
new LogEventType new LogEventType
{ {
Id = 22, Id = 22,
ModuleId = 50, ModuleId = 50,
Name = "Session Warning", Name = "Session Warning",
Format = null, Format = null,
Severity = 1, Severity = 1,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 23, Id = 23,
ModuleId = 50, ModuleId = 50,
Name = "Session Error", Name = "Session Error",
Format = "An Error Occurred: [{1}] {2}", Format = "An Error Occurred: [{1}] {2}",
Severity = 2, Severity = 2,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 24, Id = 24,
ModuleId = 50, ModuleId = 50,
Name = "Session Error with Internal", Name = "Session Error with Internal",
Format = "An Error Occurred: [{1}] {2}; Internal Error: [{3}] {4}", Format = "An Error Occurred: [{1}] {2}; Internal Error: [{3}] {4}",
Severity = 2, Severity = 2,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = (int)EventTypeIds.SessionClientError, Id = (int)EventTypeIds.SessionClientError,
ModuleId = _ModuleId, ModuleId = _ModuleId,
Name = "Client Error", Name = "Client Error",
Format = "IP: {1}; Device ID: {2}; Version: {3} Error: {4}; Session# {0}", Format = "IP: {1}; Device ID: {2}; Version: {3} Error: {4}; Session# {0}",
Severity = (int)LogEventType.Severities.Error, Severity = (int)LogEventType.Severities.Error,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 50, Id = 50,
ModuleId = 50, ModuleId = 50,
Name = "Task - Added Device", Name = "Task - Added Device",
Format = "Creating Disco Device {1}", Format = "Creating Disco Device {1}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 51, Id = 51,
ModuleId = 50, ModuleId = 50,
Name = "Task - Updating Device", Name = "Task - Updating Device",
Format = "Updating Disco Device {1}", Format = "Updating Disco Device {1}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 56, Id = 56,
ModuleId = 50, ModuleId = 50,
Name = "Task - Creating Device Model", Name = "Task - Creating Device Model",
Format = "Creating Device Model '{2} {3}' for Device {1}", Format = "Creating Device Model '{2} {3}' for Device {1}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 58, Id = 58,
ModuleId = 50, ModuleId = 50,
Name = "Task - Provisioning Active Directory Account", Name = "Task - Provisioning Active Directory Account",
Format = "Provisioning Active Directory Account '{2}' for Device {1}", Format = "Provisioning Active Directory Account '{2}' for Device {1}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 60, Id = 60,
ModuleId = 50, ModuleId = 50,
Name = "Task - Assigning User", Name = "Task - Assigning User",
Format = "Assigning User '{2}' ({4}\\{3} {{{5}}}) for Device {1}", Format = "Assigning User '{2}' ({4}\\{3} {{{5}}}) for Device {1}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 62, Id = 62,
ModuleId = 50, ModuleId = 50,
Name = "Task - Provisioning Wireless Certificate", Name = "Task - Provisioning Wireless Certificate",
Format = "Provisioning Wireless Certificate '{2}' for Device {1}", Format = "Provisioning Wireless Certificate '{2}' for Device {1}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 64, Id = 64,
ModuleId = 50, ModuleId = 50,
Name = "Task - Renaming Device", Name = "Task - Renaming Device",
Format = "Renaming Device '{1}' to '{2}'", Format = "Renaming Device '{1}' to '{2}'",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 66, Id = 66,
ModuleId = 50, ModuleId = 50,
Name = "Task - Moving Device Organisation Unit", Name = "Task - Moving Device Organisation Unit",
Format = "Moving Device Organisation Unit '{1}' to '{2}'", Format = "Moving Device Organisation Unit '{1}' to '{2}'",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = (int)EventTypeIds.ClientError, Id = (int)EventTypeIds.ClientError,
ModuleId = _ModuleId, ModuleId = _ModuleId,
Name = "Client Error", Name = "Client Error",
Format = "IP: {0}; Device ID: {1}; Version: {2} Error: {3}", Format = "IP: {0}; Device ID: {1}; Version: {2} Error: {3}",
Severity = (int)LogEventType.Severities.Error, Severity = (int)LogEventType.Severities.Error,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
} }
}; };
} }
} }
} }
+56 -56
View File
@@ -1,56 +1,56 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.BI.Search; using Disco.Models.BI.Search;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
namespace Disco.BI.DeviceBI namespace Disco.BI.DeviceBI
{ {
public static class Searching public static class Searching
{ {
private static List<DeviceSearchResultItem> Search_SelectDeviceSearchResultItem(IQueryable<Device> Query, int? LimitCount = null){ private static List<DeviceSearchResultItem> Search_SelectDeviceSearchResultItem(IQueryable<Device> Query, int? LimitCount = null){
if (LimitCount.HasValue) if (LimitCount.HasValue)
Query = Query.Take(LimitCount.Value); Query = Query.Take(LimitCount.Value);
return Query.Select(d => new DeviceSearchResultItem() return Query.Select(d => new DeviceSearchResultItem()
{ {
SerialNumber = d.SerialNumber, SerialNumber = d.SerialNumber,
AssetNumber = d.AssetNumber, AssetNumber = d.AssetNumber,
ComputerName = d.ComputerName, ComputerName = d.ComputerName,
DeviceModelDescription = d.DeviceModel.Description, DeviceModelDescription = d.DeviceModel.Description,
DeviceProfileDescription = d.DeviceProfile.Description, DeviceProfileDescription = d.DeviceProfile.Description,
DecommissionedDate = d.DecommissionedDate, DecommissionedDate = d.DecommissionedDate,
AssignedUserId = d.AssignedUserId, AssignedUserId = d.AssignedUserId,
AssignedUserDisplayName = d.AssignedUser.DisplayName, AssignedUserDisplayName = d.AssignedUser.DisplayName,
JobCount = d.Jobs.Count() JobCount = d.Jobs.Count()
}).ToList(); }).ToList();
} }
public static List<DeviceSearchResultItem> Search(DiscoDataContext dbContext, string Term, int? LimitCount = null) public static List<DeviceSearchResultItem> Search(DiscoDataContext dbContext, string Term, int? LimitCount = null)
{ {
return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d =>
d.AssetNumber.Contains(Term) || d.AssetNumber.Contains(Term) ||
d.ComputerName.Contains(Term) || d.ComputerName.Contains(Term) ||
d.SerialNumber.Contains(Term) || d.SerialNumber.Contains(Term) ||
d.Location.Contains(Term) || d.Location.Contains(Term) ||
Term.Contains(d.SerialNumber) Term.Contains(d.SerialNumber)
), LimitCount); ), LimitCount);
} }
public static List<DeviceSearchResultItem> SearchDeviceModel(DiscoDataContext dbContext, int DeviceModelId, int? LimitCount = null) public static List<DeviceSearchResultItem> SearchDeviceModel(DiscoDataContext dbContext, int DeviceModelId, int? LimitCount = null)
{ {
return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceModelId == DeviceModelId), LimitCount); return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceModelId == DeviceModelId), LimitCount);
} }
public static List<DeviceSearchResultItem> SearchDeviceProfile(DiscoDataContext dbContext, int DeviceProfileId, int? LimitCount = null) public static List<DeviceSearchResultItem> SearchDeviceProfile(DiscoDataContext dbContext, int DeviceProfileId, int? LimitCount = null)
{ {
return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceProfileId == DeviceProfileId), LimitCount); return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceProfileId == DeviceProfileId), LimitCount);
} }
public static List<DeviceSearchResultItem> SearchDeviceBatch(DiscoDataContext dbContext, int DeviceBatchId, int? LimitCount = null) public static List<DeviceSearchResultItem> SearchDeviceBatch(DiscoDataContext dbContext, int DeviceBatchId, int? LimitCount = null)
{ {
return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceBatchId == DeviceBatchId), LimitCount); return Search_SelectDeviceSearchResultItem(dbContext.Devices.Where(d => d.DeviceBatchId == DeviceBatchId), LimitCount);
} }
} }
} }
+21 -21
View File
@@ -1,21 +1,21 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Drawing; using System.Drawing;
namespace Disco.BI namespace Disco.BI
{ {
public class DisposableImageCollection : List<Bitmap>, IDisposable public class DisposableImageCollection : List<Bitmap>, IDisposable
{ {
public void Dispose() public void Dispose()
{ {
foreach (Image i in this) foreach (Image i in this)
{ {
if (i != null) if (i != null)
i.Dispose(); i.Dispose();
} }
} }
} }
} }
@@ -1,72 +1,72 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using System.Web; using System.Web;
using System.Drawing; using System.Drawing;
using iTextSharp.text.pdf; using iTextSharp.text.pdf;
namespace Disco.BI.DocumentTemplateBI namespace Disco.BI.DocumentTemplateBI
{ {
class DocumentTemplateQRCodeLocationCache class DocumentTemplateQRCodeLocationCache
{ {
private static ConcurrentDictionary<string, List<RectangleF>> _Cache = new ConcurrentDictionary<string, List<RectangleF>>(); private static ConcurrentDictionary<string, List<RectangleF>> _Cache = new ConcurrentDictionary<string, List<RectangleF>>();
public static List<RectangleF> GetLocations(DocumentTemplate dt, DiscoDataContext dbContext) public static List<RectangleF> GetLocations(DocumentTemplate dt, DiscoDataContext dbContext)
{ {
// Check Cache // Check Cache
List<RectangleF> locations; List<RectangleF> locations;
if (_Cache.TryGetValue(dt.Id, out locations)) if (_Cache.TryGetValue(dt.Id, out locations))
{ {
return locations; return locations;
} }
// Generate Cache // Generate Cache
return GenerateLocations(dt, dbContext); return GenerateLocations(dt, dbContext);
} }
public static bool InvalidateLocations(DocumentTemplate dt) public static bool InvalidateLocations(DocumentTemplate dt)
{ {
List<RectangleF> locations; List<RectangleF> locations;
return _Cache.TryRemove(dt.Id, out locations); return _Cache.TryRemove(dt.Id, out locations);
} }
private static bool SetValue(string DocumentTemplateId, List<RectangleF> Locations) private static bool SetValue(string DocumentTemplateId, List<RectangleF> Locations)
{ {
if (_Cache.ContainsKey(DocumentTemplateId)) if (_Cache.ContainsKey(DocumentTemplateId))
{ {
List<RectangleF> oldLocations; List<RectangleF> oldLocations;
if (_Cache.TryGetValue(DocumentTemplateId, out oldLocations)) if (_Cache.TryGetValue(DocumentTemplateId, out oldLocations))
{ {
return _Cache.TryUpdate(DocumentTemplateId, Locations, oldLocations); return _Cache.TryUpdate(DocumentTemplateId, Locations, oldLocations);
} }
} }
return _Cache.TryAdd(DocumentTemplateId, Locations); return _Cache.TryAdd(DocumentTemplateId, Locations);
} }
internal static List<RectangleF> GenerateLocations(DocumentTemplate dt, DiscoDataContext dbContext) internal static List<RectangleF> GenerateLocations(DocumentTemplate dt, DiscoDataContext dbContext)
{ {
string templateFilename = dt.RepositoryFilename(dbContext); string templateFilename = dt.RepositoryFilename(dbContext);
PdfReader pdfReader = new PdfReader(templateFilename); PdfReader pdfReader = new PdfReader(templateFilename);
List<RectangleF> locations = new List<RectangleF>(); List<RectangleF> locations = new List<RectangleF>();
if (pdfReader.AcroFields.Fields.ContainsKey("DiscoAttachmentId")) if (pdfReader.AcroFields.Fields.ContainsKey("DiscoAttachmentId"))
{ {
foreach (var pdfFieldPosition in pdfReader.AcroFields.GetFieldPositions("DiscoAttachmentId")) foreach (var pdfFieldPosition in pdfReader.AcroFields.GetFieldPositions("DiscoAttachmentId"))
{ {
var pdfPageSize = pdfReader.GetPageSize(pdfFieldPosition.page); var pdfPageSize = pdfReader.GetPageSize(pdfFieldPosition.page);
locations.Add(new RectangleF((float)System.Math.Min(1.0, System.Math.Max(0.0, (double)(pdfFieldPosition.position.Left / pdfPageSize.Width) - 0.1)), (float)System.Math.Min(1.0, System.Math.Max(0.0, (double)((pdfPageSize.Height - pdfFieldPosition.position.Top) / pdfPageSize.Height) - 0.1)), (float)System.Math.Min(1.0, System.Math.Max(0.0, (double)(pdfFieldPosition.position.Width / pdfPageSize.Width) + 0.2)), (float)System.Math.Min(1.0, System.Math.Max(0.0, (double)(pdfFieldPosition.position.Height / pdfPageSize.Height) + 0.2)))); locations.Add(new RectangleF((float)System.Math.Min(1.0, System.Math.Max(0.0, (double)(pdfFieldPosition.position.Left / pdfPageSize.Width) - 0.1)), (float)System.Math.Min(1.0, System.Math.Max(0.0, (double)((pdfPageSize.Height - pdfFieldPosition.position.Top) / pdfPageSize.Height) - 0.1)), (float)System.Math.Min(1.0, System.Math.Max(0.0, (double)(pdfFieldPosition.position.Width / pdfPageSize.Width) + 0.2)), (float)System.Math.Min(1.0, System.Math.Max(0.0, (double)(pdfFieldPosition.position.Height / pdfPageSize.Height) + 0.2))));
} }
} }
pdfReader.Close(); pdfReader.Close();
// Update Cache // Update Cache
SetValue(dt.Id, locations); SetValue(dt.Id, locations);
return locations; return locations;
} }
} }
} }
@@ -1,203 +1,203 @@
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.Repository; using Disco.Models.Repository;
using System; using System;
namespace Disco.BI.DocumentTemplateBI namespace Disco.BI.DocumentTemplateBI
{ {
public class DocumentUniqueIdentifier public class DocumentUniqueIdentifier
{ {
private bool? _loadedComponentsOk; private bool? _loadedComponentsOk;
private DocumentTemplate _documentTemplate; private DocumentTemplate _documentTemplate;
private object _data; private object _data;
private string _dataDescription; private string _dataDescription;
public string TemplateTypeId { get; private set; } public string TemplateTypeId { get; private set; }
public string DataId { get; private set; } public string DataId { get; private set; }
public string DocumentUniqueId public string DocumentUniqueId
{ {
get get
{ {
return string.Format("{0}|{1}", this.TemplateTypeId, this.DataId); return string.Format("{0}|{1}", this.TemplateTypeId, this.DataId);
} }
} }
public string CreatorId { get; private set; } public string CreatorId { get; private set; }
public System.DateTime TimeStamp { get; private set; } public System.DateTime TimeStamp { get; private set; }
public int Page { get; private set; } public int Page { get; private set; }
public string Tag { get; private set; } public string Tag { get; private set; }
public DocumentTemplate DocumentTemplate public DocumentTemplate DocumentTemplate
{ {
get get
{ {
bool flag = this._loadedComponentsOk.HasValue && this._loadedComponentsOk.Value; bool flag = this._loadedComponentsOk.HasValue && this._loadedComponentsOk.Value;
if (flag) if (flag)
{ {
return this._documentTemplate; return this._documentTemplate;
} }
throw new System.Exception("Document Unique Identifier Components not loaded or invalid"); throw new System.Exception("Document Unique Identifier Components not loaded or invalid");
} }
} }
public object Data public object Data
{ {
get get
{ {
bool flag = this._loadedComponentsOk.HasValue && this._loadedComponentsOk.Value; bool flag = this._loadedComponentsOk.HasValue && this._loadedComponentsOk.Value;
if (flag) if (flag)
{ {
return this._data; return this._data;
} }
throw new System.Exception("Document Unique Identifier Components not loaded or invalid"); throw new System.Exception("Document Unique Identifier Components not loaded or invalid");
} }
} }
public string DataDescription public string DataDescription
{ {
get get
{ {
bool flag = this._loadedComponentsOk.HasValue && this._loadedComponentsOk.Value; bool flag = this._loadedComponentsOk.HasValue && this._loadedComponentsOk.Value;
if (flag) if (flag)
{ {
return this._dataDescription; return this._dataDescription;
} }
throw new System.Exception("Document Unique Identifier Components not loaded or invalid"); throw new System.Exception("Document Unique Identifier Components not loaded or invalid");
} }
} }
public string DataScope { get; private set; } public string DataScope { get; private set; }
public static bool IsDocumentUniqueIdentifier(string UniqueIdentifier) public static bool IsDocumentUniqueIdentifier(string UniqueIdentifier)
{ {
return UniqueIdentifier.StartsWith("Disco|", System.StringComparison.InvariantCultureIgnoreCase); return UniqueIdentifier.StartsWith("Disco|", System.StringComparison.InvariantCultureIgnoreCase);
} }
public DocumentUniqueIdentifier(string TemplateTypeId, string DataId, string CreatorId, DateTime TimeStamp, int? Page = null, string Tag = null) public DocumentUniqueIdentifier(string TemplateTypeId, string DataId, string CreatorId, DateTime TimeStamp, int? Page = null, string Tag = null)
{ {
this.Tag = Tag; this.Tag = Tag;
this.TemplateTypeId = TemplateTypeId; this.TemplateTypeId = TemplateTypeId;
this.DataId = DataId; this.DataId = DataId;
this.CreatorId = CreatorId; this.CreatorId = CreatorId;
this.TimeStamp = TimeStamp; this.TimeStamp = TimeStamp;
this.Page = Page ?? 0; this.Page = Page ?? 0;
} }
public DocumentUniqueIdentifier(string UniqueIdentifier, string Tag) public DocumentUniqueIdentifier(string UniqueIdentifier, string Tag)
{ {
if (!DocumentUniqueIdentifier.IsDocumentUniqueIdentifier(UniqueIdentifier)) if (!DocumentUniqueIdentifier.IsDocumentUniqueIdentifier(UniqueIdentifier))
{ {
throw new System.ArgumentException("Invalid Document Unique Identifier", "UniqueIdentifier"); throw new System.ArgumentException("Invalid Document Unique Identifier", "UniqueIdentifier");
} }
this.Tag = Tag; this.Tag = Tag;
string[] s = UniqueIdentifier.Split(new char[] { '|' }); string[] s = UniqueIdentifier.Split(new char[] { '|' });
string left = s[1].ToUpper(); string left = s[1].ToUpper();
if (left == "AT" || left == "1") if (left == "AT" || left == "1")
{ {
if (s.Length >= 3) if (s.Length >= 3)
{ {
this.TemplateTypeId = s[2]; this.TemplateTypeId = s[2];
} }
if (s.Length >= 4) if (s.Length >= 4)
{ {
this.DataId = s[3]; this.DataId = s[3];
} }
if (s.Length >= 5) if (s.Length >= 5)
{ {
this.CreatorId = s[4]; this.CreatorId = s[4];
} }
if (s.Length >= 6) if (s.Length >= 6)
{ {
System.DateTime timeStamp; System.DateTime timeStamp;
if (System.DateTime.TryParse(s[5], out timeStamp)) if (System.DateTime.TryParse(s[5], out timeStamp))
{ {
this.TimeStamp = timeStamp; this.TimeStamp = timeStamp;
} }
} }
if (s.Length >= 7) if (s.Length >= 7)
{ {
int page = 0; int page = 0;
if (int.TryParse(s[6], out page)) if (int.TryParse(s[6], out page))
{ {
this.Page = page; this.Page = page;
} }
} }
return; return;
} }
throw new System.ArgumentException(string.Format("Invalid Document Unique Identifier Version ({0})", s[1]), "UniqueIdentifier"); throw new System.ArgumentException(string.Format("Invalid Document Unique Identifier Version ({0})", s[1]), "UniqueIdentifier");
} }
public bool LoadComponents(DiscoDataContext Context) public bool LoadComponents(DiscoDataContext Context)
{ {
bool LoadComponents; bool LoadComponents;
if (!this._loadedComponentsOk.HasValue) if (!this._loadedComponentsOk.HasValue)
{ {
string scopeType; string scopeType;
if (this.TemplateTypeId.StartsWith("--")) if (this.TemplateTypeId.StartsWith("--"))
{ {
string templateTypeId = this.TemplateTypeId; string templateTypeId = this.TemplateTypeId;
switch (this.TemplateTypeId) switch (this.TemplateTypeId)
{ {
case "--DEVICE": case "--DEVICE":
scopeType = DocumentTemplate.DocumentTemplateScopes.Device; scopeType = DocumentTemplate.DocumentTemplateScopes.Device;
break; break;
case "--JOB": case "--JOB":
scopeType = DocumentTemplate.DocumentTemplateScopes.Job; scopeType = DocumentTemplate.DocumentTemplateScopes.Job;
break; break;
case "--USER": case "--USER":
scopeType = DocumentTemplate.DocumentTemplateScopes.User; scopeType = DocumentTemplate.DocumentTemplateScopes.User;
break; break;
default: default:
scopeType = null; scopeType = null;
break; break;
} }
} }
else else
{ {
this._documentTemplate = Context.DocumentTemplates.Find(this.TemplateTypeId); this._documentTemplate = Context.DocumentTemplates.Find(this.TemplateTypeId);
if (this._documentTemplate != null) if (this._documentTemplate != null)
{ {
scopeType = this._documentTemplate.Scope; scopeType = this._documentTemplate.Scope;
} }
else else
{ {
scopeType = null; scopeType = null;
} }
} }
if (scopeType != null) if (scopeType != null)
{ {
this.DataScope = scopeType; this.DataScope = scopeType;
switch (scopeType) switch (scopeType)
{ {
case DocumentTemplate.DocumentTemplateScopes.Device: case DocumentTemplate.DocumentTemplateScopes.Device:
Device d = Context.Devices.Find(this.DataId); Device d = Context.Devices.Find(this.DataId);
if (d != null) if (d != null)
{ {
this._data = d; this._data = d;
this._dataDescription = d.SerialNumber; this._dataDescription = d.SerialNumber;
this._loadedComponentsOk = true; this._loadedComponentsOk = true;
LoadComponents = true; LoadComponents = true;
return LoadComponents; return LoadComponents;
} }
break; break;
case DocumentTemplate.DocumentTemplateScopes.Job: case DocumentTemplate.DocumentTemplateScopes.Job:
Job i = Context.Jobs.Find(int.Parse(this.DataId)); Job i = Context.Jobs.Find(int.Parse(this.DataId));
if (i != null) if (i != null)
{ {
this._data = i; this._data = i;
this._dataDescription = i.Id.ToString(); this._dataDescription = i.Id.ToString();
this._loadedComponentsOk = true; this._loadedComponentsOk = true;
LoadComponents = true; LoadComponents = true;
return LoadComponents; return LoadComponents;
} }
break; break;
case DocumentTemplate.DocumentTemplateScopes.User: case DocumentTemplate.DocumentTemplateScopes.User:
User u = Context.Users.Find(this.DataId); User u = Context.Users.Find(this.DataId);
if (u != null) if (u != null)
{ {
this._data = u; this._data = u;
this._dataDescription = u.DisplayName; this._dataDescription = u.DisplayName;
this._loadedComponentsOk = true; this._loadedComponentsOk = true;
LoadComponents = true; LoadComponents = true;
return LoadComponents; return LoadComponents;
} }
break; break;
default: default:
break; break;
} }
} }
this._loadedComponentsOk = false; this._loadedComponentsOk = false;
} }
LoadComponents = this._loadedComponentsOk.Value; LoadComponents = this._loadedComponentsOk.Value;
return LoadComponents; return LoadComponents;
} }
} }
} }
@@ -1,85 +1,85 @@
using System; using System;
using System.IO; using System.IO;
using System.Web.Caching; using System.Web.Caching;
using Disco.Data.Repository; using Disco.Data.Repository;
using Quartz; using Quartz;
using Quartz.Impl; using Quartz.Impl;
using Quartz.Impl.Triggers; using Quartz.Impl.Triggers;
namespace Disco.BI.DocumentTemplateBI.Importer namespace Disco.BI.DocumentTemplateBI.Importer
{ {
public class DocumentDropBoxMonitor : System.IDisposable public class DocumentDropBoxMonitor : System.IDisposable
{ {
private IScheduler _scheduler; private IScheduler _scheduler;
private FileSystemWatcher _fsw; private FileSystemWatcher _fsw;
private Cache _httpCache; private Cache _httpCache;
public const string WatcherFilter = "*.pdf"; public const string WatcherFilter = "*.pdf";
public string DropBoxLocation { get; private set; } public string DropBoxLocation { get; private set; }
public DocumentDropBoxMonitor(DiscoDataContext Context, ISchedulerFactory SchedulerFactory, Cache HttpCache) public DocumentDropBoxMonitor(DiscoDataContext Context, ISchedulerFactory SchedulerFactory, Cache HttpCache)
{ {
if (Context == null) if (Context == null)
throw new System.ArgumentNullException("Context"); throw new System.ArgumentNullException("Context");
this._httpCache = HttpCache; this._httpCache = HttpCache;
var location = DataStore.CreateLocation(Context, "DocumentDropBox"); var location = DataStore.CreateLocation(Context, "DocumentDropBox");
this.DropBoxLocation = location.EndsWith(@"\") ? location : string.Concat(location, @"\"); this.DropBoxLocation = location.EndsWith(@"\") ? location : string.Concat(location, @"\");
this._scheduler = SchedulerFactory.GetScheduler(); this._scheduler = SchedulerFactory.GetScheduler();
this._scheduler.Start(); this._scheduler.Start();
} }
public void ScheduleCurrentFiles(int Delay) public void ScheduleCurrentFiles(int Delay)
{ {
foreach (var filename in System.IO.Directory.GetFiles(this.DropBoxLocation, "*.pdf")) foreach (var filename in System.IO.Directory.GetFiles(this.DropBoxLocation, "*.pdf"))
{ {
this.ScheduleFile(filename, Delay); this.ScheduleFile(filename, Delay);
} }
} }
public void StartWatching() public void StartWatching()
{ {
if (this._fsw == null) if (this._fsw == null)
{ {
this._fsw = new FileSystemWatcher(this.DropBoxLocation, "*.pdf"); this._fsw = new FileSystemWatcher(this.DropBoxLocation, "*.pdf");
this._fsw.Created += new FileSystemEventHandler(this.FSW_Created); this._fsw.Created += new FileSystemEventHandler(this.FSW_Created);
} }
this._fsw.EnableRaisingEvents = true; this._fsw.EnableRaisingEvents = true;
} }
public void StopWatching() public void StopWatching()
{ {
if (this._fsw != null) if (this._fsw != null)
{ {
this._fsw.EnableRaisingEvents = false; this._fsw.EnableRaisingEvents = false;
} }
} }
public void ScheduleFile(string Filename, int Delay) public void ScheduleFile(string Filename, int Delay)
{ {
System.Guid guid = System.Guid.NewGuid(); System.Guid guid = System.Guid.NewGuid();
JobDetailImpl jd = new JobDetailImpl(guid.ToString(), typeof(DocumentImporterJob)); JobDetailImpl jd = new JobDetailImpl(guid.ToString(), typeof(DocumentImporterJob));
jd.JobDataMap.Add("Filename", Filename); jd.JobDataMap.Add("Filename", Filename);
jd.JobDataMap.Add("RetryCount", 0); jd.JobDataMap.Add("RetryCount", 0);
jd.JobDataMap.Add("HttpCache", this._httpCache); jd.JobDataMap.Add("HttpCache", this._httpCache);
guid = System.Guid.NewGuid(); guid = System.Guid.NewGuid();
System.DateTimeOffset startTimeUtc = new System.DateTimeOffset(DateTime.Now.AddSeconds((double)Delay)); System.DateTimeOffset startTimeUtc = new System.DateTimeOffset(DateTime.Now.AddSeconds((double)Delay));
SimpleTriggerImpl trig = new SimpleTriggerImpl(guid.ToString(), startTimeUtc); SimpleTriggerImpl trig = new SimpleTriggerImpl(guid.ToString(), startTimeUtc);
this._scheduler.ScheduleJob(jd, trig); this._scheduler.ScheduleJob(jd, trig);
} }
private void FSW_Created(object sender, FileSystemEventArgs e) private void FSW_Created(object sender, FileSystemEventArgs e)
{ {
if ((e.ChangeType & WatcherChangeTypes.Deleted) != WatcherChangeTypes.Deleted) if ((e.ChangeType & WatcherChangeTypes.Deleted) != WatcherChangeTypes.Deleted)
this.ScheduleFile(e.FullPath, 5); this.ScheduleFile(e.FullPath, 5);
} }
public void Dispose() public void Dispose()
{ {
this.StopWatching(); this.StopWatching();
if (this._fsw != null) if (this._fsw != null)
this._fsw.Dispose(); this._fsw.Dispose();
if (this._scheduler != null) if (this._scheduler != null)
this._scheduler.Shutdown(false); this._scheduler.Shutdown(false);
} }
} }
} }
@@ -1,63 +1,63 @@
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Services.Logging; using Disco.Services.Logging;
using Quartz; using Quartz;
using Quartz.Impl; using Quartz.Impl;
using Disco.Services.Tasks; using Disco.Services.Tasks;
namespace Disco.BI.DocumentTemplateBI.Importer namespace Disco.BI.DocumentTemplateBI.Importer
{ {
public class DocumentImporterCleanCacheJob : ScheduledTask public class DocumentImporterCleanCacheJob : ScheduledTask
{ {
public override string TaskName { get { return "Document Importer - Clean Cache Task"; } } public override string TaskName { get { return "Document Importer - Clean Cache Task"; } }
public override bool SingleInstanceTask { get { return true; } } public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext dbContext)
{ {
// Trigger Daily @ 12:30am // Trigger Daily @ 12:30am
TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 30)); TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 30));
this.ScheduleTask(triggerBuilder); this.ScheduleTask(triggerBuilder);
} }
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
string dataStoreLocation; string dataStoreLocation;
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext dbContext = new DiscoDataContext())
{ {
dataStoreLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages"); dataStoreLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages");
} }
int deleteCount = 0; int deleteCount = 0;
int errorCount = 0; int errorCount = 0;
System.IO.DirectoryInfo dataStoreInfo = new System.IO.DirectoryInfo(dataStoreLocation); System.IO.DirectoryInfo dataStoreInfo = new System.IO.DirectoryInfo(dataStoreLocation);
System.DateTime today = System.DateTime.Today; System.DateTime today = System.DateTime.Today;
foreach (System.IO.FileInfo file in dataStoreInfo.GetFiles()) foreach (System.IO.FileInfo file in dataStoreInfo.GetFiles())
{ {
try try
{ {
if (file.CreationTime < today) if (file.CreationTime < today)
{ {
file.Delete(); file.Delete();
deleteCount++; deleteCount++;
} }
} }
catch catch
{ {
errorCount++; errorCount++;
} }
} }
SystemLog.LogInformation( SystemLog.LogInformation(
string.Format("Cleared DocumentDropBox_SessionPages Cache, Deleted {0} File/s, with {1} Error/s", deleteCount, errorCount), string.Format("Cleared DocumentDropBox_SessionPages Cache, Deleted {0} File/s, with {1} Error/s", deleteCount, errorCount),
deleteCount, deleteCount,
errorCount errorCount
); );
} }
} }
} }
@@ -1,120 +1,120 @@
using System; using System;
using System.IO; using System.IO;
using System.Web.Caching; using System.Web.Caching;
using Disco.Data.Repository; using Disco.Data.Repository;
using Quartz; using Quartz;
using Quartz.Impl.Triggers; using Quartz.Impl.Triggers;
namespace Disco.BI.DocumentTemplateBI.Importer namespace Disco.BI.DocumentTemplateBI.Importer
{ {
[PersistJobDataAfterExecution] [PersistJobDataAfterExecution]
public class DocumentImporterJob : IJob public class DocumentImporterJob : IJob
{ {
void IJob.Execute(IJobExecutionContext context) void IJob.Execute(IJobExecutionContext context)
{ {
string sessionId = context.JobDetail.JobDataMap["SessionId"] as string; string sessionId = context.JobDetail.JobDataMap["SessionId"] as string;
if (string.IsNullOrEmpty(sessionId)) if (string.IsNullOrEmpty(sessionId))
{ {
sessionId = Guid.NewGuid().ToString(); sessionId = Guid.NewGuid().ToString();
context.JobDetail.JobDataMap["SessionId"] = sessionId; context.JobDetail.JobDataMap["SessionId"] = sessionId;
} }
string filename = context.JobDetail.JobDataMap["Filename"] as string; string filename = context.JobDetail.JobDataMap["Filename"] as string;
int retryCount = (int)context.JobDetail.JobDataMap["RetryCount"]; int retryCount = (int)context.JobDetail.JobDataMap["RetryCount"];
Cache httpCache = context.JobDetail.JobDataMap["HttpCache"] as Cache; Cache httpCache = context.JobDetail.JobDataMap["HttpCache"] as Cache;
var friendlyFilename = filename; var friendlyFilename = filename;
if (!string.IsNullOrEmpty(friendlyFilename)) if (!string.IsNullOrEmpty(friendlyFilename))
friendlyFilename = System.IO.Path.GetFileName(friendlyFilename); friendlyFilename = System.IO.Path.GetFileName(friendlyFilename);
DocumentImporterLog.LogImportStarting(sessionId, friendlyFilename); DocumentImporterLog.LogImportStarting(sessionId, friendlyFilename);
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
DocumentImporterLog.LogImportWarning(sessionId, string.Format("File not found: {0}", filename)); DocumentImporterLog.LogImportWarning(sessionId, string.Format("File not found: {0}", filename));
DocumentImporterLog.LogImportFinished(sessionId); DocumentImporterLog.LogImportFinished(sessionId);
context.Scheduler.DeleteJob(context.JobDetail.Key); context.Scheduler.DeleteJob(context.JobDetail.Key);
return; return;
} }
try try
{ {
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext dbContext = new DiscoDataContext())
{ {
if (retryCount < 18) if (retryCount < 18)
{ {
context.JobDetail.JobDataMap["RetryCount"] = (++retryCount); context.JobDetail.JobDataMap["RetryCount"] = (++retryCount);
bool processResult = Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, dbContext, sessionId, httpCache); bool processResult = Interop.Pdf.PdfImporter.ProcessPdfAttachment(filename, dbContext, sessionId, httpCache);
if (processResult) if (processResult)
{ {
// Import Successful - Delete // Import Successful - Delete
if (File.Exists(filename)) if (File.Exists(filename))
File.Delete(filename); File.Delete(filename);
} }
else else
{ {
// Import Failed - Move to Errors Folder // Import Failed - Move to Errors Folder
if (File.Exists(filename)) if (File.Exists(filename))
{ {
try try
{ {
string folderError = DataStore.CreateLocation(dbContext, "DocumentDropBox_Errors"); string folderError = DataStore.CreateLocation(dbContext, "DocumentDropBox_Errors");
string filenameError = Path.Combine(folderError, Path.GetFileName(filename)); string filenameError = Path.Combine(folderError, Path.GetFileName(filename));
int filenameErrorCount = 0; int filenameErrorCount = 0;
while (File.Exists(filenameError)) while (File.Exists(filenameError))
{ {
filenameError = Path.Combine(folderError, string.Format("{0} ({1}){2}", Path.GetFileNameWithoutExtension(filename), ++filenameErrorCount, Path.GetExtension(filename))); filenameError = Path.Combine(folderError, string.Format("{0} ({1}){2}", Path.GetFileNameWithoutExtension(filename), ++filenameErrorCount, Path.GetExtension(filename)));
} }
File.Move(filename, filenameError); File.Move(filename, filenameError);
} }
catch catch
{ {
// Ignore Errors // Ignore Errors
} }
} }
} }
} }
else else
{ {
// To Many Errors // To Many Errors
DocumentImporterLog.LogImportError(sessionId, string.Format("To many errors occurred trying to import '{1}' (SessionId: {0})", sessionId, friendlyFilename)); DocumentImporterLog.LogImportError(sessionId, string.Format("To many errors occurred trying to import '{1}' (SessionId: {0})", sessionId, friendlyFilename));
// Move to Errors Folder // Move to Errors Folder
if (File.Exists(filename)) if (File.Exists(filename))
{ {
try try
{ {
string folderError = DataStore.CreateLocation(dbContext, "DocumentDropBox_Errors"); string folderError = DataStore.CreateLocation(dbContext, "DocumentDropBox_Errors");
string filenameError = Path.Combine(folderError, Path.GetFileName(filename)); string filenameError = Path.Combine(folderError, Path.GetFileName(filename));
int filenameErrorCount = 0; int filenameErrorCount = 0;
while (File.Exists(filenameError)) while (File.Exists(filenameError))
{ {
filenameError = Path.Combine(folderError, string.Format("{0} ({1}){2}", Path.GetFileNameWithoutExtension(filename), ++filenameErrorCount, Path.GetExtension(filename))); filenameError = Path.Combine(folderError, string.Format("{0} ({1}){2}", Path.GetFileNameWithoutExtension(filename), ++filenameErrorCount, Path.GetExtension(filename)));
} }
File.Move(filename, filenameError); File.Move(filename, filenameError);
} }
catch catch
{ {
// Ignore Errors // Ignore Errors
} }
} }
} }
} }
DocumentImporterLog.LogImportFinished(sessionId); DocumentImporterLog.LogImportFinished(sessionId);
// All Done // All Done
context.Scheduler.DeleteJob(context.JobDetail.Key); context.Scheduler.DeleteJob(context.JobDetail.Key);
} }
catch (Exception ex) catch (Exception ex)
{ {
DocumentImporterLog.LogImportWarning(sessionId, string.Format("{0}; Will try again in 10 Seconds", ex.Message)); DocumentImporterLog.LogImportWarning(sessionId, string.Format("{0}; Will try again in 10 Seconds", ex.Message));
// Reschedule Job for 10 seconds // Reschedule Job for 10 seconds
SimpleTriggerImpl trig = new SimpleTriggerImpl(Guid.NewGuid().ToString(), new DateTimeOffset(DateTime.Now.AddSeconds(10))); SimpleTriggerImpl trig = new SimpleTriggerImpl(Guid.NewGuid().ToString(), new DateTimeOffset(DateTime.Now.AddSeconds(10)));
context.Scheduler.RescheduleJob(context.Trigger.Key, trig); context.Scheduler.RescheduleJob(context.Trigger.Key, trig);
} }
} }
} }
} }
@@ -1,304 +1,304 @@
using Disco.Services.Logging; using Disco.Services.Logging;
using Disco.Services.Logging.Models; using Disco.Services.Logging.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
namespace Disco.BI.DocumentTemplateBI.Importer namespace Disco.BI.DocumentTemplateBI.Importer
{ {
public class DocumentImporterLog : LogBase public class DocumentImporterLog : LogBase
{ {
public enum EventTypeIds public enum EventTypeIds
{ {
ImportStarting = 10, ImportStarting = 10,
ImportProgress, ImportProgress,
ImportFinished, ImportFinished,
ImportWarning = 15, ImportWarning = 15,
ImportError, ImportError,
ImportPageStarting = 100, ImportPageStarting = 100,
ImportPageImageUpdate = 104, ImportPageImageUpdate = 104,
ImportPageProgress, ImportPageProgress,
ImportPageDetected = 110, ImportPageDetected = 110,
ImportPageUndetected = 115, ImportPageUndetected = 115,
ImportPageError = 120, ImportPageError = 120,
ImportPageUndetectedStored = 150 ImportPageUndetectedStored = 150
} }
private const int _ModuleId = 40; private const int _ModuleId = 40;
public static DocumentImporterLog Current public static DocumentImporterLog Current
{ {
get get
{ {
return (DocumentImporterLog)LogContext.LogModules[_ModuleId]; return (DocumentImporterLog)LogContext.LogModules[_ModuleId];
} }
} }
public override string ModuleDescription public override string ModuleDescription
{ {
get get
{ {
return "Document Importer"; return "Document Importer";
} }
} }
public override int ModuleId public override int ModuleId
{ {
get get
{ {
return _ModuleId; return _ModuleId;
} }
} }
public override string ModuleName public override string ModuleName
{ {
get get
{ {
return "DocumentImporter"; return "DocumentImporter";
} }
} }
private static void Log(DocumentImporterLog.EventTypeIds EventTypeId, params object[] Args) private static void Log(DocumentImporterLog.EventTypeIds EventTypeId, params object[] Args)
{ {
DocumentImporterLog.Current.Log((int)EventTypeId, Args); DocumentImporterLog.Current.Log((int)EventTypeId, Args);
} }
public static void LogImportStarting(string SessionId, string DocumentName) public static void LogImportStarting(string SessionId, string DocumentName)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportStarting, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportStarting, new object[]
{ {
SessionId, SessionId,
DocumentName DocumentName
}); });
} }
public static void LogImportProgress(string SessionId, int? Progress, string Status) public static void LogImportProgress(string SessionId, int? Progress, string Status)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportProgress, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportProgress, new object[]
{ {
SessionId, SessionId,
Progress, Progress,
Status Status
}); });
} }
public static void LogImportFinished(string SessionId) public static void LogImportFinished(string SessionId)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportFinished, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportFinished, new object[]
{ {
SessionId SessionId
}); });
} }
public static void LogImportWarning(string SessionId, string Message) public static void LogImportWarning(string SessionId, string Message)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportWarning, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportWarning, new object[]
{ {
SessionId, SessionId,
Message Message
}); });
} }
public static void LogImportError(string SessionId, string Message) public static void LogImportError(string SessionId, string Message)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportError, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportError, new object[]
{ {
SessionId, SessionId,
Message Message
}); });
} }
public static void LogImportPageStarting(string SessionId, int PageNumber) public static void LogImportPageStarting(string SessionId, int PageNumber)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageStarting, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageStarting, new object[]
{ {
SessionId, SessionId,
PageNumber PageNumber
}); });
} }
public static void LogImportPageImageUpdate(string SessionId, int PageNumber) public static void LogImportPageImageUpdate(string SessionId, int PageNumber)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageImageUpdate, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageImageUpdate, new object[]
{ {
SessionId, SessionId,
PageNumber PageNumber
}); });
} }
public static void LogImportPageProgress(string SessionId, int PageNumber, int? Progress, string Status) public static void LogImportPageProgress(string SessionId, int PageNumber, int? Progress, string Status)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageProgress, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageProgress, new object[]
{ {
SessionId, SessionId,
PageNumber, PageNumber,
Progress, Progress,
Status Status
}); });
} }
public static void LogImportPageDetected(string SessionId, int PageNumber, string DocumentTypeId, string DocumentTypeName, string TargetType, string AssignedId, string AssignedName) public static void LogImportPageDetected(string SessionId, int PageNumber, string DocumentTypeId, string DocumentTypeName, string TargetType, string AssignedId, string AssignedName)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageDetected, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageDetected, new object[]
{ {
SessionId, SessionId,
PageNumber, PageNumber,
DocumentTypeId, DocumentTypeId,
DocumentTypeName, DocumentTypeName,
TargetType, TargetType,
AssignedId, AssignedId,
AssignedName AssignedName
}); });
} }
public static void LogImportPageUndetected(string SessionId, int PageNumber) public static void LogImportPageUndetected(string SessionId, int PageNumber)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageUndetected, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageUndetected, new object[]
{ {
SessionId, SessionId,
PageNumber PageNumber
}); });
} }
public static void LogImportPageError(string SessionId, int PageNumber, string Message) public static void LogImportPageError(string SessionId, int PageNumber, string Message)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageError, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageError, new object[]
{ {
SessionId, SessionId,
PageNumber, PageNumber,
Message Message
}); });
} }
public static void LogImportPageUndetectedStored(string SessionId, int PageNumber) public static void LogImportPageUndetectedStored(string SessionId, int PageNumber)
{ {
DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageUndetectedStored, new object[] DocumentImporterLog.Log(DocumentImporterLog.EventTypeIds.ImportPageUndetectedStored, new object[]
{ {
SessionId, SessionId,
PageNumber PageNumber
}); });
} }
protected override System.Collections.Generic.List<LogEventType> LoadEventTypes() protected override System.Collections.Generic.List<LogEventType> LoadEventTypes()
{ {
return new System.Collections.Generic.List<LogEventType> return new System.Collections.Generic.List<LogEventType>
{ {
new LogEventType new LogEventType
{ {
Id = 10, Id = 10,
ModuleId = 40, ModuleId = 40,
Name = "Import Starting", Name = "Import Starting",
Format = "Starting import of document: {1} (SessionId: {0})", Format = "Starting import of document: {1} (SessionId: {0})",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 11, Id = 11,
ModuleId = 40, ModuleId = 40,
Name = "Import Progress", Name = "Import Progress",
Format = "Processing: {1}% Complete; Status: {2}", Format = "Processing: {1}% Complete; Status: {2}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = false, UsePersist = false,
UseDisplay = false UseDisplay = false
}, },
new LogEventType new LogEventType
{ {
Id = 12, Id = 12,
ModuleId = 40, ModuleId = 40,
Name = "Import Finished", Name = "Import Finished",
Format = "Import of document complete (SessionId: {0})", Format = "Import of document complete (SessionId: {0})",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 15, Id = 15,
ModuleId = 40, ModuleId = 40,
Name = "Import Warning", Name = "Import Warning",
Format = "Import Warning: {1} (SessionId: {0})", Format = "Import Warning: {1} (SessionId: {0})",
Severity = 1, Severity = 1,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 16, Id = 16,
ModuleId = 40, ModuleId = 40,
Name = "Import Error", Name = "Import Error",
Format = "Import Error: {1} (SessionId: {0})", Format = "Import Error: {1} (SessionId: {0})",
Severity = 2, Severity = 2,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 100, Id = 100,
ModuleId = 40, ModuleId = 40,
Name = "Import Page Starting", Name = "Import Page Starting",
Format = "Starting import of page: {1} (SessionId: {0})", Format = "Starting import of page: {1} (SessionId: {0})",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 104, Id = 104,
ModuleId = 40, ModuleId = 40,
Name = "Import Page Image Update", Name = "Import Page Image Update",
Format = null, Format = null,
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = false, UsePersist = false,
UseDisplay = false UseDisplay = false
}, },
new LogEventType new LogEventType
{ {
Id = 105, Id = 105,
ModuleId = 40, ModuleId = 40,
Name = "Import Page Progress", Name = "Import Page Progress",
Format = "Processing: Page {1}; {2}% Complete; Status: {3}", Format = "Processing: Page {1}; {2}% Complete; Status: {3}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = false, UsePersist = false,
UseDisplay = false UseDisplay = false
}, },
new LogEventType new LogEventType
{ {
Id = 110, Id = 110,
ModuleId = 40, ModuleId = 40,
Name = "Import Page Assigned", Name = "Import Page Assigned",
Format = "Page {1} of type '{3}' assigned to {4}: '{6}'", Format = "Page {1} of type '{3}' assigned to {4}: '{6}'",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 115, Id = 115,
ModuleId = 40, ModuleId = 40,
Name = "Import Page Undetected", Name = "Import Page Undetected",
Format = "Page {1} not detected", Format = "Page {1} not detected",
Severity = 1, Severity = 1,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 120, Id = 120,
ModuleId = 40, ModuleId = 40,
Name = "Import Page Error", Name = "Import Page Error",
Format = "Page {1}, Import Error: {2}", Format = "Page {1}, Import Error: {2}",
Severity = 2, Severity = 2,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 150, Id = 150,
ModuleId = 40, ModuleId = 40,
Name = "Import Page Undetected Stored", Name = "Import Page Undetected Stored",
Format = null, Format = null,
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = false, UsePersist = false,
UseDisplay = false UseDisplay = false
} }
}; };
} }
} }
} }
+49 -49
View File
@@ -1,49 +1,49 @@
using iTextSharp.text; using iTextSharp.text;
using iTextSharp.text.pdf; using iTextSharp.text.pdf;
namespace Disco.BI.DocumentTemplateBI namespace Disco.BI.DocumentTemplateBI
{ {
public static class Utilities public static class Utilities
{ {
public static System.IO.Stream JoinPdfs(params System.IO.Stream[] Pdfs) public static System.IO.Stream JoinPdfs(params System.IO.Stream[] Pdfs)
{ {
if (Pdfs.Length == 0) if (Pdfs.Length == 0)
throw new System.ArgumentNullException("Pdfs"); throw new System.ArgumentNullException("Pdfs");
// Only One PDF - Possible Reference Bug v's Memory/Speed (Returning Param Memory Stream) // Only One PDF - Possible Reference Bug v's Memory/Speed (Returning Param Memory Stream)
if (Pdfs.Length == 1) if (Pdfs.Length == 1)
return Pdfs[0]; return Pdfs[0];
// Join Pdfs // Join Pdfs
System.IO.MemoryStream msBuilder = new System.IO.MemoryStream(); System.IO.MemoryStream msBuilder = new System.IO.MemoryStream();
Document pdfDoc = new Document(); Document pdfDoc = new Document();
PdfCopy pdfCopy = new PdfCopy(pdfDoc, msBuilder); PdfCopy pdfCopy = new PdfCopy(pdfDoc, msBuilder);
pdfDoc.Open(); pdfDoc.Open();
pdfCopy.CloseStream = false; pdfCopy.CloseStream = false;
for (int i = 0; i < Pdfs.Length; i++) for (int i = 0; i < Pdfs.Length; i++)
{ {
System.IO.Stream pdf = Pdfs[i]; System.IO.Stream pdf = Pdfs[i];
PdfReader pdfReader = new PdfReader(pdf); PdfReader pdfReader = new PdfReader(pdf);
for (int indexPage = 1; indexPage <= pdfReader.NumberOfPages; indexPage++) for (int indexPage = 1; indexPage <= pdfReader.NumberOfPages; indexPage++)
{ {
iTextSharp.text.Rectangle pageSize = pdfReader.GetPageSizeWithRotation(indexPage); iTextSharp.text.Rectangle pageSize = pdfReader.GetPageSizeWithRotation(indexPage);
PdfImportedPage page = pdfCopy.GetImportedPage(pdfReader, indexPage); PdfImportedPage page = pdfCopy.GetImportedPage(pdfReader, indexPage);
pdfDoc.SetPageSize(pageSize); pdfDoc.SetPageSize(pageSize);
pdfDoc.NewPage(); pdfDoc.NewPage();
pdfCopy.AddPage(page); pdfCopy.AddPage(page);
} }
pdfReader.Close(); pdfReader.Close();
} }
pdfDoc.Close(); pdfDoc.Close();
pdfCopy.Close(); pdfCopy.Close();
msBuilder.Position = 0; msBuilder.Position = 0;
return msBuilder; return msBuilder;
} }
} }
} }
@@ -1,27 +1,27 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Spring.Expressions.Parser.antlr; using Spring.Expressions.Parser.antlr;
namespace Disco.BI.Expressions namespace Disco.BI.Expressions
{ {
public class EvaluateExpressionParseException public class EvaluateExpressionParseException
{ {
public string Expression { get; set; } public string Expression { get; set; }
public int PositionRow { get; set; } public int PositionRow { get; set; }
public int PositionColumn { get; set; } public int PositionColumn { get; set; }
public string Message { get; set; } public string Message { get; set; }
internal static EvaluateExpressionParseException FromRecognitionException(RecognitionException e, string Expression) internal static EvaluateExpressionParseException FromRecognitionException(RecognitionException e, string Expression)
{ {
return new EvaluateExpressionParseException() return new EvaluateExpressionParseException()
{ {
Expression = Expression, Expression = Expression,
Message = e.Message, Message = e.Message,
PositionRow = e.getLine(), PositionRow = e.getLine(),
PositionColumn = e.getColumn() PositionColumn = e.getColumn()
}; };
} }
} }
} }
@@ -1,84 +1,84 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Spring.Expressions.Parser.antlr; using Spring.Expressions.Parser.antlr;
namespace Disco.BI.Expressions namespace Disco.BI.Expressions
{ {
public class EvaluateExpressionPart : IExpressionPart public class EvaluateExpressionPart : IExpressionPart
{ {
private Spring.Expressions.IExpression _Expression; private Spring.Expressions.IExpression _Expression;
private RecognitionException _ExpressionParseException; private RecognitionException _ExpressionParseException;
private EvaluateExpressionParseException _EvaluateParseException; private EvaluateExpressionParseException _EvaluateParseException;
public string RawSource { get; set; } public string RawSource { get; set; }
public string Source { get; set; } public string Source { get; set; }
public bool ErrorsAllowed { get; set; } public bool ErrorsAllowed { get; set; }
public bool IsDynamic { get { return true; } set { return; } } public bool IsDynamic { get { return true; } set { return; } }
public EvaluateExpressionParseException ParseException public EvaluateExpressionParseException ParseException
{ {
get get
{ {
if (_ExpressionParseException == null) if (_ExpressionParseException == null)
return null; return null;
else else
if (_EvaluateParseException == null) if (_EvaluateParseException == null)
_EvaluateParseException = EvaluateExpressionParseException.FromRecognitionException(_ExpressionParseException, this.Source); _EvaluateParseException = EvaluateExpressionParseException.FromRecognitionException(_ExpressionParseException, this.Source);
return _EvaluateParseException; return _EvaluateParseException;
} }
} }
public bool ParseError public bool ParseError
{ {
get { return (_ExpressionParseException != null); } get { return (_ExpressionParseException != null); }
} }
public string ParseErrorMessage public string ParseErrorMessage
{ {
get get
{ {
if (ParseError) if (ParseError)
return ParseException.Message; return ParseException.Message;
else else
return null; return null;
} }
} }
public EvaluateExpressionPart(string Source) public EvaluateExpressionPart(string Source)
{ {
this.RawSource = Source; this.RawSource = Source;
if (Source.StartsWith("{") && Source.EndsWith("}")) if (Source.StartsWith("{") && Source.EndsWith("}"))
Source = Source.Substring(1, Source.Length - 2); Source = Source.Substring(1, Source.Length - 2);
if (Source[0] == '~') if (Source[0] == '~')
{ {
this.ErrorsAllowed = true; this.ErrorsAllowed = true;
this.Source = Source.Substring(1); this.Source = Source.Substring(1);
} }
else else
{ {
this.ErrorsAllowed = false; this.ErrorsAllowed = false;
this.Source = Source; this.Source = Source;
} }
try try
{ {
this._Expression = Spring.Expressions.Expression.Parse(this.Source); this._Expression = Spring.Expressions.Expression.Parse(this.Source);
} }
catch (RecognitionException ex) catch (RecognitionException ex)
{ {
this._ExpressionParseException = ex; this._ExpressionParseException = ex;
} }
} }
object IExpressionPart.Evaluate(object ExpressionContext, System.Collections.IDictionary Variables) object IExpressionPart.Evaluate(object ExpressionContext, System.Collections.IDictionary Variables)
{ {
if (this._ExpressionParseException == null) if (this._ExpressionParseException == null)
{ {
return this._Expression.GetValue(ExpressionContext, Variables); return this._Expression.GetValue(ExpressionContext, Variables);
} }
throw this._ExpressionParseException; throw this._ExpressionParseException;
} }
} }
} }
+259 -259
View File
@@ -1,259 +1,259 @@
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.BI.DocumentTemplates; using Disco.Models.BI.DocumentTemplates;
using Disco.Models.Repository; using Disco.Models.Repository;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using Disco.Models.BI.Expressions; using Disco.Models.BI.Expressions;
namespace Disco.BI.Expressions namespace Disco.BI.Expressions
{ {
public sealed class Expression : System.Collections.Generic.List<IExpressionPart> public sealed class Expression : System.Collections.Generic.List<IExpressionPart>
{ {
public string Name { get; private set; } public string Name { get; private set; }
public string Source { get; private set; } public string Source { get; private set; }
public bool IsDynamic { get; private set; } public bool IsDynamic { get; private set; }
public int Ordinal { get; private set; } public int Ordinal { get; private set; }
private Expression(string Name, string Source, int Ordinal) private Expression(string Name, string Source, int Ordinal)
{ {
this.Name = Name; this.Name = Name;
this.Source = Source; this.Source = Source;
this.Ordinal = Ordinal; this.Ordinal = Ordinal;
} }
public static void InitializeExpressions() public static void InitializeExpressions()
{ {
Spring.Core.TypeResolution.TypeRegistry.RegisterType("DataExt", typeof(Extensions.DataExt)); Spring.Core.TypeResolution.TypeRegistry.RegisterType("DataExt", typeof(Extensions.DataExt));
Spring.Core.TypeResolution.TypeRegistry.RegisterType("UserExt", typeof(Extensions.UserExt)); Spring.Core.TypeResolution.TypeRegistry.RegisterType("UserExt", typeof(Extensions.UserExt));
Spring.Core.TypeResolution.TypeRegistry.RegisterType("DeviceExt", typeof(Extensions.DeviceExt)); Spring.Core.TypeResolution.TypeRegistry.RegisterType("DeviceExt", typeof(Extensions.DeviceExt));
Spring.Core.TypeResolution.TypeRegistry.RegisterType("ImageExt", typeof(Extensions.ImageExt)); Spring.Core.TypeResolution.TypeRegistry.RegisterType("ImageExt", typeof(Extensions.ImageExt));
} }
public T EvaluateFirst<T>(object ExpressionContext, System.Collections.IDictionary Variables) public T EvaluateFirst<T>(object ExpressionContext, System.Collections.IDictionary Variables)
{ {
T result = default(T); T result = default(T);
if (this.Count > 0) if (this.Count > 0)
{ {
try try
{ {
object expressionResult = this[0].Evaluate(ExpressionContext, Variables); object expressionResult = this[0].Evaluate(ExpressionContext, Variables);
if (expressionResult != null) if (expressionResult != null)
{ {
if (expressionResult is T) if (expressionResult is T)
{ {
result = (T)expressionResult; result = (T)expressionResult;
} }
else else
{ {
throw new InvalidOperationException("Expression returned an invalid type"); throw new InvalidOperationException("Expression returned an invalid type");
} }
} }
} }
catch (System.Exception ex) catch (System.Exception ex)
{ {
throw new InvalidOperationException("Expression evaluation resulted in an error", ex); throw new InvalidOperationException("Expression evaluation resulted in an error", ex);
} }
} }
return result; return result;
} }
public Tuple<string, bool, object> Evaluate(object ExpressionContext, System.Collections.IDictionary Variables) public Tuple<string, bool, object> Evaluate(object ExpressionContext, System.Collections.IDictionary Variables)
{ {
System.Text.StringBuilder resultValue = new System.Text.StringBuilder(); System.Text.StringBuilder resultValue = new System.Text.StringBuilder();
object resultObject = null; object resultObject = null;
bool resultError = false; bool resultError = false;
foreach (var expressionPart in this) foreach (var expressionPart in this)
{ {
try try
{ {
object partValue = expressionPart.Evaluate(ExpressionContext, Variables); object partValue = expressionPart.Evaluate(ExpressionContext, Variables);
if (partValue != null) if (partValue != null)
{ {
// Check for Result Objects // Check for Result Objects
if (partValue is IImageExpressionResult) if (partValue is IImageExpressionResult)
resultObject = partValue; resultObject = partValue;
else else
resultValue.Append(partValue.ToString()); resultValue.Append(partValue.ToString());
} }
} }
catch (System.Exception ex) catch (System.Exception ex)
{ {
if (!expressionPart.ErrorsAllowed) if (!expressionPart.ErrorsAllowed)
{ {
resultValue.Append("## ERROR # "); resultValue.Append("## ERROR # ");
resultValue.Append(ex.Message); resultValue.Append(ex.Message);
resultValue.Append(" ##"); resultValue.Append(" ##");
resultError = true; resultError = true;
} }
} }
} }
return new Tuple<string, bool, object>(resultValue.ToString(), resultError, resultObject); return new Tuple<string, bool, object>(resultValue.ToString(), resultError, resultObject);
} }
public static Expression TokenizeSingleDynamic(string Name, string ExpressionSource, int Ordinal) public static Expression TokenizeSingleDynamic(string Name, string ExpressionSource, int Ordinal)
{ {
Expression e = new Expression(Name, ExpressionSource, Ordinal); Expression e = new Expression(Name, ExpressionSource, Ordinal);
if (ExpressionSource != null && !string.IsNullOrWhiteSpace(ExpressionSource)) if (ExpressionSource != null && !string.IsNullOrWhiteSpace(ExpressionSource))
e.Add(new EvaluateExpressionPart(ExpressionSource)); e.Add(new EvaluateExpressionPart(ExpressionSource));
e.IsDynamic = true; e.IsDynamic = true;
return e; return e;
} }
public static Expression Tokenize(string Name, string ExpressionSource, int Ordinal) public static Expression Tokenize(string Name, string ExpressionSource, int Ordinal)
{ {
Expression e = new Expression(Name, ExpressionSource, Ordinal); Expression e = new Expression(Name, ExpressionSource, Ordinal);
if (!ExpressionSource.Contains("{") || !ExpressionSource.Contains("}")) if (!ExpressionSource.Contains("{") || !ExpressionSource.Contains("}"))
{ {
e.Add(new TextExpressionPart(ExpressionSource)); e.Add(new TextExpressionPart(ExpressionSource));
} }
else else
{ {
System.Text.StringBuilder token = new System.Text.StringBuilder(); System.Text.StringBuilder token = new System.Text.StringBuilder();
bool tokenEval = false; bool tokenEval = false;
int tokenEvalDepth = 0; int tokenEvalDepth = 0;
foreach (char c in ExpressionSource) foreach (char c in ExpressionSource)
{ {
switch (c) switch (c)
{ {
case '{': case '{':
{ {
if (!tokenEval) if (!tokenEval)
{ {
if (token.Length > 0) if (token.Length > 0)
{ {
e.Add(new TextExpressionPart(token.ToString())); e.Add(new TextExpressionPart(token.ToString()));
token = new System.Text.StringBuilder(); token = new System.Text.StringBuilder();
} }
tokenEval = true; tokenEval = true;
tokenEvalDepth = 0; tokenEvalDepth = 0;
} }
tokenEvalDepth++; tokenEvalDepth++;
token.Append(c); token.Append(c);
break; break;
} }
case '}': case '}':
{ {
token.Append(c); token.Append(c);
if (tokenEval) if (tokenEval)
{ {
tokenEvalDepth--; tokenEvalDepth--;
if (tokenEvalDepth <= 0) if (tokenEvalDepth <= 0)
{ {
if (token.Length != 2 && (token.Length != 3 || token[1] != '@')) if (token.Length != 2 && (token.Length != 3 || token[1] != '@'))
{ {
e.Add(new EvaluateExpressionPart(token.ToString())); e.Add(new EvaluateExpressionPart(token.ToString()));
e.IsDynamic = true; e.IsDynamic = true;
token = new System.Text.StringBuilder(); token = new System.Text.StringBuilder();
} }
tokenEval = false; tokenEval = false;
} }
} }
break; break;
} }
default: default:
{ {
token.Append(c); token.Append(c);
break; break;
} }
} }
} }
if (token.Length > 0) if (token.Length > 0)
{ {
e.Add(new TextExpressionPart(token.ToString())); e.Add(new TextExpressionPart(token.ToString()));
} }
} }
return e; return e;
} }
public static IDictionary StandardVariables(DocumentTemplate AttachmentType, DiscoDataContext DataContext, User User, System.DateTime TimeStamp, DocumentState DocumentState) public static IDictionary StandardVariables(DocumentTemplate AttachmentType, DiscoDataContext DataContext, User User, System.DateTime TimeStamp, DocumentState DocumentState)
{ {
return new Hashtable return new Hashtable
{ {
{ {
"DataContext", "DataContext",
DataContext DataContext
}, },
{ {
"User", "User",
User User
}, },
{ {
"TimeStamp", "TimeStamp",
TimeStamp TimeStamp
}, },
{ {
"AttachmentType", "AttachmentType",
AttachmentType AttachmentType
}, },
{ {
"State", "State",
DocumentState DocumentState
} }
}; };
} }
public static Dictionary<string, string> StandardVariableTypes() public static Dictionary<string, string> StandardVariableTypes()
{ {
return new Dictionary<string, string> return new Dictionary<string, string>
{ {
{ {
"#DataContext", "#DataContext",
typeof(DiscoDataContext).AssemblyQualifiedName typeof(DiscoDataContext).AssemblyQualifiedName
}, },
{ {
"#User", "#User",
typeof(User).AssemblyQualifiedName typeof(User).AssemblyQualifiedName
}, },
{ {
"#TimeStamp", "#TimeStamp",
typeof(System.DateTime).AssemblyQualifiedName typeof(System.DateTime).AssemblyQualifiedName
}, },
{ {
"#AttachmentType", "#AttachmentType",
typeof(DocumentTemplate).AssemblyQualifiedName typeof(DocumentTemplate).AssemblyQualifiedName
}, },
{ {
"#State", "#State",
typeof(DocumentState).AssemblyQualifiedName typeof(DocumentState).AssemblyQualifiedName
} }
}; };
} }
public static Dictionary<string, string> ExtensionLibraryTypes() public static Dictionary<string, string> ExtensionLibraryTypes()
{ {
return new Dictionary<string, string> return new Dictionary<string, string>
{ {
{ {
"DataExt", "DataExt",
typeof(Extensions.DataExt).AssemblyQualifiedName typeof(Extensions.DataExt).AssemblyQualifiedName
}, },
{ {
"DeviceExt", "DeviceExt",
typeof(Extensions.DeviceExt).AssemblyQualifiedName typeof(Extensions.DeviceExt).AssemblyQualifiedName
}, },
{ {
"ImageExt", "ImageExt",
typeof(Extensions.ImageExt).AssemblyQualifiedName typeof(Extensions.ImageExt).AssemblyQualifiedName
}, },
{ {
"UserExt", "UserExt",
typeof(Extensions.UserExt).AssemblyQualifiedName typeof(Extensions.UserExt).AssemblyQualifiedName
} }
}; };
} }
} }
} }
+103 -103
View File
@@ -1,103 +1,103 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Collections.Concurrent; using System.Collections.Concurrent;
namespace Disco.BI.Expressions namespace Disco.BI.Expressions
{ {
public static class ExpressionCache public static class ExpressionCache
{ {
private static ConcurrentDictionary<string, ConcurrentDictionary<string, Expression>> _Cache = new ConcurrentDictionary<string, ConcurrentDictionary<string, Expression>>(); private static ConcurrentDictionary<string, ConcurrentDictionary<string, Expression>> _Cache = new ConcurrentDictionary<string, ConcurrentDictionary<string, Expression>>();
public delegate Expression CreateValueDelegate(); public delegate Expression CreateValueDelegate();
public static ConcurrentDictionary<string, Expression> GetModule(string Module, bool Create = false) public static ConcurrentDictionary<string, Expression> GetModule(string Module, bool Create = false)
{ {
ConcurrentDictionary<string, Expression> moduleCache; ConcurrentDictionary<string, Expression> moduleCache;
if (_Cache.TryGetValue(Module, out moduleCache)) if (_Cache.TryGetValue(Module, out moduleCache))
return moduleCache; return moduleCache;
else else
{ {
if (Create) if (Create)
{ {
moduleCache = new ConcurrentDictionary<string, Expression>(); moduleCache = new ConcurrentDictionary<string, Expression>();
_Cache.TryAdd(Module, moduleCache); _Cache.TryAdd(Module, moduleCache);
return moduleCache; return moduleCache;
} }
else else
return null; return null;
} }
} }
private static Expression GetModuleValue(string Module, string Key, CreateValueDelegate CreateValue) private static Expression GetModuleValue(string Module, string Key, CreateValueDelegate CreateValue)
{ {
ConcurrentDictionary<string, Expression> moduleCache = GetModule(Module, (CreateValue != null)); ConcurrentDictionary<string, Expression> moduleCache = GetModule(Module, (CreateValue != null));
if (moduleCache != null) if (moduleCache != null)
{ {
Expression expression; Expression expression;
if (moduleCache.TryGetValue(Key, out expression)) if (moduleCache.TryGetValue(Key, out expression))
{ {
return expression; return expression;
} }
if (CreateValue != null) if (CreateValue != null)
{ {
expression = CreateValue(); expression = CreateValue();
Expression oldExpression; Expression oldExpression;
if (moduleCache.TryGetValue(Key, out oldExpression)) if (moduleCache.TryGetValue(Key, out oldExpression))
moduleCache.TryUpdate(Key, expression, oldExpression); moduleCache.TryUpdate(Key, expression, oldExpression);
else else
moduleCache.TryAdd(Key, expression); moduleCache.TryAdd(Key, expression);
return expression; return expression;
} }
} }
return null; return null;
} }
public static Expression GetValue(string Module, string Key, CreateValueDelegate CreateValue) public static Expression GetValue(string Module, string Key, CreateValueDelegate CreateValue)
{ {
return GetModuleValue(Module, Key, CreateValue); return GetModuleValue(Module, Key, CreateValue);
} }
public static Expression GetValue(string Module, string Key) public static Expression GetValue(string Module, string Key)
{ {
return GetModuleValue(Module, Key, null); return GetModuleValue(Module, Key, null);
} }
public static bool InvalidModule(string Module) public static bool InvalidModule(string Module)
{ {
ConcurrentDictionary<string, Expression> moduleCache; ConcurrentDictionary<string, Expression> moduleCache;
return _Cache.TryRemove(Module, out moduleCache); return _Cache.TryRemove(Module, out moduleCache);
} }
public static bool InvalidateKey(string Module, string Key) public static bool InvalidateKey(string Module, string Key)
{ {
Expression expression; Expression expression;
ConcurrentDictionary<string, Expression> moduleCache = GetModule(Module, false); ConcurrentDictionary<string, Expression> moduleCache = GetModule(Module, false);
if (moduleCache != null) if (moduleCache != null)
{ {
bool removeResult = moduleCache.TryRemove(Key, out expression); bool removeResult = moduleCache.TryRemove(Key, out expression);
if (moduleCache.Count == 0) if (moduleCache.Count == 0)
InvalidModule(Module); InvalidModule(Module);
return removeResult; return removeResult;
} }
else else
return false; return false;
} }
public static bool SetValue(string Module, string Key, Expression Expression) public static bool SetValue(string Module, string Key, Expression Expression)
{ {
ConcurrentDictionary<string, Expression> moduleCache = GetModule(Module, true); ConcurrentDictionary<string, Expression> moduleCache = GetModule(Module, true);
if (moduleCache.ContainsKey(Key)) if (moduleCache.ContainsKey(Key))
{ {
Expression oldExpression; Expression oldExpression;
if (moduleCache.TryGetValue(Key, out oldExpression)) if (moduleCache.TryGetValue(Key, out oldExpression))
{ {
return moduleCache.TryUpdate(Key, Expression, oldExpression); return moduleCache.TryUpdate(Key, Expression, oldExpression);
} }
} }
return moduleCache.TryAdd(Key, Expression); return moduleCache.TryAdd(Key, Expression);
} }
} }
} }
@@ -1,43 +1,43 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Services.Tasks; using Disco.Services.Tasks;
using Disco.Data.Repository; using Disco.Data.Repository;
using Quartz; using Quartz;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using System.Diagnostics; using System.Diagnostics;
namespace Disco.BI.Expressions namespace Disco.BI.Expressions
{ {
public class ExpressionCachePreloadTask : ScheduledTask public class ExpressionCachePreloadTask : ScheduledTask
{ {
public override string TaskName { get { return "Expression Cache - Preload Task"; } } public override string TaskName { get { return "Expression Cache - Preload Task"; } }
public override bool SingleInstanceTask { get { return true; } } public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext dbContext)
{ {
// Run in Background 1 Second after Scheduled (on App Startup) // Run in Background 1 Second after Scheduled (on App Startup)
TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(new DateTimeOffset(DateTime.Now).AddSeconds(5)); TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(new DateTimeOffset(DateTime.Now).AddSeconds(5));
this.ScheduleTask(triggerBuilder); this.ScheduleTask(triggerBuilder);
} }
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
// Cache Document Template Filter Expressions // Cache Document Template Filter Expressions
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext dbContext = new DiscoDataContext())
{ {
foreach (var documentTemplate in dbContext.DocumentTemplates.Where(dt => dt.FilterExpression != null && dt.FilterExpression != string.Empty)) foreach (var documentTemplate in dbContext.DocumentTemplates.Where(dt => dt.FilterExpression != null && dt.FilterExpression != string.Empty))
{ {
if (!string.IsNullOrWhiteSpace(documentTemplate.FilterExpression)) if (!string.IsNullOrWhiteSpace(documentTemplate.FilterExpression))
documentTemplate.FilterExpressionFromCache(); documentTemplate.FilterExpressionFromCache();
} }
} }
} }
} }
} }
@@ -1,58 +1,58 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
namespace Disco.BI.Expressions namespace Disco.BI.Expressions
{ {
public class ExpressionTypeDescriptor public class ExpressionTypeDescriptor
{ {
public string ExpressionType { get; set; } public string ExpressionType { get; set; }
public string Name { get; set; } public string Name { get; set; }
public List<ExpressionTypeMemberDescriptor> Members { get; set; } public List<ExpressionTypeMemberDescriptor> Members { get; set; }
public static ExpressionTypeDescriptor Build(System.Type t, bool StaticDeclaredMembersOnly = true) public static ExpressionTypeDescriptor Build(System.Type t, bool StaticDeclaredMembersOnly = true)
{ {
ExpressionTypeDescriptor i = new ExpressionTypeDescriptor ExpressionTypeDescriptor i = new ExpressionTypeDescriptor
{ {
ExpressionType = t.AssemblyQualifiedName, ExpressionType = t.AssemblyQualifiedName,
Name = t.Name Name = t.Name
}; };
i.Members = new System.Collections.Generic.List<ExpressionTypeMemberDescriptor>(); i.Members = new System.Collections.Generic.List<ExpressionTypeMemberDescriptor>();
System.Reflection.MemberInfo[] members; System.Reflection.MemberInfo[] members;
if (StaticDeclaredMembersOnly) if (StaticDeclaredMembersOnly)
members = t.GetMembers(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); members = t.GetMembers(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
else else
members = t.GetMembers(BindingFlags.Public | BindingFlags.Instance); members = t.GetMembers(BindingFlags.Public | BindingFlags.Instance);
for (int j = 0; j < members.Length; j++) for (int j = 0; j < members.Length; j++)
{ {
System.Reflection.MemberInfo member = members[j]; System.Reflection.MemberInfo member = members[j];
if (member is System.Reflection.PropertyInfo) if (member is System.Reflection.PropertyInfo)
{ {
System.Reflection.PropertyInfo pi = (System.Reflection.PropertyInfo)member; System.Reflection.PropertyInfo pi = (System.Reflection.PropertyInfo)member;
if (!pi.IsSpecialName && pi.CanRead) if (!pi.IsSpecialName && pi.CanRead)
{ {
i.Members.Add(ExpressionTypeMemberDescriptor.Build(pi)); i.Members.Add(ExpressionTypeMemberDescriptor.Build(pi));
} }
} }
if (member is System.Reflection.MethodInfo) if (member is System.Reflection.MethodInfo)
{ {
System.Reflection.MethodInfo mi2 = (System.Reflection.MethodInfo)member; System.Reflection.MethodInfo mi2 = (System.Reflection.MethodInfo)member;
if (!mi2.IsSpecialName) if (!mi2.IsSpecialName)
{ {
i.Members.Add(ExpressionTypeMemberDescriptor.Build(mi2)); i.Members.Add(ExpressionTypeMemberDescriptor.Build(mi2));
} }
} }
} }
i.Members = ( i.Members = (
from mi in i.Members from mi in i.Members
orderby mi.Name orderby mi.Name
select mi).ToList(); select mi).ToList();
return i; return i;
} }
} }
} }
@@ -1,61 +1,61 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
namespace Disco.BI.Expressions namespace Disco.BI.Expressions
{ {
public class ExpressionTypeMemberDescriptor public class ExpressionTypeMemberDescriptor
{ {
public const string FunctionKind = "function"; public const string FunctionKind = "function";
public const string PropertyKind = "property"; public const string PropertyKind = "property";
public const string ParameterKind = "parameter"; public const string ParameterKind = "parameter";
public string Kind {get;set;} public string Kind {get;set;}
public string Name {get;set;} public string Name {get;set;}
public string ReturnType {get;set;} public string ReturnType {get;set;}
public string ReturnExpressionType{get;set;} public string ReturnExpressionType{get;set;}
public List<ExpressionTypeMemberDescriptor> Parameters{get;set;} public List<ExpressionTypeMemberDescriptor> Parameters{get;set;}
public static ExpressionTypeMemberDescriptor Build(System.Reflection.MethodInfo m) public static ExpressionTypeMemberDescriptor Build(System.Reflection.MethodInfo m)
{ {
ExpressionTypeMemberDescriptor md = new ExpressionTypeMemberDescriptor ExpressionTypeMemberDescriptor md = new ExpressionTypeMemberDescriptor
{ {
Kind = "function", Kind = "function",
Name = m.Name, Name = m.Name,
ReturnType = m.ReturnType.Name, ReturnType = m.ReturnType.Name,
ReturnExpressionType = m.ReturnType.AssemblyQualifiedName ReturnExpressionType = m.ReturnType.AssemblyQualifiedName
}; };
md.Parameters = ( md.Parameters = (
from mdp in m.GetParameters() from mdp in m.GetParameters()
select ExpressionTypeMemberDescriptor.Build(mdp)).ToList<ExpressionTypeMemberDescriptor>(); select ExpressionTypeMemberDescriptor.Build(mdp)).ToList<ExpressionTypeMemberDescriptor>();
return md; return md;
} }
public static ExpressionTypeMemberDescriptor Build(System.Reflection.PropertyInfo p) public static ExpressionTypeMemberDescriptor Build(System.Reflection.PropertyInfo p)
{ {
ExpressionTypeMemberDescriptor md = new ExpressionTypeMemberDescriptor ExpressionTypeMemberDescriptor md = new ExpressionTypeMemberDescriptor
{ {
Kind = "property", Kind = "property",
Name = p.Name, Name = p.Name,
ReturnType = p.PropertyType.Name, ReturnType = p.PropertyType.Name,
ReturnExpressionType = p.PropertyType.AssemblyQualifiedName ReturnExpressionType = p.PropertyType.AssemblyQualifiedName
}; };
md.Parameters = ( md.Parameters = (
from mdp in p.GetIndexParameters() from mdp in p.GetIndexParameters()
select ExpressionTypeMemberDescriptor.Build(mdp)).ToList<ExpressionTypeMemberDescriptor>(); select ExpressionTypeMemberDescriptor.Build(mdp)).ToList<ExpressionTypeMemberDescriptor>();
return md; return md;
} }
public static ExpressionTypeMemberDescriptor Build(System.Reflection.ParameterInfo pi) public static ExpressionTypeMemberDescriptor Build(System.Reflection.ParameterInfo pi)
{ {
return new ExpressionTypeMemberDescriptor return new ExpressionTypeMemberDescriptor
{ {
Kind = "parameter", Kind = "parameter",
Name = pi.Name, Name = pi.Name,
ReturnType = pi.ParameterType.Name, ReturnType = pi.ParameterType.Name,
ReturnExpressionType = pi.ParameterType.AssemblyQualifiedName ReturnExpressionType = pi.ParameterType.AssemblyQualifiedName
}; };
} }
} }
} }
+176 -176
View File
@@ -1,176 +1,176 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Data; using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using System.Collections; using System.Collections;
using System.Data.Odbc; using System.Data.Odbc;
namespace Disco.BI.Expressions.Extensions namespace Disco.BI.Expressions.Extensions
{ {
public static class DataExt public static class DataExt
{ {
#region SqlClient #region SqlClient
private static SqlConnection BuildSqlConnection(string Server, string Database, string Username, string Password) private static SqlConnection BuildSqlConnection(string Server, string Database, string Username, string Password)
{ {
SqlConnectionStringBuilder dbConnectionStringBuilder = new SqlConnectionStringBuilder(); SqlConnectionStringBuilder dbConnectionStringBuilder = new SqlConnectionStringBuilder();
dbConnectionStringBuilder.ApplicationName = "Disco"; dbConnectionStringBuilder.ApplicationName = "Disco";
dbConnectionStringBuilder.DataSource = Server; dbConnectionStringBuilder.DataSource = Server;
dbConnectionStringBuilder.InitialCatalog = Database; dbConnectionStringBuilder.InitialCatalog = Database;
dbConnectionStringBuilder.MultipleActiveResultSets = true; dbConnectionStringBuilder.MultipleActiveResultSets = true;
dbConnectionStringBuilder.PersistSecurityInfo = true; dbConnectionStringBuilder.PersistSecurityInfo = true;
if (Username == null || Password == null) if (Username == null || Password == null)
dbConnectionStringBuilder.IntegratedSecurity = true; dbConnectionStringBuilder.IntegratedSecurity = true;
else else
{ {
dbConnectionStringBuilder.UserID = Username; dbConnectionStringBuilder.UserID = Username;
dbConnectionStringBuilder.Password = Password; dbConnectionStringBuilder.Password = Password;
} }
return new SqlConnection(dbConnectionStringBuilder.ConnectionString); return new SqlConnection(dbConnectionStringBuilder.ConnectionString);
} }
private static void BuildSqlParameters(SqlCommand dbCommand, Hashtable SqlParameters) private static void BuildSqlParameters(SqlCommand dbCommand, Hashtable SqlParameters)
{ {
if (SqlParameters != null) if (SqlParameters != null)
{ {
foreach (var sqlParameterKey in SqlParameters.Keys) foreach (var sqlParameterKey in SqlParameters.Keys)
{ {
string key = sqlParameterKey.ToString(); string key = sqlParameterKey.ToString();
if (!key.StartsWith("@")) if (!key.StartsWith("@"))
key = string.Concat("@", key); key = string.Concat("@", key);
dbCommand.Parameters.AddWithValue(key, SqlParameters[sqlParameterKey]); dbCommand.Parameters.AddWithValue(key, SqlParameters[sqlParameterKey]);
} }
} }
} }
public static DataTable QuerySqlDatabase(string Server, string Database, string Username, string Password, string SqlQuery, Hashtable SqlParameters) public static DataTable QuerySqlDatabase(string Server, string Database, string Username, string Password, string SqlQuery, Hashtable SqlParameters)
{ {
using (SqlConnection dbConnection = BuildSqlConnection(Server, Database, Username, Password)) using (SqlConnection dbConnection = BuildSqlConnection(Server, Database, Username, Password))
{ {
using (SqlCommand dbCommand = new SqlCommand(SqlQuery, dbConnection)) using (SqlCommand dbCommand = new SqlCommand(SqlQuery, dbConnection))
{ {
BuildSqlParameters(dbCommand, SqlParameters); BuildSqlParameters(dbCommand, SqlParameters);
using (SqlDataAdapter dbAdapter = new SqlDataAdapter(dbCommand)) using (SqlDataAdapter dbAdapter = new SqlDataAdapter(dbCommand))
{ {
var dbTable = new DataTable(); var dbTable = new DataTable();
dbAdapter.Fill(dbTable); dbAdapter.Fill(dbTable);
return dbTable; return dbTable;
} }
} }
} }
} }
public static DataTable QuerySqlDatabase(string Server, string Database, string SqlQuery, Hashtable SqlParameters) public static DataTable QuerySqlDatabase(string Server, string Database, string SqlQuery, Hashtable SqlParameters)
{ {
return QuerySqlDatabase(Server, Database, null, null, SqlQuery, SqlParameters); return QuerySqlDatabase(Server, Database, null, null, SqlQuery, SqlParameters);
} }
public static DataTable QuerySqlDatabase(string Server, string Database, string SqlQuery) public static DataTable QuerySqlDatabase(string Server, string Database, string SqlQuery)
{ {
return QuerySqlDatabase(Server, Database, null, null, SqlQuery, null); return QuerySqlDatabase(Server, Database, null, null, SqlQuery, null);
} }
public static object QuerySqlDatabaseScalar(string Server, string Database, string Username, string Password, string SqlQuery, Hashtable SqlParameters) public static object QuerySqlDatabaseScalar(string Server, string Database, string Username, string Password, string SqlQuery, Hashtable SqlParameters)
{ {
using (SqlConnection dbConnection = BuildSqlConnection(Server, Database, Username, Password)) using (SqlConnection dbConnection = BuildSqlConnection(Server, Database, Username, Password))
{ {
using (SqlCommand dbCommand = new SqlCommand(SqlQuery, dbConnection)) using (SqlCommand dbCommand = new SqlCommand(SqlQuery, dbConnection))
{ {
BuildSqlParameters(dbCommand, SqlParameters); BuildSqlParameters(dbCommand, SqlParameters);
try try
{ {
dbConnection.Open(); dbConnection.Open();
return dbCommand.ExecuteScalar(); return dbCommand.ExecuteScalar();
} }
catch (Exception) catch (Exception)
{ {
throw; throw;
} }
finally finally
{ {
dbConnection.Close(); dbConnection.Close();
} }
} }
} }
} }
public static object QuerySqlDatabaseScalar(string Server, string Database, string SqlQuery, Hashtable SqlParameters) public static object QuerySqlDatabaseScalar(string Server, string Database, string SqlQuery, Hashtable SqlParameters)
{ {
return QuerySqlDatabaseScalar(Server, Database, null, null, SqlQuery, SqlParameters); return QuerySqlDatabaseScalar(Server, Database, null, null, SqlQuery, SqlParameters);
} }
public static object QuerySqlDatabaseScalar(string Server, string Database, string SqlQuery) public static object QuerySqlDatabaseScalar(string Server, string Database, string SqlQuery)
{ {
return QuerySqlDatabaseScalar(Server, Database, null, null, SqlQuery, null); return QuerySqlDatabaseScalar(Server, Database, null, null, SqlQuery, null);
} }
#endregion #endregion
#region ODBC #region ODBC
private static OdbcConnection BuildOdbcConnection(string ConnectionString) private static OdbcConnection BuildOdbcConnection(string ConnectionString)
{ {
return new OdbcConnection(ConnectionString); return new OdbcConnection(ConnectionString);
} }
private static void BuildOdbcParameters(OdbcCommand dbCommand, Hashtable OdbcParameters) private static void BuildOdbcParameters(OdbcCommand dbCommand, Hashtable OdbcParameters)
{ {
if (OdbcParameters != null) if (OdbcParameters != null)
{ {
foreach (var odbcParameterKey in OdbcParameters.Keys) foreach (var odbcParameterKey in OdbcParameters.Keys)
{ {
string key = odbcParameterKey.ToString(); string key = odbcParameterKey.ToString();
dbCommand.Parameters.AddWithValue(key, OdbcParameters[odbcParameterKey]); dbCommand.Parameters.AddWithValue(key, OdbcParameters[odbcParameterKey]);
} }
} }
} }
public static DataTable QueryOdbcDatabase(string ConnectionString, string OdbcQuery, Hashtable OdbcParameters) public static DataTable QueryOdbcDatabase(string ConnectionString, string OdbcQuery, Hashtable OdbcParameters)
{ {
using (OdbcConnection dbConnection = BuildOdbcConnection(ConnectionString)) using (OdbcConnection dbConnection = BuildOdbcConnection(ConnectionString))
{ {
using (OdbcCommand dbCommand = new OdbcCommand(OdbcQuery, dbConnection)) using (OdbcCommand dbCommand = new OdbcCommand(OdbcQuery, dbConnection))
{ {
BuildOdbcParameters(dbCommand, OdbcParameters); BuildOdbcParameters(dbCommand, OdbcParameters);
using (OdbcDataAdapter dbAdapter = new OdbcDataAdapter(dbCommand)) using (OdbcDataAdapter dbAdapter = new OdbcDataAdapter(dbCommand))
{ {
var dbTable = new DataTable(); var dbTable = new DataTable();
dbAdapter.Fill(dbTable); dbAdapter.Fill(dbTable);
return dbTable; return dbTable;
} }
} }
} }
} }
public static DataTable QueryOdbcDatabase(string ConnectionString, string OdbcQuery) public static DataTable QueryOdbcDatabase(string ConnectionString, string OdbcQuery)
{ {
return QueryOdbcDatabase(ConnectionString, OdbcQuery, null); return QueryOdbcDatabase(ConnectionString, OdbcQuery, null);
} }
public static object QueryOdbcDatabaseScalar(string ConnectionString, string OdbcQuery, Hashtable OdbcParameters) public static object QueryOdbcDatabaseScalar(string ConnectionString, string OdbcQuery, Hashtable OdbcParameters)
{ {
using (OdbcConnection dbConnection = BuildOdbcConnection(ConnectionString)) using (OdbcConnection dbConnection = BuildOdbcConnection(ConnectionString))
{ {
using (OdbcCommand dbCommand = new OdbcCommand(OdbcQuery, dbConnection)) using (OdbcCommand dbCommand = new OdbcCommand(OdbcQuery, dbConnection))
{ {
BuildOdbcParameters(dbCommand, OdbcParameters); BuildOdbcParameters(dbCommand, OdbcParameters);
try try
{ {
dbConnection.Open(); dbConnection.Open();
return dbCommand.ExecuteScalar(); return dbCommand.ExecuteScalar();
} }
catch (Exception) catch (Exception)
{ {
throw; throw;
} }
finally finally
{ {
dbConnection.Close(); dbConnection.Close();
} }
} }
} }
} }
public static object QueryOdbcDatabaseScalar(string ConnectionString, string OdbcQuery) public static object QueryOdbcDatabaseScalar(string ConnectionString, string OdbcQuery)
{ {
return QueryOdbcDatabaseScalar(ConnectionString, OdbcQuery, null); return QueryOdbcDatabaseScalar(ConnectionString, OdbcQuery, null);
} }
#endregion #endregion
} }
} }
+51 -51
View File
@@ -1,51 +1,51 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using Disco.BI.Interop.ActiveDirectory; using Disco.BI.Interop.ActiveDirectory;
namespace Disco.BI.Expressions.Extensions namespace Disco.BI.Expressions.Extensions
{ {
public static class DeviceExt public static class DeviceExt
{ {
public static object GetActiveDirectoryObjectValue(Device Device, string PropertyName, int Index = 0) public static object GetActiveDirectoryObjectValue(Device Device, string PropertyName, int Index = 0)
{ {
var adMachineAccount = Device.ActiveDirectoryAccount(PropertyName); var adMachineAccount = Device.ActiveDirectoryAccount(PropertyName);
if (adMachineAccount != null) if (adMachineAccount != null)
return adMachineAccount.GetPropertyValue(PropertyName, Index); return adMachineAccount.GetPropertyValue(PropertyName, Index);
else else
return null; return null;
} }
public static string GetActiveDirectoryStringValue(Device Device, string PropertyName, int Index = 0) public static string GetActiveDirectoryStringValue(Device Device, string PropertyName, int Index = 0)
{ {
var objectValue = GetActiveDirectoryObjectValue(Device, PropertyName, Index); var objectValue = GetActiveDirectoryObjectValue(Device, PropertyName, Index);
string stringValue = objectValue as string; string stringValue = objectValue as string;
if (stringValue == null && objectValue != null) if (stringValue == null && objectValue != null)
stringValue = objectValue.ToString(); stringValue = objectValue.ToString();
return stringValue; return stringValue;
} }
public static int GetActiveDirectoryIntegerValue(Device Device, string PropertyName, int Index = 0) public static int GetActiveDirectoryIntegerValue(Device Device, string PropertyName, int Index = 0)
{ {
var objectValue = GetActiveDirectoryObjectValue(Device, PropertyName, Index); var objectValue = GetActiveDirectoryObjectValue(Device, PropertyName, Index);
if (objectValue == null) if (objectValue == null)
return default(int); return default(int);
else else
{ {
int intValue; int intValue;
try try
{ {
intValue = (int)Convert.ChangeType(objectValue, typeof(int)); intValue = (int)Convert.ChangeType(objectValue, typeof(int));
} }
catch (Exception) catch (Exception)
{ {
throw; throw;
} }
return intValue; return intValue;
} }
} }
} }
} }
+140 -140
View File
@@ -1,140 +1,140 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.BI.Expressions; using Disco.Models.BI.Expressions;
using Disco.BI.Expressions.Extensions.ImageResultImplementations; using Disco.BI.Expressions.Extensions.ImageResultImplementations;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using Disco.Data.Repository; using Disco.Data.Repository;
using System.Collections; using System.Collections;
using System.IO; using System.IO;
using System.Drawing; using System.Drawing;
namespace Disco.BI.Expressions.Extensions namespace Disco.BI.Expressions.Extensions
{ {
public static class ImageExt public static class ImageExt
{ {
public static FileImageExpressionResult ImageFromFile(string AbsoluteFilePath) public static FileImageExpressionResult ImageFromFile(string AbsoluteFilePath)
{ {
return new FileImageExpressionResult(AbsoluteFilePath); return new FileImageExpressionResult(AbsoluteFilePath);
} }
public static FileImageExpressionResult ImageFromDataStoreFile(string RelativeFilePath) public static FileImageExpressionResult ImageFromDataStoreFile(string RelativeFilePath)
{ {
var configCache = new Disco.Data.Configuration.ConfigurationContext(null); var configCache = new Disco.Data.Configuration.ConfigurationContext(null);
string DataStoreLocation = configCache.DataStoreLocation; string DataStoreLocation = configCache.DataStoreLocation;
string AbsoluteFilePath = System.IO.Path.Combine(DataStoreLocation, RelativeFilePath); string AbsoluteFilePath = System.IO.Path.Combine(DataStoreLocation, RelativeFilePath);
return new FileImageExpressionResult(AbsoluteFilePath); return new FileImageExpressionResult(AbsoluteFilePath);
} }
public static FileImageExpressionResult JobAttachmentFirstImage(Job Job, DiscoDataContext dbContext) public static FileImageExpressionResult JobAttachmentFirstImage(Job Job, DiscoDataContext dbContext)
{ {
var attachment = Job.JobAttachments.FirstOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)); var attachment = Job.JobAttachments.FirstOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase));
if (attachment != null) if (attachment != null)
{ {
var filename = attachment.RepositoryFilename(dbContext); var filename = attachment.RepositoryFilename(dbContext);
return new FileImageExpressionResult(filename); return new FileImageExpressionResult(filename);
} }
else else
return null; return null;
} }
public static FileImageExpressionResult JobAttachmentLastImage(Job Job, DiscoDataContext dbContext) public static FileImageExpressionResult JobAttachmentLastImage(Job Job, DiscoDataContext dbContext)
{ {
var attachment = Job.JobAttachments.LastOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)); var attachment = Job.JobAttachments.LastOrDefault(ja => ja.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase));
if (attachment != null) if (attachment != null)
{ {
var filename = attachment.RepositoryFilename(dbContext); var filename = attachment.RepositoryFilename(dbContext);
return new FileImageExpressionResult(filename); return new FileImageExpressionResult(filename);
} }
else else
return null; return null;
} }
public static FileImageExpressionResult JobAttachmentImage(JobAttachment JobAttachment, DiscoDataContext dbContext) public static FileImageExpressionResult JobAttachmentImage(JobAttachment JobAttachment, DiscoDataContext dbContext)
{ {
if (JobAttachment == null) if (JobAttachment == null)
throw new ArgumentNullException("JobAttachment"); throw new ArgumentNullException("JobAttachment");
if (!JobAttachment.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)) if (!JobAttachment.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase))
throw new ArgumentException("Invalid Image MimeType for Attachment"); throw new ArgumentException("Invalid Image MimeType for Attachment");
var filename = JobAttachment.RepositoryFilename(dbContext); var filename = JobAttachment.RepositoryFilename(dbContext);
return new FileImageExpressionResult(filename); return new FileImageExpressionResult(filename);
} }
public static FileMontageImageExpressionResult JobAttachmentImageMontage(Job Job, DiscoDataContext dbContext) public static FileMontageImageExpressionResult JobAttachmentImageMontage(Job Job, DiscoDataContext dbContext)
{ {
if (Job == null) if (Job == null)
throw new ArgumentNullException("Job"); throw new ArgumentNullException("Job");
if (Job.JobAttachments == null) if (Job.JobAttachments == null)
throw new ArgumentException("Job.JobAttachments is null", "Job"); throw new ArgumentException("Job.JobAttachments is null", "Job");
var attachments = Job.JobAttachments.Where(a => a.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)).ToList(); var attachments = Job.JobAttachments.Where(a => a.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)).ToList();
if (attachments.Count > 0) if (attachments.Count > 0)
{ {
var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(dbContext)).ToList(); var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(dbContext)).ToList();
return new FileMontageImageExpressionResult(attachmentFilepaths); return new FileMontageImageExpressionResult(attachmentFilepaths);
} }
else else
return null; return null;
} }
public static FileMontageImageExpressionResult JobAttachmentsImageMontage(ArrayList JobAttachments, DiscoDataContext dbContext) public static FileMontageImageExpressionResult JobAttachmentsImageMontage(ArrayList JobAttachments, DiscoDataContext dbContext)
{ {
if (JobAttachments == null) if (JobAttachments == null)
throw new ArgumentNullException("JobAttachments"); throw new ArgumentNullException("JobAttachments");
var attachments = JobAttachments.Cast<JobAttachment>().Where(a => a.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)).ToList(); var attachments = JobAttachments.Cast<JobAttachment>().Where(a => a.MimeType.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase)).ToList();
if (attachments.Count > 0) if (attachments.Count > 0)
{ {
var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(dbContext)).ToList(); var attachmentFilepaths = attachments.Select(a => a.RepositoryFilename(dbContext)).ToList();
return new FileMontageImageExpressionResult(attachmentFilepaths); return new FileMontageImageExpressionResult(attachmentFilepaths);
} }
else else
return null; return null;
} }
public static BitmapImageExpressionResult ImageFromStream(Stream ImageStream) public static BitmapImageExpressionResult ImageFromStream(Stream ImageStream)
{ {
if (ImageStream == null) if (ImageStream == null)
throw new ArgumentNullException("ImageStream"); throw new ArgumentNullException("ImageStream");
return new BitmapImageExpressionResult(Bitmap.FromStream(ImageStream)); return new BitmapImageExpressionResult(Bitmap.FromStream(ImageStream));
} }
public static BitmapImageExpressionResult ImageFromByteArray(byte[] ImageByteArray) public static BitmapImageExpressionResult ImageFromByteArray(byte[] ImageByteArray)
{ {
if (ImageByteArray == null) if (ImageByteArray == null)
throw new ArgumentNullException("ImageByteArray"); throw new ArgumentNullException("ImageByteArray");
return new BitmapImageExpressionResult(Bitmap.FromStream(new MemoryStream(ImageByteArray))); return new BitmapImageExpressionResult(Bitmap.FromStream(new MemoryStream(ImageByteArray)));
} }
public static BitmapImageExpressionResult DeviceModelImage(DeviceModel DeviceModel) public static BitmapImageExpressionResult DeviceModelImage(DeviceModel DeviceModel)
{ {
if (DeviceModel == null) if (DeviceModel == null)
throw new ArgumentNullException("DeviceModel"); throw new ArgumentNullException("DeviceModel");
using (Stream deviceModelImage = DeviceModel.Image()) using (Stream deviceModelImage = DeviceModel.Image())
{ {
if (deviceModelImage == null) if (deviceModelImage == null)
return null; return null;
else else
return ImageFromStream(deviceModelImage); return ImageFromStream(deviceModelImage);
} }
//if (DeviceModel.Image == null || DeviceModel.Image.Length == 0) //if (DeviceModel.Image == null || DeviceModel.Image.Length == 0)
// return null; // return null;
//return ImageFromByteArray(DeviceModel.Image); //return ImageFromByteArray(DeviceModel.Image);
} }
public static BitmapImageExpressionResult OrganisationLogo() public static BitmapImageExpressionResult OrganisationLogo()
{ {
var configCache = new Disco.Data.Configuration.ConfigurationContext(null); var configCache = new Disco.Data.Configuration.ConfigurationContext(null);
BitmapImageExpressionResult result; BitmapImageExpressionResult result;
using (var orgLogo = configCache.OrganisationLogo) using (var orgLogo = configCache.OrganisationLogo)
{ {
result = ImageFromStream(orgLogo); result = ImageFromStream(orgLogo);
} }
result.LosslessFormat = true; result.LosslessFormat = true;
return result; return result;
} }
} }
} }
@@ -1,70 +1,70 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.BI.Expressions; using Disco.Models.BI.Expressions;
using System.IO; using System.IO;
using System.Drawing; using System.Drawing;
using Disco.BI.Extensions; using Disco.BI.Extensions;
namespace Disco.BI.Expressions.Extensions.ImageResultImplementations namespace Disco.BI.Expressions.Extensions.ImageResultImplementations
{ {
public abstract class BaseImageExpressionResult : IImageExpressionResult public abstract class BaseImageExpressionResult : IImageExpressionResult
{ {
public byte Quality { get; set; } public byte Quality { get; set; }
public bool LosslessFormat { get; set; } public bool LosslessFormat { get; set; }
public bool ShowField { get; set; } public bool ShowField { get; set; }
public string BackgroundColour { get; set; } public string BackgroundColour { get; set; }
public bool BackgroundPreferTransparent { get; set; } public bool BackgroundPreferTransparent { get; set; }
public BaseImageExpressionResult() public BaseImageExpressionResult()
{ {
this.LosslessFormat = false; this.LosslessFormat = false;
this.Quality = 90; this.Quality = 90;
this.ShowField = false; this.ShowField = false;
this.BackgroundPreferTransparent = true; this.BackgroundPreferTransparent = true;
} }
public abstract Stream GetImage(int Width, int Height); public abstract Stream GetImage(int Width, int Height);
protected Stream RenderImage(Image SourceImage, int Width, int Height) protected Stream RenderImage(Image SourceImage, int Width, int Height)
{ {
if (SourceImage == null) if (SourceImage == null)
throw new ArgumentNullException("SourceImage"); throw new ArgumentNullException("SourceImage");
if (Width <= 0) if (Width <= 0)
throw new ArgumentOutOfRangeException("Width", "Width must be > 0"); throw new ArgumentOutOfRangeException("Width", "Width must be > 0");
if (Height <= 0) if (Height <= 0)
throw new ArgumentOutOfRangeException("Height", "Height must be > 0"); throw new ArgumentOutOfRangeException("Height", "Height must be > 0");
Brush backgroundBrush = null; Brush backgroundBrush = null;
if (!LosslessFormat || !BackgroundPreferTransparent) if (!LosslessFormat || !BackgroundPreferTransparent)
{ {
if (string.IsNullOrEmpty(this.BackgroundColour)) if (string.IsNullOrEmpty(this.BackgroundColour))
backgroundBrush = Brushes.White; backgroundBrush = Brushes.White;
else else
backgroundBrush = new SolidBrush(ColorTranslator.FromHtml(this.BackgroundColour)); backgroundBrush = new SolidBrush(ColorTranslator.FromHtml(this.BackgroundColour));
} }
using (Image resizedImage = SourceImage.ResizeImage(Width, Height, backgroundBrush)) using (Image resizedImage = SourceImage.ResizeImage(Width, Height, backgroundBrush))
{ {
return OutputImage(resizedImage); return OutputImage(resizedImage);
} }
} }
protected Stream OutputImage(Image SourceImage) protected Stream OutputImage(Image SourceImage)
{ {
MemoryStream imageStream = new MemoryStream(); MemoryStream imageStream = new MemoryStream();
if (LosslessFormat) if (LosslessFormat)
{ // Lossless Format - PNG { // Lossless Format - PNG
SourceImage.SavePng(imageStream); SourceImage.SavePng(imageStream);
} }
else else
{ // Lossy Format - JPG { // Lossy Format - JPG
byte quality = Math.Min((byte)100, Math.Max((byte)1, this.Quality)); byte quality = Math.Min((byte)100, Math.Max((byte)1, this.Quality));
SourceImage.SaveJpg(quality, imageStream); SourceImage.SaveJpg(quality, imageStream);
} }
imageStream.Position = 0; imageStream.Position = 0;
return imageStream; return imageStream;
} }
} }
} }
@@ -1,27 +1,27 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.IO; using System.IO;
using System.Drawing; using System.Drawing;
namespace Disco.BI.Expressions.Extensions.ImageResultImplementations namespace Disco.BI.Expressions.Extensions.ImageResultImplementations
{ {
public class BitmapImageExpressionResult : BaseImageExpressionResult public class BitmapImageExpressionResult : BaseImageExpressionResult
{ {
public Image Image { get; set; } public Image Image { get; set; }
public BitmapImageExpressionResult(Image Image) public BitmapImageExpressionResult(Image Image)
{ {
if (Image == null) if (Image == null)
throw new ArgumentNullException("Image"); throw new ArgumentNullException("Image");
this.Image = Image; this.Image = Image;
} }
public override Stream GetImage(int Width, int Height) public override Stream GetImage(int Width, int Height)
{ {
return this.RenderImage(this.Image, Width, Height); return this.RenderImage(this.Image, Width, Height);
} }
} }
} }
@@ -1,32 +1,32 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.IO; using System.IO;
using System.Drawing; using System.Drawing;
namespace Disco.BI.Expressions.Extensions.ImageResultImplementations namespace Disco.BI.Expressions.Extensions.ImageResultImplementations
{ {
public class FileImageExpressionResult : BaseImageExpressionResult public class FileImageExpressionResult : BaseImageExpressionResult
{ {
public string AbsoluteFilePath { get; set; } public string AbsoluteFilePath { get; set; }
public FileImageExpressionResult(string AbsoluteFilePath) public FileImageExpressionResult(string AbsoluteFilePath)
{ {
if (string.IsNullOrWhiteSpace(AbsoluteFilePath)) if (string.IsNullOrWhiteSpace(AbsoluteFilePath))
throw new ArgumentNullException("AbsoluteFilePath"); throw new ArgumentNullException("AbsoluteFilePath");
if (!File.Exists(AbsoluteFilePath)) if (!File.Exists(AbsoluteFilePath))
throw new FileNotFoundException("Image not found", AbsoluteFilePath); throw new FileNotFoundException("Image not found", AbsoluteFilePath);
this.AbsoluteFilePath = AbsoluteFilePath; this.AbsoluteFilePath = AbsoluteFilePath;
} }
public override Stream GetImage(int Width, int Height) public override Stream GetImage(int Width, int Height)
{ {
using (Image SourceImage = Bitmap.FromFile(this.AbsoluteFilePath)) using (Image SourceImage = Bitmap.FromFile(this.AbsoluteFilePath))
{ {
return this.RenderImage(SourceImage, Width, Height); return this.RenderImage(SourceImage, Width, Height);
} }
} }
} }
} }
@@ -1,181 +1,181 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.IO; using System.IO;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using Disco.BI.Extensions; using Disco.BI.Extensions;
namespace Disco.BI.Expressions.Extensions.ImageResultImplementations namespace Disco.BI.Expressions.Extensions.ImageResultImplementations
{ {
public class FileMontageImageExpressionResult : BaseImageExpressionResult public class FileMontageImageExpressionResult : BaseImageExpressionResult
{ {
public List<string> AbsoluteFilePaths { get; set; } public List<string> AbsoluteFilePaths { get; set; }
public bool MontageHorizontalLayout { get; set; } public bool MontageHorizontalLayout { get; set; }
public bool MontageVerticalLayout { get; set; } public bool MontageVerticalLayout { get; set; }
public bool MontageTableLayout { get; set; } public bool MontageTableLayout { get; set; }
public int Padding { get; set; } public int Padding { get; set; }
public FileMontageImageExpressionResult(List<string> AbsoluteFilePaths) public FileMontageImageExpressionResult(List<string> AbsoluteFilePaths)
{ {
if (AbsoluteFilePaths == null) if (AbsoluteFilePaths == null)
throw new ArgumentNullException("AbsoluteFilePaths"); throw new ArgumentNullException("AbsoluteFilePaths");
if (AbsoluteFilePaths.Count == 0) if (AbsoluteFilePaths.Count == 0)
throw new ArgumentException("AbsoluteFilePaths is empty", "AbsoluteFilePaths"); throw new ArgumentException("AbsoluteFilePaths is empty", "AbsoluteFilePaths");
this.AbsoluteFilePaths = AbsoluteFilePaths; this.AbsoluteFilePaths = AbsoluteFilePaths;
this.MontageTableLayout = true; this.MontageTableLayout = true;
this.Padding = 4; this.Padding = 4;
} }
public override Stream GetImage(int Width, int Height) public override Stream GetImage(int Width, int Height)
{ {
List<Image> Images = new List<Image>(); List<Image> Images = new List<Image>();
try try
{ {
// Load Images // Load Images
foreach (string imageFilePath in this.AbsoluteFilePaths) foreach (string imageFilePath in this.AbsoluteFilePaths)
Images.Add(Bitmap.FromFile(imageFilePath)); Images.Add(Bitmap.FromFile(imageFilePath));
// Build Montage // Build Montage
using (Bitmap montageImage = new Bitmap(Width, Height)) using (Bitmap montageImage = new Bitmap(Width, Height))
{ {
using (Graphics montageGraphics = Graphics.FromImage(montageImage)) using (Graphics montageGraphics = Graphics.FromImage(montageImage))
{ {
montageGraphics.CompositingQuality = CompositingQuality.HighQuality; montageGraphics.CompositingQuality = CompositingQuality.HighQuality;
montageGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; montageGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
montageGraphics.SmoothingMode = SmoothingMode.HighQuality; montageGraphics.SmoothingMode = SmoothingMode.HighQuality;
// Draw Background // Draw Background
if (!LosslessFormat || !BackgroundPreferTransparent) if (!LosslessFormat || !BackgroundPreferTransparent)
{ {
Brush backgroundBrush = Brushes.White; Brush backgroundBrush = Brushes.White;
if (!string.IsNullOrEmpty(this.BackgroundColour)) if (!string.IsNullOrEmpty(this.BackgroundColour))
backgroundBrush = new SolidBrush(ColorTranslator.FromHtml(this.BackgroundColour)); backgroundBrush = new SolidBrush(ColorTranslator.FromHtml(this.BackgroundColour));
montageGraphics.FillRectangle(backgroundBrush, montageGraphics.VisibleClipBounds); montageGraphics.FillRectangle(backgroundBrush, montageGraphics.VisibleClipBounds);
} }
if (this.MontageHorizontalLayout) if (this.MontageHorizontalLayout)
DoHorizontalLayout(Images, montageGraphics); DoHorizontalLayout(Images, montageGraphics);
else else
if (this.MontageVerticalLayout) if (this.MontageVerticalLayout)
DoVirticalLayout(Images, montageGraphics); DoVirticalLayout(Images, montageGraphics);
else else
DoTableLayout(Images, montageGraphics); DoTableLayout(Images, montageGraphics);
} }
return this.OutputImage(montageImage); return this.OutputImage(montageImage);
} }
} }
catch (Exception) { throw; } catch (Exception) { throw; }
finally finally
{ {
// Dispose of any Images // Dispose of any Images
if (Images != null) if (Images != null)
foreach (Image i in Images) foreach (Image i in Images)
i.Dispose(); i.Dispose();
} }
} }
private void DoHorizontalLayout(List<Image> Images, Graphics MontageGraphics) private void DoHorizontalLayout(List<Image> Images, Graphics MontageGraphics)
{ {
float imageScale; float imageScale;
float imagePosition = 0; float imagePosition = 0;
int imagesWidthTotal = Images.Sum(i => i.Width); int imagesWidthTotal = Images.Sum(i => i.Width);
int imagesHeightMax = Images.Max(i => i.Height); int imagesHeightMax = Images.Max(i => i.Height);
int imagesPadding = ((Images.Count - 1) * this.Padding); int imagesPadding = ((Images.Count - 1) * this.Padding);
imageScale = (float)(MontageGraphics.VisibleClipBounds.Width - imagesPadding) / (float)imagesWidthTotal; imageScale = (float)(MontageGraphics.VisibleClipBounds.Width - imagesPadding) / (float)imagesWidthTotal;
if ((MontageGraphics.VisibleClipBounds.Height / (float)imagesHeightMax) < imageScale) if ((MontageGraphics.VisibleClipBounds.Height / (float)imagesHeightMax) < imageScale)
imageScale = (float)MontageGraphics.VisibleClipBounds.Height / (float)imagesHeightMax; imageScale = (float)MontageGraphics.VisibleClipBounds.Height / (float)imagesHeightMax;
foreach (Image image in Images) foreach (Image image in Images)
{ {
MontageGraphics.DrawImageResized(image, imageScale, imagePosition, 0); MontageGraphics.DrawImageResized(image, imageScale, imagePosition, 0);
imagePosition += (imageScale * image.Width) + this.Padding; imagePosition += (imageScale * image.Width) + this.Padding;
} }
} }
private void DoVirticalLayout(List<Image> Images, Graphics MontageGraphics) private void DoVirticalLayout(List<Image> Images, Graphics MontageGraphics)
{ {
float imageScale; float imageScale;
float imagePosition = 0; float imagePosition = 0;
int imagesWidthMax = Images.Max(i => i.Width); int imagesWidthMax = Images.Max(i => i.Width);
int imagesHeightTotal = Images.Sum(i => i.Height); int imagesHeightTotal = Images.Sum(i => i.Height);
int imagesPadding = ((Images.Count - 1) * this.Padding); int imagesPadding = ((Images.Count - 1) * this.Padding);
imageScale = (float)(MontageGraphics.VisibleClipBounds.Height - imagesPadding) / (float)imagesHeightTotal; imageScale = (float)(MontageGraphics.VisibleClipBounds.Height - imagesPadding) / (float)imagesHeightTotal;
if ((MontageGraphics.VisibleClipBounds.Width / (float)imagesWidthMax) < imageScale) if ((MontageGraphics.VisibleClipBounds.Width / (float)imagesWidthMax) < imageScale)
imageScale = (float)MontageGraphics.VisibleClipBounds.Width / (float)imagesWidthMax; imageScale = (float)MontageGraphics.VisibleClipBounds.Width / (float)imagesWidthMax;
foreach (Image image in Images) foreach (Image image in Images)
{ {
MontageGraphics.DrawImageResized(image, imageScale, 0, imagePosition); MontageGraphics.DrawImageResized(image, imageScale, 0, imagePosition);
imagePosition += (imageScale * image.Height) + this.Padding; imagePosition += (imageScale * image.Height) + this.Padding;
} }
} }
private void DoTableLayout(List<Image> Images, Graphics MontageGraphics) private void DoTableLayout(List<Image> Images, Graphics MontageGraphics)
{ {
var stageSize = MontageGraphics.VisibleClipBounds.Size.ToSize(); var stageSize = MontageGraphics.VisibleClipBounds.Size.ToSize();
var itemAverageSize = new SizeF(Images.Average(i => (float)i.Size.Width), Images.Average(i => (float)i.Size.Height)); var itemAverageSize = new SizeF(Images.Average(i => (float)i.Size.Width), Images.Average(i => (float)i.Size.Height));
var calculatedLayout = CalculateColumnCount(stageSize, itemAverageSize, Images.Count); var calculatedLayout = CalculateColumnCount(stageSize, itemAverageSize, Images.Count);
SizeF cellSize = new SizeF((MontageGraphics.VisibleClipBounds.Width - ((calculatedLayout.Item1 - 1) * this.Padding)) / calculatedLayout.Item1, SizeF cellSize = new SizeF((MontageGraphics.VisibleClipBounds.Width - ((calculatedLayout.Item1 - 1) * this.Padding)) / calculatedLayout.Item1,
(MontageGraphics.VisibleClipBounds.Height - ((calculatedLayout.Item2 - 1) * this.Padding)) / calculatedLayout.Item2); (MontageGraphics.VisibleClipBounds.Height - ((calculatedLayout.Item2 - 1) * this.Padding)) / calculatedLayout.Item2);
int imageIndex = 0; int imageIndex = 0;
for (int rowIndex = 0; rowIndex < calculatedLayout.Item2; rowIndex++) for (int rowIndex = 0; rowIndex < calculatedLayout.Item2; rowIndex++)
{ {
for (int columnIndex = 0; columnIndex < calculatedLayout.Item1; columnIndex++) for (int columnIndex = 0; columnIndex < calculatedLayout.Item1; columnIndex++)
{ {
if (imageIndex < Images.Count) if (imageIndex < Images.Count)
{ {
var image = Images[imageIndex]; var image = Images[imageIndex];
var cellPoint = new PointF((cellSize.Width * columnIndex) + (this.Padding * columnIndex), (cellSize.Height * rowIndex) + (this.Padding * rowIndex)); var cellPoint = new PointF((cellSize.Width * columnIndex) + (this.Padding * columnIndex), (cellSize.Height * rowIndex) + (this.Padding * rowIndex));
MontageGraphics.Clip = new Region(new RectangleF(cellPoint, cellSize)); MontageGraphics.Clip = new Region(new RectangleF(cellPoint, cellSize));
MontageGraphics.DrawImageResized(image); MontageGraphics.DrawImageResized(image);
imageIndex++; imageIndex++;
} }
else else
break; break;
} }
} }
} }
private Tuple<int, int, double> CalculateColumnCount(Size StageSize, SizeF ItemAverageSize, int ItemCount) private Tuple<int, int, double> CalculateColumnCount(Size StageSize, SizeF ItemAverageSize, int ItemCount)
{ {
double? bestUsedSpace = null; double? bestUsedSpace = null;
int bestColumnCount = 1; int bestColumnCount = 1;
int bestRowCount = 1; int bestRowCount = 1;
double bestItemRatio = 1; double bestItemRatio = 1;
for (int columnCount = 1; columnCount <= ItemCount; columnCount++) for (int columnCount = 1; columnCount <= ItemCount; columnCount++)
{ {
int rowCount = (int)Math.Ceiling((double)ItemCount / (double)columnCount); int rowCount = (int)Math.Ceiling((double)ItemCount / (double)columnCount);
int requiredWidthPadding = (columnCount - 1) * this.Padding; int requiredWidthPadding = (columnCount - 1) * this.Padding;
int requiredHeightPadding = (rowCount - 1) * this.Padding; int requiredHeightPadding = (rowCount - 1) * this.Padding;
Size usableStageSize = new Size(StageSize.Width - requiredWidthPadding, StageSize.Height - requiredHeightPadding); Size usableStageSize = new Size(StageSize.Width - requiredWidthPadding, StageSize.Height - requiredHeightPadding);
double stageWidthRatio = (float)usableStageSize.Width / (float)usableStageSize.Height; double stageWidthRatio = (float)usableStageSize.Width / (float)usableStageSize.Height;
double stageHeightRatio = (float)usableStageSize.Height / (float)usableStageSize.Width; double stageHeightRatio = (float)usableStageSize.Height / (float)usableStageSize.Width;
int requiredWidth = (int)Math.Ceiling(ItemAverageSize.Width * columnCount); int requiredWidth = (int)Math.Ceiling(ItemAverageSize.Width * columnCount);
int requiredHeight = (int)Math.Ceiling(ItemAverageSize.Height * rowCount); int requiredHeight = (int)Math.Ceiling(ItemAverageSize.Height * rowCount);
int usedSpace = requiredWidth * requiredHeight; int usedSpace = requiredWidth * requiredHeight;
int stageArea = Math.Max((requiredWidth * (int)Math.Ceiling(requiredWidth * stageHeightRatio)), int stageArea = Math.Max((requiredWidth * (int)Math.Ceiling(requiredWidth * stageHeightRatio)),
(requiredHeight * (int)Math.Ceiling(requiredHeight * stageWidthRatio))); (requiredHeight * (int)Math.Ceiling(requiredHeight * stageWidthRatio)));
double usedStageSpace = (double)usedSpace / stageArea; double usedStageSpace = (double)usedSpace / stageArea;
if (bestUsedSpace == null || bestUsedSpace < usedStageSpace) if (bestUsedSpace == null || bestUsedSpace < usedStageSpace)
{ {
bestUsedSpace = usedStageSpace; bestUsedSpace = usedStageSpace;
bestColumnCount = columnCount; bestColumnCount = columnCount;
bestRowCount = rowCount; bestRowCount = rowCount;
bestItemRatio = Math.Min((double)usableStageSize.Width / (double)requiredWidth, (double)usableStageSize.Height / (double)requiredHeight); bestItemRatio = Math.Min((double)usableStageSize.Width / (double)requiredWidth, (double)usableStageSize.Height / (double)requiredHeight);
} }
} }
return new Tuple<int, int, double>(bestColumnCount, bestRowCount, bestItemRatio); return new Tuple<int, int, double>(bestColumnCount, bestRowCount, bestItemRatio);
} }
} }
} }
+51 -51
View File
@@ -1,51 +1,51 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using Disco.BI.Interop.ActiveDirectory; using Disco.BI.Interop.ActiveDirectory;
namespace Disco.BI.Expressions.Extensions namespace Disco.BI.Expressions.Extensions
{ {
public static class UserExt public static class UserExt
{ {
public static object GetActiveDirectoryObjectValue(User User, string PropertyName, int Index = 0) public static object GetActiveDirectoryObjectValue(User User, string PropertyName, int Index = 0)
{ {
var adUserAccount = User.ActiveDirectoryAccount(PropertyName); var adUserAccount = User.ActiveDirectoryAccount(PropertyName);
if (adUserAccount != null) if (adUserAccount != null)
return adUserAccount.GetPropertyValue(PropertyName, Index); return adUserAccount.GetPropertyValue(PropertyName, Index);
else else
return null; return null;
} }
public static string GetActiveDirectoryStringValue(User User, string PropertyName, int Index = 0) public static string GetActiveDirectoryStringValue(User User, string PropertyName, int Index = 0)
{ {
var objectValue = GetActiveDirectoryObjectValue(User, PropertyName, Index); var objectValue = GetActiveDirectoryObjectValue(User, PropertyName, Index);
string stringValue = objectValue as string; string stringValue = objectValue as string;
if (stringValue == null && objectValue != null) if (stringValue == null && objectValue != null)
stringValue = objectValue.ToString(); stringValue = objectValue.ToString();
return stringValue; return stringValue;
} }
public static int GetActiveDirectoryIntegerValue(User User, string PropertyName, int Index = 0) public static int GetActiveDirectoryIntegerValue(User User, string PropertyName, int Index = 0)
{ {
var objectValue = GetActiveDirectoryObjectValue(User, PropertyName, Index); var objectValue = GetActiveDirectoryObjectValue(User, PropertyName, Index);
if (objectValue == null) if (objectValue == null)
return default(int); return default(int);
else else
{ {
int intValue; int intValue;
try try
{ {
intValue = (int)Convert.ChangeType(objectValue, typeof(int)); intValue = (int)Convert.ChangeType(objectValue, typeof(int));
} }
catch (Exception) catch (Exception)
{ {
throw; throw;
} }
return intValue; return intValue;
} }
} }
} }
} }
+16 -16
View File
@@ -1,16 +1,16 @@
using System; using System;
using System.Collections; using System.Collections;
namespace Disco.BI.Expressions namespace Disco.BI.Expressions
{ {
public interface IExpressionPart public interface IExpressionPart
{ {
string RawSource { get; set; } string RawSource { get; set; }
string Source { get; set; } string Source { get; set; }
bool ErrorsAllowed { get; set; } bool ErrorsAllowed { get; set; }
bool ParseError { get; } bool ParseError { get; }
string ParseErrorMessage { get; } string ParseErrorMessage { get; }
bool IsDynamic { get; set; } bool IsDynamic { get; set; }
object Evaluate(object ExpressionContext, System.Collections.IDictionary Variables); object Evaluate(object ExpressionContext, System.Collections.IDictionary Variables);
} }
} }
+74 -74
View File
@@ -1,74 +1,74 @@
using System; using System;
using System.Collections; using System.Collections;
namespace Disco.BI.Expressions namespace Disco.BI.Expressions
{ {
public class TextExpressionPart : IExpressionPart public class TextExpressionPart : IExpressionPart
{ {
private string _Source; private string _Source;
bool IExpressionPart.ErrorsAllowed bool IExpressionPart.ErrorsAllowed
{ {
get get
{ {
return false; return false;
} }
set set
{ {
return; return;
} }
} }
string IExpressionPart.Source string IExpressionPart.Source
{ {
get get
{ {
return this._Source; return this._Source;
} }
set set
{ {
return; return;
} }
} }
string IExpressionPart.RawSource string IExpressionPart.RawSource
{ {
get get
{ {
return this._Source; return this._Source;
} }
set set
{ {
return; return;
} }
} }
bool IExpressionPart.IsDynamic bool IExpressionPart.IsDynamic
{ {
get get
{ {
return false; return false;
} }
set set
{ {
return; return;
} }
} }
public bool ParseError public bool ParseError
{ {
get { return false; } get { return false; }
} }
public string ParseErrorMessage public string ParseErrorMessage
{ {
get { return null; } get { return null; }
} }
public TextExpressionPart(string Source) public TextExpressionPart(string Source)
{ {
this._Source = Source; this._Source = Source;
} }
object IExpressionPart.Evaluate(object ExpressionContext, System.Collections.IDictionary Variables) object IExpressionPart.Evaluate(object ExpressionContext, System.Collections.IDictionary Variables)
{ {
return this._Source; return this._Source;
} }
} }
} }
@@ -1,53 +1,53 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class AttachmentActionExtensions public static class AttachmentActionExtensions
{ {
#region Delete #region Delete
public static bool CanDelete(this DeviceAttachment da) public static bool CanDelete(this DeviceAttachment da)
{ {
return true; // Placeholder - Currently Can Always Delete; return true; // Placeholder - Currently Can Always Delete;
} }
public static void OnDelete(this DeviceAttachment da, DiscoDataContext dbContext) public static void OnDelete(this DeviceAttachment da, DiscoDataContext dbContext)
{ {
if (!da.CanDelete()) if (!da.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied"); throw new InvalidOperationException("Deletion of Attachment is Denied");
da.RepositoryDelete(dbContext); da.RepositoryDelete(dbContext);
dbContext.DeviceAttachments.Remove(da); dbContext.DeviceAttachments.Remove(da);
} }
public static bool CanDelete(this JobAttachment ja) public static bool CanDelete(this JobAttachment ja)
{ {
return true; // Placeholder - Currently Can Always Delete; return true; // Placeholder - Currently Can Always Delete;
} }
public static void OnDelete(this JobAttachment ja, DiscoDataContext dbContext) public static void OnDelete(this JobAttachment ja, DiscoDataContext dbContext)
{ {
if (!ja.CanDelete()) if (!ja.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied"); throw new InvalidOperationException("Deletion of Attachment is Denied");
ja.RepositoryDelete(dbContext); ja.RepositoryDelete(dbContext);
dbContext.JobAttachments.Remove(ja); dbContext.JobAttachments.Remove(ja);
} }
public static bool CanDelete(this UserAttachment ua) public static bool CanDelete(this UserAttachment ua)
{ {
return true; // Placeholder - Currently Can Always Delete; return true; // Placeholder - Currently Can Always Delete;
} }
public static void OnDelete(this UserAttachment ua, DiscoDataContext dbContext) public static void OnDelete(this UserAttachment ua, DiscoDataContext dbContext)
{ {
if (!ua.CanDelete()) if (!ua.CanDelete())
throw new InvalidOperationException("Deletion of Attachment is Denied"); throw new InvalidOperationException("Deletion of Attachment is Denied");
ua.RepositoryDelete(dbContext); ua.RepositoryDelete(dbContext);
dbContext.UserAttachments.Remove(ua); dbContext.UserAttachments.Remove(ua);
} }
#endregion #endregion
} }
} }
+196 -196
View File
@@ -1,196 +1,196 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using System.IO; using System.IO;
using Disco.BI.DocumentTemplateBI; using Disco.BI.DocumentTemplateBI;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class AttachmentExtensions public static class AttachmentExtensions
{ {
public static bool ImportPdfAttachment(this DocumentUniqueIdentifier UniqueIdentifier, DiscoDataContext dbContext, System.IO.Stream PdfContent, byte[] PdfThumbnail) public static bool ImportPdfAttachment(this DocumentUniqueIdentifier UniqueIdentifier, DiscoDataContext dbContext, System.IO.Stream PdfContent, byte[] PdfThumbnail)
{ {
UniqueIdentifier.LoadComponents(dbContext); UniqueIdentifier.LoadComponents(dbContext);
DocumentTemplate documentTemplate = UniqueIdentifier.DocumentTemplate; DocumentTemplate documentTemplate = UniqueIdentifier.DocumentTemplate;
string filename; string filename;
string comments; string comments;
if (documentTemplate == null) if (documentTemplate == null)
{ {
filename = string.Format("{0}_{1:yyyyMMdd-HHmmss}.pdf", UniqueIdentifier.DataId, UniqueIdentifier.TimeStamp); filename = string.Format("{0}_{1:yyyyMMdd-HHmmss}.pdf", UniqueIdentifier.DataId, UniqueIdentifier.TimeStamp);
comments = string.Format("Uploaded: {0:s}", UniqueIdentifier.TimeStamp); comments = string.Format("Uploaded: {0:s}", UniqueIdentifier.TimeStamp);
} }
else else
{ {
filename = string.Format("{0}_{1:yyyyMMdd-HHmmss}.pdf", UniqueIdentifier.TemplateTypeId, UniqueIdentifier.TimeStamp); filename = string.Format("{0}_{1:yyyyMMdd-HHmmss}.pdf", UniqueIdentifier.TemplateTypeId, UniqueIdentifier.TimeStamp);
comments = string.Format("Generated: {0:s}", UniqueIdentifier.TimeStamp); comments = string.Format("Generated: {0:s}", UniqueIdentifier.TimeStamp);
} }
User creatorUser = UserBI.UserCache.GetUser(UniqueIdentifier.CreatorId, dbContext); User creatorUser = UserBI.UserCache.GetUser(UniqueIdentifier.CreatorId, dbContext);
if (creatorUser == null) if (creatorUser == null)
{ {
// No Creator User (or Username invalid) // No Creator User (or Username invalid)
creatorUser = UserBI.UserCache.CurrentUser; creatorUser = UserBI.UserCache.CurrentUser;
} }
switch (UniqueIdentifier.DataScope) switch (UniqueIdentifier.DataScope)
{ {
case DocumentTemplate.DocumentTemplateScopes.Device: case DocumentTemplate.DocumentTemplateScopes.Device:
Device d = (Device)UniqueIdentifier.Data; Device d = (Device)UniqueIdentifier.Data;
d.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); d.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail);
return true; return true;
case DocumentTemplate.DocumentTemplateScopes.Job: case DocumentTemplate.DocumentTemplateScopes.Job:
Job j = (Job)UniqueIdentifier.Data; Job j = (Job)UniqueIdentifier.Data;
j.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); j.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail);
return true; return true;
case DocumentTemplate.DocumentTemplateScopes.User: case DocumentTemplate.DocumentTemplateScopes.User:
User u = (User)UniqueIdentifier.Data; User u = (User)UniqueIdentifier.Data;
u.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail); u.CreateAttachment(dbContext, creatorUser, filename, DocumentTemplate.PdfMimeType, comments, PdfContent, documentTemplate, PdfThumbnail);
return true; return true;
default: default:
return false; return false;
} }
} }
public static string RepositoryFilename(this DeviceAttachment da, DiscoDataContext dbContext) public static string RepositoryFilename(this DeviceAttachment da, DiscoDataContext dbContext)
{ {
return Path.Combine(DataStore.CreateLocation(dbContext, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_file", da.DeviceSerialNumber, da.Id)); return Path.Combine(DataStore.CreateLocation(dbContext, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_file", da.DeviceSerialNumber, da.Id));
} }
public static string RepositoryFilename(this JobAttachment ja, DiscoDataContext dbContext) public static string RepositoryFilename(this JobAttachment ja, DiscoDataContext dbContext)
{ {
return Path.Combine(DataStore.CreateLocation(dbContext, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_file", ja.JobId, ja.Id)); return Path.Combine(DataStore.CreateLocation(dbContext, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_file", ja.JobId, ja.Id));
} }
public static string RepositoryFilename(this UserAttachment ua, DiscoDataContext dbContext) public static string RepositoryFilename(this UserAttachment ua, DiscoDataContext dbContext)
{ {
return Path.Combine(DataStore.CreateLocation(dbContext, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_file", ua.UserId, ua.Id)); return Path.Combine(DataStore.CreateLocation(dbContext, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_file", ua.UserId, ua.Id));
} }
private static string RepositoryThumbnailFilenameInternal(string DirectoryPath, string Filename) private static string RepositoryThumbnailFilenameInternal(string DirectoryPath, string Filename)
{ {
return Path.Combine(DirectoryPath, Filename); return Path.Combine(DirectoryPath, Filename);
} }
public static string RepositoryThumbnailFilename(this DeviceAttachment da, DiscoDataContext dbContext) public static string RepositoryThumbnailFilename(this DeviceAttachment da, DiscoDataContext dbContext)
{ {
return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_thumb.jpg", da.DeviceSerialNumber, da.Id)); return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "DeviceAttachments", da.Timestamp), string.Format("{0}_{1}_thumb.jpg", da.DeviceSerialNumber, da.Id));
} }
public static string RepositoryThumbnailFilename(this JobAttachment ja, DiscoDataContext dbContext) public static string RepositoryThumbnailFilename(this JobAttachment ja, DiscoDataContext dbContext)
{ {
return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_thumb.jpg", ja.JobId, ja.Id)); return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "JobAttachments", ja.Timestamp), string.Format("{0}_{1}_thumb.jpg", ja.JobId, ja.Id));
} }
public static string RepositoryThumbnailFilename(this UserAttachment ua, DiscoDataContext dbContext) public static string RepositoryThumbnailFilename(this UserAttachment ua, DiscoDataContext dbContext)
{ {
return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_thumb.jpg", ua.UserId, ua.Id)); return RepositoryThumbnailFilenameInternal(DataStore.CreateLocation(dbContext, "UserAttachments", ua.Timestamp), string.Format("{0}_{1}_thumb.jpg", ua.UserId, ua.Id));
} }
public static void RepositoryDelete(this DeviceAttachment da, DiscoDataContext dbContext) public static void RepositoryDelete(this DeviceAttachment da, DiscoDataContext dbContext)
{ {
RepositoryDelete(da.RepositoryFilename(dbContext), da.RepositoryThumbnailFilename(dbContext)); RepositoryDelete(da.RepositoryFilename(dbContext), da.RepositoryThumbnailFilename(dbContext));
} }
public static void RepositoryDelete(this JobAttachment ja, DiscoDataContext dbContext) public static void RepositoryDelete(this JobAttachment ja, DiscoDataContext dbContext)
{ {
RepositoryDelete(ja.RepositoryFilename(dbContext), ja.RepositoryThumbnailFilename(dbContext)); RepositoryDelete(ja.RepositoryFilename(dbContext), ja.RepositoryThumbnailFilename(dbContext));
} }
public static void RepositoryDelete(this UserAttachment ua, DiscoDataContext dbContext) public static void RepositoryDelete(this UserAttachment ua, DiscoDataContext dbContext)
{ {
RepositoryDelete(ua.RepositoryFilename(dbContext), ua.RepositoryThumbnailFilename(dbContext)); RepositoryDelete(ua.RepositoryFilename(dbContext), ua.RepositoryThumbnailFilename(dbContext));
} }
private static void RepositoryDelete(params string[] filePaths) private static void RepositoryDelete(params string[] filePaths)
{ {
foreach (string filePath in filePaths) foreach (string filePath in filePaths)
{ {
if (File.Exists(filePath)) if (File.Exists(filePath))
File.Delete(filePath); File.Delete(filePath);
} }
} }
public static string SaveAttachment(this DeviceAttachment da, DiscoDataContext dbContext, Stream FileContent) public static string SaveAttachment(this DeviceAttachment da, DiscoDataContext dbContext, Stream FileContent)
{ {
string filePath = da.RepositoryFilename(dbContext); string filePath = da.RepositoryFilename(dbContext);
SaveAttachment(filePath, FileContent); SaveAttachment(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveAttachment(this JobAttachment ja, DiscoDataContext dbContext, Stream FileContent) public static string SaveAttachment(this JobAttachment ja, DiscoDataContext dbContext, Stream FileContent)
{ {
string filePath = ja.RepositoryFilename(dbContext); string filePath = ja.RepositoryFilename(dbContext);
SaveAttachment(filePath, FileContent); SaveAttachment(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveAttachment(this UserAttachment ua, DiscoDataContext dbContext, Stream FileContent) public static string SaveAttachment(this UserAttachment ua, DiscoDataContext dbContext, Stream FileContent)
{ {
string filePath = ua.RepositoryFilename(dbContext); string filePath = ua.RepositoryFilename(dbContext);
SaveAttachment(filePath, FileContent); SaveAttachment(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveThumbnailAttachment(this DeviceAttachment da, DiscoDataContext dbContext, byte[] FileContent) public static string SaveThumbnailAttachment(this DeviceAttachment da, DiscoDataContext dbContext, byte[] FileContent)
{ {
string filePath = da.RepositoryThumbnailFilename(dbContext); string filePath = da.RepositoryThumbnailFilename(dbContext);
File.WriteAllBytes(filePath, FileContent); File.WriteAllBytes(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveThumbnailAttachment(this JobAttachment ja, DiscoDataContext dbContext, byte[] FileContent) public static string SaveThumbnailAttachment(this JobAttachment ja, DiscoDataContext dbContext, byte[] FileContent)
{ {
string filePath = ja.RepositoryThumbnailFilename(dbContext); string filePath = ja.RepositoryThumbnailFilename(dbContext);
File.WriteAllBytes(filePath, FileContent); File.WriteAllBytes(filePath, FileContent);
return filePath; return filePath;
} }
public static string SaveThumbnailAttachment(this UserAttachment ua, DiscoDataContext dbContext, byte[] FileContent) public static string SaveThumbnailAttachment(this UserAttachment ua, DiscoDataContext dbContext, byte[] FileContent)
{ {
string filePath = ua.RepositoryThumbnailFilename(dbContext); string filePath = ua.RepositoryThumbnailFilename(dbContext);
File.WriteAllBytes(filePath, FileContent); File.WriteAllBytes(filePath, FileContent);
return filePath; return filePath;
} }
private static void SaveAttachment(string FilePath, Stream FileContent) private static void SaveAttachment(string FilePath, Stream FileContent)
{ {
using (FileStream sw = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None)) using (FileStream sw = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{ {
FileContent.CopyTo(sw); FileContent.CopyTo(sw);
sw.Flush(); sw.Flush();
sw.Close(); sw.Close();
} }
} }
public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext dbContext) public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext dbContext)
{ {
string filePath = da.RepositoryThumbnailFilename(dbContext); string filePath = da.RepositoryThumbnailFilename(dbContext);
AttachmentBI.Utilities.GenerateThumbnail(da.RepositoryFilename(dbContext), da.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(da.RepositoryFilename(dbContext), da.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext dbContext) public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext dbContext)
{ {
string filePath = ja.RepositoryThumbnailFilename(dbContext); string filePath = ja.RepositoryThumbnailFilename(dbContext);
AttachmentBI.Utilities.GenerateThumbnail(ja.RepositoryFilename(dbContext), ja.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(ja.RepositoryFilename(dbContext), ja.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext dbContext) public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext dbContext)
{ {
string filePath = ua.RepositoryThumbnailFilename(dbContext); string filePath = ua.RepositoryThumbnailFilename(dbContext);
AttachmentBI.Utilities.GenerateThumbnail(ua.RepositoryFilename(dbContext), ua.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(ua.RepositoryFilename(dbContext), ua.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext dbContext, Stream SourceFile) public static string GenerateThumbnail(this DeviceAttachment da, DiscoDataContext dbContext, Stream SourceFile)
{ {
string filePath = da.RepositoryThumbnailFilename(dbContext); string filePath = da.RepositoryThumbnailFilename(dbContext);
AttachmentBI.Utilities.GenerateThumbnail(SourceFile, da.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(SourceFile, da.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext dbContext, Stream SourceFile) public static string GenerateThumbnail(this JobAttachment ja, DiscoDataContext dbContext, Stream SourceFile)
{ {
string filePath = ja.RepositoryThumbnailFilename(dbContext); string filePath = ja.RepositoryThumbnailFilename(dbContext);
AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ja.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ja.MimeType, filePath);
return filePath; return filePath;
} }
public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext dbContext, Stream SourceFile) public static string GenerateThumbnail(this UserAttachment ua, DiscoDataContext dbContext, Stream SourceFile)
{ {
string filePath = ua.RepositoryThumbnailFilename(dbContext); string filePath = ua.RepositoryThumbnailFilename(dbContext);
AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ua.MimeType, filePath); AttachmentBI.Utilities.GenerateThumbnail(SourceFile, ua.MimeType, filePath);
return filePath; return filePath;
} }
} }
} }
@@ -1,70 +1,70 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.ClientServices; using Disco.Models.ClientServices;
using System.Web; using System.Web;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.Repository; using Disco.Models.Repository;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class ClientServicesExtensions public static class ClientServicesExtensions
{ {
public static EnrolResponse BuildResponse(this Enrol request) public static EnrolResponse BuildResponse(this Enrol request)
{ {
if (HttpContext.Current == null) if (HttpContext.Current == null)
throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET"); throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET");
string username = null; string username = null;
if (HttpContext.Current.Request.IsAuthenticated) if (HttpContext.Current.Request.IsAuthenticated)
username = HttpContext.Current.User.Identity.Name; username = HttpContext.Current.User.Identity.Name;
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext dbContext = new DiscoDataContext())
{ {
EnrolResponse response = DeviceBI.DeviceEnrol.Enrol(dbContext, username, request); EnrolResponse response = DeviceBI.DeviceEnrol.Enrol(dbContext, username, request);
dbContext.SaveChanges(); dbContext.SaveChanges();
return response; return response;
} }
} }
public static WhoAmIResponse BuildResponse(this WhoAmI request) public static WhoAmIResponse BuildResponse(this WhoAmI request)
{ {
if (HttpContext.Current == null) if (HttpContext.Current == null)
throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET"); throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET");
string username = null; string username = null;
if (HttpContext.Current.Request.IsAuthenticated) if (HttpContext.Current.Request.IsAuthenticated)
username = HttpContext.Current.User.Identity.Name; username = HttpContext.Current.User.Identity.Name;
if (username == null) if (username == null)
throw new InvalidOperationException("Unauthenticated Http Context"); throw new InvalidOperationException("Unauthenticated Http Context");
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext dbContext = new DiscoDataContext())
{ {
User user = UserBI.UserCache.GetUser(username, dbContext, true); User user = UserBI.UserCache.GetUser(username, dbContext, true);
WhoAmIResponse response = new WhoAmIResponse() WhoAmIResponse response = new WhoAmIResponse()
{ {
Username = user.Id, Username = user.Id,
DisplayName = user.DisplayName, DisplayName = user.DisplayName,
Type = user.Type Type = user.Type
}; };
return response; return response;
} }
} }
public static MacEnrolResponse BuildResponse(this MacEnrol request) public static MacEnrolResponse BuildResponse(this MacEnrol request)
{ {
if (HttpContext.Current == null) if (HttpContext.Current == null)
throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET"); throw new PlatformNotSupportedException("This function can only be accessed from within ASP.NET");
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext dbContext = new DiscoDataContext())
{ {
MacEnrolResponse response = DeviceBI.DeviceEnrol.MacEnrol(dbContext, request, false); MacEnrolResponse response = DeviceBI.DeviceEnrol.MacEnrol(dbContext, request, false);
dbContext.SaveChanges(); dbContext.SaveChanges();
return response; return response;
} }
} }
} }
} }
+133 -133
View File
@@ -1,133 +1,133 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.BI.Interop.ActiveDirectory; using Disco.BI.Interop.ActiveDirectory;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class DeviceActionExtensions public static class DeviceActionExtensions
{ {
public static bool CanCreateJob(this Device d) public static bool CanCreateJob(this Device d)
{ {
return !d.DecommissionedDate.HasValue; return !d.DecommissionedDate.HasValue;
} }
#region Decommission #region Decommission
public static bool CanDecommission(this Device d) public static bool CanDecommission(this Device d)
{ {
if (d.DecommissionedDate.HasValue) if (d.DecommissionedDate.HasValue)
return false; // Already Decommissioned return false; // Already Decommissioned
if (d.AssignedUserId != null) if (d.AssignedUserId != null)
return false; // User Assigned to Device return false; // User Assigned to Device
if (d.Jobs.Count(j => !j.ClosedDate.HasValue) > 0) if (d.Jobs.Count(j => !j.ClosedDate.HasValue) > 0)
return false; // Device linked to > 0 Open Jobs return false; // Device linked to > 0 Open Jobs
return true; return true;
} }
public static void OnDecommission(this Device d) public static void OnDecommission(this Device d)
{ {
if (!d.CanDecommission()) if (!d.CanDecommission())
throw new InvalidOperationException("Decommission of Device is Denied"); throw new InvalidOperationException("Decommission of Device is Denied");
d.DecommissionedDate = DateTime.Now; d.DecommissionedDate = DateTime.Now;
// Disable AD Account // Disable AD Account
if (d.ComputerName != null) if (d.ComputerName != null)
{ {
var adAccount = d.ActiveDirectoryAccount(); var adAccount = d.ActiveDirectoryAccount();
if (adAccount != null) if (adAccount != null)
{ {
adAccount.DisableAccount(); adAccount.DisableAccount();
} }
} }
} }
#endregion #endregion
#region Recommission #region Recommission
public static bool CanRecommission(this Device d) public static bool CanRecommission(this Device d)
{ {
return d.DecommissionedDate.HasValue; return d.DecommissionedDate.HasValue;
} }
public static void OnRecommission(this Device d) public static void OnRecommission(this Device d)
{ {
if (!d.CanRecommission()) if (!d.CanRecommission())
throw new InvalidOperationException("Recommission of Device is Denied"); throw new InvalidOperationException("Recommission of Device is Denied");
d.DecommissionedDate = null; d.DecommissionedDate = null;
// Enable AD Account // Enable AD Account
if (d.ComputerName != null) if (d.ComputerName != null)
{ {
var adAccount = d.ActiveDirectoryAccount(); var adAccount = d.ActiveDirectoryAccount();
if (adAccount != null) if (adAccount != null)
{ {
adAccount.EnableAccount(); adAccount.EnableAccount();
} }
} }
} }
#endregion #endregion
#region Delete #region Delete
public static bool CanDelete(this Device d) public static bool CanDelete(this Device d)
{ {
return d.DecommissionedDate.HasValue; return d.DecommissionedDate.HasValue;
} }
public static void OnDelete(this Device d, DiscoDataContext dbContext) public static void OnDelete(this Device d, DiscoDataContext dbContext)
{ {
// Delete Jobs // Delete Jobs
foreach (Job j in dbContext.Jobs.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (Job j in dbContext.Jobs.Where(i => i.DeviceSerialNumber == d.SerialNumber))
{ {
if (j.UserId == null) if (j.UserId == null)
{ // No User associated, thus must Delete whole Job { // No User associated, thus must Delete whole Job
if (j.CanDelete()) if (j.CanDelete())
j.OnDelete(dbContext); j.OnDelete(dbContext);
else else
throw new InvalidOperationException(string.Format("Deletion of Device is Denied (See Job# {0})", j.Id)); throw new InvalidOperationException(string.Format("Deletion of Device is Denied (See Job# {0})", j.Id));
} }
else else
{ {
// User associated to Job, thus just remove Devices' association // User associated to Job, thus just remove Devices' association
j.DeviceSerialNumber = null; j.DeviceSerialNumber = null;
// Write Job Log // Write Job Log
JobLog jobLog = new JobLog() JobLog jobLog = new JobLog()
{ {
JobId = j.Id, JobId = j.Id,
TechUserId = UserBI.UserCache.CurrentUser.Id, TechUserId = UserBI.UserCache.CurrentUser.Id,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("Device Deleted{0}{0}Serial Number: {1}{0}Computer Name: {2}{0}Model: {3}{0}Profile: {4}", Comments = string.Format("Device Deleted{0}{0}Serial Number: {1}{0}Computer Name: {2}{0}Model: {3}{0}Profile: {4}",
Environment.NewLine, d.SerialNumber, d.ComputerName, d.DeviceModel, d.DeviceProfile) Environment.NewLine, d.SerialNumber, d.ComputerName, d.DeviceModel, d.DeviceProfile)
}; };
dbContext.JobLogs.Add(jobLog); dbContext.JobLogs.Add(jobLog);
} }
} }
// Disable Wireless Certificates // Disable Wireless Certificates
foreach (var wc in dbContext.DeviceCertificates.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (var wc in dbContext.DeviceCertificates.Where(i => i.DeviceSerialNumber == d.SerialNumber))
{ {
wc.DeviceSerialNumber = null; wc.DeviceSerialNumber = null;
wc.Enabled = false; wc.Enabled = false;
} }
// Delete Device Details // Delete Device Details
foreach (var dd in dbContext.DeviceDetails.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (var dd in dbContext.DeviceDetails.Where(i => i.DeviceSerialNumber == d.SerialNumber))
dbContext.DeviceDetails.Remove(dd); dbContext.DeviceDetails.Remove(dd);
// Delete Device Attachments // Delete Device Attachments
foreach (var da in dbContext.DeviceAttachments.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (var da in dbContext.DeviceAttachments.Where(i => i.DeviceSerialNumber == d.SerialNumber))
{ {
da.RepositoryDelete(dbContext); da.RepositoryDelete(dbContext);
dbContext.DeviceAttachments.Remove(da); dbContext.DeviceAttachments.Remove(da);
} }
// Delete Device User Assignments // Delete Device User Assignments
foreach (var dua in dbContext.DeviceUserAssignments.Where(i => i.DeviceSerialNumber == d.SerialNumber)) foreach (var dua in dbContext.DeviceUserAssignments.Where(i => i.DeviceSerialNumber == d.SerialNumber))
dbContext.DeviceUserAssignments.Remove(dua); dbContext.DeviceUserAssignments.Remove(dua);
dbContext.Devices.Remove(d); dbContext.Devices.Remove(d);
} }
#endregion #endregion
} }
} }
+31 -31
View File
@@ -1,31 +1,31 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class DeviceBatchExtensions public static class DeviceBatchExtensions
{ {
public static bool CanDelete(this DeviceBatch db, DiscoDataContext dbContext) public static bool CanDelete(this DeviceBatch db, DiscoDataContext dbContext)
{ {
// Can't Delete if Contains Devices // Can't Delete if Contains Devices
var deviceCount = dbContext.Devices.Count(d => d.DeviceBatchId == db.Id); var deviceCount = dbContext.Devices.Count(d => d.DeviceBatchId == db.Id);
if (deviceCount > 0) if (deviceCount > 0)
return false; return false;
return true; return true;
} }
public static void Delete(this DeviceBatch db, DiscoDataContext dbContext) public static void Delete(this DeviceBatch db, DiscoDataContext dbContext)
{ {
if (!db.CanDelete(dbContext)) if (!db.CanDelete(dbContext))
throw new InvalidOperationException("The state of this Device Batch doesn't allow it to be deleted"); throw new InvalidOperationException("The state of this Device Batch doesn't allow it to be deleted");
// Delete Batch // Delete Batch
dbContext.DeviceBatches.Remove(db); dbContext.DeviceBatches.Remove(db);
} }
} }
} }
@@ -1,44 +1,44 @@
using System.Linq; using System.Linq;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Services.Plugins; using Disco.Services.Plugins;
using Disco.Services.Plugins.Features.CertificateProvider; using Disco.Services.Plugins.Features.CertificateProvider;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class DeviceCertificateExtensions public static class DeviceCertificateExtensions
{ {
public static Tuple<DeviceCertificate, List<string>> AllocateCertificate(this Device device, DiscoDataContext dbContext) public static Tuple<DeviceCertificate, List<string>> AllocateCertificate(this Device device, DiscoDataContext dbContext)
{ {
if (!string.IsNullOrEmpty(device.DeviceProfile.CertificateProviderId)) if (!string.IsNullOrEmpty(device.DeviceProfile.CertificateProviderId))
{ {
// REMOVED 2012-07-18 G# - Plugin is responsible for checking // REMOVED 2012-07-18 G# - Plugin is responsible for checking
//var deviceCertificates = dbContext.DeviceCertificates.Where(c => //var deviceCertificates = dbContext.DeviceCertificates.Where(c =>
// c.DeviceSerialNumber == device.SerialNumber && // c.DeviceSerialNumber == device.SerialNumber &&
// c.ProviderId == device.DeviceProfile.CertificateProviderId && // c.ProviderId == device.DeviceProfile.CertificateProviderId &&
// c.Enabled == true).ToList(); // c.Enabled == true).ToList();
// Load Plugin // Load Plugin
PluginFeatureManifest featureManifest = Plugins.GetPluginFeature(device.DeviceProfile.CertificateProviderId, typeof(CertificateProviderFeature)); PluginFeatureManifest featureManifest = Plugins.GetPluginFeature(device.DeviceProfile.CertificateProviderId, typeof(CertificateProviderFeature));
using (CertificateProviderFeature providerFeature = featureManifest.CreateInstance<CertificateProviderFeature>()) using (CertificateProviderFeature providerFeature = featureManifest.CreateInstance<CertificateProviderFeature>())
{ {
// REMOVED 2012-07-18 G# - Plugin is responsible for checking // REMOVED 2012-07-18 G# - Plugin is responsible for checking
// Already Allocated Certificate // Already Allocated Certificate
//if (deviceCertificates.Count > 0) //if (deviceCertificates.Count > 0)
// return new Tuple<DeviceCertificate, List<string>>(deviceCertificates[0], providerPlugin.RemoveExistingCertificateNames()); // return new Tuple<DeviceCertificate, List<string>>(deviceCertificates[0], providerPlugin.RemoveExistingCertificateNames());
//else //else
return providerFeature.AllocateCertificate(dbContext, device); return providerFeature.AllocateCertificate(dbContext, device);
} }
} }
// Device Profile does not allow certificate allocation // Device Profile does not allow certificate allocation
return null; return null;
} }
} }
} }
@@ -1,54 +1,54 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Data.Configuration.Modules; using Disco.Data.Configuration.Modules;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class DeviceProfileExtensions public static class DeviceProfileExtensions
{ {
public const string ComputerNameExpressionCacheModule = "ComputerNameTemplate"; public const string ComputerNameExpressionCacheModule = "ComputerNameTemplate";
public static void ComputerNameInvalidateCache(this DeviceProfile deviceProfile) public static void ComputerNameInvalidateCache(this DeviceProfile deviceProfile)
{ {
Expressions.ExpressionCache.InvalidateKey(ComputerNameExpressionCacheModule, deviceProfile.Id.ToString()); Expressions.ExpressionCache.InvalidateKey(ComputerNameExpressionCacheModule, deviceProfile.Id.ToString());
} }
public static bool CanDelete(this DeviceProfile dp, DiscoDataContext dbContext) public static bool CanDelete(this DeviceProfile dp, DiscoDataContext dbContext)
{ {
// Can't Delete Default Profile (Id: 1) // Can't Delete Default Profile (Id: 1)
if (dp.Id == 1) if (dp.Id == 1)
return false; return false;
// Can't Delete if Contains Devices // Can't Delete if Contains Devices
if (dbContext.Devices.Count(d => d.DeviceProfileId == dp.Id) > 0) if (dbContext.Devices.Count(d => d.DeviceProfileId == dp.Id) > 0)
return false; return false;
return true; return true;
} }
public static void Delete(this DeviceProfile dp, DiscoDataContext dbContext) public static void Delete(this DeviceProfile dp, DiscoDataContext dbContext)
{ {
if (!dp.CanDelete(dbContext)) if (!dp.CanDelete(dbContext))
throw new InvalidOperationException("The state of this Device Profile doesn't allow it to be deleted"); throw new InvalidOperationException("The state of this Device Profile doesn't allow it to be deleted");
// Update Defaults // Update Defaults
if (dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId == dp.Id) if (dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId == dp.Id)
dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = 1; dbContext.DiscoConfiguration.DeviceProfiles.DefaultDeviceProfileId = 1;
if (dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId == dp.Id) if (dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId == dp.Id)
dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = 1; dbContext.DiscoConfiguration.DeviceProfiles.DefaultAddDeviceOfflineDeviceProfileId = 1;
// Delete Profile // Delete Profile
dbContext.DeviceProfiles.Remove(dp); dbContext.DeviceProfiles.Remove(dp);
} }
// Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3. // Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3.
//public static DeviceProfileConfiguration Configuration(this DeviceProfile dp, DiscoDataContext dbContext) //public static DeviceProfileConfiguration Configuration(this DeviceProfile dp, DiscoDataContext dbContext)
//{ //{
// return dbContext.DiscoConfiguration.DeviceProfiles.DeviceProfile(dp); // return dbContext.DiscoConfiguration.DeviceProfiles.DeviceProfile(dp);
//} //}
} }
} }
@@ -1,220 +1,220 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Linq; using System.Linq;
using System.Web; using System.Web;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.BI.DocumentTemplates; using Disco.Models.BI.DocumentTemplates;
using Disco.Models.Repository; using Disco.Models.Repository;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using iTextSharp.text.pdf; using iTextSharp.text.pdf;
using Disco.BI.Expressions; using Disco.BI.Expressions;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using Disco.BI.DocumentTemplateBI; using Disco.BI.DocumentTemplateBI;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class DocumentTemplateExtensions public static class DocumentTemplateExtensions
{ {
private const string DocumentTemplateExpressionCacheTemplate = "DocumentTemplate_{0}"; private const string DocumentTemplateExpressionCacheTemplate = "DocumentTemplate_{0}";
public static string RepositoryFilename(this DocumentTemplate dt, DiscoDataContext dbContext) public static string RepositoryFilename(this DocumentTemplate dt, DiscoDataContext dbContext)
{ {
return System.IO.Path.Combine(DataStore.CreateLocation(dbContext, "DocumentTemplates"), string.Format("{0}.pdf", dt.Id)); return System.IO.Path.Combine(DataStore.CreateLocation(dbContext, "DocumentTemplates"), string.Format("{0}.pdf", dt.Id));
} }
public static string SavePdfTemplate(this DocumentTemplate dt, DiscoDataContext dbContext, Stream TemplateFile) public static string SavePdfTemplate(this DocumentTemplate dt, DiscoDataContext dbContext, Stream TemplateFile)
{ {
string filePath = dt.RepositoryFilename(dbContext); string filePath = dt.RepositoryFilename(dbContext);
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{ {
TemplateFile.CopyTo(fs); TemplateFile.CopyTo(fs);
} }
Expressions.ExpressionCache.InvalidModule(string.Format(DocumentTemplateExpressionCacheTemplate, dt.Id)); Expressions.ExpressionCache.InvalidModule(string.Format(DocumentTemplateExpressionCacheTemplate, dt.Id));
return filePath; return filePath;
} }
public static DisposableImageCollection PdfPageImages(this PdfReader pdfReader, int PageNumber) public static DisposableImageCollection PdfPageImages(this PdfReader pdfReader, int PageNumber)
{ {
return Interop.Pdf.PdfImporter.GetPageImages(pdfReader, PageNumber); return Interop.Pdf.PdfImporter.GetPageImages(pdfReader, PageNumber);
} }
public static ConcurrentDictionary<string, Expression> PdfExpressionsFromCache(this DocumentTemplate dt, DiscoDataContext dbContext) public static ConcurrentDictionary<string, Expression> PdfExpressionsFromCache(this DocumentTemplate dt, DiscoDataContext dbContext)
{ {
string cacheModuleKey = string.Format(DocumentTemplateExpressionCacheTemplate, dt.Id); string cacheModuleKey = string.Format(DocumentTemplateExpressionCacheTemplate, dt.Id);
var module = Expressions.ExpressionCache.GetModule(cacheModuleKey); var module = Expressions.ExpressionCache.GetModule(cacheModuleKey);
if (module == null) if (module == null)
{ {
// Cache // Cache
string templateFilename = dt.RepositoryFilename(dbContext); string templateFilename = dt.RepositoryFilename(dbContext);
PdfReader pdfReader = new PdfReader(templateFilename); PdfReader pdfReader = new PdfReader(templateFilename);
int pdfFieldOrdinal = 0; int pdfFieldOrdinal = 0;
foreach (string pdfFieldKey in pdfReader.AcroFields.Fields.Keys) foreach (string pdfFieldKey in pdfReader.AcroFields.Fields.Keys)
{ {
var pdfFieldValue = pdfReader.AcroFields.GetField(pdfFieldKey); var pdfFieldValue = pdfReader.AcroFields.GetField(pdfFieldKey);
Expressions.ExpressionCache.SetValue(cacheModuleKey, pdfFieldKey, Expressions.Expression.Tokenize(pdfFieldKey, pdfFieldValue, pdfFieldOrdinal)); Expressions.ExpressionCache.SetValue(cacheModuleKey, pdfFieldKey, Expressions.Expression.Tokenize(pdfFieldKey, pdfFieldValue, pdfFieldOrdinal));
pdfFieldOrdinal++; pdfFieldOrdinal++;
} }
pdfReader.Close(); pdfReader.Close();
module = Expressions.ExpressionCache.GetModule(cacheModuleKey, true); module = Expressions.ExpressionCache.GetModule(cacheModuleKey, true);
} }
return module; return module;
} }
public static List<BI.Expressions.Expression> ExtractPdfExpressions(this DocumentTemplate dt, DiscoDataContext dbContext) public static List<BI.Expressions.Expression> ExtractPdfExpressions(this DocumentTemplate dt, DiscoDataContext dbContext)
{ {
return dt.PdfExpressionsFromCache(dbContext).Values.OrderBy(e => e.Ordinal).ToList(); return dt.PdfExpressionsFromCache(dbContext).Values.OrderBy(e => e.Ordinal).ToList();
} }
public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds) public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds)
{ {
return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjectsIds); return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjectsIds);
} }
public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects) public static System.IO.Stream GeneratePdfBulk(this DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects)
{ {
return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjects); return Interop.Pdf.PdfGenerator.GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjects);
} }
public static System.IO.Stream GeneratePdf(this DocumentTemplate dt, DiscoDataContext dbContext, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false) public static System.IO.Stream GeneratePdf(this DocumentTemplate dt, DiscoDataContext dbContext, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false)
{ {
return Interop.Pdf.PdfGenerator.GenerateFromTemplate(dt, dbContext, Data, CreatorUser, TimeStamp, State, FlattenFields); return Interop.Pdf.PdfGenerator.GenerateFromTemplate(dt, dbContext, Data, CreatorUser, TimeStamp, State, FlattenFields);
} }
public static Expression FilterExpressionFromCache(this DocumentTemplate dt) public static Expression FilterExpressionFromCache(this DocumentTemplate dt)
{ {
return ExpressionCache.GetValue("DocumentTemplateFilterExpression", dt.Id, () => { return Expression.TokenizeSingleDynamic(null, dt.FilterExpression, 0); }); return ExpressionCache.GetValue("DocumentTemplateFilterExpression", dt.Id, () => { return Expression.TokenizeSingleDynamic(null, dt.FilterExpression, 0); });
} }
public static void FilterExpressionInvalidateCache(this DocumentTemplate dt) public static void FilterExpressionInvalidateCache(this DocumentTemplate dt)
{ {
ExpressionCache.InvalidateKey("DocumentTemplateFilterExpression", dt.Id); ExpressionCache.InvalidateKey("DocumentTemplateFilterExpression", dt.Id);
} }
public static bool FilterExpressionMatches(this DocumentTemplate dt, object Data, DiscoDataContext DataContext, User User, System.DateTime TimeStamp, DocumentState State) public static bool FilterExpressionMatches(this DocumentTemplate dt, object Data, DiscoDataContext DataContext, User User, System.DateTime TimeStamp, DocumentState State)
{ {
if (!string.IsNullOrEmpty(dt.FilterExpression)) if (!string.IsNullOrEmpty(dt.FilterExpression))
{ {
Expression compiledExpression = dt.FilterExpressionFromCache(); Expression compiledExpression = dt.FilterExpressionFromCache();
System.Collections.IDictionary evaluatorVariables = Expression.StandardVariables(dt, DataContext, User, TimeStamp, State); System.Collections.IDictionary evaluatorVariables = Expression.StandardVariables(dt, DataContext, User, TimeStamp, State);
try try
{ {
object er = compiledExpression.EvaluateFirst<object>(Data, evaluatorVariables); object er = compiledExpression.EvaluateFirst<object>(Data, evaluatorVariables);
if (er is bool) if (er is bool)
{ {
return (bool)er; return (bool)er;
} }
bool erBool; bool erBool;
if (bool.TryParse(er.ToString(), out erBool)) if (bool.TryParse(er.ToString(), out erBool))
{ {
return erBool; return erBool;
} }
} }
catch catch
{ {
return false; return false;
} }
} }
return true; return true;
} }
public static string GetDataId(this DocumentTemplate dt, object Data) public static string GetDataId(this DocumentTemplate dt, object Data)
{ {
if (Data is string) if (Data is string)
{ {
return (string)Data; return (string)Data;
} }
else else
{ {
switch (dt.Scope) switch (dt.Scope)
{ {
case Models.Repository.DocumentTemplate.DocumentTemplateScopes.Device: case Models.Repository.DocumentTemplate.DocumentTemplateScopes.Device:
if (!(Data is Device)) if (!(Data is Device))
throw new ArgumentException("This Document Template is configured for Devices only", "Data"); throw new ArgumentException("This Document Template is configured for Devices only", "Data");
Device d = (Device)Data; Device d = (Device)Data;
return d.SerialNumber; return d.SerialNumber;
case Models.Repository.DocumentTemplate.DocumentTemplateScopes.Job: case Models.Repository.DocumentTemplate.DocumentTemplateScopes.Job:
if (!(Data is Job)) if (!(Data is Job))
throw new ArgumentException("This Document Template is configured for Jobs only", "Data"); throw new ArgumentException("This Document Template is configured for Jobs only", "Data");
Job d2 = (Job)Data; Job d2 = (Job)Data;
return d2.Id.ToString(); return d2.Id.ToString();
case Models.Repository.DocumentTemplate.DocumentTemplateScopes.User: case Models.Repository.DocumentTemplate.DocumentTemplateScopes.User:
if (!(Data is User)) if (!(Data is User))
throw new ArgumentException("This Document Template is configured for Users only", "Data"); throw new ArgumentException("This Document Template is configured for Users only", "Data");
User d3 = (User)Data; User d3 = (User)Data;
return d3.Id; return d3.Id;
default: default:
throw new InvalidOperationException("Invalid Document Template Scope"); throw new InvalidOperationException("Invalid Document Template Scope");
} }
} }
} }
public static string UniqueIdentifier(string DocumentTemplateId, string DataId, string CreatorId, System.DateTime Timestamp) public static string UniqueIdentifier(string DocumentTemplateId, string DataId, string CreatorId, System.DateTime Timestamp)
{ {
return string.Format("Disco|1|{0}|{1}|{2}|{3:s}", return string.Format("Disco|1|{0}|{1}|{2}|{3:s}",
DocumentTemplateId, DocumentTemplateId,
DataId, DataId,
CreatorId, CreatorId,
Timestamp Timestamp
); );
} }
public static string UniqueIdentifier(this DocumentTemplate dt, object Data, string CreatorId, System.DateTime Timestamp) public static string UniqueIdentifier(this DocumentTemplate dt, object Data, string CreatorId, System.DateTime Timestamp)
{ {
return string.Format("Disco|1|{0}|{1}|{2}|{3:s}", return string.Format("Disco|1|{0}|{1}|{2}|{3:s}",
dt.Id, dt.Id,
dt.GetDataId(System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Data)), dt.GetDataId(System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Data)),
CreatorId, CreatorId,
Timestamp Timestamp
); );
} }
public static string UniquePageIdentifier(this DocumentTemplate dt, object Data, string CreatorId, System.DateTime Timestamp, int Page) public static string UniquePageIdentifier(this DocumentTemplate dt, object Data, string CreatorId, System.DateTime Timestamp, int Page)
{ {
return string.Format("Disco|1|{0}|{1}|{2}|{3:s}|{4}", return string.Format("Disco|1|{0}|{1}|{2}|{3:s}|{4}",
dt.Id, dt.Id,
dt.GetDataId(System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Data)), dt.GetDataId(System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Data)),
CreatorId, CreatorId,
Timestamp, Timestamp,
Page Page
); );
} }
public static List<RectangleF> QRCodeLocations(this DocumentTemplate dt, DiscoDataContext dbContext) public static List<RectangleF> QRCodeLocations(this DocumentTemplate dt, DiscoDataContext dbContext)
{ {
return DocumentTemplateBI.DocumentTemplateQRCodeLocationCache.GetLocations(dt, dbContext); return DocumentTemplateBI.DocumentTemplateQRCodeLocationCache.GetLocations(dt, dbContext);
} }
public static void Delete(this DocumentTemplate dt, DiscoDataContext Context) public static void Delete(this DocumentTemplate dt, DiscoDataContext Context)
{ {
// Find & Rename all references // Find & Rename all references
foreach (DeviceAttachment a in Context.DeviceAttachments.Where(a => a.DocumentTemplateId == dt.Id)) foreach (DeviceAttachment a in Context.DeviceAttachments.Where(a => a.DocumentTemplateId == dt.Id))
{ {
a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments); a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments);
if (a.Comments.Length > 500) if (a.Comments.Length > 500)
a.Comments = a.Comments.Substring(0, 500); a.Comments = a.Comments.Substring(0, 500);
a.DocumentTemplateId = null; a.DocumentTemplateId = null;
a.DocumentTemplate = null; a.DocumentTemplate = null;
} }
foreach (JobAttachment a in Context.JobAttachments.Where(a => a.DocumentTemplateId == dt.Id)) foreach (JobAttachment a in Context.JobAttachments.Where(a => a.DocumentTemplateId == dt.Id))
{ {
a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments); a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments);
if (a.Comments.Length > 500) if (a.Comments.Length > 500)
a.Comments = a.Comments.Substring(0, 500); a.Comments = a.Comments.Substring(0, 500);
a.DocumentTemplateId = null; a.DocumentTemplateId = null;
a.DocumentTemplate = null; a.DocumentTemplate = null;
} }
foreach (UserAttachment a in Context.UserAttachments.Where(a => a.DocumentTemplateId == dt.Id)) foreach (UserAttachment a in Context.UserAttachments.Where(a => a.DocumentTemplateId == dt.Id))
{ {
a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments); a.Comments = string.Format("{0} - {1}", dt.Description, a.Comments);
if (a.Comments.Length > 500) if (a.Comments.Length > 500)
a.Comments = a.Comments.Substring(0, 500); a.Comments = a.Comments.Substring(0, 500);
a.DocumentTemplateId = null; a.DocumentTemplateId = null;
a.DocumentTemplate = null; a.DocumentTemplate = null;
} }
// Delete SubTypes // Delete SubTypes
dt.JobSubTypes.Clear(); dt.JobSubTypes.Clear();
// Delete Template // Delete Template
string templateRepositoryFilename = dt.RepositoryFilename(Context); string templateRepositoryFilename = dt.RepositoryFilename(Context);
if (System.IO.File.Exists(templateRepositoryFilename)) if (System.IO.File.Exists(templateRepositoryFilename))
System.IO.File.Delete(templateRepositoryFilename); System.IO.File.Delete(templateRepositoryFilename);
// Remove from Cache // Remove from Cache
dt.FilterExpressionInvalidateCache(); dt.FilterExpressionInvalidateCache();
// Delete Document Template from Repository // Delete Document Template from Repository
Context.DocumentTemplates.Remove(dt); Context.DocumentTemplates.Remove(dt);
} }
} }
} }
+415 -415
View File
@@ -1,415 +1,415 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.BI.Config; using Disco.Models.BI.Config;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Services.Plugins; using Disco.Services.Plugins;
using Disco.Services.Plugins.Features.WarrantyProvider; using Disco.Services.Plugins.Features.WarrantyProvider;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class JobActionExtensions public static class JobActionExtensions
{ {
#region Device Held #region Device Held
public static bool CanDeviceHeld(this Job j) public static bool CanDeviceHeld(this Job j)
{ {
return (!j.ClosedDate.HasValue) && (j.DeviceSerialNumber != null) && return (!j.ClosedDate.HasValue) && (j.DeviceSerialNumber != null) &&
(!j.DeviceHeld.HasValue || j.DeviceReturnedDate.HasValue); (!j.DeviceHeld.HasValue || j.DeviceReturnedDate.HasValue);
} }
public static void OnDeviceHeld(this Job j, User Technician) public static void OnDeviceHeld(this Job j, User Technician)
{ {
if (!j.CanDeviceHeld()) if (!j.CanDeviceHeld())
throw new InvalidOperationException("Holding Device was Denied"); throw new InvalidOperationException("Holding Device was Denied");
j.DeviceHeld = DateTime.Now; j.DeviceHeld = DateTime.Now;
j.DeviceHeldTechUserId = Technician.Id; j.DeviceHeldTechUserId = Technician.Id;
j.DeviceReadyForReturn = null; j.DeviceReadyForReturn = null;
j.DeviceReadyForReturnTechUserId = null; j.DeviceReadyForReturnTechUserId = null;
j.DeviceReturnedDate = null; j.DeviceReturnedDate = null;
j.DeviceReturnedTechUserId = null; j.DeviceReturnedTechUserId = null;
} }
#endregion #endregion
#region Device Ready for Return #region Device Ready for Return
public static bool CanDeviceReadyForReturn(this Job j) public static bool CanDeviceReadyForReturn(this Job j)
{ {
return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue && return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue &&
!j.DeviceReadyForReturn.HasValue && !j.DeviceReturnedDate.HasValue; !j.DeviceReadyForReturn.HasValue && !j.DeviceReturnedDate.HasValue;
} }
public static void OnDeviceReadyForReturn(this Job j, User Technician) public static void OnDeviceReadyForReturn(this Job j, User Technician)
{ {
if (!j.CanDeviceReadyForReturn()) if (!j.CanDeviceReadyForReturn())
throw new InvalidOperationException("Device Ready for Return was Denied"); throw new InvalidOperationException("Device Ready for Return was Denied");
j.DeviceReadyForReturn = DateTime.Now; j.DeviceReadyForReturn = DateTime.Now;
j.DeviceReadyForReturnTechUserId = Technician.Id; j.DeviceReadyForReturnTechUserId = Technician.Id;
} }
#endregion #endregion
#region Device Returned #region Device Returned
public static bool CanDeviceReturned(this Job j) public static bool CanDeviceReturned(this Job j)
{ {
return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue && return (!j.ClosedDate.HasValue) && j.DeviceHeld.HasValue &&
!j.DeviceReturnedDate.HasValue; !j.DeviceReturnedDate.HasValue;
} }
public static void OnDeviceReturned(this Job j, User Technician) public static void OnDeviceReturned(this Job j, User Technician)
{ {
if (!j.CanDeviceReturned()) if (!j.CanDeviceReturned())
throw new InvalidOperationException("Device Return was Denied"); throw new InvalidOperationException("Device Return was Denied");
j.DeviceReturnedDate = DateTime.Now; j.DeviceReturnedDate = DateTime.Now;
j.DeviceReturnedTechUserId = Technician.Id; j.DeviceReturnedTechUserId = Technician.Id;
} }
#endregion #endregion
#region Waiting For User Action #region Waiting For User Action
public static bool CanWaitingForUserAction(this Job j) public static bool CanWaitingForUserAction(this Job j)
{ {
return !j.ClosedDate.HasValue && (j.UserId != null) && !j.WaitingForUserAction.HasValue; return !j.ClosedDate.HasValue && (j.UserId != null) && !j.WaitingForUserAction.HasValue;
} }
public static void OnWaitingForUserAction(this Job j, DiscoDataContext dbContext, User Technician, string Reason) public static void OnWaitingForUserAction(this Job j, DiscoDataContext dbContext, User Technician, string Reason)
{ {
if (!j.CanWaitingForUserAction()) if (!j.CanWaitingForUserAction())
throw new InvalidOperationException("Waiting for User Action was Denied"); throw new InvalidOperationException("Waiting for User Action was Denied");
j.WaitingForUserAction = DateTime.Now; j.WaitingForUserAction = DateTime.Now;
// Write Log // Write Log
JobLog jobLog = new JobLog() JobLog jobLog = new JobLog()
{ {
JobId = j.Id, JobId = j.Id,
TechUserId = Technician.Id, TechUserId = Technician.Id,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("Waiting on User Action{0}Reason: {1}", Environment.NewLine, Reason) Comments = string.Format("Waiting on User Action{0}Reason: {1}", Environment.NewLine, Reason)
}; };
dbContext.JobLogs.Add(jobLog); dbContext.JobLogs.Add(jobLog);
} }
#endregion #endregion
#region Not Waiting For User Action #region Not Waiting For User Action
public static bool CanNotWaitingForUserAction(this Job j) public static bool CanNotWaitingForUserAction(this Job j)
{ {
return j.WaitingForUserAction.HasValue; return j.WaitingForUserAction.HasValue;
} }
public static void OnNotWaitingForUserAction(this Job j, DiscoDataContext dbContext, User Technician, string Resolution) public static void OnNotWaitingForUserAction(this Job j, DiscoDataContext dbContext, User Technician, string Resolution)
{ {
if (!j.CanNotWaitingForUserAction()) if (!j.CanNotWaitingForUserAction())
throw new InvalidOperationException("Not Waiting for User Action was Denied"); throw new InvalidOperationException("Not Waiting for User Action was Denied");
j.WaitingForUserAction = null; j.WaitingForUserAction = null;
// Write Log // Write Log
JobLog jobLog = new JobLog() JobLog jobLog = new JobLog()
{ {
JobId = j.Id, JobId = j.Id,
TechUserId = Technician.Id, TechUserId = Technician.Id,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("User Action Resolved{0}Resolution: {1}", Environment.NewLine, Resolution) Comments = string.Format("User Action Resolved{0}Resolution: {1}", Environment.NewLine, Resolution)
}; };
dbContext.JobLogs.Add(jobLog); dbContext.JobLogs.Add(jobLog);
} }
#endregion #endregion
#region Log Warranty #region Log Warranty
public static bool CanLogWarranty(this Job j) public static bool CanLogWarranty(this Job j)
{ {
return !j.ClosedDate.HasValue && return !j.ClosedDate.HasValue &&
(j.DeviceSerialNumber != null) && (j.DeviceSerialNumber != null) &&
j.JobTypeId == JobType.JobTypeIds.HWar && j.JobTypeId == JobType.JobTypeIds.HWar &&
string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference); string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference);
} }
public static void OnLogWarranty(this Job j, DiscoDataContext dbContext, string FaultDescription, PluginFeatureManifest WarrantyProviderDefinition, OrganisationAddress Address, User TechUser, Dictionary<string, string> WarrantyProviderProperties) public static void OnLogWarranty(this Job j, DiscoDataContext dbContext, string FaultDescription, PluginFeatureManifest WarrantyProviderDefinition, OrganisationAddress Address, User TechUser, Dictionary<string, string> WarrantyProviderProperties)
{ {
if (!j.CanLogWarranty()) if (!j.CanLogWarranty())
throw new InvalidOperationException("Log Warranty was Denied"); throw new InvalidOperationException("Log Warranty was Denied");
if (string.IsNullOrWhiteSpace(FaultDescription)) if (string.IsNullOrWhiteSpace(FaultDescription))
FaultDescription = j.GenerateFaultDescriptionFooter(dbContext, WarrantyProviderDefinition); FaultDescription = j.GenerateFaultDescriptionFooter(dbContext, WarrantyProviderDefinition);
else else
FaultDescription = string.Concat(FaultDescription, Environment.NewLine, Environment.NewLine, j.GenerateFaultDescriptionFooter(dbContext, WarrantyProviderDefinition)); FaultDescription = string.Concat(FaultDescription, Environment.NewLine, Environment.NewLine, j.GenerateFaultDescriptionFooter(dbContext, WarrantyProviderDefinition));
using (WarrantyProviderFeature WarrantyProvider = WarrantyProviderDefinition.CreateInstance<WarrantyProviderFeature>()) using (WarrantyProviderFeature WarrantyProvider = WarrantyProviderDefinition.CreateInstance<WarrantyProviderFeature>())
{ {
string providerRef = WarrantyProvider.SubmitJob(dbContext, j, Address, TechUser, FaultDescription, WarrantyProviderProperties); string providerRef = WarrantyProvider.SubmitJob(dbContext, j, Address, TechUser, FaultDescription, WarrantyProviderProperties);
j.JobMetaWarranty.ExternalLoggedDate = DateTime.Now; j.JobMetaWarranty.ExternalLoggedDate = DateTime.Now;
j.JobMetaWarranty.ExternalName = WarrantyProvider.WarrantyProviderId; j.JobMetaWarranty.ExternalName = WarrantyProvider.WarrantyProviderId;
if (providerRef.Length > 100) if (providerRef.Length > 100)
j.JobMetaWarranty.ExternalReference = providerRef.Substring(0, 100); j.JobMetaWarranty.ExternalReference = providerRef.Substring(0, 100);
else else
j.JobMetaWarranty.ExternalReference = providerRef; j.JobMetaWarranty.ExternalReference = providerRef;
// Write Log // Write Log
JobLog jobLog = new JobLog() JobLog jobLog = new JobLog()
{ {
JobId = j.Id, JobId = j.Id,
TechUserId = TechUser.Id, TechUserId = TechUser.Id,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("Warranty Claim Submitted{0}{0}Provider: {1}{0}Repair Address: {2}{0}Provider Reference: {3}{0}{0}{4}", Environment.NewLine, WarrantyProvider.Manifest.Name, Address.Name, providerRef, FaultDescription) Comments = string.Format("Warranty Claim Submitted{0}{0}Provider: {1}{0}Repair Address: {2}{0}Provider Reference: {3}{0}{0}{4}", Environment.NewLine, WarrantyProvider.Manifest.Name, Address.Name, providerRef, FaultDescription)
}; };
dbContext.JobLogs.Add(jobLog); dbContext.JobLogs.Add(jobLog);
} }
} }
#endregion #endregion
#region Convert HWar to HNWar #region Convert HWar to HNWar
public static bool CanConvertHWarToHNWar(this Job j) public static bool CanConvertHWarToHNWar(this Job j)
{ {
return !j.ClosedDate.HasValue && (j.DeviceSerialNumber != null) && return !j.ClosedDate.HasValue && (j.DeviceSerialNumber != null) &&
j.JobTypeId == JobType.JobTypeIds.HWar && string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference); j.JobTypeId == JobType.JobTypeIds.HWar && string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference);
} }
public static void OnConvertHWarToHNWar(this Job j, DiscoDataContext dbContext) public static void OnConvertHWarToHNWar(this Job j, DiscoDataContext dbContext)
{ {
if (!j.CanConvertHWarToHNWar()) if (!j.CanConvertHWarToHNWar())
throw new InvalidOperationException("Convert HWar to HNWar was Denied"); throw new InvalidOperationException("Convert HWar to HNWar was Denied");
var techUser = UserBI.UserCache.CurrentUser; var techUser = UserBI.UserCache.CurrentUser;
// Remove JobMetaWarranty // Remove JobMetaWarranty
if (j.JobMetaWarranty != null) if (j.JobMetaWarranty != null)
dbContext.JobMetaWarranties.Remove(j.JobMetaWarranty); dbContext.JobMetaWarranties.Remove(j.JobMetaWarranty);
// Add JobMetaNonWarranty // Add JobMetaNonWarranty
var metaHNWar = new JobMetaNonWarranty() { Job = j }; var metaHNWar = new JobMetaNonWarranty() { Job = j };
dbContext.JobMetaNonWarranties.Add(metaHNWar); dbContext.JobMetaNonWarranties.Add(metaHNWar);
// Swap Job Sub Types // Swap Job Sub Types
List<string> jobSubTypes = j.JobSubTypes.Select(jst => jst.Id).ToList(); List<string> jobSubTypes = j.JobSubTypes.Select(jst => jst.Id).ToList();
j.JobSubTypes.Clear(); j.JobSubTypes.Clear();
foreach (var jst in dbContext.JobSubTypes.Where(i => i.JobTypeId == JobType.JobTypeIds.HNWar && jobSubTypes.Contains(i.Id))) foreach (var jst in dbContext.JobSubTypes.Where(i => i.JobTypeId == JobType.JobTypeIds.HNWar && jobSubTypes.Contains(i.Id)))
j.JobSubTypes.Add(jst); j.JobSubTypes.Add(jst);
// Add Components // Add Components
var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId);
var jobComponents = new List<DeviceComponent>(); var jobComponents = new List<DeviceComponent>();
foreach (var component in components) foreach (var component in components)
{ {
if (!component.DeviceModelId.HasValue) if (!component.DeviceModelId.HasValue)
{ {
jobComponents.Add(component); jobComponents.Add(component);
} }
else else
{ {
foreach (var st in component.JobSubTypes) foreach (var st in component.JobSubTypes)
{ {
foreach (var jst in j.JobSubTypes) foreach (var jst in j.JobSubTypes)
{ {
if (st.JobTypeId == jst.JobTypeId && st.Id == jst.Id) if (st.JobTypeId == jst.JobTypeId && st.Id == jst.Id)
{ {
jobComponents.Add(component); jobComponents.Add(component);
break; break;
} }
} }
if (jobComponents.Contains(component)) if (jobComponents.Contains(component))
break; break;
} }
} }
} }
foreach (var component in jobComponents) foreach (var component in jobComponents)
{ {
dbContext.JobComponents.Add(new JobComponent() dbContext.JobComponents.Add(new JobComponent()
{ {
Job = j, Job = j,
TechUserId = techUser.Id, TechUserId = techUser.Id,
Cost = component.Cost, Cost = component.Cost,
Description = component.Description Description = component.Description
}); });
} }
// Write Log // Write Log
JobLog jobLog = new JobLog() JobLog jobLog = new JobLog()
{ {
JobId = j.Id, JobId = j.Id,
TechUserId = techUser.Id, TechUserId = techUser.Id,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = string.Format("Job Type Converted{0}From: {1}{0}To: {2}", Environment.NewLine, dbContext.JobTypes.Find(JobType.JobTypeIds.HWar), dbContext.JobTypes.Find(JobType.JobTypeIds.HNWar)) Comments = string.Format("Job Type Converted{0}From: {1}{0}To: {2}", Environment.NewLine, dbContext.JobTypes.Find(JobType.JobTypeIds.HWar), dbContext.JobTypes.Find(JobType.JobTypeIds.HNWar))
}; };
dbContext.JobLogs.Add(jobLog); dbContext.JobLogs.Add(jobLog);
j.JobTypeId = JobType.JobTypeIds.HNWar; j.JobTypeId = JobType.JobTypeIds.HNWar;
} }
#endregion #endregion
#region Warranty Completed #region Warranty Completed
public static bool CanWarrantyCompleted(this Job j) public static bool CanWarrantyCompleted(this Job j)
{ {
return (j.JobTypeId == JobType.JobTypeIds.HWar) && return (j.JobTypeId == JobType.JobTypeIds.HWar) &&
j.JobMetaWarranty.ExternalLoggedDate.HasValue && j.JobMetaWarranty.ExternalLoggedDate.HasValue &&
!j.JobMetaWarranty.ExternalCompletedDate.HasValue; !j.JobMetaWarranty.ExternalCompletedDate.HasValue;
} }
public static void OnWarrantyCompleted(this Job j) public static void OnWarrantyCompleted(this Job j)
{ {
if (!j.CanWarrantyCompleted()) if (!j.CanWarrantyCompleted())
throw new InvalidOperationException("Warranty Completed was Denied"); throw new InvalidOperationException("Warranty Completed was Denied");
j.JobMetaWarranty.ExternalCompletedDate = DateTime.Now; j.JobMetaWarranty.ExternalCompletedDate = DateTime.Now;
} }
#endregion #endregion
#region Insurance Claim Form Sent #region Insurance Claim Form Sent
public static bool CanInsuranceClaimFormSent(this Job j) public static bool CanInsuranceClaimFormSent(this Job j)
{ {
return (j.JobTypeId == JobType.JobTypeIds.HNWar) && return (j.JobTypeId == JobType.JobTypeIds.HNWar) &&
j.JobMetaNonWarranty.IsInsuranceClaim && j.JobMetaNonWarranty.IsInsuranceClaim &&
!j.JobMetaInsurance.ClaimFormSentDate.HasValue; !j.JobMetaInsurance.ClaimFormSentDate.HasValue;
} }
public static void OnInsuranceClaimFormSent(this Job j) public static void OnInsuranceClaimFormSent(this Job j)
{ {
if (!j.CanInsuranceClaimFormSent()) if (!j.CanInsuranceClaimFormSent())
throw new InvalidOperationException("Insurance Claim Form Sent was Denied"); throw new InvalidOperationException("Insurance Claim Form Sent was Denied");
var techUser = UserBI.UserCache.CurrentUser; var techUser = UserBI.UserCache.CurrentUser;
j.JobMetaInsurance.ClaimFormSentDate = DateTime.Now; j.JobMetaInsurance.ClaimFormSentDate = DateTime.Now;
j.JobMetaInsurance.ClaimFormSentUserId = techUser.Id; j.JobMetaInsurance.ClaimFormSentUserId = techUser.Id;
} }
#endregion #endregion
#region Log Repair #region Log Repair
public static bool CanLogRepair(this Job j) public static bool CanLogRepair(this Job j)
{ {
return (j.JobTypeId == JobType.JobTypeIds.HNWar) && return (j.JobTypeId == JobType.JobTypeIds.HNWar) &&
(j.DeviceSerialNumber != null) && (j.DeviceSerialNumber != null) &&
!j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && !j.JobMetaNonWarranty.RepairerLoggedDate.HasValue &&
!j.JobMetaNonWarranty.RepairerCompletedDate.HasValue; !j.JobMetaNonWarranty.RepairerCompletedDate.HasValue;
} }
public static void OnLogRepair(this Job j, string RepairerName, string RepairerReference) public static void OnLogRepair(this Job j, string RepairerName, string RepairerReference)
{ {
if (!j.CanLogRepair()) if (!j.CanLogRepair())
throw new InvalidOperationException("Log Repair was Denied"); throw new InvalidOperationException("Log Repair was Denied");
if (j.JobMetaNonWarranty.RepairerName != RepairerName) if (j.JobMetaNonWarranty.RepairerName != RepairerName)
j.JobMetaNonWarranty.RepairerName = RepairerName; j.JobMetaNonWarranty.RepairerName = RepairerName;
if (j.JobMetaNonWarranty.RepairerReference != RepairerReference) if (j.JobMetaNonWarranty.RepairerReference != RepairerReference)
j.JobMetaNonWarranty.RepairerReference = RepairerReference; j.JobMetaNonWarranty.RepairerReference = RepairerReference;
j.JobMetaNonWarranty.RepairerLoggedDate = DateTime.Now; j.JobMetaNonWarranty.RepairerLoggedDate = DateTime.Now;
} }
#endregion #endregion
#region Repair Complete #region Repair Complete
public static bool CanRepairComplete(this Job j) public static bool CanRepairComplete(this Job j)
{ {
return (j.JobTypeId == JobType.JobTypeIds.HNWar) && return (j.JobTypeId == JobType.JobTypeIds.HNWar) &&
j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && j.JobMetaNonWarranty.RepairerLoggedDate.HasValue &&
!j.JobMetaNonWarranty.RepairerCompletedDate.HasValue; !j.JobMetaNonWarranty.RepairerCompletedDate.HasValue;
} }
public static void OnRepairComplete(this Job j) public static void OnRepairComplete(this Job j)
{ {
if (!j.CanRepairComplete()) if (!j.CanRepairComplete())
throw new InvalidOperationException("Repair Complete was Denied"); throw new InvalidOperationException("Repair Complete was Denied");
j.JobMetaNonWarranty.RepairerCompletedDate = DateTime.Now; j.JobMetaNonWarranty.RepairerCompletedDate = DateTime.Now;
} }
#endregion #endregion
#region Close #region Close
public static bool CanClose(this Job j) public static bool CanClose(this Job j)
{ {
if (j.ClosedDate.HasValue) if (j.ClosedDate.HasValue)
return false; // Job already Closed return false; // Job already Closed
if (j.DeviceHeld.HasValue && !j.DeviceReturnedDate.HasValue) if (j.DeviceHeld.HasValue && !j.DeviceReturnedDate.HasValue)
return false; // Device not returned to User return false; // Device not returned to User
if (j.WaitingForUserAction.HasValue) if (j.WaitingForUserAction.HasValue)
return false; // Job waiting on User Action return false; // Job waiting on User Action
switch (j.JobTypeId) switch (j.JobTypeId)
{ {
case JobType.JobTypeIds.HWar: case JobType.JobTypeIds.HWar:
if (!string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference) && !j.JobMetaWarranty.ExternalCompletedDate.HasValue) if (!string.IsNullOrEmpty(j.JobMetaWarranty.ExternalReference) && !j.JobMetaWarranty.ExternalCompletedDate.HasValue)
return false; // Job Logged (Warranty) but not completed return false; // Job Logged (Warranty) but not completed
break; break;
case JobType.JobTypeIds.HNWar: case JobType.JobTypeIds.HNWar:
if (j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && !j.JobMetaNonWarranty.RepairerCompletedDate.HasValue) if (j.JobMetaNonWarranty.RepairerLoggedDate.HasValue && !j.JobMetaNonWarranty.RepairerCompletedDate.HasValue)
return false; // Job Logged (Repair) but not completed return false; // Job Logged (Repair) but not completed
if (j.JobMetaNonWarranty.AccountingChargeRequiredDate.HasValue && (!j.JobMetaNonWarranty.AccountingChargePaidDate.HasValue || !j.JobMetaNonWarranty.AccountingChargeAddedDate.HasValue)) if (j.JobMetaNonWarranty.AccountingChargeRequiredDate.HasValue && (!j.JobMetaNonWarranty.AccountingChargePaidDate.HasValue || !j.JobMetaNonWarranty.AccountingChargeAddedDate.HasValue))
return false; // Accounting Charge Required, but not added or paid return false; // Accounting Charge Required, but not added or paid
// Removed Rule: 2012-05-31 - A Job can be closed if the decision has been made for the user not to pay... // Removed Rule: 2012-05-31 - A Job can be closed if the decision has been made for the user not to pay...
//if (j.JobMetaNonWarranty.AccountingChargeAddedDate.HasValue && !j.JobMetaNonWarranty.AccountingChargePaidDate.HasValue) //if (j.JobMetaNonWarranty.AccountingChargeAddedDate.HasValue && !j.JobMetaNonWarranty.AccountingChargePaidDate.HasValue)
// return false; // Accounting Charge Added, but not paid // return false; // Accounting Charge Added, but not paid
if (j.JobMetaNonWarranty.IsInsuranceClaim && !j.JobMetaInsurance.ClaimFormSentDate.HasValue) if (j.JobMetaNonWarranty.IsInsuranceClaim && !j.JobMetaInsurance.ClaimFormSentDate.HasValue)
return false; // Is Insurance Claim, but claim form not sent return false; // Is Insurance Claim, but claim form not sent
break; break;
} }
return true; return true;
} }
public static void OnClose(this Job j, User Technician) public static void OnClose(this Job j, User Technician)
{ {
if (!j.CanClose()) if (!j.CanClose())
throw new InvalidOperationException("Close was Denied"); throw new InvalidOperationException("Close was Denied");
j.ClosedDate = DateTime.Now; j.ClosedDate = DateTime.Now;
j.ClosedTechUserId = Technician.Id; j.ClosedTechUserId = Technician.Id;
} }
#endregion #endregion
#region Reopen #region Reopen
public static bool CanReopen(this Job j) public static bool CanReopen(this Job j)
{ {
return j.ClosedDate.HasValue; return j.ClosedDate.HasValue;
} }
public static void OnReopen(this Job j) public static void OnReopen(this Job j)
{ {
if (!j.CanReopen()) if (!j.CanReopen())
throw new InvalidOperationException("Reopen was Denied"); throw new InvalidOperationException("Reopen was Denied");
j.ClosedDate = null; j.ClosedDate = null;
j.ClosedTechUserId = null; j.ClosedTechUserId = null;
} }
#endregion #endregion
#region Delete #region Delete
public static bool CanDelete(this Job j) public static bool CanDelete(this Job j)
{ {
return j.ClosedDate.HasValue; return j.ClosedDate.HasValue;
} }
public static void OnDelete(this Job j, DiscoDataContext dbContext) public static void OnDelete(this Job j, DiscoDataContext dbContext)
{ {
// Job Sub Types // Job Sub Types
j.JobSubTypes.Clear(); j.JobSubTypes.Clear();
// Job Attachments // Job Attachments
foreach (var ja in j.JobAttachments.ToArray()) foreach (var ja in j.JobAttachments.ToArray())
ja.OnDelete(dbContext); ja.OnDelete(dbContext);
j.JobAttachments.Clear(); j.JobAttachments.Clear();
// Job Components // Job Components
foreach (var jc in j.JobComponents.ToArray()) foreach (var jc in j.JobComponents.ToArray())
dbContext.JobComponents.Remove(jc); dbContext.JobComponents.Remove(jc);
j.JobComponents.Clear(); j.JobComponents.Clear();
// Job Logs // Job Logs
foreach (var jl in j.JobLogs.ToArray()) foreach (var jl in j.JobLogs.ToArray())
dbContext.JobLogs.Remove(jl); dbContext.JobLogs.Remove(jl);
j.JobLogs.Clear(); j.JobLogs.Clear();
// Job Meta // Job Meta
if (j.JobMetaInsurance != null) if (j.JobMetaInsurance != null)
{ {
dbContext.JobMetaInsurances.Remove(j.JobMetaInsurance); dbContext.JobMetaInsurances.Remove(j.JobMetaInsurance);
j.JobMetaInsurance = null; j.JobMetaInsurance = null;
} }
if (j.JobMetaNonWarranty != null) if (j.JobMetaNonWarranty != null)
{ {
dbContext.JobMetaNonWarranties.Remove(j.JobMetaNonWarranty); dbContext.JobMetaNonWarranties.Remove(j.JobMetaNonWarranty);
j.JobMetaNonWarranty = null; j.JobMetaNonWarranty = null;
} }
if (j.JobMetaWarranty != null) if (j.JobMetaWarranty != null)
{ {
dbContext.JobMetaWarranties.Remove(j.JobMetaWarranty); dbContext.JobMetaWarranties.Remove(j.JobMetaWarranty);
j.JobMetaWarranty = null; j.JobMetaWarranty = null;
} }
// Job // Job
dbContext.Jobs.Remove(j); dbContext.Jobs.Remove(j);
} }
#endregion #endregion
} }
} }
+80 -80
View File
@@ -1,80 +1,80 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class JobFlagExtensions public static class JobFlagExtensions
{ {
private static Dictionary<string, Dictionary<long, string>> allFlags; private static Dictionary<string, Dictionary<long, string>> allFlags;
private static void CacheAllFlags() private static void CacheAllFlags()
{ {
if (allFlags == null) if (allFlags == null)
{ {
var fType = typeof(Job.UserManagementFlags); var fType = typeof(Job.UserManagementFlags);
var fMembers = fType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); var fMembers = fType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
var flags = new Dictionary<string, Dictionary<long, string>>(); var flags = new Dictionary<string, Dictionary<long, string>>();
foreach (var f in fMembers) foreach (var f in fMembers)
{ {
DisplayAttribute display = (DisplayAttribute)(f.GetCustomAttributes(typeof(DisplayAttribute), false)[0]); DisplayAttribute display = (DisplayAttribute)(f.GetCustomAttributes(typeof(DisplayAttribute), false)[0]);
string gn = display.GroupName; string gn = display.GroupName;
Dictionary<long, string> g; Dictionary<long, string> g;
if (!flags.TryGetValue(gn, out g)) if (!flags.TryGetValue(gn, out g))
{ {
g = new Dictionary<long, string>(); g = new Dictionary<long, string>();
flags.Add(gn, g); flags.Add(gn, g);
} }
g[(long)f.GetRawConstantValue()] = display.Name; g[(long)f.GetRawConstantValue()] = display.Name;
} }
allFlags = flags; allFlags = flags;
} }
} }
public static Dictionary<string, List<Tuple<long, string, bool>>> ValidFlagsGrouped(this Job j) public static Dictionary<string, List<Tuple<long, string, bool>>> ValidFlagsGrouped(this Job j)
{ {
Dictionary<string, List<Tuple<long, string, bool>>> validFlags = new Dictionary<string, List<Tuple<long, string, bool>>>(); Dictionary<string, List<Tuple<long, string, bool>>> validFlags = new Dictionary<string, List<Tuple<long, string, bool>>>();
CacheAllFlags(); CacheAllFlags();
var currentFlags = j.Flags ?? 0; var currentFlags = j.Flags ?? 0;
foreach (var jt in j.JobSubTypes) foreach (var jt in j.JobSubTypes)
{ {
Dictionary<long, string> g; Dictionary<long, string> g;
if (allFlags.TryGetValue(jt.Id, out g)) if (allFlags.TryGetValue(jt.Id, out g))
{ {
validFlags[jt.Id] = g.Select(f => new Tuple<long, string, bool>(f.Key, f.Value, ((currentFlags & f.Key) == f.Key))).ToList(); validFlags[jt.Id] = g.Select(f => new Tuple<long, string, bool>(f.Key, f.Value, ((currentFlags & f.Key) == f.Key))).ToList();
} }
else else
{ {
validFlags[jt.Id] = null; validFlags[jt.Id] = null;
} }
} }
return validFlags; return validFlags;
} }
public static Dictionary<long, Tuple<string, bool>> ValidFlags(this Job j) public static Dictionary<long, Tuple<string, bool>> ValidFlags(this Job j)
{ {
Dictionary<long, Tuple<string, bool>> validFlags = new Dictionary<long, Tuple<string, bool>>(); Dictionary<long, Tuple<string, bool>> validFlags = new Dictionary<long, Tuple<string, bool>>();
CacheAllFlags(); CacheAllFlags();
var currentFlags = j.Flags ?? 0; var currentFlags = j.Flags ?? 0;
foreach (var jt in j.JobSubTypes) foreach (var jt in j.JobSubTypes)
{ {
Dictionary<long, string> g; Dictionary<long, string> g;
if (allFlags.TryGetValue(jt.Id, out g)) if (allFlags.TryGetValue(jt.Id, out g))
{ {
foreach (var f in g) foreach (var f in g)
validFlags[f.Key] = new Tuple<string, bool>(string.Format("{0}: {1}", jt.Description, f.Value), ((currentFlags & f.Key) == f.Key)); validFlags[f.Key] = new Tuple<string, bool>(string.Format("{0}: {1}", jt.Description, f.Value), ((currentFlags & f.Key) == f.Key));
} }
} }
return validFlags; return validFlags;
} }
} }
} }
+94 -94
View File
@@ -1,94 +1,94 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.BI.Job; using Disco.Models.BI.Job;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class JobTableExtensions public static class JobTableExtensions
{ {
public static void Fill(this JobTableModel model, DiscoDataContext dbContext, IQueryable<Job> Jobs) public static void Fill(this JobTableModel model, DiscoDataContext dbContext, IQueryable<Job> Jobs)
{ {
if (model.ShowStatus) if (model.ShowStatus)
{ {
var jobItems = Jobs.Select(j => new JobTableModel.JobTableItemModelIncludeStatus() var jobItems = Jobs.Select(j => new JobTableModel.JobTableItemModelIncludeStatus()
{ {
Id = j.Id, Id = j.Id,
DeviceAddressId = j.Device.DeviceProfile.DefaultOrganisationAddress, DeviceAddressId = j.Device.DeviceProfile.DefaultOrganisationAddress,
OpenedDate = j.OpenedDate, OpenedDate = j.OpenedDate,
ClosedDate = j.ClosedDate, ClosedDate = j.ClosedDate,
TypeId = j.JobTypeId, TypeId = j.JobTypeId,
TypeDescription = j.JobType.Description, TypeDescription = j.JobType.Description,
DeviceSerialNumber = j.Device.SerialNumber, DeviceSerialNumber = j.Device.SerialNumber,
DeviceModelDescription = j.Device.DeviceModel.Description, DeviceModelDescription = j.Device.DeviceModel.Description,
UserId = j.UserId, UserId = j.UserId,
UserDisplayName = j.User.DisplayName, UserDisplayName = j.User.DisplayName,
OpenedTechUserId = j.OpenedTechUserId, OpenedTechUserId = j.OpenedTechUserId,
OpenedTechUserDisplayName = j.OpenedTechUser.DisplayName, OpenedTechUserDisplayName = j.OpenedTechUser.DisplayName,
Location = j.DeviceHeldLocation, Location = j.DeviceHeldLocation,
JobMetaWarranty_ExternalReference = j.JobMetaWarranty.ExternalReference, JobMetaWarranty_ExternalReference = j.JobMetaWarranty.ExternalReference,
JobMetaWarranty_ExternalCompletedDate = j.JobMetaWarranty.ExternalCompletedDate, JobMetaWarranty_ExternalCompletedDate = j.JobMetaWarranty.ExternalCompletedDate,
JobMetaNonWarranty_RepairerLoggedDate = j.JobMetaNonWarranty.RepairerLoggedDate, JobMetaNonWarranty_RepairerLoggedDate = j.JobMetaNonWarranty.RepairerLoggedDate,
JobMetaNonWarranty_RepairerCompletedDate = j.JobMetaNonWarranty.RepairerCompletedDate, JobMetaNonWarranty_RepairerCompletedDate = j.JobMetaNonWarranty.RepairerCompletedDate,
JobMetaNonWarranty_AccountingChargeAddedDate = j.JobMetaNonWarranty.AccountingChargeAddedDate, JobMetaNonWarranty_AccountingChargeAddedDate = j.JobMetaNonWarranty.AccountingChargeAddedDate,
JobMetaNonWarranty_AccountingChargePaidDate = j.JobMetaNonWarranty.AccountingChargePaidDate, JobMetaNonWarranty_AccountingChargePaidDate = j.JobMetaNonWarranty.AccountingChargePaidDate,
JobMetaNonWarranty_AccountingChargeRequiredDate = j.JobMetaNonWarranty.AccountingChargeRequiredDate, JobMetaNonWarranty_AccountingChargeRequiredDate = j.JobMetaNonWarranty.AccountingChargeRequiredDate,
JobMetaNonWarranty_IsInsuranceClaim = j.JobMetaNonWarranty.IsInsuranceClaim, JobMetaNonWarranty_IsInsuranceClaim = j.JobMetaNonWarranty.IsInsuranceClaim,
JobMetaInsurance_ClaimFormSentDate = j.JobMetaInsurance.ClaimFormSentDate, JobMetaInsurance_ClaimFormSentDate = j.JobMetaInsurance.ClaimFormSentDate,
WaitingForUserAction = j.WaitingForUserAction, WaitingForUserAction = j.WaitingForUserAction,
DeviceReadyForReturn = j.DeviceReadyForReturn, DeviceReadyForReturn = j.DeviceReadyForReturn,
DeviceHeld = j.DeviceHeld, DeviceHeld = j.DeviceHeld,
DeviceReturnedDate = j.DeviceReturnedDate, DeviceReturnedDate = j.DeviceReturnedDate,
JobMetaWarranty_ExternalName = j.JobMetaWarranty.ExternalName, JobMetaWarranty_ExternalName = j.JobMetaWarranty.ExternalName,
JobMetaNonWarranty_RepairerName = j.JobMetaNonWarranty.RepairerName JobMetaNonWarranty_RepairerName = j.JobMetaNonWarranty.RepairerName
}); });
model.Items = new List<JobTableModel.JobTableItemModel>(); model.Items = new List<JobTableModel.JobTableItemModel>();
foreach (var j in jobItems) foreach (var j in jobItems)
{ {
j.StatusId = j.CalculateStatusId(); j.StatusId = j.CalculateStatusId();
j.StatusDescription = JobBI.Utilities.JobStatusDescription(j.StatusId, j); j.StatusDescription = JobBI.Utilities.JobStatusDescription(j.StatusId, j);
model.Items.Add(j); model.Items.Add(j);
} }
} }
else else
{ {
model.Items = Jobs.Select(j => new JobTableModel.JobTableItemModel() model.Items = Jobs.Select(j => new JobTableModel.JobTableItemModel()
{ {
Id = j.Id, Id = j.Id,
DeviceAddressId = j.Device.DeviceProfile.DefaultOrganisationAddress, DeviceAddressId = j.Device.DeviceProfile.DefaultOrganisationAddress,
OpenedDate = j.OpenedDate, OpenedDate = j.OpenedDate,
ClosedDate = j.ClosedDate, ClosedDate = j.ClosedDate,
TypeId = j.JobTypeId, TypeId = j.JobTypeId,
TypeDescription = j.JobType.Description, TypeDescription = j.JobType.Description,
DeviceSerialNumber = j.Device.SerialNumber, DeviceSerialNumber = j.Device.SerialNumber,
DeviceModelDescription = j.Device.DeviceModel.Description, DeviceModelDescription = j.Device.DeviceModel.Description,
UserId = j.UserId, UserId = j.UserId,
UserDisplayName = j.User.DisplayName, UserDisplayName = j.User.DisplayName,
OpenedTechUserId = j.OpenedTechUserId, OpenedTechUserId = j.OpenedTechUserId,
OpenedTechUserDisplayName = j.OpenedTechUser.DisplayName, OpenedTechUserDisplayName = j.OpenedTechUser.DisplayName,
Location = j.DeviceHeldLocation Location = j.DeviceHeldLocation
}).ToList(); }).ToList();
} }
if (!model.ShowDeviceAddress.HasValue) if (!model.ShowDeviceAddress.HasValue)
model.ShowDeviceAddress = dbContext.DiscoConfiguration.MultiSiteMode; model.ShowDeviceAddress = dbContext.DiscoConfiguration.MultiSiteMode;
if (model.ShowDeviceAddress.Value) if (model.ShowDeviceAddress.Value)
{ {
foreach (var j in model.Items) foreach (var j in model.Items)
if (j.DeviceAddressId.HasValue) if (j.DeviceAddressId.HasValue)
j.DeviceAddress = dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(j.DeviceAddressId.Value).Name; j.DeviceAddress = dbContext.DiscoConfiguration.OrganisationAddresses.GetAddress(j.DeviceAddressId.Value).Name;
} }
} }
} }
} }
+65 -65
View File
@@ -1,65 +1,65 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using System.IO; using System.IO;
using Disco.Models.BI.DocumentTemplates; using Disco.Models.BI.DocumentTemplates;
using Disco.Models.Interop.ActiveDirectory; using Disco.Models.Interop.ActiveDirectory;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class UserExtensions public static class UserExtensions
{ {
public static UserAttachment CreateAttachment(this User User, DiscoDataContext dbContext, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null) public static UserAttachment CreateAttachment(this User User, DiscoDataContext dbContext, User CreatorUser, string Filename, string MimeType, string Comments, Stream Content, DocumentTemplate DocumentTemplate = null, byte[] PdfThumbnail = null)
{ {
if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase)) if (string.IsNullOrEmpty(MimeType) || MimeType.Equals("unknown/unknown", StringComparison.InvariantCultureIgnoreCase))
MimeType = Interop.MimeTypes.ResolveMimeType(Filename); MimeType = Interop.MimeTypes.ResolveMimeType(Filename);
UserAttachment ua = new UserAttachment() UserAttachment ua = new UserAttachment()
{ {
UserId = User.Id, UserId = User.Id,
TechUserId = CreatorUser.Id, TechUserId = CreatorUser.Id,
Filename = Filename, Filename = Filename,
MimeType = MimeType, MimeType = MimeType,
Timestamp = DateTime.Now, Timestamp = DateTime.Now,
Comments = Comments Comments = Comments
}; };
if (DocumentTemplate != null) if (DocumentTemplate != null)
ua.DocumentTemplateId = DocumentTemplate.Id; ua.DocumentTemplateId = DocumentTemplate.Id;
dbContext.UserAttachments.Add(ua); dbContext.UserAttachments.Add(ua);
dbContext.SaveChanges(); dbContext.SaveChanges();
ua.SaveAttachment(dbContext, Content); ua.SaveAttachment(dbContext, Content);
Content.Position = 0; Content.Position = 0;
if (PdfThumbnail == null) if (PdfThumbnail == null)
ua.GenerateThumbnail(dbContext, Content); ua.GenerateThumbnail(dbContext, Content);
else else
ua.SaveThumbnailAttachment(dbContext, PdfThumbnail); ua.SaveThumbnailAttachment(dbContext, PdfThumbnail);
return ua; return ua;
} }
public static List<DocumentTemplate> AvailableDocumentTemplates(this User u, DiscoDataContext dbContext, User User, DateTime TimeStamp) public static List<DocumentTemplate> AvailableDocumentTemplates(this User u, DiscoDataContext dbContext, User User, DateTime TimeStamp)
{ {
var dts = dbContext.DocumentTemplates.Include("JobSubTypes") var dts = dbContext.DocumentTemplates.Include("JobSubTypes")
.Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.User) .Where(dt => dt.Scope == DocumentTemplate.DocumentTemplateScopes.User)
.ToArray() .ToArray()
.Where(dt => dt.FilterExpressionMatches(u, dbContext, User, TimeStamp, DocumentState.DefaultState())).ToList(); .Where(dt => dt.FilterExpressionMatches(u, dbContext, User, TimeStamp, DocumentState.DefaultState())).ToList();
return dts; return dts;
} }
public static List<DeviceUserAssignment> CurrentDeviceUserAssignments(this User u) public static List<DeviceUserAssignment> CurrentDeviceUserAssignments(this User u)
{ {
return u.DeviceUserAssignments.Where(dua => !dua.UnassignedDate.HasValue).ToList(); return u.DeviceUserAssignments.Where(dua => !dua.UnassignedDate.HasValue).ToList();
} }
public static ActiveDirectoryUserAccount ActiveDirectoryAccount(this User User, params string[] AdditionalProperties) public static ActiveDirectoryUserAccount ActiveDirectoryAccount(this User User, params string[] AdditionalProperties)
{ {
return Interop.ActiveDirectory.ActiveDirectory.GetUserAccount(User.Id, AdditionalProperties); return Interop.ActiveDirectory.ActiveDirectory.GetUserAccount(User.Id, AdditionalProperties);
} }
} }
} }
+313 -313
View File
@@ -1,313 +1,313 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Drawing; using System.Drawing;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using System.IO; using System.IO;
using System.Drawing.Imaging; using System.Drawing.Imaging;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class UtilityExtensions public static class UtilityExtensions
{ {
public static string StreamToString(this System.IO.Stream stream) public static string StreamToString(this System.IO.Stream stream)
{ {
if (stream.Position != 0 && stream.CanSeek) if (stream.Position != 0 && stream.CanSeek)
{ {
stream.Position = 0; stream.Position = 0;
} }
using (System.IO.StreamReader sr = new System.IO.StreamReader(stream)) using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
{ {
return sr.ReadToEnd(); return sr.ReadToEnd();
} }
} }
#region Date/Time Extensions #region Date/Time Extensions
public static string ToFuzzy(this DateTime d) public static string ToFuzzy(this DateTime d)
{ {
var n = DateTime.Now; var n = DateTime.Now;
// Today // Today
if (d.Date == n.Date) if (d.Date == n.Date)
{ {
if (d < n) if (d < n)
{ {
// Earlier // Earlier
if (d > n.AddMinutes(-1)) if (d > n.AddMinutes(-1))
return "A moment ago"; return "A moment ago";
if (d > n.AddMinutes(-10)) if (d > n.AddMinutes(-10))
return "A few minutes ago"; return "A few minutes ago";
} }
else else
{ {
// Later // Later
if (d < n.AddMinutes(1)) if (d < n.AddMinutes(1))
return "In a moment"; return "In a moment";
if (d < n.AddMinutes(10)) if (d < n.AddMinutes(10))
return "In a few minutes"; return "In a few minutes";
} }
return string.Format("Today at {0:h:mm tt}", d); return string.Format("Today at {0:h:mm tt}", d);
} }
if (d.Date < n.Date) if (d.Date < n.Date)
{ {
// PAST // PAST
var dif = n.Subtract(d); var dif = n.Subtract(d);
// Yesterday // Yesterday
if (d.Date == n.Date.AddDays(-1)) if (d.Date == n.Date.AddDays(-1))
return string.Format("Yesterday at {0:h:mm tt}", d); return string.Format("Yesterday at {0:h:mm tt}", d);
// Last Week // Last Week
if (dif.TotalDays <= 7) if (dif.TotalDays <= 7)
return string.Format("Last {0:dddd} at {0:h:mm tt}", d); return string.Format("Last {0:dddd} at {0:h:mm tt}", d);
// Within 8 Weeks // Within 8 Weeks
if (d > n.Date.AddMonths(-2)) if (d > n.Date.AddMonths(-2))
return string.Format("{0} Weeks ago, {1:ddd, d MMM}", (int)(dif.TotalDays / 7), d); return string.Format("{0} Weeks ago, {1:ddd, d MMM}", (int)(dif.TotalDays / 7), d);
// Same Year // Same Year
if (d.Year == n.Year) if (d.Year == n.Year)
return string.Format("{0} Months ago, {1:ddd, d MMM}", (int)(dif.TotalDays / 30), d); return string.Format("{0} Months ago, {1:ddd, d MMM}", (int)(dif.TotalDays / 30), d);
} }
else else
{ {
// Future // Future
var dif = d.Subtract(n); var dif = d.Subtract(n);
// Tomorrow // Tomorrow
if (d.Date == n.Date.AddDays(1)) if (d.Date == n.Date.AddDays(1))
return string.Format("Tomorrow at {0:h:mm tt}", d); return string.Format("Tomorrow at {0:h:mm tt}", d);
// Next Week // Next Week
if (dif.TotalDays <= 7) if (dif.TotalDays <= 7)
return string.Format("Next {0:dddd} at {0:h:mm tt}", d); return string.Format("Next {0:dddd} at {0:h:mm tt}", d);
// < 2 Month // < 2 Month
if (d < n.Date.AddMonths(2)) if (d < n.Date.AddMonths(2))
return string.Format("In {0} Weeks, {1:ddd, d MMM}", (int)(dif.TotalDays / 7), d); return string.Format("In {0} Weeks, {1:ddd, d MMM}", (int)(dif.TotalDays / 7), d);
// Same Year // Same Year
if (d.Year == n.Year) if (d.Year == n.Year)
return string.Format("In {0} Months, {1:ddd, d MMM}", (int)(dif.TotalDays / 30), d); return string.Format("In {0} Months, {1:ddd, d MMM}", (int)(dif.TotalDays / 30), d);
} }
return d.ToString("ddd, d MMM yyyy"); return d.ToString("ddd, d MMM yyyy");
} }
public static string ToFuzzy(this DateTime? d, string NullValue = "N/A") public static string ToFuzzy(this DateTime? d, string NullValue = "N/A")
{ {
if (d.HasValue) if (d.HasValue)
return ToFuzzy(d.Value); return ToFuzzy(d.Value);
else else
return NullValue; return NullValue;
} }
public static string ToFullDateTime(this DateTime d) public static string ToFullDateTime(this DateTime d)
{ {
return d.ToString("ddd, d MMM yyyy @ h:mm:sstt"); return d.ToString("ddd, d MMM yyyy @ h:mm:sstt");
} }
public static string ToFullDateTime(this DateTime? d, string NullValue = "N/A") public static string ToFullDateTime(this DateTime? d, string NullValue = "N/A")
{ {
if (d.HasValue) if (d.HasValue)
return ToFullDateTime(d.Value); return ToFullDateTime(d.Value);
else else
return NullValue; return NullValue;
} }
public static long ToSortableDateTime(this DateTime? d) public static long ToSortableDateTime(this DateTime? d)
{ {
if (d.HasValue) if (d.HasValue)
return d.Value.ToBinary(); return d.Value.ToBinary();
else else
return -1; return -1;
} }
public static long ToSortableDateTime(this DateTime d) public static long ToSortableDateTime(this DateTime d)
{ {
return d.ToBinary(); return d.ToBinary();
} }
#endregion #endregion
#region Image Extensions #region Image Extensions
public static Bitmap ResizeImage(this Image Source, int Width, int Height, Brush BackgroundColor = null) public static Bitmap ResizeImage(this Image Source, int Width, int Height, Brush BackgroundColor = null)
{ {
Bitmap destination = new Bitmap(Width, Height); Bitmap destination = new Bitmap(Width, Height);
destination.SetResolution(72, 72); destination.SetResolution(72, 72);
using (Graphics destinationGraphics = Graphics.FromImage(destination)) using (Graphics destinationGraphics = Graphics.FromImage(destination))
{ {
destinationGraphics.CompositingQuality = CompositingQuality.HighQuality; destinationGraphics.CompositingQuality = CompositingQuality.HighQuality;
destinationGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; destinationGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
destinationGraphics.SmoothingMode = SmoothingMode.HighQuality; destinationGraphics.SmoothingMode = SmoothingMode.HighQuality;
if (BackgroundColor != null) if (BackgroundColor != null)
destinationGraphics.FillRectangle(BackgroundColor, destinationGraphics.VisibleClipBounds); destinationGraphics.FillRectangle(BackgroundColor, destinationGraphics.VisibleClipBounds);
float ratio = Math.Min((float)(destination.Width) / (float)(Source.Width), (float)(destination.Height) / (float)(Source.Height)); float ratio = Math.Min((float)(destination.Width) / (float)(Source.Width), (float)(destination.Height) / (float)(Source.Height));
destinationGraphics.DrawImageResized(Source, ratio); destinationGraphics.DrawImageResized(Source, ratio);
} }
return destination; return destination;
} }
public static void DrawImageResized(this Graphics graphics, Image SourceImage, float? Scale = null, float LocationX = -1, float LocationY = -1) public static void DrawImageResized(this Graphics graphics, Image SourceImage, float? Scale = null, float LocationX = -1, float LocationY = -1)
{ {
RectangleF clipBounds = graphics.VisibleClipBounds; RectangleF clipBounds = graphics.VisibleClipBounds;
if (Scale == null) // Calculate Scale if (Scale == null) // Calculate Scale
Scale = Math.Min(clipBounds.Width / SourceImage.Width, clipBounds.Height / SourceImage.Height); Scale = Math.Min(clipBounds.Width / SourceImage.Width, clipBounds.Height / SourceImage.Height);
float newWidth = SourceImage.Width * Scale.Value; float newWidth = SourceImage.Width * Scale.Value;
float newHeight = SourceImage.Height * Scale.Value; float newHeight = SourceImage.Height * Scale.Value;
float newLeft = LocationX; float newLeft = LocationX;
float newTop = LocationY; float newTop = LocationY;
if (newLeft < 0 || newTop < 0) if (newLeft < 0 || newTop < 0)
{ {
if (newWidth < clipBounds.Width) if (newWidth < clipBounds.Width)
newLeft = (clipBounds.Width - newWidth) / 2; newLeft = (clipBounds.Width - newWidth) / 2;
else else
newLeft = 0; newLeft = 0;
if (newHeight < clipBounds.Height) if (newHeight < clipBounds.Height)
newTop = (clipBounds.Height - newHeight) / 2; newTop = (clipBounds.Height - newHeight) / 2;
else else
newTop = 0; newTop = 0;
} }
newLeft += clipBounds.Left; newLeft += clipBounds.Left;
newTop += clipBounds.Top; newTop += clipBounds.Top;
graphics.DrawImage(SourceImage, new RectangleF(newLeft, newTop, newWidth, newHeight), new RectangleF(0, 0, SourceImage.Width, SourceImage.Height), GraphicsUnit.Pixel); graphics.DrawImage(SourceImage, new RectangleF(newLeft, newTop, newWidth, newHeight), new RectangleF(0, 0, SourceImage.Width, SourceImage.Height), GraphicsUnit.Pixel);
} }
public static void EmbedIconOverlay(this Image Source, Image Icon) public static void EmbedIconOverlay(this Image Source, Image Icon)
{ {
int top = Math.Max(0, Source.Height - Icon.Height); int top = Math.Max(0, Source.Height - Icon.Height);
int left = Math.Max(0, Source.Width - Icon.Width); int left = Math.Max(0, Source.Width - Icon.Width);
using (Graphics sourceGraphics = Graphics.FromImage(Source)) using (Graphics sourceGraphics = Graphics.FromImage(Source))
{ {
sourceGraphics.DrawImage(Icon, left, top); sourceGraphics.DrawImage(Icon, left, top);
} }
} }
public static void SavePng(this Image Source, string Filename) public static void SavePng(this Image Source, string Filename)
{ {
using (FileStream outStream = new FileStream(Filename, FileMode.Create, FileAccess.Write, FileShare.None)) using (FileStream outStream = new FileStream(Filename, FileMode.Create, FileAccess.Write, FileShare.None))
{ {
SavePng(Source, outStream); SavePng(Source, outStream);
outStream.Flush(); outStream.Flush();
outStream.Close(); outStream.Close();
} }
} }
public static void SavePng(this Image Source, Stream OutStream) public static void SavePng(this Image Source, Stream OutStream)
{ {
Source.Save(OutStream, ImageFormat.Png); Source.Save(OutStream, ImageFormat.Png);
} }
public static Stream SavePng(this Image Source) public static Stream SavePng(this Image Source)
{ {
MemoryStream outStream = new MemoryStream(); MemoryStream outStream = new MemoryStream();
Source.SavePng(outStream); Source.SavePng(outStream);
outStream.Position = 0; outStream.Position = 0;
return outStream; return outStream;
} }
public static Stream SaveJpg(this Image Source, int Quality) public static Stream SaveJpg(this Image Source, int Quality)
{ {
MemoryStream outStream = new MemoryStream(); MemoryStream outStream = new MemoryStream();
Source.SaveJpg(Quality, outStream); Source.SaveJpg(Quality, outStream);
outStream.Position = 0; outStream.Position = 0;
return outStream; return outStream;
} }
public static void SaveJpg(this Image Source, int Quality, string Filename) public static void SaveJpg(this Image Source, int Quality, string Filename)
{ {
using (FileStream outStream = new FileStream(Filename, FileMode.Create, FileAccess.Write, FileShare.None)) using (FileStream outStream = new FileStream(Filename, FileMode.Create, FileAccess.Write, FileShare.None))
{ {
SaveJpg(Source, Quality, outStream); SaveJpg(Source, Quality, outStream);
outStream.Flush(); outStream.Flush();
outStream.Close(); outStream.Close();
} }
} }
public static void SaveJpg(this Image Source, int Quality, Stream OutStream) public static void SaveJpg(this Image Source, int Quality, Stream OutStream)
{ {
ImageCodecInfo jpgCodec = ImageCodecInfo.GetImageEncoders().Where(c => c.MimeType.Equals("image/jpeg", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); ImageCodecInfo jpgCodec = ImageCodecInfo.GetImageEncoders().Where(c => c.MimeType.Equals("image/jpeg", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
if (jpgCodec != null) if (jpgCodec != null)
{ {
if (Quality < 0 || Quality > 100) if (Quality < 0 || Quality > 100)
throw new ArgumentOutOfRangeException("Quality", "Quality must be a positive integer <= 100"); throw new ArgumentOutOfRangeException("Quality", "Quality must be a positive integer <= 100");
using (EncoderParameters ep = new EncoderParameters(1)) using (EncoderParameters ep = new EncoderParameters(1))
{ {
ep.Param[0] = new EncoderParameter(Encoder.Quality, Quality); ep.Param[0] = new EncoderParameter(Encoder.Quality, Quality);
Source.Save(OutStream, jpgCodec, ep); Source.Save(OutStream, jpgCodec, ep);
} }
} }
else else
{ {
// Fallback // Fallback
Source.Save(OutStream, ImageFormat.Jpeg); Source.Save(OutStream, ImageFormat.Jpeg);
} }
} }
public static ImageMontage BuildImageMontage(this IEnumerable<Image> Images, int MaxHeight = -1, int MaxWidth = -1, bool EnforceDimensions = false) public static ImageMontage BuildImageMontage(this IEnumerable<Image> Images, int MaxHeight = -1, int MaxWidth = -1, bool EnforceDimensions = false)
{ {
if (EnforceDimensions && (MaxHeight < 0 || MaxWidth < 0)) if (EnforceDimensions && (MaxHeight < 0 || MaxWidth < 0))
throw new ArgumentOutOfRangeException("EnforceDimensions", "Dimensions can only be enforced when a MaxHeight and MaxWidth is supplied"); throw new ArgumentOutOfRangeException("EnforceDimensions", "Dimensions can only be enforced when a MaxHeight and MaxWidth is supplied");
Dictionary<Image, int> imageLocations = new Dictionary<Image, int>(); Dictionary<Image, int> imageLocations = new Dictionary<Image, int>();
double imageScale = 1.0; double imageScale = 1.0;
int totalHeight = Images.Max(i => i.Height); int totalHeight = Images.Max(i => i.Height);
int totalWidth = Images.Sum(i => i.Width); int totalWidth = Images.Sum(i => i.Width);
if (MaxHeight > 0 && totalHeight > MaxHeight) if (MaxHeight > 0 && totalHeight > MaxHeight)
{ {
imageScale = (double)MaxHeight / (double)totalHeight; imageScale = (double)MaxHeight / (double)totalHeight;
} }
if (MaxWidth > 0 && totalWidth > MaxWidth) if (MaxWidth > 0 && totalWidth > MaxWidth)
{ {
imageScale = System.Math.Min(imageScale, (double)MaxWidth / (double)totalWidth); imageScale = System.Math.Min(imageScale, (double)MaxWidth / (double)totalWidth);
} }
int scaledHeight = EnforceDimensions ? MaxHeight : (int)System.Math.Round((double)totalHeight * imageScale); int scaledHeight = EnforceDimensions ? MaxHeight : (int)System.Math.Round((double)totalHeight * imageScale);
int scaledWidth = EnforceDimensions ? MaxWidth : (int)System.Math.Round((double)totalWidth * imageScale); int scaledWidth = EnforceDimensions ? MaxWidth : (int)System.Math.Round((double)totalWidth * imageScale);
System.Drawing.Bitmap imageResult = new System.Drawing.Bitmap(scaledWidth, scaledHeight); System.Drawing.Bitmap imageResult = new System.Drawing.Bitmap(scaledWidth, scaledHeight);
imageResult.SetResolution(72f, 72f); imageResult.SetResolution(72f, 72f);
using (Graphics g = Graphics.FromImage(imageResult)) using (Graphics g = Graphics.FromImage(imageResult))
{ {
g.FillRectangle(Brushes.White, new Rectangle(Point.Empty, imageResult.Size)); g.FillRectangle(Brushes.White, new Rectangle(Point.Empty, imageResult.Size));
int imageResultNextOffset = 0; int imageResultNextOffset = 0;
foreach (Image i in Images) foreach (Image i in Images)
{ {
Rectangle imagePosition = new Rectangle(imageResultNextOffset, 0, (int)System.Math.Round((double)i.Width * imageScale), (int)System.Math.Round((double)i.Height * imageScale)); Rectangle imagePosition = new Rectangle(imageResultNextOffset, 0, (int)System.Math.Round((double)i.Width * imageScale), (int)System.Math.Round((double)i.Height * imageScale));
System.Drawing.Rectangle imageSize = new System.Drawing.Rectangle(0, 0, i.Width, i.Height); System.Drawing.Rectangle imageSize = new System.Drawing.Rectangle(0, 0, i.Width, i.Height);
g.DrawImage(i, imagePosition, imageSize, System.Drawing.GraphicsUnit.Pixel); g.DrawImage(i, imagePosition, imageSize, System.Drawing.GraphicsUnit.Pixel);
imageLocations[i] = imageResultNextOffset; imageLocations[i] = imageResultNextOffset;
imageResultNextOffset += imagePosition.Width; imageResultNextOffset += imagePosition.Width;
} }
} }
return new ImageMontage() { Montage = imageResult, MontageScale = imageScale, MontageSourceImageOffsets = imageLocations }; return new ImageMontage() { Montage = imageResult, MontageScale = imageScale, MontageSourceImageOffsets = imageLocations };
} }
public class ImageMontage : IDisposable public class ImageMontage : IDisposable
{ {
public Image Montage { get; set; } public Image Montage { get; set; }
public double MontageScale { get; set; } public double MontageScale { get; set; }
public Dictionary<Image, int> MontageSourceImageOffsets { get; set; } public Dictionary<Image, int> MontageSourceImageOffsets { get; set; }
public void Dispose() public void Dispose()
{ {
if (Montage != null) if (Montage != null)
{ {
Montage.Dispose(); Montage.Dispose();
Montage = null; Montage = null;
} }
if (MontageSourceImageOffsets != null) if (MontageSourceImageOffsets != null)
{ {
MontageSourceImageOffsets.Clear(); MontageSourceImageOffsets.Clear();
MontageSourceImageOffsets = null; MontageSourceImageOffsets = null;
} }
} }
} }
public static Color InterpolateColours(this Color Start, Color End, double Progress) public static Color InterpolateColours(this Color Start, Color End, double Progress)
{ {
if (Progress > 1 || Progress < 0) if (Progress > 1 || Progress < 0)
throw new ArgumentOutOfRangeException("Progress", "Progress must be >= 0 && <= 1"); throw new ArgumentOutOfRangeException("Progress", "Progress must be >= 0 && <= 1");
return Color.FromArgb( return Color.FromArgb(
(byte)(Start.A * (1 - Progress) + (End.A * Progress)), (byte)(Start.A * (1 - Progress) + (End.A * Progress)),
(byte)(Start.R * (1 - Progress) + (End.R * Progress)), (byte)(Start.R * (1 - Progress) + (End.R * Progress)),
(byte)(Start.G * (1 - Progress) + (End.G * Progress)), (byte)(Start.G * (1 - Progress) + (End.G * Progress)),
(byte)(Start.B * (1 - Progress) + (End.B * Progress)) (byte)(Start.B * (1 - Progress) + (End.B * Progress))
); );
} }
#endregion #endregion
} }
} }
@@ -1,18 +1,18 @@
using Disco.Models.Repository; using Disco.Models.Repository;
using System; using System;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
namespace Disco.BI.Extensions namespace Disco.BI.Extensions
{ {
public static class WirelessCertificateExtensions public static class WirelessCertificateExtensions
{ {
public static System.DateTime? CertificateExpirationDate(this DeviceCertificate wc) public static System.DateTime? CertificateExpirationDate(this DeviceCertificate wc)
{ {
if (wc.Content == null || wc.Content.Length == 0) if (wc.Content == null || wc.Content.Length == 0)
{ {
return null; return null;
} }
X509Certificate2 c = new X509Certificate2(wc.Content, "password"); X509Certificate2 c = new X509Certificate2(wc.Content, "password");
return c.NotAfter; return c.NotAfter;
} }
} }
} }
@@ -1,397 +1,397 @@
using Disco.Models.Interop.ActiveDirectory; using Disco.Models.Interop.ActiveDirectory;
using Disco.BI.DeviceBI; using Disco.BI.DeviceBI;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.DirectoryServices; using System.DirectoryServices;
using System.Linq; using System.Linq;
using System.IO; using System.IO;
namespace Disco.BI.Interop.ActiveDirectory namespace Disco.BI.Interop.ActiveDirectory
{ {
public static class ActiveDirectory public static class ActiveDirectory
{ {
public static ActiveDirectoryMachineAccount GetMachineAccount(string ComputerName, System.Guid? UUIDNetbootGUID = null, System.Guid? MacAddressNetbootGUID = null, params string[] AdditionalProperties) public static ActiveDirectoryMachineAccount GetMachineAccount(string ComputerName, System.Guid? UUIDNetbootGUID = null, System.Guid? MacAddressNetbootGUID = null, params string[] AdditionalProperties)
{ {
if (string.IsNullOrWhiteSpace(ComputerName)) if (string.IsNullOrWhiteSpace(ComputerName))
throw new System.ArgumentException("Invalid Computer Name - Empty", "ComputerName"); throw new System.ArgumentException("Invalid Computer Name - Empty", "ComputerName");
if (ComputerName.Contains("\\")) if (ComputerName.Contains("\\"))
ComputerName = ComputerName.Substring(checked(ComputerName.IndexOf("\\") + 1)); ComputerName = ComputerName.Substring(checked(ComputerName.IndexOf("\\") + 1));
if (ComputerName.Length > 24) if (ComputerName.Length > 24)
throw new System.ArgumentException("Invalid Computer Name - Length > 24", "ComputerName"); throw new System.ArgumentException("Invalid Computer Name - Length > 24", "ComputerName");
string sAMAccountName = ComputerName; string sAMAccountName = ComputerName;
if (!sAMAccountName.EndsWith("$")) if (!sAMAccountName.EndsWith("$"))
sAMAccountName = string.Format("{0}$", sAMAccountName); sAMAccountName = string.Format("{0}$", sAMAccountName);
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot)
{ {
var loadProperties = new List<string> { "name", "distinguishedName", "sAMAccountName", "objectSid", "dNSHostName", "netbootGUID", "isCriticalSystemObject" }; var loadProperties = new List<string> { "name", "distinguishedName", "sAMAccountName", "objectSid", "dNSHostName", "netbootGUID", "isCriticalSystemObject" };
loadProperties.AddRange(AdditionalProperties); loadProperties.AddRange(AdditionalProperties);
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties.ToArray(), SearchScope.Subtree)) using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties.ToArray(), SearchScope.Subtree))
{ {
SearchResult dResult = dSearcher.FindOne(); SearchResult dResult = dSearcher.FindOne();
if (dResult != null) if (dResult != null)
{ {
return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties); return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties);
} }
} }
if (UUIDNetbootGUID.HasValue) if (UUIDNetbootGUID.HasValue)
{ {
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(UUIDNetbootGUID.Value)), loadProperties.ToArray(), SearchScope.Subtree)) using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(UUIDNetbootGUID.Value)), loadProperties.ToArray(), SearchScope.Subtree))
{ {
SearchResult dResult = dSearcher.FindOne(); SearchResult dResult = dSearcher.FindOne();
if (dResult != null) if (dResult != null)
{ {
return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties); return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties);
} }
} }
} }
if (MacAddressNetbootGUID.HasValue) if (MacAddressNetbootGUID.HasValue)
{ {
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(MacAddressNetbootGUID.Value)), loadProperties.ToArray(), SearchScope.Subtree)) using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=computer)(netbootGUID={0}))", ActiveDirectoryHelpers.FormatGuidForLdapQuery(MacAddressNetbootGUID.Value)), loadProperties.ToArray(), SearchScope.Subtree))
{ {
SearchResult dResult = dSearcher.FindOne(); SearchResult dResult = dSearcher.FindOne();
if (dResult != null) if (dResult != null)
{ {
return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties); return ActiveDirectory.DirectorySearchResultToMachineAccount(dResult, AdditionalProperties);
} }
} }
} }
} }
return null; return null;
} }
private static ActiveDirectoryMachineAccount DirectorySearchResultToMachineAccount(SearchResult result, params string[] AdditionalProperties) private static ActiveDirectoryMachineAccount DirectorySearchResultToMachineAccount(SearchResult result, params string[] AdditionalProperties)
{ {
string name = result.Properties["name"][0].ToString(); string name = result.Properties["name"][0].ToString();
string sAMAccountName = result.Properties["sAMAccountName"][0].ToString(); string sAMAccountName = result.Properties["sAMAccountName"][0].ToString();
string distinguishedName = result.Properties["distinguishedName"][0].ToString(); string distinguishedName = result.Properties["distinguishedName"][0].ToString();
string objectSid = ActiveDirectoryHelpers.ConvertBytesToSIDString((byte[])result.Properties["objectSid"][0]); string objectSid = ActiveDirectoryHelpers.ConvertBytesToSIDString((byte[])result.Properties["objectSid"][0]);
var dNSNameProperty = result.Properties["dNSHostName"]; var dNSNameProperty = result.Properties["dNSHostName"];
string dNSName = null; string dNSName = null;
if (dNSNameProperty.Count > 0) if (dNSNameProperty.Count > 0)
dNSName = dNSNameProperty[0].ToString(); dNSName = dNSNameProperty[0].ToString();
else else
dNSName = string.Format("{0}.{1}", sAMAccountName.TrimEnd('$'), ActiveDirectoryHelpers.DefaultDomainQualifiedName); dNSName = string.Format("{0}.{1}", sAMAccountName.TrimEnd('$'), ActiveDirectoryHelpers.DefaultDomainQualifiedName);
bool isCriticalSystemObject = (bool)result.Properties["isCriticalSystemObject"][0]; bool isCriticalSystemObject = (bool)result.Properties["isCriticalSystemObject"][0];
System.Guid netbootGUIDResult = default(System.Guid); System.Guid netbootGUIDResult = default(System.Guid);
ResultPropertyValueCollection netbootGUIDProp = result.Properties["netbootGUID"]; ResultPropertyValueCollection netbootGUIDProp = result.Properties["netbootGUID"];
if (netbootGUIDProp.Count > 0) if (netbootGUIDProp.Count > 0)
{ {
netbootGUIDResult = new System.Guid((byte[])netbootGUIDProp[0]); netbootGUIDResult = new System.Guid((byte[])netbootGUIDProp[0]);
} }
// Additional Properties // Additional Properties
Dictionary<string, object[]> additionalProperties = new Dictionary<string, object[]>(); Dictionary<string, object[]> additionalProperties = new Dictionary<string, object[]>();
foreach (string propertyName in AdditionalProperties) foreach (string propertyName in AdditionalProperties)
{ {
var property = result.Properties[propertyName]; var property = result.Properties[propertyName];
var propertyValues = new List<object>(); var propertyValues = new List<object>();
for (int index = 0; index < property.Count; index++) for (int index = 0; index < property.Count; index++)
propertyValues.Add(property[index]); propertyValues.Add(property[index]);
additionalProperties.Add(propertyName, propertyValues.ToArray()); additionalProperties.Add(propertyName, propertyValues.ToArray());
} }
return new ActiveDirectoryMachineAccount return new ActiveDirectoryMachineAccount
{ {
Name = name, Name = name,
DistinguishedName = distinguishedName, DistinguishedName = distinguishedName,
sAMAccountName = sAMAccountName, sAMAccountName = sAMAccountName,
ObjectSid = objectSid, ObjectSid = objectSid,
NetbootGUID = netbootGUIDResult, NetbootGUID = netbootGUIDResult,
Path = result.Path, Path = result.Path,
Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName, Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName,
DnsName = dNSName, DnsName = dNSName,
IsCriticalSystemObject = isCriticalSystemObject, IsCriticalSystemObject = isCriticalSystemObject,
LoadedProperties = additionalProperties LoadedProperties = additionalProperties
}; };
} }
private static ActiveDirectoryUserAccount SearchResultToActiveDirectoryUserAccount(SearchResult result, params string[] AdditionalProperties) private static ActiveDirectoryUserAccount SearchResultToActiveDirectoryUserAccount(SearchResult result, params string[] AdditionalProperties)
{ {
string name = result.Properties["name"][0].ToString(); string name = result.Properties["name"][0].ToString();
string username = result.Properties["sAMAccountName"][0].ToString(); string username = result.Properties["sAMAccountName"][0].ToString();
string distinguishedName = result.Properties["distinguishedName"][0].ToString(); string distinguishedName = result.Properties["distinguishedName"][0].ToString();
string objectSid = ActiveDirectoryHelpers.ConvertBytesToSIDString((byte[])result.Properties["objectSid"][0]); string objectSid = ActiveDirectoryHelpers.ConvertBytesToSIDString((byte[])result.Properties["objectSid"][0]);
ResultPropertyValueCollection displayNameProp = result.Properties["displayName"]; ResultPropertyValueCollection displayNameProp = result.Properties["displayName"];
string displayName = username; string displayName = username;
if (displayNameProp.Count > 0) if (displayNameProp.Count > 0)
displayName = displayNameProp[0].ToString(); displayName = displayNameProp[0].ToString();
string surname = null; string surname = null;
ResultPropertyValueCollection surnameProp = result.Properties["sn"]; ResultPropertyValueCollection surnameProp = result.Properties["sn"];
if (surnameProp.Count > 0) if (surnameProp.Count > 0)
surname = surnameProp[0].ToString(); surname = surnameProp[0].ToString();
string givenName = null; string givenName = null;
ResultPropertyValueCollection givenNameProp = result.Properties["givenName"]; ResultPropertyValueCollection givenNameProp = result.Properties["givenName"];
if (givenNameProp.Count > 0) if (givenNameProp.Count > 0)
givenName = givenNameProp[0].ToString(); givenName = givenNameProp[0].ToString();
string email = null; string email = null;
ResultPropertyValueCollection emailProp = result.Properties["mail"]; ResultPropertyValueCollection emailProp = result.Properties["mail"];
if (emailProp.Count > 0) if (emailProp.Count > 0)
email = emailProp[0].ToString(); email = emailProp[0].ToString();
string phone = null; string phone = null;
ResultPropertyValueCollection phoneProp = result.Properties["telephoneNumber"]; ResultPropertyValueCollection phoneProp = result.Properties["telephoneNumber"];
if (phoneProp.Count > 0) if (phoneProp.Count > 0)
phone = phoneProp[0].ToString(); phone = phoneProp[0].ToString();
IEnumerable<string> groupCNs = result.Properties["memberOf"].Cast<string>(); IEnumerable<string> groupCNs = result.Properties["memberOf"].Cast<string>();
List<string> groups = ActiveDirectoryCachedGroups.GetGroups(groupCNs).Select(g => g.ToLower()).ToList(); List<string> groups = ActiveDirectoryCachedGroups.GetGroups(groupCNs).Select(g => g.ToLower()).ToList();
//foreach (string groupCN in result.Properties["memberOf"]) //foreach (string groupCN in result.Properties["memberOf"])
//{ //{
// Removed 2012-11-30 G# - Moved to Recursive Cache // Removed 2012-11-30 G# - Moved to Recursive Cache
//var groupCNlower = groupCN.ToLower(); //var groupCNlower = groupCN.ToLower();
//if (groupCNlower.StartsWith("cn=")) //if (groupCNlower.StartsWith("cn="))
// groups.Add(groupCNlower.Substring(3, groupCNlower.IndexOf(",") - 3)); // groups.Add(groupCNlower.Substring(3, groupCNlower.IndexOf(",") - 3));
// End Removed 2012-11-30 G# // End Removed 2012-11-30 G#
//} //}
string type = null; string type = null;
if (groups.Contains("domain admins") || groups.Contains("disco admins")) if (groups.Contains("domain admins") || groups.Contains("disco admins"))
{ {
type = "Admin"; type = "Admin";
} }
else else
{ {
if (groups.Contains("staff")) if (groups.Contains("staff"))
{ {
type = "Staff"; type = "Staff";
} }
else else
{ {
if (groups.Contains("students")) if (groups.Contains("students"))
{ {
type = "Student"; type = "Student";
} }
} }
} }
// Additional Properties // Additional Properties
Dictionary<string, object[]> additionalProperties = new Dictionary<string, object[]>(); Dictionary<string, object[]> additionalProperties = new Dictionary<string, object[]>();
foreach (string propertyName in AdditionalProperties) foreach (string propertyName in AdditionalProperties)
{ {
var property = result.Properties[propertyName]; var property = result.Properties[propertyName];
var propertyValues = new List<object>(); var propertyValues = new List<object>();
for (int index = 0; index < property.Count; index++) for (int index = 0; index < property.Count; index++)
propertyValues.Add(property[index]); propertyValues.Add(property[index]);
additionalProperties.Add(propertyName, propertyValues.ToArray()); additionalProperties.Add(propertyName, propertyValues.ToArray());
} }
return new ActiveDirectoryUserAccount return new ActiveDirectoryUserAccount
{ {
Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName, Domain = ActiveDirectoryHelpers.DefaultDomainNetBiosName,
Name = name, Name = name,
Surname = surname, Surname = surname,
GivenName = givenName, GivenName = givenName,
Email = email, Email = email,
Phone = phone, Phone = phone,
DistinguishedName = distinguishedName, DistinguishedName = distinguishedName,
sAMAccountName = username, sAMAccountName = username,
DisplayName = displayName, DisplayName = displayName,
ObjectSid = objectSid, ObjectSid = objectSid,
Type = type, Type = type,
Path = result.Path, Path = result.Path,
LoadedProperties = additionalProperties LoadedProperties = additionalProperties
}; };
} }
public static ActiveDirectoryUserAccount GetUserAccount(string Username, params string[] AdditionalProperties) public static ActiveDirectoryUserAccount GetUserAccount(string Username, params string[] AdditionalProperties)
{ {
if (string.IsNullOrWhiteSpace(Username)) if (string.IsNullOrWhiteSpace(Username))
throw new System.ArgumentException("Invalid User Account", "Username"); throw new System.ArgumentException("Invalid User Account", "Username");
string sAMAccountName = Username; string sAMAccountName = Username;
if (sAMAccountName.Contains("\\")) if (sAMAccountName.Contains("\\"))
sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1)); sAMAccountName = sAMAccountName.Substring(checked(sAMAccountName.IndexOf("\\") + 1));
using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot) using (DirectoryEntry dRootEntry = ActiveDirectoryHelpers.DefaultLdapRoot)
{ {
var loadProperties = new List<string> { var loadProperties = new List<string> {
"name", "name",
"distinguishedName", "distinguishedName",
"sAMAccountName", "sAMAccountName",
"objectSid", "objectSid",
"displayName", "displayName",
"sn", "sn",
"givenName", "givenName",
"memberOf", "memberOf",
"mail", "mail",
"telephoneNumber" "telephoneNumber"
}; };
loadProperties.AddRange(AdditionalProperties); loadProperties.AddRange(AdditionalProperties);
using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=user)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties.ToArray(), SearchScope.Subtree)) using (DirectorySearcher dSearcher = new DirectorySearcher(dRootEntry, string.Format("(&(objectClass=user)(sAMAccountName={0}))", ActiveDirectoryHelpers.EscapeLdapQuery(sAMAccountName)), loadProperties.ToArray(), SearchScope.Subtree))
{ {
SearchResult dResult = dSearcher.FindOne(); SearchResult dResult = dSearcher.FindOne();
if (dResult != null) if (dResult != null)
return ActiveDirectory.SearchResultToActiveDirectoryUserAccount(dResult, AdditionalProperties); return ActiveDirectory.SearchResultToActiveDirectoryUserAccount(dResult, AdditionalProperties);
else else
return null; return null;
} }
} }
} }
public static string OfflineDomainJoinProvision(ref ActiveDirectoryMachineAccount ExistingAccount, string ComputerName, string OrganisationalUnit = null, string EnrolSessionId = null) public static string OfflineDomainJoinProvision(ref ActiveDirectoryMachineAccount ExistingAccount, string ComputerName, string OrganisationalUnit = null, string EnrolSessionId = null)
{ {
if (ExistingAccount != null && ExistingAccount.IsCriticalSystemObject) if (ExistingAccount != null && ExistingAccount.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", ExistingAccount.DistinguishedName)); throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", ExistingAccount.DistinguishedName));
string DJoinResult = null; string DJoinResult = null;
if (string.IsNullOrWhiteSpace(ComputerName) || ComputerName.Length > 24) if (string.IsNullOrWhiteSpace(ComputerName) || ComputerName.Length > 24)
throw new System.ArgumentException("Invalid Computer Name; > 0 and <= 24", "ComputerName"); throw new System.ArgumentException("Invalid Computer Name; > 0 and <= 24", "ComputerName");
// Added 2012-10-25 G# // Added 2012-10-25 G#
// Ensure Specified OU Exists // Ensure Specified OU Exists
if (!string.IsNullOrEmpty(OrganisationalUnit)) if (!string.IsNullOrEmpty(OrganisationalUnit))
{ {
var ouPath = string.Format("{0}{1},{2}", ActiveDirectoryHelpers.DefaultLdapPath, OrganisationalUnit, ActiveDirectoryHelpers.DefaultDomainQualifiedName); var ouPath = string.Format("{0}{1},{2}", ActiveDirectoryHelpers.DefaultLdapPath, OrganisationalUnit, ActiveDirectoryHelpers.DefaultDomainQualifiedName);
try try
{ {
using (DirectoryEntry ou = new DirectoryEntry(ouPath)) using (DirectoryEntry ou = new DirectoryEntry(ouPath))
{ {
if (ou == null) if (ou == null)
{ {
throw new Exception("OU's Directory Entry couldn't be found"); throw new Exception("OU's Directory Entry couldn't be found");
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new ArgumentException(string.Format("An error occurred while trying to locate the specified OU: {0}", ouPath), "OrganisationalUnit", ex); throw new ArgumentException(string.Format("An error occurred while trying to locate the specified OU: {0}", ouPath), "OrganisationalUnit", ex);
} }
} }
// End Added 2012-10-25 G# // End Added 2012-10-25 G#
// Delete Existing // Delete Existing
if (ExistingAccount != null) if (ExistingAccount != null)
ExistingAccount.DeleteAccount(); ExistingAccount.DeleteAccount();
string tempFileName = System.IO.Path.GetTempFileName(); string tempFileName = System.IO.Path.GetTempFileName();
string argumentOU = (!string.IsNullOrWhiteSpace(OrganisationalUnit)) ? string.Format(" /MACHINEOU \"{0},{1}\"", OrganisationalUnit, ActiveDirectoryHelpers.DefaultDomainQualifiedName) : string.Empty; string argumentOU = (!string.IsNullOrWhiteSpace(OrganisationalUnit)) ? string.Format(" /MACHINEOU \"{0},{1}\"", OrganisationalUnit, ActiveDirectoryHelpers.DefaultDomainQualifiedName) : string.Empty;
string arguments = string.Format("/PROVISION /DOMAIN \"{0}\" /DCNAME \"{1}\" /MACHINE \"{2}\"{3} /REUSE /SAVEFILE \"{4}\"", string arguments = string.Format("/PROVISION /DOMAIN \"{0}\" /DCNAME \"{1}\" /MACHINE \"{2}\"{3} /REUSE /SAVEFILE \"{4}\"",
ActiveDirectoryHelpers.DefaultDomainName, ActiveDirectoryHelpers.DefaultDomainName,
ActiveDirectoryHelpers.DefaultDomainPDCName, ActiveDirectoryHelpers.DefaultDomainPDCName,
ComputerName, ComputerName,
argumentOU, argumentOU,
tempFileName tempFileName
); );
ProcessStartInfo commandStarter = new ProcessStartInfo("DJOIN.EXE", arguments) ProcessStartInfo commandStarter = new ProcessStartInfo("DJOIN.EXE", arguments)
{ {
CreateNoWindow = true, CreateNoWindow = true,
ErrorDialog = false, ErrorDialog = false,
LoadUserProfile = false, LoadUserProfile = false,
RedirectStandardOutput = true, RedirectStandardOutput = true,
RedirectStandardError = true, RedirectStandardError = true,
UseShellExecute = false UseShellExecute = false
}; };
if (EnrolSessionId != null) if (EnrolSessionId != null)
{ {
EnrolmentLog.LogSessionDiagnosticInformation(EnrolSessionId, string.Format("{0} {1}{2}", "DJOIN.EXE", arguments, System.Environment.NewLine)); EnrolmentLog.LogSessionDiagnosticInformation(EnrolSessionId, string.Format("{0} {1}{2}", "DJOIN.EXE", arguments, System.Environment.NewLine));
} }
string stdOutput; string stdOutput;
string stdError; string stdError;
using (Process commandProc = Process.Start(commandStarter)) using (Process commandProc = Process.Start(commandStarter))
{ {
commandProc.WaitForExit(20000); commandProc.WaitForExit(20000);
stdOutput = commandProc.StandardOutput.ReadToEnd(); stdOutput = commandProc.StandardOutput.ReadToEnd();
stdError = commandProc.StandardError.ReadToEnd(); stdError = commandProc.StandardError.ReadToEnd();
} }
if (EnrolSessionId != null) if (EnrolSessionId != null)
{ {
if (!string.IsNullOrWhiteSpace(stdOutput)) if (!string.IsNullOrWhiteSpace(stdOutput))
EnrolmentLog.LogSessionDiagnosticInformation(EnrolSessionId, stdOutput + System.Environment.NewLine); EnrolmentLog.LogSessionDiagnosticInformation(EnrolSessionId, stdOutput + System.Environment.NewLine);
if (!string.IsNullOrWhiteSpace(stdError)) if (!string.IsNullOrWhiteSpace(stdError))
EnrolmentLog.LogSessionDiagnosticInformation(EnrolSessionId, stdError + System.Environment.NewLine); EnrolmentLog.LogSessionDiagnosticInformation(EnrolSessionId, stdError + System.Environment.NewLine);
} }
if (System.IO.File.Exists(tempFileName)) if (System.IO.File.Exists(tempFileName))
{ {
DJoinResult = System.Convert.ToBase64String(System.IO.File.ReadAllBytes(tempFileName)); DJoinResult = System.Convert.ToBase64String(System.IO.File.ReadAllBytes(tempFileName));
System.IO.File.Delete(tempFileName); System.IO.File.Delete(tempFileName);
} }
if (string.IsNullOrWhiteSpace(DJoinResult)) if (string.IsNullOrWhiteSpace(DJoinResult))
throw new System.InvalidOperationException(string.Format("Domain Join Unsuccessful{0}Error: {1}{0}Output: {2}", System.Environment.NewLine, stdError, stdOutput)); throw new System.InvalidOperationException(string.Format("Domain Join Unsuccessful{0}Error: {1}{0}Output: {2}", System.Environment.NewLine, stdError, stdOutput));
ExistingAccount = ActiveDirectory.GetMachineAccount(ComputerName); ExistingAccount = ActiveDirectory.GetMachineAccount(ComputerName);
return DJoinResult; return DJoinResult;
} }
public static List<ActiveDirectoryUserAccount> SearchUsers(string term) public static List<ActiveDirectoryUserAccount> SearchUsers(string term)
{ {
List<ActiveDirectoryUserAccount> users = new List<ActiveDirectoryUserAccount>(); List<ActiveDirectoryUserAccount> users = new List<ActiveDirectoryUserAccount>();
string defaultQualifiedDomainName = ActiveDirectoryHelpers.DefaultDomainQualifiedName; string defaultQualifiedDomainName = ActiveDirectoryHelpers.DefaultDomainQualifiedName;
string defaultNetBiosDomainName = ActiveDirectoryHelpers.DefaultDomainNetBiosName; string defaultNetBiosDomainName = ActiveDirectoryHelpers.DefaultDomainNetBiosName;
term = ActiveDirectoryHelpers.EscapeLdapQuery(term); term = ActiveDirectoryHelpers.EscapeLdapQuery(term);
using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", defaultQualifiedDomainName))) using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", defaultQualifiedDomainName)))
{ {
using (DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(&(objectClass=User)(objectCategory=Person)(|(sAMAccountName=*{0}*)(displayName=*{0}*)))", term), new string[] using (DirectorySearcher searcher = new DirectorySearcher(entry, string.Format("(&(objectClass=User)(objectCategory=Person)(|(sAMAccountName=*{0}*)(displayName=*{0}*)))", term), new string[]
{ {
"name", "name",
"distinguishedName", "distinguishedName",
"sAMAccountName", "sAMAccountName",
"objectSid", "objectSid",
"displayName", "displayName",
"sn", "sn",
"givenName", "givenName",
"memberOf", "memberOf",
"mail", "mail",
"telephoneNumber" "telephoneNumber"
}, SearchScope.Subtree)) }, SearchScope.Subtree))
{ {
searcher.SizeLimit = 30; searcher.SizeLimit = 30;
SearchResultCollection results = searcher.FindAll(); SearchResultCollection results = searcher.FindAll();
foreach (SearchResult result in results) foreach (SearchResult result in results)
{ {
users.Add(ActiveDirectory.SearchResultToActiveDirectoryUserAccount(result)); users.Add(ActiveDirectory.SearchResultToActiveDirectoryUserAccount(result));
} }
} }
} }
return users; return users;
} }
public static List<ActiveDirectoryOrganisationalUnit> GetOrganisationalUnitStructure() public static List<ActiveDirectoryOrganisationalUnit> GetOrganisationalUnitStructure()
{ {
ActiveDirectoryOrganisationalUnit DomainOUs = new ActiveDirectoryOrganisationalUnit ActiveDirectoryOrganisationalUnit DomainOUs = new ActiveDirectoryOrganisationalUnit
{ {
Children = new System.Collections.Generic.List<ActiveDirectoryOrganisationalUnit>() Children = new System.Collections.Generic.List<ActiveDirectoryOrganisationalUnit>()
}; };
string defaultQualifiedDomainName = ActiveDirectoryHelpers.DefaultDomainQualifiedName; string defaultQualifiedDomainName = ActiveDirectoryHelpers.DefaultDomainQualifiedName;
using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", defaultQualifiedDomainName))) using (DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", defaultQualifiedDomainName)))
{ {
ActiveDirectory.GetOrganisationalUnitStructure_Recursive(ref DomainOUs, entry); ActiveDirectory.GetOrganisationalUnitStructure_Recursive(ref DomainOUs, entry);
} }
return DomainOUs.Children; return DomainOUs.Children;
} }
private static void GetOrganisationalUnitStructure_Recursive(ref ActiveDirectoryOrganisationalUnit ParentOU, DirectoryEntry Container) private static void GetOrganisationalUnitStructure_Recursive(ref ActiveDirectoryOrganisationalUnit ParentOU, DirectoryEntry Container)
{ {
using (DirectorySearcher searcher = new DirectorySearcher(Container, "(objectCategory=organizationalUnit)", new string[] using (DirectorySearcher searcher = new DirectorySearcher(Container, "(objectCategory=organizationalUnit)", new string[]
{ {
"name", "name",
"distinguishedName" "distinguishedName"
}, SearchScope.OneLevel)) }, SearchScope.OneLevel))
{ {
using (SearchResultCollection results = searcher.FindAll()) using (SearchResultCollection results = searcher.FindAll())
{ {
foreach (SearchResult result in results) foreach (SearchResult result in results)
{ {
string i = result.Properties["name"][0].ToString(); string i = result.Properties["name"][0].ToString();
string dn = result.Properties["distinguishedName"][0].ToString(); string dn = result.Properties["distinguishedName"][0].ToString();
ActiveDirectoryOrganisationalUnit ChildOU = new ActiveDirectoryOrganisationalUnit ActiveDirectoryOrganisationalUnit ChildOU = new ActiveDirectoryOrganisationalUnit
{ {
Name = i, Name = i,
Path = dn.Substring(0, dn.IndexOf(",DC=")), Path = dn.Substring(0, dn.IndexOf(",DC=")),
Children = new List<ActiveDirectoryOrganisationalUnit>() Children = new List<ActiveDirectoryOrganisationalUnit>()
}; };
ActiveDirectory.GetOrganisationalUnitStructure_Recursive(ref ChildOU, result.GetDirectoryEntry()); ActiveDirectory.GetOrganisationalUnitStructure_Recursive(ref ChildOU, result.GetDirectoryEntry());
if (ChildOU.Children.Count == 0) if (ChildOU.Children.Count == 0)
ChildOU.Children = null; ChildOU.Children = null;
ParentOU.Children.Add(ChildOU); ParentOU.Children.Add(ChildOU);
} }
} }
} }
} }
} }
} }
@@ -1,186 +1,186 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.DirectoryServices; using System.DirectoryServices;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Services.Tasks; using Disco.Services.Tasks;
using Quartz; using Quartz;
namespace Disco.BI.Interop.ActiveDirectory namespace Disco.BI.Interop.ActiveDirectory
{ {
public class ActiveDirectoryCachedGroups : ScheduledTask public class ActiveDirectoryCachedGroups : ScheduledTask
{ {
private static ConcurrentDictionary<string, Tuple<ADCachedGroup, DateTime>> _Cache = new ConcurrentDictionary<string, Tuple<ADCachedGroup, DateTime>>(); private static ConcurrentDictionary<string, Tuple<ADCachedGroup, DateTime>> _Cache = new ConcurrentDictionary<string, Tuple<ADCachedGroup, DateTime>>();
private const long CacheTimeoutTicks = 6000000000; // 10 Minutes private const long CacheTimeoutTicks = 6000000000; // 10 Minutes
public static IEnumerable<string> GetGroups(IEnumerable<string> GroupCNs) public static IEnumerable<string> GetGroups(IEnumerable<string> GroupCNs)
{ {
List<ADCachedGroup> groups = new List<ADCachedGroup>(); List<ADCachedGroup> groups = new List<ADCachedGroup>();
foreach (var groupCN in GroupCNs) foreach (var groupCN in GroupCNs)
foreach (var group in GetGroupsRecursive(groupCN, new Stack<ADCachedGroup>())) foreach (var group in GetGroupsRecursive(groupCN, new Stack<ADCachedGroup>()))
if (!groups.Contains(group)) if (!groups.Contains(group))
{ {
groups.Add(group); groups.Add(group);
yield return group.FriendlyName; yield return group.FriendlyName;
} }
} }
public static IEnumerable<string> GetGroups(string GroupCN) public static IEnumerable<string> GetGroups(string GroupCN)
{ {
foreach (var group in GetGroupsRecursive(GroupCN, new Stack<ADCachedGroup>())) foreach (var group in GetGroupsRecursive(GroupCN, new Stack<ADCachedGroup>()))
yield return group.FriendlyName; yield return group.FriendlyName;
} }
private static IEnumerable<ADCachedGroup> GetGroupsRecursive(string GroupCN, Stack<ADCachedGroup> RecursiveTree) private static IEnumerable<ADCachedGroup> GetGroupsRecursive(string GroupCN, Stack<ADCachedGroup> RecursiveTree)
{ {
var group = GetGroup(GroupCN); var group = GetGroup(GroupCN);
if (group != null && !RecursiveTree.Contains(group)) if (group != null && !RecursiveTree.Contains(group))
{ {
yield return group; yield return group;
if (group.MemberOf != null) if (group.MemberOf != null)
{ {
RecursiveTree.Push(group); RecursiveTree.Push(group);
foreach (var memberOfGroupCN in group.MemberOf) foreach (var memberOfGroupCN in group.MemberOf)
foreach (var memberOfGroup in GetGroupsRecursive(memberOfGroupCN, RecursiveTree)) foreach (var memberOfGroup in GetGroupsRecursive(memberOfGroupCN, RecursiveTree))
yield return memberOfGroup; yield return memberOfGroup;
RecursiveTree.Pop(); RecursiveTree.Pop();
} }
} }
} }
private static ADCachedGroup GetGroup(string GroupCN) private static ADCachedGroup GetGroup(string GroupCN)
{ {
// Check Cache // Check Cache
Tuple<ADCachedGroup, DateTime> groupRecord = TryCache(GroupCN); Tuple<ADCachedGroup, DateTime> groupRecord = TryCache(GroupCN);
if (groupRecord == null) if (groupRecord == null)
{ {
// Load from AD // Load from AD
var group = ADCachedGroup.LoadFromAD(GroupCN); var group = ADCachedGroup.LoadFromAD(GroupCN);
SetValue(GroupCN, group); SetValue(GroupCN, group);
return group; return group;
} }
else else
{ {
// Return from Cache // Return from Cache
return groupRecord.Item1; return groupRecord.Item1;
} }
} }
private static Tuple<ADCachedGroup, DateTime> TryCache(string GroupCN) private static Tuple<ADCachedGroup, DateTime> TryCache(string GroupCN)
{ {
string groupCN = GroupCN.ToLower(); string groupCN = GroupCN.ToLower();
Tuple<ADCachedGroup, DateTime> groupRecord; Tuple<ADCachedGroup, DateTime> groupRecord;
if (_Cache.TryGetValue(groupCN, out groupRecord)) if (_Cache.TryGetValue(groupCN, out groupRecord))
{ {
if (groupRecord.Item2 > DateTime.Now) if (groupRecord.Item2 > DateTime.Now)
return groupRecord; return groupRecord;
else else
_Cache.TryRemove(groupCN, out groupRecord); _Cache.TryRemove(groupCN, out groupRecord);
} }
return null; return null;
} }
private static bool SetValue(string GroupCN, ADCachedGroup GroupRecord) private static bool SetValue(string GroupCN, ADCachedGroup GroupRecord)
{ {
string key = GroupCN.ToLower(); string key = GroupCN.ToLower();
Tuple<ADCachedGroup, DateTime> groupRecord = new Tuple<ADCachedGroup, DateTime>(GroupRecord, DateTime.Now.AddTicks(CacheTimeoutTicks)); Tuple<ADCachedGroup, DateTime> groupRecord = new Tuple<ADCachedGroup, DateTime>(GroupRecord, DateTime.Now.AddTicks(CacheTimeoutTicks));
if (_Cache.ContainsKey(key)) if (_Cache.ContainsKey(key))
{ {
Tuple<ADCachedGroup, DateTime> oldGroupRecord; Tuple<ADCachedGroup, DateTime> oldGroupRecord;
if (_Cache.TryGetValue(key, out oldGroupRecord)) if (_Cache.TryGetValue(key, out oldGroupRecord))
{ {
return _Cache.TryUpdate(key, groupRecord, oldGroupRecord); return _Cache.TryUpdate(key, groupRecord, oldGroupRecord);
} }
} }
return _Cache.TryAdd(key, groupRecord); return _Cache.TryAdd(key, groupRecord);
} }
private class ADCachedGroup private class ADCachedGroup
{ {
public string CN { get; private set; } public string CN { get; private set; }
public string FriendlyName { get; private set; } public string FriendlyName { get; private set; }
public List<string> MemberOf { get; private set; } public List<string> MemberOf { get; private set; }
public static ADCachedGroup LoadFromAD(string CN) public static ADCachedGroup LoadFromAD(string CN)
{ {
ADCachedGroup group = null; ADCachedGroup group = null;
using (DirectoryEntry groupDE = new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, CN))) using (DirectoryEntry groupDE = new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, CN)))
{ {
if (groupDE != null) if (groupDE != null)
{ {
group = new ADCachedGroup() group = new ADCachedGroup()
{ {
CN = CN CN = CN
}; };
group.FriendlyName = (string)groupDE.Properties["sAMAccountName"].Value; group.FriendlyName = (string)groupDE.Properties["sAMAccountName"].Value;
var groupMemberOf = groupDE.Properties["memberOf"]; var groupMemberOf = groupDE.Properties["memberOf"];
if (groupMemberOf != null && groupMemberOf.Count > 0) if (groupMemberOf != null && groupMemberOf.Count > 0)
{ {
group.MemberOf = groupMemberOf.Cast<string>().ToList(); group.MemberOf = groupMemberOf.Cast<string>().ToList();
} }
} }
} }
return group; return group;
} }
private ADCachedGroup() private ADCachedGroup()
{ {
// Private Constructor // Private Constructor
} }
} }
private static void CleanStaleCache() private static void CleanStaleCache()
{ {
var groupKeys = _Cache.Keys.ToArray(); var groupKeys = _Cache.Keys.ToArray();
foreach (string groupKey in groupKeys) foreach (string groupKey in groupKeys)
{ {
Tuple<ADCachedGroup, DateTime> groupRecord; Tuple<ADCachedGroup, DateTime> groupRecord;
if (_Cache.TryGetValue(groupKey, out groupRecord)) if (_Cache.TryGetValue(groupKey, out groupRecord))
{ {
if (groupRecord.Item2 <= DateTime.Now) if (groupRecord.Item2 <= DateTime.Now)
_Cache.TryRemove(groupKey, out groupRecord); _Cache.TryRemove(groupKey, out groupRecord);
} }
} }
} }
public override string TaskName { get { return "AD Group Cache - Clean Stale Cache"; } } public override string TaskName { get { return "AD Group Cache - Clean Stale Cache"; } }
public override bool SingleInstanceTask { get { return true; } } public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override bool LogExceptionsOnly { get { return true; } } public override bool LogExceptionsOnly { get { return true; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext dbContext)
{ {
// Run @ every 15mins // Run @ every 15mins
// Next 15min interval // Next 15min interval
DateTime now = DateTime.Now; DateTime now = DateTime.Now;
int mins = (15 - (now.Minute % 15)); int mins = (15 - (now.Minute % 15));
if (mins < 10) if (mins < 10)
mins += 15; mins += 15;
DateTimeOffset startAt = new DateTimeOffset(now).AddMinutes(mins).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1); DateTimeOffset startAt = new DateTimeOffset(now).AddMinutes(mins).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1);
TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(startAt). TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(startAt).
WithSchedule(SimpleScheduleBuilder.RepeatMinutelyForever(15)); WithSchedule(SimpleScheduleBuilder.RepeatMinutelyForever(15));
this.ScheduleTask(triggerBuilder); this.ScheduleTask(triggerBuilder);
} }
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
CleanStaleCache(); CleanStaleCache();
} }
} }
} }
@@ -1,169 +1,169 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.DirectoryServices; using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory; using System.DirectoryServices.ActiveDirectory;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
namespace Disco.BI.Interop.ActiveDirectory namespace Disco.BI.Interop.ActiveDirectory
{ {
internal static class ActiveDirectoryHelpers internal static class ActiveDirectoryHelpers
{ {
#region Static Cached Properties #region Static Cached Properties
private static string _DefaultDomainName; private static string _DefaultDomainName;
private static string _DefaultDomainPDCName; private static string _DefaultDomainPDCName;
private static System.Collections.Generic.List<string> _DefaultDomainDCNames; private static System.Collections.Generic.List<string> _DefaultDomainDCNames;
private static string _DefaultDomainNetBiosName; private static string _DefaultDomainNetBiosName;
private static string _DefaultDomainQualifiedName; private static string _DefaultDomainQualifiedName;
private static string _DefaultLdapPath; private static string _DefaultLdapPath;
private static bool _DetermineDomainProperties_Loaded = false; private static bool _DetermineDomainProperties_Loaded = false;
private static object _DetermineDomainProperties_Lock = new object(); private static object _DetermineDomainProperties_Lock = new object();
internal static string DefaultDomainName internal static string DefaultDomainName
{ {
get get
{ {
ActiveDirectoryHelpers.DetermineDomainProperties(); ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainName; return ActiveDirectoryHelpers._DefaultDomainName;
} }
} }
internal static string DefaultDomainPDCName internal static string DefaultDomainPDCName
{ {
get get
{ {
ActiveDirectoryHelpers.DetermineDomainProperties(); ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainPDCName; return ActiveDirectoryHelpers._DefaultDomainPDCName;
} }
} }
internal static System.Collections.Generic.List<string> DefaultDomainDCNames internal static System.Collections.Generic.List<string> DefaultDomainDCNames
{ {
get get
{ {
ActiveDirectoryHelpers.DetermineDomainProperties(); ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainDCNames; return ActiveDirectoryHelpers._DefaultDomainDCNames;
} }
} }
internal static string DefaultDomainNetBiosName internal static string DefaultDomainNetBiosName
{ {
get get
{ {
ActiveDirectoryHelpers.DetermineDomainProperties(); ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainNetBiosName; return ActiveDirectoryHelpers._DefaultDomainNetBiosName;
} }
} }
internal static string DefaultDomainQualifiedName internal static string DefaultDomainQualifiedName
{ {
get get
{ {
ActiveDirectoryHelpers.DetermineDomainProperties(); ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultDomainQualifiedName; return ActiveDirectoryHelpers._DefaultDomainQualifiedName;
} }
} }
internal static string DefaultLdapPath internal static string DefaultLdapPath
{ {
get get
{ {
ActiveDirectoryHelpers.DetermineDomainProperties(); ActiveDirectoryHelpers.DetermineDomainProperties();
return ActiveDirectoryHelpers._DefaultLdapPath; return ActiveDirectoryHelpers._DefaultLdapPath;
} }
} }
internal static string DefaultDCLdapPath(string DC) internal static string DefaultDCLdapPath(string DC)
{ {
return string.Format("LDAP://{0}/", DC); return string.Format("LDAP://{0}/", DC);
} }
internal static DirectoryEntry DefaultLdapRoot internal static DirectoryEntry DefaultLdapRoot
{ {
get get
{ {
return new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, ActiveDirectoryHelpers.DefaultDomainQualifiedName)); return new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultLdapPath, ActiveDirectoryHelpers.DefaultDomainQualifiedName));
} }
} }
internal static DirectoryEntry DefaultDCLdapRoot(string DC) internal static DirectoryEntry DefaultDCLdapRoot(string DC)
{ {
return new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultDCLdapPath(DC), ActiveDirectoryHelpers.DefaultDomainQualifiedName)); return new DirectoryEntry(string.Concat(ActiveDirectoryHelpers.DefaultDCLdapPath(DC), ActiveDirectoryHelpers.DefaultDomainQualifiedName));
} }
private static void DetermineDomainProperties() private static void DetermineDomainProperties()
{ {
if (!ActiveDirectoryHelpers._DetermineDomainProperties_Loaded) if (!ActiveDirectoryHelpers._DetermineDomainProperties_Loaded)
{ {
lock (ActiveDirectoryHelpers._DetermineDomainProperties_Lock) lock (ActiveDirectoryHelpers._DetermineDomainProperties_Lock)
{ {
if (!ActiveDirectoryHelpers._DetermineDomainProperties_Loaded) if (!ActiveDirectoryHelpers._DetermineDomainProperties_Loaded)
{ {
using (Domain domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain))) using (Domain domain = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain)))
{ {
ActiveDirectoryHelpers._DefaultDomainName = domain.Name; ActiveDirectoryHelpers._DefaultDomainName = domain.Name;
ActiveDirectoryHelpers._DefaultDomainPDCName = domain.PdcRoleOwner.Name; ActiveDirectoryHelpers._DefaultDomainPDCName = domain.PdcRoleOwner.Name;
ActiveDirectoryHelpers._DefaultDomainDCNames = new System.Collections.Generic.List<string>(domain.DomainControllers.Count); ActiveDirectoryHelpers._DefaultDomainDCNames = new System.Collections.Generic.List<string>(domain.DomainControllers.Count);
foreach (DomainController dc in domain.DomainControllers) foreach (DomainController dc in domain.DomainControllers)
{ {
ActiveDirectoryHelpers._DefaultDomainDCNames.Add(dc.Name); ActiveDirectoryHelpers._DefaultDomainDCNames.Add(dc.Name);
} }
} }
ActiveDirectoryHelpers._DefaultDomainQualifiedName = string.Format("DC={0}", ActiveDirectoryHelpers._DefaultDomainName.Replace(".", ",DC=")); ActiveDirectoryHelpers._DefaultDomainQualifiedName = string.Format("DC={0}", ActiveDirectoryHelpers._DefaultDomainName.Replace(".", ",DC="));
ActiveDirectoryHelpers._DefaultLdapPath = string.Format("LDAP://{0}/", ActiveDirectoryHelpers._DefaultDomainPDCName); ActiveDirectoryHelpers._DefaultLdapPath = string.Format("LDAP://{0}/", ActiveDirectoryHelpers._DefaultDomainPDCName);
using (DirectoryEntry entry = new DirectoryEntry(string.Format("{0}CN=Partitions,CN=Configuration,{1}", ActiveDirectoryHelpers._DefaultLdapPath, ActiveDirectoryHelpers._DefaultDomainQualifiedName))) using (DirectoryEntry entry = new DirectoryEntry(string.Format("{0}CN=Partitions,CN=Configuration,{1}", ActiveDirectoryHelpers._DefaultLdapPath, ActiveDirectoryHelpers._DefaultDomainQualifiedName)))
{ {
using (DirectorySearcher searcher = new DirectorySearcher(entry, "(&(objectClass=crossRef)(nETBIOSName=*))", new string[] { "nETBIOSName" })) using (DirectorySearcher searcher = new DirectorySearcher(entry, "(&(objectClass=crossRef)(nETBIOSName=*))", new string[] { "nETBIOSName" }))
{ {
SearchResult result = searcher.FindOne(); SearchResult result = searcher.FindOne();
if (result != null) if (result != null)
{ {
ActiveDirectoryHelpers._DefaultDomainNetBiosName = result.Properties["nETBIOSName"][0].ToString(); ActiveDirectoryHelpers._DefaultDomainNetBiosName = result.Properties["nETBIOSName"][0].ToString();
} }
else else
{ {
ActiveDirectoryHelpers._DefaultDomainNetBiosName = ActiveDirectoryHelpers._DefaultDomainQualifiedName; ActiveDirectoryHelpers._DefaultDomainNetBiosName = ActiveDirectoryHelpers._DefaultDomainQualifiedName;
} }
} }
} }
} }
ActiveDirectoryHelpers._DetermineDomainProperties_Loaded = true; ActiveDirectoryHelpers._DetermineDomainProperties_Loaded = true;
} }
} }
} }
#endregion #endregion
[System.Runtime.InteropServices.DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] [System.Runtime.InteropServices.DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool ConvertSidToStringSid(byte[] pSID, ref System.Text.StringBuilder ptrSid); private static extern bool ConvertSidToStringSid(byte[] pSID, ref System.Text.StringBuilder ptrSid);
internal static string ConvertBytesToSIDString(byte[] SID) internal static string ConvertBytesToSIDString(byte[] SID)
{ {
System.Text.StringBuilder sidString = new System.Text.StringBuilder(); System.Text.StringBuilder sidString = new System.Text.StringBuilder();
bool flag = ActiveDirectoryHelpers.ConvertSidToStringSid(SID, ref sidString); bool flag = ActiveDirectoryHelpers.ConvertSidToStringSid(SID, ref sidString);
string ConvertBytesToSIDString; string ConvertBytesToSIDString;
if (flag) if (flag)
{ {
ConvertBytesToSIDString = sidString.ToString(); ConvertBytesToSIDString = sidString.ToString();
} }
else else
{ {
ConvertBytesToSIDString = null; ConvertBytesToSIDString = null;
} }
return ConvertBytesToSIDString; return ConvertBytesToSIDString;
} }
internal static string EscapeLdapQuery(string query) internal static string EscapeLdapQuery(string query)
{ {
return query.Replace("*", "\\2a").Replace("(", "\\28").Replace(")", "\\29").Replace("\\", "\\5c").Replace("NUL", "\\00").Replace("/", "\\2f"); return query.Replace("*", "\\2a").Replace("(", "\\28").Replace(")", "\\29").Replace("\\", "\\5c").Replace("NUL", "\\00").Replace("/", "\\2f");
} }
internal static string FormatGuidForLdapQuery(System.Guid g) internal static string FormatGuidForLdapQuery(System.Guid g)
{ {
checked checked
{ {
System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.Text.StringBuilder sb = new System.Text.StringBuilder();
byte[] array = g.ToByteArray(); byte[] array = g.ToByteArray();
for (int i = 0; i < array.Length; i++) for (int i = 0; i < array.Length; i++)
{ {
byte b = array[i]; byte b = array[i];
sb.Append("\\"); sb.Append("\\");
sb.Append(b.ToString("X2")); sb.Append(b.ToString("X2"));
} }
return sb.ToString(); return sb.ToString();
} }
} }
} }
} }
@@ -1,296 +1,296 @@
using Disco.Models.Interop.ActiveDirectory; using Disco.Models.Interop.ActiveDirectory;
using Disco.Models.Repository; using Disco.Models.Repository;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.DirectoryServices; using System.DirectoryServices;
using System.Text; using System.Text;
using System.Net.NetworkInformation; using System.Net.NetworkInformation;
using System.Management; using System.Management;
namespace Disco.BI.Interop.ActiveDirectory namespace Disco.BI.Interop.ActiveDirectory
{ {
public static class ActiveDirectoryMachineAccountExtensions public static class ActiveDirectoryMachineAccountExtensions
{ {
public static void DeleteAccount(this ActiveDirectoryMachineAccount account) public static void DeleteAccount(this ActiveDirectoryMachineAccount account)
{ {
if (account.IsCriticalSystemObject) if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName)); throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path)) using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{ {
DeleteAccountRecursive(machineDE); DeleteAccountRecursive(machineDE);
using (var machineDEParent = machineDE.Parent) using (var machineDEParent = machineDE.Parent)
{ {
machineDEParent.Children.Remove(machineDE); machineDEParent.Children.Remove(machineDE);
} }
} }
} }
private static void DeleteAccountRecursive(DirectoryEntry parent) private static void DeleteAccountRecursive(DirectoryEntry parent)
{ {
List<DirectoryEntry> children = new List<DirectoryEntry>(); List<DirectoryEntry> children = new List<DirectoryEntry>();
foreach (DirectoryEntry child in parent.Children) foreach (DirectoryEntry child in parent.Children)
children.Add(child); children.Add(child);
foreach (var child in children) foreach (var child in children)
{ {
DeleteAccountRecursive(child); DeleteAccountRecursive(child);
parent.Children.Remove(child); parent.Children.Remove(child);
child.Dispose(); child.Dispose();
} }
} }
private static void SetNetbootGUID(this ActiveDirectoryMachineAccount account, System.Guid updatedNetbootGUID) private static void SetNetbootGUID(this ActiveDirectoryMachineAccount account, System.Guid updatedNetbootGUID)
{ {
if (account.IsCriticalSystemObject) if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName)); throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path)) using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{ {
PropertyValueCollection netbootGUIDProp = machineDE.Properties["netbootGUID"]; PropertyValueCollection netbootGUIDProp = machineDE.Properties["netbootGUID"];
bool flag = netbootGUIDProp.Count > 0; bool flag = netbootGUIDProp.Count > 0;
if (flag) if (flag)
{ {
netbootGUIDProp.Clear(); netbootGUIDProp.Clear();
} }
netbootGUIDProp.Add(updatedNetbootGUID.ToByteArray()); netbootGUIDProp.Add(updatedNetbootGUID.ToByteArray());
machineDE.CommitChanges(); machineDE.CommitChanges();
} }
} }
public static void SetDescription(this ActiveDirectoryMachineAccount account, string Description) public static void SetDescription(this ActiveDirectoryMachineAccount account, string Description)
{ {
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path)) using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{ {
PropertyValueCollection descriptionProp = machineDE.Properties["description"]; PropertyValueCollection descriptionProp = machineDE.Properties["description"];
bool flag = descriptionProp.Count > 0; bool flag = descriptionProp.Count > 0;
if (flag) if (flag)
{ {
descriptionProp.Clear(); descriptionProp.Clear();
} }
flag = !string.IsNullOrEmpty(Description); flag = !string.IsNullOrEmpty(Description);
if (flag) if (flag)
{ {
descriptionProp.Add(Description); descriptionProp.Add(Description);
} }
machineDE.CommitChanges(); machineDE.CommitChanges();
} }
} }
public static void SetDescription(this ActiveDirectoryMachineAccount account, Device Device) public static void SetDescription(this ActiveDirectoryMachineAccount account, Device Device)
{ {
System.Text.StringBuilder descriptionBuilder = new System.Text.StringBuilder(); System.Text.StringBuilder descriptionBuilder = new System.Text.StringBuilder();
bool flag = Device.AssignedUserId != null; bool flag = Device.AssignedUserId != null;
if (flag) if (flag)
{ {
descriptionBuilder.Append(Device.AssignedUser.Id); descriptionBuilder.Append(Device.AssignedUser.Id);
descriptionBuilder.Append(" ("); descriptionBuilder.Append(" (");
descriptionBuilder.Append(Device.AssignedUser.DisplayName); descriptionBuilder.Append(Device.AssignedUser.DisplayName);
descriptionBuilder.Append("); "); descriptionBuilder.Append("); ");
} }
flag = Device.DeviceModelId.HasValue; flag = Device.DeviceModelId.HasValue;
if (flag) if (flag)
{ {
descriptionBuilder.Append(Device.DeviceModel.Description); descriptionBuilder.Append(Device.DeviceModel.Description);
descriptionBuilder.Append("; "); descriptionBuilder.Append("; ");
} }
descriptionBuilder.Append(Device.DeviceProfile.Description); descriptionBuilder.Append(Device.DeviceProfile.Description);
descriptionBuilder.Append("; "); descriptionBuilder.Append("; ");
string description = descriptionBuilder.ToString().Trim(); string description = descriptionBuilder.ToString().Trim();
flag = (description.Length > 1024); flag = (description.Length > 1024);
if (flag) if (flag)
{ {
description = description.Substring(0, 1024); description = description.Substring(0, 1024);
} }
account.SetDescription(description); account.SetDescription(description);
} }
public static void DisableAccount(this ActiveDirectoryMachineAccount account) public static void DisableAccount(this ActiveDirectoryMachineAccount account)
{ {
if (account.IsCriticalSystemObject) if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName)); throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path)) using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{ {
int accountControl = (int)machineDE.Properties["userAccountControl"][0]; int accountControl = (int)machineDE.Properties["userAccountControl"][0];
int updatedAccountControl = (accountControl | 2); int updatedAccountControl = (accountControl | 2);
if (accountControl != updatedAccountControl) if (accountControl != updatedAccountControl)
{ {
machineDE.Properties["userAccountControl"][0] = updatedAccountControl; machineDE.Properties["userAccountControl"][0] = updatedAccountControl;
machineDE.CommitChanges(); machineDE.CommitChanges();
} }
} }
} }
public static void EnableAccount(this ActiveDirectoryMachineAccount account) public static void EnableAccount(this ActiveDirectoryMachineAccount account)
{ {
if (account.IsCriticalSystemObject) if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName)); throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
using (DirectoryEntry machineDE = new DirectoryEntry(account.Path)) using (DirectoryEntry machineDE = new DirectoryEntry(account.Path))
{ {
int accountControl = (int)machineDE.Properties["userAccountControl"][0]; int accountControl = (int)machineDE.Properties["userAccountControl"][0];
if ((accountControl & 2) == 2) if ((accountControl & 2) == 2)
{ {
int updatedAccountControl = (accountControl ^ 2); int updatedAccountControl = (accountControl ^ 2);
machineDE.Properties["userAccountControl"][0] = updatedAccountControl; machineDE.Properties["userAccountControl"][0] = updatedAccountControl;
machineDE.CommitChanges(); machineDE.CommitChanges();
} }
} }
} }
public static bool UpdateNetbootGUID(this ActiveDirectoryMachineAccount account, string UUID, string MACAddress) public static bool UpdateNetbootGUID(this ActiveDirectoryMachineAccount account, string UUID, string MACAddress)
{ {
if (account.IsCriticalSystemObject) if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName)); throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
System.Guid netbootGUID = System.Guid.Empty; System.Guid netbootGUID = System.Guid.Empty;
bool flag = !string.IsNullOrWhiteSpace(UUID); bool flag = !string.IsNullOrWhiteSpace(UUID);
if (flag) if (flag)
{ {
netbootGUID = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromUUID(UUID); netbootGUID = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromUUID(UUID);
} }
else else
{ {
flag = !string.IsNullOrWhiteSpace(MACAddress); flag = !string.IsNullOrWhiteSpace(MACAddress);
if (flag) if (flag)
{ {
netbootGUID = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromMACAddress(MACAddress); netbootGUID = ActiveDirectoryMachineAccountExtensions.NetbootGUIDFromMACAddress(MACAddress);
} }
} }
flag = (netbootGUID != System.Guid.Empty && netbootGUID != account.NetbootGUID); flag = (netbootGUID != System.Guid.Empty && netbootGUID != account.NetbootGUID);
bool UpdateNetbootGUID; bool UpdateNetbootGUID;
if (flag) if (flag)
{ {
account.SetNetbootGUID(netbootGUID); account.SetNetbootGUID(netbootGUID);
UpdateNetbootGUID = true; UpdateNetbootGUID = true;
} }
else else
{ {
UpdateNetbootGUID = false; UpdateNetbootGUID = false;
} }
return UpdateNetbootGUID; return UpdateNetbootGUID;
} }
internal static System.Guid NetbootGUIDFromMACAddress(string MACAddress) internal static System.Guid NetbootGUIDFromMACAddress(string MACAddress)
{ {
string strippedMACAddress = MACAddress.Trim().Replace(":", string.Empty).Replace("-", string.Empty); string strippedMACAddress = MACAddress.Trim().Replace(":", string.Empty).Replace("-", string.Empty);
bool flag = strippedMACAddress.Length == 12; bool flag = strippedMACAddress.Length == 12;
System.Guid NetbootGUIDFromMACAddress; System.Guid NetbootGUIDFromMACAddress;
if (flag) if (flag)
{ {
System.Guid guid = new System.Guid(string.Format("00000000-0000-0000-0000-{0}", strippedMACAddress)); System.Guid guid = new System.Guid(string.Format("00000000-0000-0000-0000-{0}", strippedMACAddress));
NetbootGUIDFromMACAddress = guid; NetbootGUIDFromMACAddress = guid;
} }
else else
{ {
NetbootGUIDFromMACAddress = System.Guid.Empty; NetbootGUIDFromMACAddress = System.Guid.Empty;
} }
return NetbootGUIDFromMACAddress; return NetbootGUIDFromMACAddress;
} }
internal static System.Guid NetbootGUIDFromUUID(string UUID) internal static System.Guid NetbootGUIDFromUUID(string UUID)
{ {
System.Guid result = new System.Guid(UUID); System.Guid result = new System.Guid(UUID);
return result; return result;
} }
public static object GetPropertyValue(this ActiveDirectoryMachineAccount account, string PropertyName, int Index = 0) public static object GetPropertyValue(this ActiveDirectoryMachineAccount account, string PropertyName, int Index = 0)
{ {
switch (PropertyName.ToLower()) switch (PropertyName.ToLower())
{ {
case "name": case "name":
return account.Name; return account.Name;
case "samaccountname": case "samaccountname":
return account.sAMAccountName; return account.sAMAccountName;
case "distinguishedname": case "distinguishedname":
return account.DistinguishedName; return account.DistinguishedName;
case "objectsid": case "objectsid":
return account.ObjectSid; return account.ObjectSid;
case "netbootguid": case "netbootguid":
return account.NetbootGUID; return account.NetbootGUID;
default: default:
object[] adProperty; object[] adProperty;
if (account.LoadedProperties.TryGetValue(PropertyName, out adProperty) && Index <= adProperty.Length) if (account.LoadedProperties.TryGetValue(PropertyName, out adProperty) && Index <= adProperty.Length)
return adProperty[Index]; return adProperty[Index];
else else
return null; return null;
} }
} }
public static IPStatus PingComputer(this ActiveDirectoryMachineAccount account, int Timeout = 2000) public static IPStatus PingComputer(this ActiveDirectoryMachineAccount account, int Timeout = 2000)
{ {
using (var p = new Ping()) using (var p = new Ping())
{ {
PingReply reply = p.Send(account.DnsName, Timeout); PingReply reply = p.Send(account.DnsName, Timeout);
return reply.Status; return reply.Status;
} }
} }
// Didn't Work - WMI Limitation? // Didn't Work - WMI Limitation?
// G# - 2012-06-18 // G# - 2012-06-18
//public static void OnlineRenameComputer(this ActiveDirectoryMachineAccount account, string NewComputerName) //public static void OnlineRenameComputer(this ActiveDirectoryMachineAccount account, string NewComputerName)
//{ //{
// if (account.IsCriticalSystemObject) // if (account.IsCriticalSystemObject)
// throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName)); // throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
// try // try
// { // {
// IPStatus pingResult = account.PingComputer(); // IPStatus pingResult = account.PingComputer();
// if (pingResult != IPStatus.Success) // if (pingResult != IPStatus.Success)
// throw new Exception(string.Format("Ping Error Result: {0}", pingResult.ToString())); // throw new Exception(string.Format("Ping Error Result: {0}", pingResult.ToString()));
// } // }
// catch (Exception ex) // catch (Exception ex)
// { // {
// throw new Exception(string.Format("Error trying to Ping the Device: {0}; {1}", account.DnsName, ex.Message), ex); // throw new Exception(string.Format("Error trying to Ping the Device: {0}; {1}", account.DnsName, ex.Message), ex);
// } // }
// ConnectionOptions wmiConnectionOptions = new ConnectionOptions() // ConnectionOptions wmiConnectionOptions = new ConnectionOptions()
// { // {
// Authentication = AuthenticationLevel.PacketPrivacy, // Authentication = AuthenticationLevel.PacketPrivacy,
// Impersonation = ImpersonationLevel.Impersonate, // Impersonation = ImpersonationLevel.Impersonate,
// EnablePrivileges = true, // EnablePrivileges = true,
// Timeout = new TimeSpan(0, 0, 6) // Timeout = new TimeSpan(0, 0, 6)
// }; // };
// ManagementPath wmiPath = new ManagementPath() // ManagementPath wmiPath = new ManagementPath()
// { // {
// Server = account.DnsName, // Server = account.DnsName,
// NamespacePath = @"root\cimv2", // NamespacePath = @"root\cimv2",
// ClassName = "Win32_ComputerSystem" // ClassName = "Win32_ComputerSystem"
// }; // };
// ManagementScope wmiScope = new ManagementScope(wmiPath, wmiConnectionOptions); // ManagementScope wmiScope = new ManagementScope(wmiPath, wmiConnectionOptions);
// ObjectGetOptions wmiGetOptions = new ObjectGetOptions() { Timeout = new TimeSpan(0, 1, 0) }; // ObjectGetOptions wmiGetOptions = new ObjectGetOptions() { Timeout = new TimeSpan(0, 1, 0) };
// using (ManagementClass wmiClass = new ManagementClass(wmiScope, wmiPath, wmiGetOptions)) // using (ManagementClass wmiClass = new ManagementClass(wmiScope, wmiPath, wmiGetOptions))
// { // {
// foreach (ManagementObject wmiWin32ComputerSystem in wmiClass.GetInstances()) // foreach (ManagementObject wmiWin32ComputerSystem in wmiClass.GetInstances())
// { // {
// UInt32 result = (UInt32)wmiWin32ComputerSystem.InvokeMethod("Rename", new object[] { NewComputerName }); // UInt32 result = (UInt32)wmiWin32ComputerSystem.InvokeMethod("Rename", new object[] { NewComputerName });
// if (result != 0) // if (result != 0)
// throw new Exception(string.Format("Error Renaming Computer; WMI Remote Method 'Rename' returned: {0}", result)); // throw new Exception(string.Format("Error Renaming Computer; WMI Remote Method 'Rename' returned: {0}", result));
// } // }
// } // }
//} //}
public static void MoveOrganisationUnit(this ActiveDirectoryMachineAccount account, string NewOrganisationUnit) public static void MoveOrganisationUnit(this ActiveDirectoryMachineAccount account, string NewOrganisationUnit)
{ {
if (account.IsCriticalSystemObject) if (account.IsCriticalSystemObject)
throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName)); throw new InvalidOperationException(string.Format("This account {0} is a Critical System Active Directory Object and Disco refuses to modify it", account.DistinguishedName));
if (!account.ParentDistinguishedName.Equals(NewOrganisationUnit, StringComparison.InvariantCultureIgnoreCase)) if (!account.ParentDistinguishedName.Equals(NewOrganisationUnit, StringComparison.InvariantCultureIgnoreCase))
{ {
string ouPath; string ouPath;
if (string.IsNullOrWhiteSpace(NewOrganisationUnit)) if (string.IsNullOrWhiteSpace(NewOrganisationUnit))
ouPath = string.Format("{0}CN=Computers,{1}", ActiveDirectoryHelpers.DefaultLdapPath, ActiveDirectoryHelpers.DefaultDomainQualifiedName); ouPath = string.Format("{0}CN=Computers,{1}", ActiveDirectoryHelpers.DefaultLdapPath, ActiveDirectoryHelpers.DefaultDomainQualifiedName);
else else
ouPath = string.Format("{0}{1},{2}", ActiveDirectoryHelpers.DefaultLdapPath, NewOrganisationUnit, ActiveDirectoryHelpers.DefaultDomainQualifiedName); ouPath = string.Format("{0}{1},{2}", ActiveDirectoryHelpers.DefaultLdapPath, NewOrganisationUnit, ActiveDirectoryHelpers.DefaultDomainQualifiedName);
using (DirectoryEntry ou = new DirectoryEntry(ouPath)) using (DirectoryEntry ou = new DirectoryEntry(ouPath))
{ {
using (DirectoryEntry i = new DirectoryEntry(account.Path) { UsePropertyCache = false }) using (DirectoryEntry i = new DirectoryEntry(account.Path) { UsePropertyCache = false })
{ {
i.MoveTo(ou); i.MoveTo(ou);
} }
} }
} }
} }
} }
} }
@@ -1,14 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
namespace Disco.BI.Interop.ActiveDirectory namespace Disco.BI.Interop.ActiveDirectory
{ {
public class ActiveDirectoryOrganisationalUnit public class ActiveDirectoryOrganisationalUnit
{ {
public string Name { get; set; } public string Name { get; set; }
public string Path { get; set; } public string Path { get; set; }
public List<ActiveDirectoryOrganisationalUnit> Children { get; set; } public List<ActiveDirectoryOrganisationalUnit> Children { get; set; }
} }
} }
@@ -1,42 +1,42 @@
using Disco.Models.Interop.ActiveDirectory; using Disco.Models.Interop.ActiveDirectory;
using System; using System;
using Disco.Models.Repository; using Disco.Models.Repository;
namespace Disco.BI.Interop.ActiveDirectory namespace Disco.BI.Interop.ActiveDirectory
{ {
internal static class ActiveDirectoryUserAccountExtensions internal static class ActiveDirectoryUserAccountExtensions
{ {
public static bool HasRole(this ActiveDirectoryUserAccount account, string Role) public static bool HasRole(this ActiveDirectoryUserAccount account, string Role)
{ {
return account.Groups != null && account.Groups.Contains(Role.ToLower()); return account.Groups != null && account.Groups.Contains(Role.ToLower());
} }
public static object GetPropertyValue(this ActiveDirectoryUserAccount account, string PropertyName, int Index = 0) public static object GetPropertyValue(this ActiveDirectoryUserAccount account, string PropertyName, int Index = 0)
{ {
switch (PropertyName.ToLower()) switch (PropertyName.ToLower())
{ {
case "name": case "name":
return account.Name; return account.Name;
case "samaccountname": case "samaccountname":
return account.sAMAccountName; return account.sAMAccountName;
case "distinguishedname": case "distinguishedname":
return account.DistinguishedName; return account.DistinguishedName;
case "objectsid": case "objectsid":
return account.ObjectSid; return account.ObjectSid;
case "sn": case "sn":
return account.Surname; return account.Surname;
case "givenname": case "givenname":
return account.GivenName; return account.GivenName;
case "mail": case "mail":
return account.Email; return account.Email;
case "telephonenumber": case "telephonenumber":
return account.Phone; return account.Phone;
default: default:
object[] adProperty; object[] adProperty;
if (account.LoadedProperties.TryGetValue(PropertyName, out adProperty) && Index <= adProperty.Length) if (account.LoadedProperties.TryGetValue(PropertyName, out adProperty) && Index <= adProperty.Length)
return adProperty[Index]; return adProperty[Index];
else else
return null; return null;
} }
} }
} }
} }
+85 -85
View File
@@ -1,85 +1,85 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Microsoft.Win32; using Microsoft.Win32;
namespace Disco.BI.Interop namespace Disco.BI.Interop
{ {
public static class MimeTypes public static class MimeTypes
{ {
public static string ResolveMimeType(string Filename) public static string ResolveMimeType(string Filename)
{ {
string fileExtension; string fileExtension;
if (Filename.Contains(".")) if (Filename.Contains("."))
fileExtension = Filename.Substring(Filename.LastIndexOf(".") + 1).ToLower(); fileExtension = Filename.Substring(Filename.LastIndexOf(".") + 1).ToLower();
else else
fileExtension = Filename.ToLower(); fileExtension = Filename.ToLower();
// Try Known Mime Types // Try Known Mime Types
switch (fileExtension) switch (fileExtension)
{ {
case "pdf": case "pdf":
return "application/pdf"; return "application/pdf";
case "doc": case "doc":
return "application/msword"; return "application/msword";
case "docx": case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "docm": case "docm":
return "application/vnd.ms-word.document.macroEnabled.12"; return "application/vnd.ms-word.document.macroEnabled.12";
case "xml": case "xml":
return "text/xml"; return "text/xml";
case "xls": case "xls":
return "application/vnd.ms-excel"; return "application/vnd.ms-excel";
case "xlsx": case "xlsx":
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
case "xlsm": case "xlsm":
return "application/vnd.ms-excel.sheet.macroEnabled.12"; return "application/vnd.ms-excel.sheet.macroEnabled.12";
case "csv": case "csv":
return "application/vnd.ms-excel"; return "application/vnd.ms-excel";
case "jpg": case "jpg":
return "image/jpeg"; return "image/jpeg";
case "gif": case "gif":
return "image/gif"; return "image/gif";
case "png": case "png":
return "image/png"; return "image/png";
case "bmp": case "bmp":
return "image/bmp"; return "image/bmp";
case "avi": case "avi":
return "video/avi"; return "video/avi";
case "mpeg": case "mpeg":
case "mpg": case "mpg":
return "video/mpeg"; return "video/mpeg";
case "mp3": case "mp3":
return "audio/mpeg"; return "audio/mpeg";
case "mp4": case "mp4":
return "video/mp4"; return "video/mp4";
case "wmv": case "wmv":
return "video/x-ms-wmv"; return "video/x-ms-wmv";
case "mov": case "mov":
return "video/quicktime"; return "video/quicktime";
} }
// Check System Registry // Check System Registry
try try
{ {
RegistryKey regExtensionKey = Registry.ClassesRoot.OpenSubKey("." + fileExtension); RegistryKey regExtensionKey = Registry.ClassesRoot.OpenSubKey("." + fileExtension);
if (regExtensionKey != null) if (regExtensionKey != null)
{ {
string regExtensionContentType = regExtensionKey.GetValue("Content Type") as string; string regExtensionContentType = regExtensionKey.GetValue("Content Type") as string;
if (regExtensionContentType != null) if (regExtensionContentType != null)
{ {
return regExtensionContentType; return regExtensionContentType;
} }
} }
} }
catch catch
{ {
// Ignore Errors // Ignore Errors
} }
// Return Default // Return Default
return "unknown/unknown"; return "unknown/unknown";
} }
} }
} }
+251 -251
View File
@@ -1,251 +1,251 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.BI.DocumentTemplates; using Disco.Models.BI.DocumentTemplates;
using System.IO; using System.IO;
using iTextSharp.text.pdf; using iTextSharp.text.pdf;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using Disco.BI.Expressions; using Disco.BI.Expressions;
using System.Collections; using System.Collections;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using Disco.Models.BI.Expressions; using Disco.Models.BI.Expressions;
namespace Disco.BI.Interop.Pdf namespace Disco.BI.Interop.Pdf
{ {
public static class PdfGenerator public static class PdfGenerator
{ {
public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects) public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params object[] DataObjects)
{ {
if (DataObjects.Length > 0) if (DataObjects.Length > 0)
{ {
List<Stream> generatedPdfs = new List<Stream>(DataObjects.Length); List<Stream> generatedPdfs = new List<Stream>(DataObjects.Length);
using (Models.BI.DocumentTemplates.DocumentState state = Models.BI.DocumentTemplates.DocumentState.DefaultState()) using (Models.BI.DocumentTemplates.DocumentState state = Models.BI.DocumentTemplates.DocumentState.DefaultState())
{ {
foreach (object d in DataObjects) foreach (object d in DataObjects)
{ {
generatedPdfs.Add(dt.GeneratePdf(dbContext, d, CreatorUser, Timestamp, state, true)); generatedPdfs.Add(dt.GeneratePdf(dbContext, d, CreatorUser, Timestamp, state, true));
state.SequenceNumber++; state.SequenceNumber++;
state.FlushScopeCache(); state.FlushScopeCache();
} }
} }
if (generatedPdfs.Count == 1) if (generatedPdfs.Count == 1)
{ {
return generatedPdfs[0]; return generatedPdfs[0];
} }
else else
{ {
Stream bulkPdf = DocumentTemplateBI.Utilities.JoinPdfs(generatedPdfs.ToArray()); Stream bulkPdf = DocumentTemplateBI.Utilities.JoinPdfs(generatedPdfs.ToArray());
foreach (Stream singlePdf in generatedPdfs) foreach (Stream singlePdf in generatedPdfs)
singlePdf.Dispose(); singlePdf.Dispose();
return bulkPdf; return bulkPdf;
} }
} }
return null; return null;
} }
public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds) public static System.IO.Stream GenerateBulkFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, User CreatorUser, System.DateTime Timestamp, params string[] DataObjectsIds)
{ {
object[] DataObjects; object[] DataObjects;
switch (dt.Scope) switch (dt.Scope)
{ {
case DocumentTemplate.DocumentTemplateScopes.Device: case DocumentTemplate.DocumentTemplateScopes.Device:
DataObjects = dbContext.Devices.Where(d => DataObjectsIds.Contains(d.SerialNumber)).ToArray(); DataObjects = dbContext.Devices.Where(d => DataObjectsIds.Contains(d.SerialNumber)).ToArray();
break; break;
case DocumentTemplate.DocumentTemplateScopes.Job: case DocumentTemplate.DocumentTemplateScopes.Job:
int[] intDataObjectsIds = DataObjectsIds.Select(i => int.Parse(i)).ToArray(); int[] intDataObjectsIds = DataObjectsIds.Select(i => int.Parse(i)).ToArray();
DataObjects = dbContext.Jobs.Where(j => intDataObjectsIds.Contains(j.Id)).ToArray(); DataObjects = dbContext.Jobs.Where(j => intDataObjectsIds.Contains(j.Id)).ToArray();
break; break;
case DocumentTemplate.DocumentTemplateScopes.User: case DocumentTemplate.DocumentTemplateScopes.User:
DataObjects = new object[DataObjectsIds.Length]; DataObjects = new object[DataObjectsIds.Length];
for (int idIndex = 0; idIndex < DataObjectsIds.Length; idIndex++) for (int idIndex = 0; idIndex < DataObjectsIds.Length; idIndex++)
{ {
DataObjects[idIndex] = UserBI.UserCache.GetUser(DataObjectsIds[idIndex], dbContext, true); DataObjects[idIndex] = UserBI.UserCache.GetUser(DataObjectsIds[idIndex], dbContext, true);
if (DataObjects[idIndex] == null) if (DataObjects[idIndex] == null)
throw new Exception(string.Format("Unknown Username specified: {0}", DataObjectsIds[idIndex])); throw new Exception(string.Format("Unknown Username specified: {0}", DataObjectsIds[idIndex]));
} }
break; break;
default: default:
throw new InvalidOperationException("Invalid DocumentType Scope"); throw new InvalidOperationException("Invalid DocumentType Scope");
} }
return GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjects); return GenerateBulkFromTemplate(dt, dbContext, CreatorUser, Timestamp, DataObjects);
} }
public static System.IO.Stream GenerateFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false) public static System.IO.Stream GenerateFromTemplate(DocumentTemplate dt, DiscoDataContext dbContext, object Data, User CreatorUser, System.DateTime TimeStamp, DocumentState State, bool FlattenFields = false)
{ {
// Validate Data // Validate Data
switch (dt.Scope) switch (dt.Scope)
{ {
case DocumentTemplate.DocumentTemplateScopes.Device: case DocumentTemplate.DocumentTemplateScopes.Device:
if (!(Data is Device)) if (!(Data is Device))
throw new ArgumentException("This AttachmentType is configured for Devices only", "Data"); throw new ArgumentException("This AttachmentType is configured for Devices only", "Data");
break; break;
case DocumentTemplate.DocumentTemplateScopes.Job: case DocumentTemplate.DocumentTemplateScopes.Job:
if (!(Data is Job)) if (!(Data is Job))
throw new ArgumentException("This AttachmentType is configured for Jobs only", "Data"); throw new ArgumentException("This AttachmentType is configured for Jobs only", "Data");
break; break;
case DocumentTemplate.DocumentTemplateScopes.User: case DocumentTemplate.DocumentTemplateScopes.User:
if (!(Data is User)) if (!(Data is User))
throw new ArgumentException("This AttachmentType is configured for Users only", "Data"); throw new ArgumentException("This AttachmentType is configured for Users only", "Data");
break; break;
default: default:
throw new InvalidOperationException("Invalid AttachmentType Scope"); throw new InvalidOperationException("Invalid AttachmentType Scope");
} }
dbContext.Configuration.LazyLoadingEnabled = true; dbContext.Configuration.LazyLoadingEnabled = true;
// Override FlattenFields if Document Template instructs. // Override FlattenFields if Document Template instructs.
if (dt.FlattenForm) if (dt.FlattenForm)
FlattenFields = true; FlattenFields = true;
ConcurrentDictionary<string, Expression> expressionCache = dt.PdfExpressionsFromCache(dbContext); ConcurrentDictionary<string, Expression> expressionCache = dt.PdfExpressionsFromCache(dbContext);
string templateFilename = dt.RepositoryFilename(dbContext); string templateFilename = dt.RepositoryFilename(dbContext);
PdfReader pdfReader = new PdfReader(templateFilename); PdfReader pdfReader = new PdfReader(templateFilename);
MemoryStream pdfGeneratedStream = new MemoryStream(); MemoryStream pdfGeneratedStream = new MemoryStream();
PdfStamper pdfStamper = new PdfStamper(pdfReader, pdfGeneratedStream); PdfStamper pdfStamper = new PdfStamper(pdfReader, pdfGeneratedStream);
pdfStamper.FormFlattening = FlattenFields; pdfStamper.FormFlattening = FlattenFields;
pdfStamper.Writer.CloseStream = false; pdfStamper.Writer.CloseStream = false;
IDictionary expressionVariables = Expression.StandardVariables(dt, dbContext, CreatorUser, TimeStamp, State); IDictionary expressionVariables = Expression.StandardVariables(dt, dbContext, CreatorUser, TimeStamp, State);
foreach (string pdfFieldKey in pdfStamper.AcroFields.Fields.Keys) foreach (string pdfFieldKey in pdfStamper.AcroFields.Fields.Keys)
{ {
if (pdfFieldKey.Equals("DiscoAttachmentId", StringComparison.InvariantCultureIgnoreCase)) if (pdfFieldKey.Equals("DiscoAttachmentId", StringComparison.InvariantCultureIgnoreCase))
{ {
AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey]; AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey];
string fieldValue = dt.UniqueIdentifier(Data, CreatorUser.Id, TimeStamp); string fieldValue = dt.UniqueIdentifier(Data, CreatorUser.Id, TimeStamp);
if (FlattenFields) if (FlattenFields)
pdfStamper.AcroFields.SetField(pdfFieldKey, String.Empty); pdfStamper.AcroFields.SetField(pdfFieldKey, String.Empty);
else else
pdfStamper.AcroFields.SetField(pdfFieldKey, fieldValue); pdfStamper.AcroFields.SetField(pdfFieldKey, fieldValue);
IList<AcroFields.FieldPosition> pdfFieldPositions = pdfStamper.AcroFields.GetFieldPositions(pdfFieldKey); IList<AcroFields.FieldPosition> pdfFieldPositions = pdfStamper.AcroFields.GetFieldPositions(pdfFieldKey);
for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++) for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++)
{ {
AcroFields.FieldPosition pdfFieldPosition = pdfFieldPositions[pdfFieldOrdinal]; AcroFields.FieldPosition pdfFieldPosition = pdfFieldPositions[pdfFieldOrdinal];
string pdfBarcodeContent = dt.UniquePageIdentifier(Data, CreatorUser.Id, TimeStamp, pdfFieldPosition.page); string pdfBarcodeContent = dt.UniquePageIdentifier(Data, CreatorUser.Id, TimeStamp, pdfFieldPosition.page);
BarcodeQRCode pdfBarcode = new BarcodeQRCode(pdfBarcodeContent, (int)pdfFieldPosition.position.Width, (int)pdfFieldPosition.position.Height, null); BarcodeQRCode pdfBarcode = new BarcodeQRCode(pdfBarcodeContent, (int)pdfFieldPosition.position.Width, (int)pdfFieldPosition.position.Height, null);
iTextSharp.text.Image pdfBarcodeImage = pdfBarcode.GetImage(); iTextSharp.text.Image pdfBarcodeImage = pdfBarcode.GetImage();
pdfBarcodeImage.SetAbsolutePosition(pdfFieldPosition.position.Left, pdfFieldPosition.position.Bottom); pdfBarcodeImage.SetAbsolutePosition(pdfFieldPosition.position.Left, pdfFieldPosition.position.Bottom);
pdfStamper.GetOverContent(pdfFieldPosition.page).AddImage(pdfBarcodeImage); pdfStamper.GetOverContent(pdfFieldPosition.page).AddImage(pdfBarcodeImage);
} }
// Hide Fields // Hide Fields
PdfDictionary field = fields.GetValue(0); PdfDictionary field = fields.GetValue(0);
if ((PdfName)field.Get(PdfName.TYPE) == PdfName.ANNOT) if ((PdfName)field.Get(PdfName.TYPE) == PdfName.ANNOT)
{ {
field.Put(PdfName.F, new PdfNumber(6)); field.Put(PdfName.F, new PdfNumber(6));
} }
else else
{ {
PdfArray fieldKids = (PdfArray)field.Get(PdfName.KIDS); PdfArray fieldKids = (PdfArray)field.Get(PdfName.KIDS);
foreach (PdfIndirectReference fieldKidRef in fieldKids) foreach (PdfIndirectReference fieldKidRef in fieldKids)
{ {
((PdfDictionary)pdfReader.GetPdfObject(fieldKidRef.Number)).Put(PdfName.F, new PdfNumber(6)); ((PdfDictionary)pdfReader.GetPdfObject(fieldKidRef.Number)).Put(PdfName.F, new PdfNumber(6));
} }
} }
} }
else else
{ {
Expression fieldExpression = null; Expression fieldExpression = null;
if (expressionCache.TryGetValue(pdfFieldKey, out fieldExpression)) if (expressionCache.TryGetValue(pdfFieldKey, out fieldExpression))
{ {
if (fieldExpression.IsDynamic) if (fieldExpression.IsDynamic)
{ {
Tuple<string, bool, object> fieldExpressionResult = fieldExpression.Evaluate(Data, expressionVariables); Tuple<string, bool, object> fieldExpressionResult = fieldExpression.Evaluate(Data, expressionVariables);
if (fieldExpressionResult.Item3 != null) if (fieldExpressionResult.Item3 != null)
{ {
IImageExpressionResult imageResult = (fieldExpressionResult.Item3 as IImageExpressionResult); IImageExpressionResult imageResult = (fieldExpressionResult.Item3 as IImageExpressionResult);
if (imageResult != null) if (imageResult != null)
{ {
// Output Image // Output Image
AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey]; AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey];
IList<AcroFields.FieldPosition> pdfFieldPositions = pdfStamper.AcroFields.GetFieldPositions(pdfFieldKey); IList<AcroFields.FieldPosition> pdfFieldPositions = pdfStamper.AcroFields.GetFieldPositions(pdfFieldKey);
for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++) for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++)
{ {
AcroFields.FieldPosition pdfFieldPosition = pdfFieldPositions[pdfFieldOrdinal]; AcroFields.FieldPosition pdfFieldPosition = pdfFieldPositions[pdfFieldOrdinal];
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(imageResult.GetImage((int)pdfFieldPosition.position.Width, (int)pdfFieldPosition.position.Height)); iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(imageResult.GetImage((int)pdfFieldPosition.position.Width, (int)pdfFieldPosition.position.Height));
pdfImage.SetAbsolutePosition(pdfFieldPosition.position.Left, pdfFieldPosition.position.Bottom); pdfImage.SetAbsolutePosition(pdfFieldPosition.position.Left, pdfFieldPosition.position.Bottom);
pdfStamper.GetOverContent(pdfFieldPosition.page).AddImage(pdfImage); pdfStamper.GetOverContent(pdfFieldPosition.page).AddImage(pdfImage);
} }
if (!fieldExpressionResult.Item2 && !imageResult.ShowField) if (!fieldExpressionResult.Item2 && !imageResult.ShowField)
{ {
// Hide Fields // Hide Fields
PdfDictionary field = fields.GetValue(0); PdfDictionary field = fields.GetValue(0);
if ((PdfName)field.Get(PdfName.TYPE) == PdfName.ANNOT) if ((PdfName)field.Get(PdfName.TYPE) == PdfName.ANNOT)
{ {
field.Put(PdfName.F, new PdfNumber(6)); field.Put(PdfName.F, new PdfNumber(6));
} }
else else
{ {
PdfArray fieldKids = (PdfArray)field.Get(PdfName.KIDS); PdfArray fieldKids = (PdfArray)field.Get(PdfName.KIDS);
foreach (PdfIndirectReference fieldKidRef in fieldKids) foreach (PdfIndirectReference fieldKidRef in fieldKids)
{ {
((PdfDictionary)pdfReader.GetPdfObject(fieldKidRef.Number)).Put(PdfName.F, new PdfNumber(6)); ((PdfDictionary)pdfReader.GetPdfObject(fieldKidRef.Number)).Put(PdfName.F, new PdfNumber(6));
} }
} }
} }
} }
} }
pdfStamper.AcroFields.SetField(pdfFieldKey, fieldExpressionResult.Item1); pdfStamper.AcroFields.SetField(pdfFieldKey, fieldExpressionResult.Item1);
if (fieldExpressionResult.Item2) // Expression Error if (fieldExpressionResult.Item2) // Expression Error
{ {
AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey]; AcroFields.Item fields = pdfStamper.AcroFields.Fields[pdfFieldKey];
for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++) for (int pdfFieldOrdinal = 0; pdfFieldOrdinal < fields.Size; pdfFieldOrdinal++)
{ {
PdfDictionary field = fields.GetValue(pdfFieldOrdinal); PdfDictionary field = fields.GetValue(pdfFieldOrdinal);
PdfDictionary fieldMK; PdfDictionary fieldMK;
if (field.Contains(PdfName.MK)) if (field.Contains(PdfName.MK))
fieldMK = field.GetAsDict(PdfName.MK); fieldMK = field.GetAsDict(PdfName.MK);
else else
{ {
fieldMK = new PdfDictionary(PdfName.MK); fieldMK = new PdfDictionary(PdfName.MK);
field.Put(PdfName.MK, fieldMK); field.Put(PdfName.MK, fieldMK);
} }
fieldMK.Put(PdfName.BC, new PdfArray(new float[] { 1, 0, 0 })); fieldMK.Put(PdfName.BC, new PdfArray(new float[] { 1, 0, 0 }));
} }
} }
} }
} }
else else
{ {
throw new InvalidOperationException("Pdf template field expressions are out of sync with the expression cache"); throw new InvalidOperationException("Pdf template field expressions are out of sync with the expression cache");
} }
} }
State.FlushFieldCache(); State.FlushFieldCache();
} }
pdfStamper.Close(); pdfStamper.Close();
pdfReader.Close(); pdfReader.Close();
if (dt.Scope == DocumentTemplate.DocumentTemplateScopes.Job) if (dt.Scope == DocumentTemplate.DocumentTemplateScopes.Job)
{ {
// Write Job Log // Write Job Log
Job j = (Job)Data; Job j = (Job)Data;
JobLog jl = new JobLog() JobLog jl = new JobLog()
{ {
JobId = j.Id, JobId = j.Id,
TechUserId = CreatorUser.Id, TechUserId = CreatorUser.Id,
Timestamp = DateTime.Now Timestamp = DateTime.Now
}; };
jl.Comments = string.Format("Document Generated{0}{1} [{2}]", Environment.NewLine, dt.Description, dt.Id); jl.Comments = string.Format("Document Generated{0}{1} [{2}]", Environment.NewLine, dt.Description, dt.Id);
dbContext.JobLogs.Add(jl); dbContext.JobLogs.Add(jl);
} }
pdfGeneratedStream.Position = 0; pdfGeneratedStream.Position = 0;
return pdfGeneratedStream; return pdfGeneratedStream;
} }
} }
} }
+471 -471
View File
@@ -1,471 +1,471 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using iTextSharp.text.pdf; using iTextSharp.text.pdf;
using System.IO; using System.IO;
using System.Drawing; using System.Drawing;
using Disco.BI.DocumentTemplateBI.Importer; using Disco.BI.DocumentTemplateBI.Importer;
using Disco.BI.DocumentTemplateBI; using Disco.BI.DocumentTemplateBI;
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
using com.google.zxing; using com.google.zxing;
using com.google.zxing.multi.qrcode; using com.google.zxing.multi.qrcode;
using Disco.Data.Repository; using Disco.Data.Repository;
using System.Web.Caching; using System.Web.Caching;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using Disco.Models.Repository; using Disco.Models.Repository;
using System.Collections; using System.Collections;
using com.google.zxing.common; using com.google.zxing.common;
using BitMiracle.LibTiff.Classic; using BitMiracle.LibTiff.Classic;
namespace Disco.BI.Interop.Pdf namespace Disco.BI.Interop.Pdf
{ {
public static class PdfImporter public static class PdfImporter
{ {
private class DetectImageResult : IDisposable private class DetectImageResult : IDisposable
{ {
public Result Result { get; set; } public Result Result { get; set; }
public Point ResultOffset { get; set; } public Point ResultOffset { get; set; }
public double ResultScale { get; set; } public double ResultScale { get; set; }
public void Dispose() public void Dispose()
{ {
// Do Nothing; yet... // Do Nothing; yet...
} }
} }
private class DetectPageResult : IDisposable private class DetectPageResult : IDisposable
{ {
public int PageNumber { get; set; } public int PageNumber { get; set; }
public DocumentUniqueIdentifier DetectedIdentifier { get; set; } public DocumentUniqueIdentifier DetectedIdentifier { get; set; }
public Disco.BI.Extensions.UtilityExtensions.ImageMontage ThumbnailImage { get; set; } public Disco.BI.Extensions.UtilityExtensions.ImageMontage ThumbnailImage { get; set; }
public MemoryStream AttachmentThumbnailImage { get; set; } public MemoryStream AttachmentThumbnailImage { get; set; }
public Disco.BI.Extensions.UtilityExtensions.ImageMontage UndetectedPageImage { get; set; } public Disco.BI.Extensions.UtilityExtensions.ImageMontage UndetectedPageImage { get; set; }
public void DrawThumbnailImageResult(DetectImageResult Result, Image DetectedImage) public void DrawThumbnailImageResult(DetectImageResult Result, Image DetectedImage)
{ {
if (Result.Result.ResultPoints.Length == 4) if (Result.Result.ResultPoints.Length == 4)
{ // Draw Square on Thumbnail { // Draw Square on Thumbnail
using (Graphics thumbnailGraphics = Graphics.FromImage(ThumbnailImage.Montage)) using (Graphics thumbnailGraphics = Graphics.FromImage(ThumbnailImage.Montage))
{ {
var thumbnailOffset = ThumbnailImage.MontageSourceImageOffsets[DetectedImage]; var thumbnailOffset = ThumbnailImage.MontageSourceImageOffsets[DetectedImage];
var linePoints = Result.Result.ResultPoints.Select(p => new Point((int)(thumbnailOffset + ((Result.ResultOffset.X + p.X) * Result.ResultScale * ThumbnailImage.MontageScale)), (int)((p.Y + Result.ResultOffset.Y) * Result.ResultScale * ThumbnailImage.MontageScale))).ToArray(); var linePoints = Result.Result.ResultPoints.Select(p => new Point((int)(thumbnailOffset + ((Result.ResultOffset.X + p.X) * Result.ResultScale * ThumbnailImage.MontageScale)), (int)((p.Y + Result.ResultOffset.Y) * Result.ResultScale * ThumbnailImage.MontageScale))).ToArray();
using (GraphicsPath graphicsPath = new GraphicsPath()) using (GraphicsPath graphicsPath = new GraphicsPath())
{ {
for (int linePointIndex = 0; linePointIndex < (linePoints.Length - 1); linePointIndex++) for (int linePointIndex = 0; linePointIndex < (linePoints.Length - 1); linePointIndex++)
graphicsPath.AddLine(linePoints[linePointIndex], linePoints[linePointIndex + 1]); graphicsPath.AddLine(linePoints[linePointIndex], linePoints[linePointIndex + 1]);
graphicsPath.AddLine(linePoints[linePoints.Length - 1], linePoints[0]); graphicsPath.AddLine(linePoints[linePoints.Length - 1], linePoints[0]);
using (SolidBrush graphicsBrush = new SolidBrush(Color.FromArgb(128, 255, 0, 0))) using (SolidBrush graphicsBrush = new SolidBrush(Color.FromArgb(128, 255, 0, 0)))
thumbnailGraphics.FillPath(graphicsBrush, graphicsPath); thumbnailGraphics.FillPath(graphicsBrush, graphicsPath);
using (Pen graphicsPen = new Pen(Color.FromArgb(200, 255, 0, 0), 2)) using (Pen graphicsPen = new Pen(Color.FromArgb(200, 255, 0, 0), 2))
thumbnailGraphics.DrawPath(graphicsPen, graphicsPath); thumbnailGraphics.DrawPath(graphicsPen, graphicsPath);
} }
} }
} }
} }
public void Dispose() public void Dispose()
{ {
if (ThumbnailImage != null) if (ThumbnailImage != null)
{ {
ThumbnailImage.Dispose(); ThumbnailImage.Dispose();
ThumbnailImage = null; ThumbnailImage = null;
} }
if (AttachmentThumbnailImage != null) if (AttachmentThumbnailImage != null)
{ {
AttachmentThumbnailImage.Dispose(); AttachmentThumbnailImage.Dispose();
AttachmentThumbnailImage = null; AttachmentThumbnailImage = null;
} }
if (UndetectedPageImage != null) if (UndetectedPageImage != null)
{ {
UndetectedPageImage.Dispose(); UndetectedPageImage.Dispose();
UndetectedPageImage = null; UndetectedPageImage = null;
} }
} }
} }
private static DetectImageResult DetectImage(DiscoDataContext dbContext, Bitmap pageImageOriginal, string SessionId, IEnumerable<DocumentTemplate> detectDocumentTemplates) private static DetectImageResult DetectImage(DiscoDataContext dbContext, Bitmap pageImageOriginal, string SessionId, IEnumerable<DocumentTemplate> detectDocumentTemplates)
{ {
Bitmap pageImage = pageImageOriginal; Bitmap pageImage = pageImageOriginal;
double pageImageModifiedScale = 1; double pageImageModifiedScale = 1;
try try
{ {
// Resize if Resolution > 80; Set to 72 Dpi // Resize if Resolution > 80; Set to 72 Dpi
if (pageImage.HorizontalResolution > 80 || pageImage.VerticalResolution > 80) if (pageImage.HorizontalResolution > 80 || pageImage.VerticalResolution > 80)
{ {
pageImageModifiedScale = pageImage.HorizontalResolution / 72; pageImageModifiedScale = pageImage.HorizontalResolution / 72;
int newWidth = (int)((72 / pageImage.HorizontalResolution) * pageImage.Width); int newWidth = (int)((72 / pageImage.HorizontalResolution) * pageImage.Width);
int newHeight = (int)((72 / pageImage.VerticalResolution) * pageImage.Height); int newHeight = (int)((72 / pageImage.VerticalResolution) * pageImage.Height);
pageImage = pageImage.ResizeImage(newWidth, newHeight); pageImage = pageImage.ResizeImage(newWidth, newHeight);
} }
Result zxingResult = default(Result); Result zxingResult = default(Result);
Point zxingResultOffset = Point.Empty; Point zxingResultOffset = Point.Empty;
QRCodeMultiReader zxingMfr = new QRCodeMultiReader(); QRCodeMultiReader zxingMfr = new QRCodeMultiReader();
Hashtable zxingMfrHints = new Hashtable(); Hashtable zxingMfrHints = new Hashtable();
zxingMfrHints.Add(DecodeHintType.TRY_HARDER, true); zxingMfrHints.Add(DecodeHintType.TRY_HARDER, true);
// Look in 'Known' locations // Look in 'Known' locations
foreach (DocumentTemplate dt in detectDocumentTemplates) foreach (DocumentTemplate dt in detectDocumentTemplates)
{ {
var locationBag = dt.QRCodeLocations(dbContext); var locationBag = dt.QRCodeLocations(dbContext);
foreach (var location in locationBag) foreach (var location in locationBag)
{ {
System.Drawing.Rectangle region = new Rectangle( System.Drawing.Rectangle region = new Rectangle(
(int)(pageImage.Width * location.Left), (int)(pageImage.Width * location.Left),
(int)(pageImage.Width * location.Top), (int)(pageImage.Width * location.Top),
(int)(pageImage.Width * location.Width), (int)(pageImage.Width * location.Width),
(int)(pageImage.Height * location.Height)); (int)(pageImage.Height * location.Height));
RGBLuminanceSource zxingSource; RGBLuminanceSource zxingSource;
using (Bitmap pageImageRegion = new Bitmap(region.Width, region.Height)) using (Bitmap pageImageRegion = new Bitmap(region.Width, region.Height))
{ {
using (Graphics pageImageRegionGraphics = Graphics.FromImage(pageImageRegion)) using (Graphics pageImageRegionGraphics = Graphics.FromImage(pageImageRegion))
{ {
pageImageRegionGraphics.DrawImage(pageImage, 0, 0, region, GraphicsUnit.Pixel); pageImageRegionGraphics.DrawImage(pageImage, 0, 0, region, GraphicsUnit.Pixel);
} }
zxingSource = new RGBLuminanceSource(pageImageRegion, region.Width, region.Height); zxingSource = new RGBLuminanceSource(pageImageRegion, region.Width, region.Height);
} }
var zxingHB = new HybridBinarizer(zxingSource); var zxingHB = new HybridBinarizer(zxingSource);
var zxingBB = new BinaryBitmap(zxingHB); var zxingBB = new BinaryBitmap(zxingHB);
try try
{ {
zxingResult = zxingMfr.decode(zxingBB, zxingMfrHints); zxingResult = zxingMfr.decode(zxingBB, zxingMfrHints);
zxingResultOffset = region.Location; zxingResultOffset = region.Location;
break; break;
} }
catch (ReaderException) catch (ReaderException)
{ {
// Ignore Location Errors // Ignore Location Errors
} }
} }
if (zxingResult != null) if (zxingResult != null)
break; break;
} }
if (zxingResult == null) if (zxingResult == null)
{ {
// Not found with 'known' locations // Not found with 'known' locations
// Try whole image // Try whole image
var zxingSource = new RGBLuminanceSource(pageImage, pageImage.Width, pageImage.Height); var zxingSource = new RGBLuminanceSource(pageImage, pageImage.Width, pageImage.Height);
var zxingHB = new HybridBinarizer(zxingSource); var zxingHB = new HybridBinarizer(zxingSource);
var zxingBB = new BinaryBitmap(zxingHB); var zxingBB = new BinaryBitmap(zxingHB);
try try
{ {
zxingResult = zxingMfr.decode(zxingBB, zxingMfrHints); zxingResult = zxingMfr.decode(zxingBB, zxingMfrHints);
} }
catch (ReaderException) catch (ReaderException)
{ {
// Ignore Errors // Ignore Errors
} }
} }
if (zxingResult != null) if (zxingResult != null)
return new DetectImageResult() { Result = zxingResult, ResultOffset = zxingResultOffset, ResultScale = pageImageModifiedScale }; return new DetectImageResult() { Result = zxingResult, ResultOffset = zxingResultOffset, ResultScale = pageImageModifiedScale };
else else
return null; return null;
} }
catch (Exception ex) catch (Exception ex)
{ {
throw ex; throw ex;
} }
finally finally
{ {
if (pageImageOriginal != pageImage) if (pageImageOriginal != pageImage)
pageImage.Dispose(); pageImage.Dispose();
} }
} }
private static DetectPageResult DetectPage(DiscoDataContext dbContext, PdfReader pdfReader, int PageNumber, string SessionId, string DataStoreSessionCacheLocation, IEnumerable<DocumentTemplate> detectDocumentTemplates) private static DetectPageResult DetectPage(DiscoDataContext dbContext, PdfReader pdfReader, int PageNumber, string SessionId, string DataStoreSessionCacheLocation, IEnumerable<DocumentTemplate> detectDocumentTemplates)
{ {
DetectPageResult result = new DetectPageResult() { PageNumber = PageNumber }; DetectPageResult result = new DetectPageResult() { PageNumber = PageNumber };
DocumentImporterLog.LogImportPageProgress(SessionId, PageNumber, 10, "Loading Page Images"); DocumentImporterLog.LogImportPageProgress(SessionId, PageNumber, 10, "Loading Page Images");
using (DisposableImageCollection pageImages = pdfReader.PdfPageImages(PageNumber)) using (DisposableImageCollection pageImages = pdfReader.PdfPageImages(PageNumber))
{ {
if (pageImages.Count > 0) if (pageImages.Count > 0)
{ {
result.ThumbnailImage = pageImages.BuildImageMontage(256, 256); result.ThumbnailImage = pageImages.BuildImageMontage(256, 256);
var pageThumbnailFilename = Path.Combine(DataStoreSessionCacheLocation, string.Format("{0}-{1}", SessionId, PageNumber)); var pageThumbnailFilename = Path.Combine(DataStoreSessionCacheLocation, string.Format("{0}-{1}", SessionId, PageNumber));
result.ThumbnailImage.Montage.SavePng(pageThumbnailFilename); result.ThumbnailImage.Montage.SavePng(pageThumbnailFilename);
DocumentImporterLog.LogImportPageImageUpdate(SessionId, PageNumber); DocumentImporterLog.LogImportPageImageUpdate(SessionId, PageNumber);
double pageProgressInterval = 90 / pageImages.Count; double pageProgressInterval = 90 / pageImages.Count;
foreach (var pageImageOriginal in pageImages) foreach (var pageImageOriginal in pageImages)
{ {
DocumentImporterLog.LogImportPageProgress(SessionId, PageNumber, (int)(10 + (pageProgressInterval * pageImages.IndexOf(pageImageOriginal))), String.Format("Processing Page Image {0} of {1}", pageImages.IndexOf(pageImageOriginal) + 1, pageImages.Count)); DocumentImporterLog.LogImportPageProgress(SessionId, PageNumber, (int)(10 + (pageProgressInterval * pageImages.IndexOf(pageImageOriginal))), String.Format("Processing Page Image {0} of {1}", pageImages.IndexOf(pageImageOriginal) + 1, pageImages.Count));
using (var zxingResult = DetectImage(dbContext, pageImageOriginal, SessionId, detectDocumentTemplates)) using (var zxingResult = DetectImage(dbContext, pageImageOriginal, SessionId, detectDocumentTemplates))
{ {
if (zxingResult != null) if (zxingResult != null)
{ {
if (DocumentUniqueIdentifier.IsDocumentUniqueIdentifier(zxingResult.Result.Text)) if (DocumentUniqueIdentifier.IsDocumentUniqueIdentifier(zxingResult.Result.Text))
{ {
result.DrawThumbnailImageResult(zxingResult, pageImageOriginal); result.DrawThumbnailImageResult(zxingResult, pageImageOriginal);
result.ThumbnailImage.Montage.SavePng(pageThumbnailFilename); result.ThumbnailImage.Montage.SavePng(pageThumbnailFilename);
DocumentImporterLog.LogImportPageImageUpdate(SessionId, PageNumber); DocumentImporterLog.LogImportPageImageUpdate(SessionId, PageNumber);
result.AttachmentThumbnailImage = new MemoryStream(); result.AttachmentThumbnailImage = new MemoryStream();
using (var attachmentThumbImage = pageImages.BuildImageMontage(48, 48, true)) using (var attachmentThumbImage = pageImages.BuildImageMontage(48, 48, true))
{ {
using (Image mimeTypeIcon = Disco.Properties.Resources.MimeType_pdf16) using (Image mimeTypeIcon = Disco.Properties.Resources.MimeType_pdf16)
attachmentThumbImage.Montage.EmbedIconOverlay(mimeTypeIcon); attachmentThumbImage.Montage.EmbedIconOverlay(mimeTypeIcon);
attachmentThumbImage.Montage.SaveJpg(95, result.AttachmentThumbnailImage); attachmentThumbImage.Montage.SaveJpg(95, result.AttachmentThumbnailImage);
} }
result.DetectedIdentifier = new DocumentUniqueIdentifier(zxingResult.Result.Text, PageNumber.ToString()); result.DetectedIdentifier = new DocumentUniqueIdentifier(zxingResult.Result.Text, PageNumber.ToString());
return result; return result;
} }
} }
} }
} }
// Page Unassigned // Page Unassigned
result.UndetectedPageImage = pageImages.BuildImageMontage(700, 700); result.UndetectedPageImage = pageImages.BuildImageMontage(700, 700);
} }
return result; return result;
} }
} }
public static bool ProcessPdfAttachment(string Filename, DiscoDataContext dbContext, string SessionId, Cache HttpCache) public static bool ProcessPdfAttachment(string Filename, DiscoDataContext dbContext, string SessionId, Cache HttpCache)
{ {
var dataStoreUnassignedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned"); var dataStoreUnassignedLocation = DataStore.CreateLocation(dbContext, "DocumentDropBox_Unassigned");
DocumentImporterLog.LogImportProgress(SessionId, 0, "Reading File"); DocumentImporterLog.LogImportProgress(SessionId, 0, "Reading File");
using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{ {
var pdfReader = new PdfReader(fs); var pdfReader = new PdfReader(fs);
var pdfPagesAssigned = new Dictionary<int, Tuple<DocumentUniqueIdentifier, byte[]>>(); var pdfPagesAssigned = new Dictionary<int, Tuple<DocumentUniqueIdentifier, byte[]>>();
var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages"); var dataStoreSessionPagesCacheLocation = DataStore.CreateLocation(dbContext, "Cache\\DocumentDropBox_SessionPages");
var detectDocumentTemplates = dbContext.DocumentTemplates.ToArray(); var detectDocumentTemplates = dbContext.DocumentTemplates.ToArray();
double progressInterval = 70 / pdfReader.NumberOfPages; double progressInterval = 70 / pdfReader.NumberOfPages;
for (int PageNumber = 1; PageNumber <= pdfReader.NumberOfPages; PageNumber++) for (int PageNumber = 1; PageNumber <= pdfReader.NumberOfPages; PageNumber++)
{ {
DocumentImporterLog.LogImportProgress(SessionId, (int)(PageNumber * progressInterval), string.Format("Processing Page {0} of {1}", PageNumber, pdfReader.NumberOfPages)); DocumentImporterLog.LogImportProgress(SessionId, (int)(PageNumber * progressInterval), string.Format("Processing Page {0} of {1}", PageNumber, pdfReader.NumberOfPages));
DocumentImporterLog.LogImportPageStarting(SessionId, PageNumber); DocumentImporterLog.LogImportPageStarting(SessionId, PageNumber);
using (var pageResult = DetectPage(dbContext, pdfReader, PageNumber, SessionId, dataStoreSessionPagesCacheLocation, detectDocumentTemplates)) using (var pageResult = DetectPage(dbContext, pdfReader, PageNumber, SessionId, dataStoreSessionPagesCacheLocation, detectDocumentTemplates))
{ {
if (pageResult.DetectedIdentifier != null) if (pageResult.DetectedIdentifier != null)
{ {
var docId = pageResult.DetectedIdentifier; var docId = pageResult.DetectedIdentifier;
pdfPagesAssigned.Add(PageNumber, new Tuple<DocumentUniqueIdentifier, byte[]>(docId, pageResult.AttachmentThumbnailImage.ToArray())); pdfPagesAssigned.Add(PageNumber, new Tuple<DocumentUniqueIdentifier, byte[]>(docId, pageResult.AttachmentThumbnailImage.ToArray()));
docId.LoadComponents(dbContext); docId.LoadComponents(dbContext);
DocumentImporterLog.LogImportPageDetected(SessionId, PageNumber, docId.DocumentUniqueId, docId.DocumentTemplate.Description, docId.DocumentTemplate.Scope, docId.DataId, docId.DataDescription); DocumentImporterLog.LogImportPageDetected(SessionId, PageNumber, docId.DocumentUniqueId, docId.DocumentTemplate.Description, docId.DocumentTemplate.Scope, docId.DataId, docId.DataDescription);
} }
else else
{ {
// Undetected Page - Write Preview-Images while still in Memory // Undetected Page - Write Preview-Images while still in Memory
DocumentImporterLog.LogImportPageUndetected(SessionId, PageNumber); DocumentImporterLog.LogImportPageUndetected(SessionId, PageNumber);
// Thumbnail: // Thumbnail:
string unassignedImageThumbnailFilename = Path.Combine(dataStoreUnassignedLocation, string.Format("{0}_{1}_thumbnail.png", SessionId, PageNumber)); string unassignedImageThumbnailFilename = Path.Combine(dataStoreUnassignedLocation, string.Format("{0}_{1}_thumbnail.png", SessionId, PageNumber));
pageResult.ThumbnailImage.Montage.SavePng(unassignedImageThumbnailFilename); pageResult.ThumbnailImage.Montage.SavePng(unassignedImageThumbnailFilename);
// Large Preview // Large Preview
string unassignedImageFilename = Path.Combine(dataStoreUnassignedLocation, string.Format("{0}_{1}.jpg", SessionId, PageNumber)); string unassignedImageFilename = Path.Combine(dataStoreUnassignedLocation, string.Format("{0}_{1}.jpg", SessionId, PageNumber));
pageResult.UndetectedPageImage.Montage.SaveJpg(90, unassignedImageFilename); pageResult.UndetectedPageImage.Montage.SaveJpg(90, unassignedImageFilename);
} }
} }
} }
// Write out Assigned Documents // Write out Assigned Documents
var assignedDocuments = pdfPagesAssigned.GroupBy(u => u.Value.Item1.DocumentUniqueId).ToList(); var assignedDocuments = pdfPagesAssigned.GroupBy(u => u.Value.Item1.DocumentUniqueId).ToList();
if (assignedDocuments.Count > 0) if (assignedDocuments.Count > 0)
{ {
progressInterval = 20 / assignedDocuments.Count; progressInterval = 20 / assignedDocuments.Count;
foreach (var documentPortion in assignedDocuments) foreach (var documentPortion in assignedDocuments)
{ {
DocumentImporterLog.LogImportProgress(SessionId, (int)(70 + (assignedDocuments.IndexOf(documentPortion) * progressInterval)), string.Format("Importing Documents {0} of {1}", assignedDocuments.IndexOf(documentPortion) + 1, assignedDocuments.Count)); DocumentImporterLog.LogImportProgress(SessionId, (int)(70 + (assignedDocuments.IndexOf(documentPortion) * progressInterval)), string.Format("Importing Documents {0} of {1}", assignedDocuments.IndexOf(documentPortion) + 1, assignedDocuments.Count));
var documentPortionInfo = documentPortion.First().Value; var documentPortionInfo = documentPortion.First().Value;
var documentPortionIdentifier = documentPortionInfo.Item1; var documentPortionIdentifier = documentPortionInfo.Item1;
var documentPortionThumbnail = documentPortionInfo.Item2; var documentPortionThumbnail = documentPortionInfo.Item2;
if (!documentPortionIdentifier.LoadComponents(dbContext)) if (!documentPortionIdentifier.LoadComponents(dbContext))
{ {
// Unknown Document Unique Id // Unknown Document Unique Id
foreach (var dp in documentPortion) foreach (var dp in documentPortion)
{ {
var tag = int.Parse(dp.Value.Item1.Tag); var tag = int.Parse(dp.Value.Item1.Tag);
if (pdfPagesAssigned.ContainsKey(tag)) if (pdfPagesAssigned.ContainsKey(tag))
pdfPagesAssigned.Remove(tag); pdfPagesAssigned.Remove(tag);
} }
} }
else else
{ {
using (MemoryStream msBuilder = new MemoryStream()) using (MemoryStream msBuilder = new MemoryStream())
{ {
var pdfDoc = new iTextSharp.text.Document(); var pdfDoc = new iTextSharp.text.Document();
var pdfCopy = new PdfCopy(pdfDoc, msBuilder); var pdfCopy = new PdfCopy(pdfDoc, msBuilder);
pdfDoc.Open(); pdfDoc.Open();
pdfCopy.CloseStream = false; pdfCopy.CloseStream = false;
foreach (var dp in documentPortion.OrderBy(dg => dg.Value.Item1.Page)) foreach (var dp in documentPortion.OrderBy(dg => dg.Value.Item1.Page))
{ {
var pageSize = pdfReader.GetPageSizeWithRotation(dp.Key); var pageSize = pdfReader.GetPageSizeWithRotation(dp.Key);
var page = pdfCopy.GetImportedPage(pdfReader, dp.Key); var page = pdfCopy.GetImportedPage(pdfReader, dp.Key);
pdfDoc.SetPageSize(pageSize); pdfDoc.SetPageSize(pageSize);
pdfDoc.NewPage(); pdfDoc.NewPage();
pdfCopy.AddPage(page); pdfCopy.AddPage(page);
} }
pdfDoc.Close(); pdfDoc.Close();
pdfCopy.Close(); pdfCopy.Close();
msBuilder.Position = 0; msBuilder.Position = 0;
var attachmentSuccess = documentPortionIdentifier.ImportPdfAttachment(dbContext, msBuilder, documentPortionThumbnail); var attachmentSuccess = documentPortionIdentifier.ImportPdfAttachment(dbContext, msBuilder, documentPortionThumbnail);
if (!attachmentSuccess) if (!attachmentSuccess)
{ // Unable to add Attachment { // Unable to add Attachment
foreach (var dp in documentPortion) foreach (var dp in documentPortion)
{ {
var tag = int.Parse(dp.Value.Item1.Tag); var tag = int.Parse(dp.Value.Item1.Tag);
if (pdfPagesAssigned.ContainsKey(tag)) if (pdfPagesAssigned.ContainsKey(tag))
pdfPagesAssigned.Remove(tag); pdfPagesAssigned.Remove(tag);
} }
} }
} }
} }
} }
} }
// Write out Unassigned Pages // Write out Unassigned Pages
List<int> pdfPagesUnassigned = new List<int>(); List<int> pdfPagesUnassigned = new List<int>();
for (int PageNumber = 1; PageNumber <= pdfReader.NumberOfPages; PageNumber++) for (int PageNumber = 1; PageNumber <= pdfReader.NumberOfPages; PageNumber++)
if (!pdfPagesAssigned.ContainsKey(PageNumber)) if (!pdfPagesAssigned.ContainsKey(PageNumber))
pdfPagesUnassigned.Add(PageNumber); pdfPagesUnassigned.Add(PageNumber);
if (pdfPagesUnassigned.Count > 0) if (pdfPagesUnassigned.Count > 0)
{ {
progressInterval = 10 / pdfPagesUnassigned.Count; progressInterval = 10 / pdfPagesUnassigned.Count;
//dataStoreUnassignedLocation //dataStoreUnassignedLocation
foreach (var PageNumber in pdfPagesUnassigned) foreach (var PageNumber in pdfPagesUnassigned)
{ {
DocumentImporterLog.LogImportProgress(SessionId, (int)(90 + (pdfPagesUnassigned.IndexOf(PageNumber) * progressInterval)), string.Format("Processing Undetected Documents {0} of {1}", pdfPagesUnassigned.IndexOf(PageNumber) + 1, pdfPagesUnassigned.Count)); DocumentImporterLog.LogImportProgress(SessionId, (int)(90 + (pdfPagesUnassigned.IndexOf(PageNumber) * progressInterval)), string.Format("Processing Undetected Documents {0} of {1}", pdfPagesUnassigned.IndexOf(PageNumber) + 1, pdfPagesUnassigned.Count));
using (MemoryStream msBuilder = new MemoryStream()) using (MemoryStream msBuilder = new MemoryStream())
{ {
var pdfDoc = new iTextSharp.text.Document(); var pdfDoc = new iTextSharp.text.Document();
var pdfCopy = new PdfCopy(pdfDoc, msBuilder); var pdfCopy = new PdfCopy(pdfDoc, msBuilder);
pdfDoc.Open(); pdfDoc.Open();
pdfCopy.CloseStream = false; pdfCopy.CloseStream = false;
var pageSize = pdfReader.GetPageSizeWithRotation(PageNumber); var pageSize = pdfReader.GetPageSizeWithRotation(PageNumber);
var page = pdfCopy.GetImportedPage(pdfReader, PageNumber); var page = pdfCopy.GetImportedPage(pdfReader, PageNumber);
pdfDoc.SetPageSize(pageSize); pdfDoc.SetPageSize(pageSize);
pdfDoc.NewPage(); pdfDoc.NewPage();
pdfCopy.AddPage(page); pdfCopy.AddPage(page);
pdfDoc.Close(); pdfDoc.Close();
pdfCopy.Close(); pdfCopy.Close();
File.WriteAllBytes(Path.Combine(dataStoreUnassignedLocation, string.Format("{0}_{1}.pdf", SessionId, PageNumber)), msBuilder.ToArray()); File.WriteAllBytes(Path.Combine(dataStoreUnassignedLocation, string.Format("{0}_{1}.pdf", SessionId, PageNumber)), msBuilder.ToArray());
DocumentImporterLog.LogImportPageUndetectedStored(SessionId, PageNumber); DocumentImporterLog.LogImportPageUndetectedStored(SessionId, PageNumber);
} }
} }
} }
} }
DocumentImporterLog.LogImportProgress(SessionId, 100, "Finished Importing Document"); DocumentImporterLog.LogImportProgress(SessionId, 100, "Finished Importing Document");
return true; return true;
} }
public static bool ProcessPdfAttachment(string Filename, DiscoDataContext dbContext, string DocumentTemplateId, string DataId, string UserId, DateTime Timestamp) public static bool ProcessPdfAttachment(string Filename, DiscoDataContext dbContext, string DocumentTemplateId, string DataId, string UserId, DateTime Timestamp)
{ {
using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) using (FileStream fs = new FileStream(Filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{ {
DocumentUniqueIdentifier identifier = new DocumentUniqueIdentifier(DocumentTemplateId, DataId, UserId, Timestamp); DocumentUniqueIdentifier identifier = new DocumentUniqueIdentifier(DocumentTemplateId, DataId, UserId, Timestamp);
identifier.LoadComponents(dbContext); identifier.LoadComponents(dbContext);
return identifier.ImportPdfAttachment(dbContext, fs, null); return identifier.ImportPdfAttachment(dbContext, fs, null);
} }
} }
public static DisposableImageCollection GetPageImages(PdfReader pdfReader, int PageNumber) public static DisposableImageCollection GetPageImages(PdfReader pdfReader, int PageNumber)
{ {
var pageImages = new DisposableImageCollection(); var pageImages = new DisposableImageCollection();
var pdfPage = pdfReader.GetPageN(PageNumber); var pdfPage = pdfReader.GetPageN(PageNumber);
PdfDictionary pdfPageResouces = (PdfDictionary)((PdfDictionary)pdfPage.GetDirectObject(PdfName.RESOURCES)).GetDirectObject(PdfName.XOBJECT); PdfDictionary pdfPageResouces = (PdfDictionary)((PdfDictionary)pdfPage.GetDirectObject(PdfName.RESOURCES)).GetDirectObject(PdfName.XOBJECT);
foreach (var pdfResKey in pdfPageResouces.Keys) foreach (var pdfResKey in pdfPageResouces.Keys)
{ {
var pdfRes = pdfPageResouces.GetDirectObject(pdfResKey); var pdfRes = pdfPageResouces.GetDirectObject(pdfResKey);
if (pdfRes.IsStream()) if (pdfRes.IsStream())
{ {
var pdfResStream = (PdfStream)pdfRes; var pdfResStream = (PdfStream)pdfRes;
var pdfResSubType = pdfResStream.Get(PdfName.SUBTYPE); var pdfResSubType = pdfResStream.Get(PdfName.SUBTYPE);
if (pdfResSubType != null && pdfResSubType == PdfName.IMAGE) if (pdfResSubType != null && pdfResSubType == PdfName.IMAGE)
{ {
if (pdfResStream.Get(PdfName.FILTER) == PdfName.CCITTFAXDECODE) if (pdfResStream.Get(PdfName.FILTER) == PdfName.CCITTFAXDECODE)
{ // TIFF { // TIFF
// Try Using GDI+ for TIFF... // Try Using GDI+ for TIFF...
var width = ((PdfNumber)(pdfResStream.Get(PdfName.WIDTH))).IntValue; var width = ((PdfNumber)(pdfResStream.Get(PdfName.WIDTH))).IntValue;
var height = ((PdfNumber)(pdfResStream.Get(PdfName.HEIGHT))).IntValue; var height = ((PdfNumber)(pdfResStream.Get(PdfName.HEIGHT))).IntValue;
var bpc = ((PdfNumber)(pdfResStream.Get(PdfName.BITSPERCOMPONENT))).IntValue; var bpc = ((PdfNumber)(pdfResStream.Get(PdfName.BITSPERCOMPONENT))).IntValue;
var compressionMethod = Compression.CCITTFAX3; var compressionMethod = Compression.CCITTFAX3;
var decodeParams = pdfResStream.GetAsDict(PdfName.DECODEPARMS); var decodeParams = pdfResStream.GetAsDict(PdfName.DECODEPARMS);
if (decodeParams != null && decodeParams.Contains(PdfName.K) && decodeParams.GetAsNumber(PdfName.K).IntValue < 0) if (decodeParams != null && decodeParams.Contains(PdfName.K) && decodeParams.GetAsNumber(PdfName.K).IntValue < 0)
compressionMethod = Compression.CCITTFAX4; compressionMethod = Compression.CCITTFAX4;
using (MemoryStream tiffStream = PdfToTiffStream(PdfReader.GetStreamBytesRaw((PRStream)pdfResStream), width, height, bpc, compressionMethod)) using (MemoryStream tiffStream = PdfToTiffStream(PdfReader.GetStreamBytesRaw((PRStream)pdfResStream), width, height, bpc, compressionMethod))
{ {
pageImages.Add((Bitmap)Bitmap.FromStream(tiffStream)); pageImages.Add((Bitmap)Bitmap.FromStream(tiffStream));
} }
continue; continue;
} }
if (pdfResStream.Get(PdfName.FILTER) == PdfName.DCTDECODE) if (pdfResStream.Get(PdfName.FILTER) == PdfName.DCTDECODE)
{ // JPG { // JPG
using (MemoryStream jpgStream = new MemoryStream(PdfReader.GetStreamBytesRaw((PRStream)pdfResStream))) using (MemoryStream jpgStream = new MemoryStream(PdfReader.GetStreamBytesRaw((PRStream)pdfResStream)))
{ {
pageImages.Add((Bitmap)Bitmap.FromStream(jpgStream, true, true)); pageImages.Add((Bitmap)Bitmap.FromStream(jpgStream, true, true));
} }
continue; continue;
} }
} }
} }
} }
return pageImages; return pageImages;
} }
private static MemoryStream PdfToTiffStream(byte[] PdfStream, int Width, int Height, int BitsPerComponent, Compression CompressionMethod) private static MemoryStream PdfToTiffStream(byte[] PdfStream, int Width, int Height, int BitsPerComponent, Compression CompressionMethod)
{ {
var ms = new MemoryStream(); var ms = new MemoryStream();
Tiff tif = Tiff.ClientOpen("in-memory", "w", ms, new TiffStream()); Tiff tif = Tiff.ClientOpen("in-memory", "w", ms, new TiffStream());
tif.SetField(TiffTag.IMAGEWIDTH, Width); tif.SetField(TiffTag.IMAGEWIDTH, Width);
tif.SetField(TiffTag.IMAGELENGTH, Height); tif.SetField(TiffTag.IMAGELENGTH, Height);
tif.SetField(TiffTag.COMPRESSION, CompressionMethod); tif.SetField(TiffTag.COMPRESSION, CompressionMethod);
tif.SetField(TiffTag.BITSPERSAMPLE, BitsPerComponent); tif.SetField(TiffTag.BITSPERSAMPLE, BitsPerComponent);
tif.SetField(TiffTag.SAMPLESPERPIXEL, 1); tif.SetField(TiffTag.SAMPLESPERPIXEL, 1);
tif.WriteRawStrip(0, PdfStream, PdfStream.Length); tif.WriteRawStrip(0, PdfStream, PdfStream.Length);
tif.Flush(); tif.Flush();
return ms; return ms;
} }
} }
} }
@@ -1,14 +1,14 @@
//using System; //using System;
//using System.Collections.Generic; //using System.Collections.Generic;
//using System.Linq; //using System.Linq;
//using System.Text; //using System.Text;
//using Disco.Data.Repository; //using Disco.Data.Repository;
//using Quartz; //using Quartz;
//namespace Disco.BI.Interop.PluginServices //namespace Disco.BI.Interop.PluginServices
//{ //{
// interface IDiscoScheduledTask // interface IDiscoScheduledTask
// { // {
// void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler); // void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler);
// } // }
//} //}
+45 -45
View File
@@ -1,45 +1,45 @@
//using System; //using System;
//using System.Collections.Generic; //using System.Collections.Generic;
//using System.Linq; //using System.Linq;
//using System.Text; //using System.Text;
//using Disco.Data.Repository; //using Disco.Data.Repository;
//using Quartz; //using Quartz;
//namespace Disco.BI.Interop.PluginServices //namespace Disco.BI.Interop.PluginServices
//{ //{
// public static class Utilities // public static class Utilities
// { // {
// public static void InitalizeScheduledTasks(DiscoDataContext dbContext, ISchedulerFactory SchedulerFactory) // public static void InitalizeScheduledTasks(DiscoDataContext dbContext, ISchedulerFactory SchedulerFactory)
// { // {
// var scheduler = SchedulerFactory.GetScheduler(); // var scheduler = SchedulerFactory.GetScheduler();
// // Discover IDiscoScheduledTasks (Only from Disco Assemblies) // // Discover IDiscoScheduledTasks (Only from Disco Assemblies)
// var appDomain = AppDomain.CurrentDomain; // var appDomain = AppDomain.CurrentDomain;
// var scheduledTaskTypes = (from a in appDomain.GetAssemblies() // var scheduledTaskTypes = (from a in appDomain.GetAssemblies()
// where !a.GlobalAssemblyCache && !a.IsDynamic && a.FullName.StartsWith("Disco.", StringComparison.InvariantCultureIgnoreCase) // where !a.GlobalAssemblyCache && !a.IsDynamic && a.FullName.StartsWith("Disco.", StringComparison.InvariantCultureIgnoreCase)
// from type in a.GetTypes() // from type in a.GetTypes()
// where typeof(IDiscoScheduledTask).IsAssignableFrom(type) && !type.IsAbstract // where typeof(IDiscoScheduledTask).IsAssignableFrom(type) && !type.IsAbstract
// select type); // select type);
// foreach (Type scheduledTaskType in scheduledTaskTypes) // foreach (Type scheduledTaskType in scheduledTaskTypes)
// { // {
// IDiscoScheduledTask instance = (IDiscoScheduledTask)Activator.CreateInstance(scheduledTaskType); // IDiscoScheduledTask instance = (IDiscoScheduledTask)Activator.CreateInstance(scheduledTaskType);
// try // try
// { // {
// instance.InitalizeScheduledTask(dbContext, scheduler); // instance.InitalizeScheduledTask(dbContext, scheduler);
// } // }
// catch (Exception ex) // catch (Exception ex)
// { // {
// if (instance == null) // if (instance == null)
// Logging.SystemLog.LogException("Initializing Scheduled Task; Disco.BI.Interop.Plugins.Utilities.InitalizeScheduledTasks()", ex); // Logging.SystemLog.LogException("Initializing Scheduled Task; Disco.BI.Interop.Plugins.Utilities.InitalizeScheduledTasks()", ex);
// else // else
// Logging.SystemLog.LogException(string.Format("Initializing Scheduled Task: '{0}'; Disco.BI.Interop.Plugins.Utilities.InitalizeScheduledTasks()", instance.GetType().Name), ex); // Logging.SystemLog.LogException(string.Format("Initializing Scheduled Task: '{0}'; Disco.BI.Interop.Plugins.Utilities.InitalizeScheduledTasks()", instance.GetType().Name), ex);
// } // }
// } // }
// } // }
// } // }
//} //}
@@ -1,23 +1,23 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using SignalR; using SignalR;
using SignalR.Hosting.AspNet; using SignalR.Hosting.AspNet;
using SignalR.Infrastructure; using SignalR.Infrastructure;
namespace Disco.BI.Interop.SignalRHandlers namespace Disco.BI.Interop.SignalRHandlers
{ {
public class UserHeldDevices : PersistentConnection public class UserHeldDevices : PersistentConnection
{ {
internal static void UserJobUpdated(string JobUserId) internal static void UserJobUpdated(string JobUserId)
{ {
var connectionManager = GlobalHost.ConnectionManager; var connectionManager = GlobalHost.ConnectionManager;
var connectionContext = connectionManager.GetConnectionContext<UserHeldDevices>(); var connectionContext = connectionManager.GetConnectionContext<UserHeldDevices>();
if (connectionContext != null) if (connectionContext != null)
connectionContext.Connection.Broadcast(JobUserId); connectionContext.Connection.Broadcast(JobUserId);
} }
} }
} }
+93 -93
View File
@@ -1,93 +1,93 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.BI.Job; using Disco.Models.BI.Job;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.BI.Extensions; using Disco.BI.Extensions;
namespace Disco.BI.JobBI namespace Disco.BI.JobBI
{ {
public static class Searching public static class Searching
{ {
public static JobTableModel Search(DiscoDataContext dbContext, string Term, int? LimitCount = null, bool IncludeJobStatus = true, bool SearchDetails = false) public static JobTableModel Search(DiscoDataContext dbContext, string Term, int? LimitCount = null, bool IncludeJobStatus = true, bool SearchDetails = false)
{ {
int termInt = default(int); int termInt = default(int);
IQueryable<Job> query = default(IQueryable<Job>); IQueryable<Job> query = default(IQueryable<Job>);
if (int.TryParse(Term, out termInt)) if (int.TryParse(Term, out termInt))
{ {
// Term is a Number (int) // Term is a Number (int)
if (SearchDetails) if (SearchDetails)
{ {
query = BuildJobTableModel(dbContext).Where(j => query = BuildJobTableModel(dbContext).Where(j =>
j.Id == termInt || j.Id == termInt ||
j.DeviceHeldLocation.Contains(Term) || j.DeviceHeldLocation.Contains(Term) ||
j.Device.SerialNumber.Contains(Term) || j.Device.SerialNumber.Contains(Term) ||
j.Device.AssetNumber.Contains(Term) || j.Device.AssetNumber.Contains(Term) ||
j.User.Id == Term || j.User.Id == Term ||
j.User.Surname.Contains(Term) || j.User.Surname.Contains(Term) ||
j.User.GivenName.Contains(Term) || j.User.GivenName.Contains(Term) ||
j.User.DisplayName.Contains(Term) || j.User.DisplayName.Contains(Term) ||
j.JobLogs.Any(jl => jl.Comments.Contains(Term)) || j.JobLogs.Any(jl => jl.Comments.Contains(Term)) ||
j.JobAttachments.Any(ja => ja.Comments.Contains(Term))); j.JobAttachments.Any(ja => ja.Comments.Contains(Term)));
} }
else else
{ {
query = BuildJobTableModel(dbContext).Where(j => query = BuildJobTableModel(dbContext).Where(j =>
j.Id == termInt || j.Id == termInt ||
j.DeviceHeldLocation.Contains(Term) || j.DeviceHeldLocation.Contains(Term) ||
j.Device.SerialNumber.Contains(Term) || j.Device.SerialNumber.Contains(Term) ||
j.Device.AssetNumber.Contains(Term) || j.Device.AssetNumber.Contains(Term) ||
j.User.Id == Term || j.User.Id == Term ||
j.User.Surname.Contains(Term) || j.User.Surname.Contains(Term) ||
j.User.GivenName.Contains(Term) || j.User.GivenName.Contains(Term) ||
j.User.DisplayName.Contains(Term)); j.User.DisplayName.Contains(Term));
} }
} }
else else
{ {
if (SearchDetails) if (SearchDetails)
{ {
query = BuildJobTableModel(dbContext).Where(j => query = BuildJobTableModel(dbContext).Where(j =>
j.DeviceHeldLocation.Contains(Term) || j.DeviceHeldLocation.Contains(Term) ||
j.Device.SerialNumber.Contains(Term) || j.Device.SerialNumber.Contains(Term) ||
j.Device.AssetNumber.Contains(Term) || j.Device.AssetNumber.Contains(Term) ||
j.User.Id == Term || j.User.Id == Term ||
j.User.Surname.Contains(Term) || j.User.Surname.Contains(Term) ||
j.User.GivenName.Contains(Term) || j.User.GivenName.Contains(Term) ||
j.User.DisplayName.Contains(Term) || j.User.DisplayName.Contains(Term) ||
j.JobLogs.Any(jl => jl.Comments.Contains(Term)) || j.JobLogs.Any(jl => jl.Comments.Contains(Term)) ||
j.JobAttachments.Any(ja => ja.Comments.Contains(Term))); j.JobAttachments.Any(ja => ja.Comments.Contains(Term)));
} }
else else
{ {
query = BuildJobTableModel(dbContext).Where(j => query = BuildJobTableModel(dbContext).Where(j =>
j.DeviceHeldLocation.Contains(Term) || j.DeviceHeldLocation.Contains(Term) ||
j.Device.SerialNumber.Contains(Term) || j.Device.SerialNumber.Contains(Term) ||
j.Device.AssetNumber.Contains(Term) || j.Device.AssetNumber.Contains(Term) ||
j.User.Id == Term || j.User.Id == Term ||
j.User.Surname.Contains(Term) || j.User.Surname.Contains(Term) ||
j.User.GivenName.Contains(Term) || j.User.GivenName.Contains(Term) ||
j.User.DisplayName.Contains(Term)); j.User.DisplayName.Contains(Term));
} }
} }
if (LimitCount.HasValue) if (LimitCount.HasValue)
query = query.Take(LimitCount.Value); query = query.Take(LimitCount.Value);
JobTableModel model = new JobTableModel() { ShowStatus = IncludeJobStatus }; JobTableModel model = new JobTableModel() { ShowStatus = IncludeJobStatus };
model.Fill(dbContext, query); model.Fill(dbContext, query);
return model; return model;
} }
public static IQueryable<Job> BuildJobTableModel(DiscoDataContext dbContext) public static IQueryable<Job> BuildJobTableModel(DiscoDataContext dbContext)
{ {
return dbContext.Jobs.Include("JobType").Include("Device").Include("User").Include("OpenedTechUser"); return dbContext.Jobs.Include("JobType").Include("Device").Include("User").Include("OpenedTechUser");
} }
} }
} }
+142 -142
View File
@@ -1,142 +1,142 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Quartz; using Quartz;
using Disco.Models.BI.Job.Statistics; using Disco.Models.BI.Job.Statistics;
using Disco.Data.Repository; using Disco.Data.Repository;
using Quartz.Impl; using Quartz.Impl;
using Disco.Services.Tasks; using Disco.Services.Tasks;
namespace Disco.BI.JobBI.Statistics namespace Disco.BI.JobBI.Statistics
{ {
public class DailyOpenedClosed : ScheduledTask public class DailyOpenedClosed : ScheduledTask
{ {
private static List<DailyOpenedClosedItem> _data; private static List<DailyOpenedClosedItem> _data;
private static object _dataLock = new object(); private static object _dataLock = new object();
public override string TaskName { get { return "Job Statistics - Daily Opened/Closed Task"; } } public override string TaskName { get { return "Job Statistics - Daily Opened/Closed Task"; } }
public override bool SingleInstanceTask { get { return true; } } public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext dbContext)
{ {
// Trigger Daily @ 12:29am // Trigger Daily @ 12:29am
TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 29)); TriggerBuilder triggerBuilder = TriggerBuilder.Create().WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 29));
this.ScheduleTask(triggerBuilder); this.ScheduleTask(triggerBuilder);
} }
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
using (var dbContext = new DiscoDataContext()) using (var dbContext = new DiscoDataContext())
{ {
UpdateDataHistory(dbContext, true); UpdateDataHistory(dbContext, true);
} }
} }
//public void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler) //public void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler)
//{ //{
// // Run @ 12:29am // // Run @ 12:29am
// IJobDetail jobDetail = new JobDetailImpl("JobStatisticsDailyOpenedClosed", typeof(DailyOpenedClosed)); // IJobDetail jobDetail = new JobDetailImpl("JobStatisticsDailyOpenedClosed", typeof(DailyOpenedClosed));
// ITrigger trigger = TriggerBuilder.Create(). // ITrigger trigger = TriggerBuilder.Create().
// WithIdentity("JobStatisticsDailyOpenedClosedTrigger"). // WithIdentity("JobStatisticsDailyOpenedClosedTrigger").
// StartNow(). // StartNow().
// WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 29)). // WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(0, 29)).
// Build(); // Build();
// Scheduler.ScheduleJob(jobDetail, trigger); // Scheduler.ScheduleJob(jobDetail, trigger);
//} //}
//public void Execute(IJobExecutionContext context) //public void Execute(IJobExecutionContext context)
//{ //{
// try // try
// { // {
// using (var dbContext = new DiscoDataContext()) // using (var dbContext = new DiscoDataContext())
// { // {
// UpdateDataHistory(dbContext, true); // UpdateDataHistory(dbContext, true);
// } // }
// } // }
// catch (Exception ex) // catch (Exception ex)
// { // {
// Logging.SystemLog.LogException("Disco.BI.JobBI.Statistics.DailyOpenedClosed", ex); // Logging.SystemLog.LogException("Disco.BI.JobBI.Statistics.DailyOpenedClosed", ex);
// } // }
//} //}
private static void UpdateDataHistory(DiscoDataContext dbContext, bool Refresh = false) private static void UpdateDataHistory(DiscoDataContext dbContext, bool Refresh = false)
{ {
DateTime historyEnd = DateTime.Now.AddDays(-1).Date; DateTime historyEnd = DateTime.Now.AddDays(-1).Date;
if (Refresh || _data == null || _data.Count == 0 || _data.Last().Timestamp < historyEnd) if (Refresh || _data == null || _data.Count == 0 || _data.Last().Timestamp < historyEnd)
{ {
lock (_dataLock) lock (_dataLock)
{ {
if (Refresh || _data == null || _data.Count == 0 || _data.Last().Timestamp < historyEnd) if (Refresh || _data == null || _data.Count == 0 || _data.Last().Timestamp < historyEnd)
{ {
DateTime historyStart = DateTime.Now.AddDays(-28).Date; DateTime historyStart = DateTime.Now.AddDays(-28).Date;
// Initialize Memory Store // Initialize Memory Store
List<DailyOpenedClosedItem> resultData; List<DailyOpenedClosedItem> resultData;
if (Refresh || _data == null) if (Refresh || _data == null)
resultData = new List<DailyOpenedClosedItem>(); resultData = new List<DailyOpenedClosedItem>();
else else
resultData = _data; resultData = _data;
// Remove Old Data // Remove Old Data
while (resultData.Count > 0 && resultData[0].Timestamp < historyStart) while (resultData.Count > 0 && resultData[0].Timestamp < historyStart)
resultData.RemoveAt(0); resultData.RemoveAt(0);
// Calculate Update Scope // Calculate Update Scope
DateTime processDate = historyStart; DateTime processDate = historyStart;
if (resultData.Count > 0) if (resultData.Count > 0)
processDate = resultData.Last().Timestamp.AddDays(-1); processDate = resultData.Last().Timestamp.AddDays(-1);
// Cache Data // Cache Data
while (processDate <= historyEnd) while (processDate <= historyEnd)
{ {
resultData.Add(Data(dbContext, processDate)); resultData.Add(Data(dbContext, processDate));
processDate = processDate.AddDays(1); processDate = processDate.AddDays(1);
} }
_data = resultData; _data = resultData;
} }
} }
} }
} }
private static DailyOpenedClosedItem Data(DiscoDataContext dbContext, DateTime ProcessDate) private static DailyOpenedClosedItem Data(DiscoDataContext dbContext, DateTime ProcessDate)
{ {
DateTime processDateStart = ProcessDate; DateTime processDateStart = ProcessDate;
DateTime processDateEnd = ProcessDate.AddDays(1); DateTime processDateEnd = ProcessDate.AddDays(1);
int totalJobs = dbContext.Jobs.Where(j => j.OpenedDate < processDateEnd && (!j.ClosedDate.HasValue || j.ClosedDate > processDateEnd)).Count(); int totalJobs = dbContext.Jobs.Where(j => j.OpenedDate < processDateEnd && (!j.ClosedDate.HasValue || j.ClosedDate > processDateEnd)).Count();
int openedJobs = dbContext.Jobs.Where(j => j.OpenedDate > processDateStart && j.OpenedDate < processDateEnd).Count(); int openedJobs = dbContext.Jobs.Where(j => j.OpenedDate > processDateStart && j.OpenedDate < processDateEnd).Count();
int closedJobs = dbContext.Jobs.Where(j => j.ClosedDate > processDateStart && j.ClosedDate < processDateEnd).Count(); int closedJobs = dbContext.Jobs.Where(j => j.ClosedDate > processDateStart && j.ClosedDate < processDateEnd).Count();
return new DailyOpenedClosedItem() return new DailyOpenedClosedItem()
{ {
Timestamp = ProcessDate, Timestamp = ProcessDate,
TotalJobs = totalJobs, TotalJobs = totalJobs,
OpenedJobs = openedJobs, OpenedJobs = openedJobs,
ClosedJobs = closedJobs ClosedJobs = closedJobs
}; };
} }
public static List<DailyOpenedClosedItem> Data(DiscoDataContext dbContext, bool FilterUnimportantWeekends = false) public static List<DailyOpenedClosedItem> Data(DiscoDataContext dbContext, bool FilterUnimportantWeekends = false)
{ {
List<DailyOpenedClosedItem> resultData; List<DailyOpenedClosedItem> resultData;
UpdateDataHistory(dbContext); UpdateDataHistory(dbContext);
if (FilterUnimportantWeekends) if (FilterUnimportantWeekends)
resultData = _data.Where(i => (i.Timestamp.DayOfWeek != DayOfWeek.Saturday && i.Timestamp.DayOfWeek != DayOfWeek.Sunday) || resultData = _data.Where(i => (i.Timestamp.DayOfWeek != DayOfWeek.Saturday && i.Timestamp.DayOfWeek != DayOfWeek.Sunday) ||
(i.OpenedJobs > 0 || i.ClosedJobs > 0)).ToList(); (i.OpenedJobs > 0 || i.ClosedJobs > 0)).ToList();
else else
resultData = _data.ToList(); resultData = _data.ToList();
resultData.Add(Data(dbContext, DateTime.Today)); resultData.Add(Data(dbContext, DateTime.Today));
return resultData; return resultData;
} }
} }
} }
+171 -171
View File
@@ -1,171 +1,171 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.BI.Job; using Disco.Models.BI.Job;
namespace Disco.BI.JobBI namespace Disco.BI.JobBI
{ {
public static class Utilities public static class Utilities
{ {
public static Job Create(DiscoDataContext dbContext, Device device, User user, JobType type, List<JobSubType> subTypes, User initialTech) public static Job Create(DiscoDataContext dbContext, Device device, User user, JobType type, List<JobSubType> subTypes, User initialTech)
{ {
Job j = new Job() Job j = new Job()
{ {
JobType = type, JobType = type,
OpenedTechUserId = initialTech.Id, OpenedTechUserId = initialTech.Id,
OpenedTechUser = initialTech, OpenedTechUser = initialTech,
OpenedDate = DateTime.Now OpenedDate = DateTime.Now
}; };
// Device // Device
if (device != null) if (device != null)
{ {
j.Device = device; j.Device = device;
j.DeviceSerialNumber = device.SerialNumber; j.DeviceSerialNumber = device.SerialNumber;
} }
// User // User
if (user != null) if (user != null)
{ {
j.User = user; j.User = user;
j.UserId = user.Id; j.UserId = user.Id;
} }
// Sub Types // Sub Types
List<JobSubType> jobSubTypes = subTypes.ToList(); List<JobSubType> jobSubTypes = subTypes.ToList();
j.JobSubTypes = jobSubTypes; j.JobSubTypes = jobSubTypes;
dbContext.Jobs.Add(j); dbContext.Jobs.Add(j);
switch (type.Id) switch (type.Id)
{ {
case JobType.JobTypeIds.HWar: case JobType.JobTypeIds.HWar:
dbContext.JobMetaWarranties.Add(new JobMetaWarranty() { Job = j }); dbContext.JobMetaWarranties.Add(new JobMetaWarranty() { Job = j });
break; break;
case JobType.JobTypeIds.HNWar: case JobType.JobTypeIds.HNWar:
dbContext.JobMetaNonWarranties.Add(new JobMetaNonWarranty() { Job = j }); dbContext.JobMetaNonWarranties.Add(new JobMetaNonWarranty() { Job = j });
if (device != null) if (device != null)
{ {
// Add Job Components // Add Job Components
var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId); var components = dbContext.DeviceComponents.Include("JobSubTypes").Where(c => !c.DeviceModelId.HasValue || c.DeviceModelId == j.Device.DeviceModelId);
var addedComponents = new List<DeviceComponent>(); var addedComponents = new List<DeviceComponent>();
foreach (var c in components) foreach (var c in components)
{ {
if (c.JobSubTypes.Count == 0) if (c.JobSubTypes.Count == 0)
{ // No Filter { // No Filter
addedComponents.Add(c); addedComponents.Add(c);
} }
else else
{ {
foreach (var st in c.JobSubTypes) foreach (var st in c.JobSubTypes)
{ {
foreach (var jst in jobSubTypes) foreach (var jst in jobSubTypes)
{ {
if (st.JobTypeId == jst.JobTypeId && st.Id == jst.Id) if (st.JobTypeId == jst.JobTypeId && st.Id == jst.Id)
{ {
addedComponents.Add(c); addedComponents.Add(c);
break; break;
} }
} }
if (addedComponents.Contains(c)) if (addedComponents.Contains(c))
break; break;
} }
} }
} }
foreach (var c in addedComponents) foreach (var c in addedComponents)
dbContext.JobComponents.Add(new JobComponent() dbContext.JobComponents.Add(new JobComponent()
{ {
Job = j, Job = j,
TechUserId = initialTech.Id, TechUserId = initialTech.Id,
Cost = c.Cost, Cost = c.Cost,
Description = c.Description Description = c.Description
}); });
} }
break; break;
} }
return j; return j;
} }
public static string JobStatusDescription(string StatusId, Job j = null) public static string JobStatusDescription(string StatusId, Job j = null)
{ {
switch (StatusId) switch (StatusId)
{ {
case Job.JobStatusIds.Open: case Job.JobStatusIds.Open:
return "Open"; return "Open";
case Job.JobStatusIds.Closed: case Job.JobStatusIds.Closed:
return "Closed"; return "Closed";
case Job.JobStatusIds.AwaitingWarrantyRepair: case Job.JobStatusIds.AwaitingWarrantyRepair:
if (j == null) if (j == null)
return "Awaiting Warranty Repair"; return "Awaiting Warranty Repair";
else else
if (j.DeviceHeld.HasValue) if (j.DeviceHeld.HasValue)
return string.Format("Awaiting Warranty Repair ({0})", j.JobMetaWarranty.ExternalName); return string.Format("Awaiting Warranty Repair ({0})", j.JobMetaWarranty.ExternalName);
else else
return string.Format("Awaiting Warranty Repair - Not Held ({0})", j.JobMetaWarranty.ExternalName); return string.Format("Awaiting Warranty Repair - Not Held ({0})", j.JobMetaWarranty.ExternalName);
case Job.JobStatusIds.AwaitingRepairs: case Job.JobStatusIds.AwaitingRepairs:
if (j == null) if (j == null)
return "Awaiting Repairs"; return "Awaiting Repairs";
else else
if (j.DeviceHeld.HasValue) if (j.DeviceHeld.HasValue)
return string.Format("Awaiting Repairs ({0})", j.JobMetaNonWarranty.RepairerName); return string.Format("Awaiting Repairs ({0})", j.JobMetaNonWarranty.RepairerName);
else else
return string.Format("Awaiting Repairs - Not Held ({0})", j.JobMetaNonWarranty.RepairerName); return string.Format("Awaiting Repairs - Not Held ({0})", j.JobMetaNonWarranty.RepairerName);
case Job.JobStatusIds.AwaitingDeviceReturn: case Job.JobStatusIds.AwaitingDeviceReturn:
return "Awaiting Device Return"; return "Awaiting Device Return";
case Job.JobStatusIds.AwaitingUserAction: case Job.JobStatusIds.AwaitingUserAction:
return "Awaiting User Action"; return "Awaiting User Action";
case Job.JobStatusIds.AwaitingAccountingPayment: case Job.JobStatusIds.AwaitingAccountingPayment:
return "Awaiting Accounting Payment"; return "Awaiting Accounting Payment";
case Job.JobStatusIds.AwaitingAccountingCharge: case Job.JobStatusIds.AwaitingAccountingCharge:
return "Awaiting Accounting Charge"; return "Awaiting Accounting Charge";
case Job.JobStatusIds.AwaitingInsuranceProcessing: case Job.JobStatusIds.AwaitingInsuranceProcessing:
return "Awaiting Insurance Processing"; return "Awaiting Insurance Processing";
default: default:
return "Unknown"; return "Unknown";
} }
} }
public static string JobStatusDescription(string StatusId, JobTableModel.JobTableItemModelIncludeStatus j = null) public static string JobStatusDescription(string StatusId, JobTableModel.JobTableItemModelIncludeStatus j = null)
{ {
switch (StatusId) switch (StatusId)
{ {
case Job.JobStatusIds.Open: case Job.JobStatusIds.Open:
return "Open"; return "Open";
case Job.JobStatusIds.Closed: case Job.JobStatusIds.Closed:
return "Closed"; return "Closed";
case Job.JobStatusIds.AwaitingWarrantyRepair: case Job.JobStatusIds.AwaitingWarrantyRepair:
if (j == null) if (j == null)
return "Awaiting Warranty Repair"; return "Awaiting Warranty Repair";
else else
if (j.DeviceHeld.HasValue) if (j.DeviceHeld.HasValue)
return string.Format("Awaiting Warranty Repair ({0})", j.JobMetaWarranty_ExternalName); return string.Format("Awaiting Warranty Repair ({0})", j.JobMetaWarranty_ExternalName);
else else
return string.Format("Awaiting Warranty Repair - Not Held ({0})", j.JobMetaWarranty_ExternalName); return string.Format("Awaiting Warranty Repair - Not Held ({0})", j.JobMetaWarranty_ExternalName);
case Job.JobStatusIds.AwaitingRepairs: case Job.JobStatusIds.AwaitingRepairs:
if (j == null) if (j == null)
return "Awaiting Repairs"; return "Awaiting Repairs";
else else
if (j.DeviceHeld.HasValue) if (j.DeviceHeld.HasValue)
return string.Format("Awaiting Repairs ({0})", j.JobMetaNonWarranty_RepairerName); return string.Format("Awaiting Repairs ({0})", j.JobMetaNonWarranty_RepairerName);
else else
return string.Format("Awaiting Repairs - Not Held ({0})", j.JobMetaNonWarranty_RepairerName); return string.Format("Awaiting Repairs - Not Held ({0})", j.JobMetaNonWarranty_RepairerName);
case Job.JobStatusIds.AwaitingDeviceReturn: case Job.JobStatusIds.AwaitingDeviceReturn:
return "Awaiting Device Return"; return "Awaiting Device Return";
case Job.JobStatusIds.AwaitingUserAction: case Job.JobStatusIds.AwaitingUserAction:
return "Awaiting User Action"; return "Awaiting User Action";
case Job.JobStatusIds.AwaitingAccountingPayment: case Job.JobStatusIds.AwaitingAccountingPayment:
return "Awaiting Accounting Payment"; return "Awaiting Accounting Payment";
case Job.JobStatusIds.AwaitingAccountingCharge: case Job.JobStatusIds.AwaitingAccountingCharge:
return "Awaiting Accounting Charge"; return "Awaiting Accounting Charge";
case Job.JobStatusIds.AwaitingInsuranceProcessing: case Job.JobStatusIds.AwaitingInsuranceProcessing:
return "Awaiting Insurance Processing"; return "Awaiting Insurance Processing";
default: default:
return "Unknown"; return "Unknown";
} }
} }
} }
} }
+61 -61
View File
@@ -1,61 +1,61 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.BI.Search; using Disco.Models.BI.Search;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
namespace Disco.BI.UserBI namespace Disco.BI.UserBI
{ {
public static class Searching public static class Searching
{ {
public static List<User> SearchUpstream(string Term) public static List<User> SearchUpstream(string Term)
{ {
return Interop.ActiveDirectory.ActiveDirectory.SearchUsers(Term).Select(adU => adU.ToRepositoryUser()).ToList(); return Interop.ActiveDirectory.ActiveDirectory.SearchUsers(Term).Select(adU => adU.ToRepositoryUser()).ToList();
} }
private static List<UserSearchResultItem> Search_SelectUserSearchResultItems(IQueryable<User> Query, int? LimitCount = null) private static List<UserSearchResultItem> Search_SelectUserSearchResultItems(IQueryable<User> Query, int? LimitCount = null)
{ {
if (LimitCount.HasValue) if (LimitCount.HasValue)
Query = Query.Take(LimitCount.Value); Query = Query.Take(LimitCount.Value);
return Query.Select(u => new UserSearchResultItem() return Query.Select(u => new UserSearchResultItem()
{ {
Id = u.Id, Id = u.Id,
Surname = u.Surname, Surname = u.Surname,
GivenName = u.GivenName, GivenName = u.GivenName,
DisplayName = u.DisplayName, DisplayName = u.DisplayName,
AssignedDevicesCount = u.DeviceUserAssignments.Where(dua => !dua.UnassignedDate.HasValue).Count(), AssignedDevicesCount = u.DeviceUserAssignments.Where(dua => !dua.UnassignedDate.HasValue).Count(),
JobCount = u.Jobs.Count() JobCount = u.Jobs.Count()
}).ToList(); }).ToList();
} }
public static List<UserSearchResultItem> Search(DiscoDataContext dbContext, string Term, int? LimitCount = null) public static List<UserSearchResultItem> Search(DiscoDataContext dbContext, string Term, int? LimitCount = null)
{ {
if (string.IsNullOrWhiteSpace(Term) || Term.Length < 2) if (string.IsNullOrWhiteSpace(Term) || Term.Length < 2)
throw new ArgumentException("Search Term must contain at least two characters", "Term"); throw new ArgumentException("Search Term must contain at least two characters", "Term");
// Search Active Directory & Import Relevant Users // Search Active Directory & Import Relevant Users
var adImportedUsers = Interop.ActiveDirectory.ActiveDirectory.SearchUsers(Term).Select(adU => adU.ToRepositoryUser()); var adImportedUsers = Interop.ActiveDirectory.ActiveDirectory.SearchUsers(Term).Select(adU => adU.ToRepositoryUser());
foreach (var adU in adImportedUsers) foreach (var adU in adImportedUsers)
{ {
var existingUser = dbContext.Users.Find(adU.Id); var existingUser = dbContext.Users.Find(adU.Id);
if (existingUser != null) if (existingUser != null)
existingUser.UpdateSelf(adU); existingUser.UpdateSelf(adU);
else else
dbContext.Users.Add(adU); dbContext.Users.Add(adU);
dbContext.SaveChanges(); dbContext.SaveChanges();
UserCache.InvalidateValue(adU.Id); UserCache.InvalidateValue(adU.Id);
} }
return Search_SelectUserSearchResultItems(dbContext.Users.Where(u => return Search_SelectUserSearchResultItems(dbContext.Users.Where(u =>
u.Id.Contains(Term) || u.Id.Contains(Term) ||
u.Surname.Contains(Term) || u.Surname.Contains(Term) ||
u.GivenName.Contains(Term) || u.GivenName.Contains(Term) ||
u.DisplayName.Contains(Term) u.DisplayName.Contains(Term)
), LimitCount); ), LimitCount);
} }
} }
} }
+193 -193
View File
@@ -1,193 +1,193 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using System.Web; using System.Web;
using Quartz; using Quartz;
using Quartz.Impl; using Quartz.Impl;
using Disco.Services.Tasks; using Disco.Services.Tasks;
namespace Disco.BI.UserBI namespace Disco.BI.UserBI
{ {
public class UserCache : ScheduledTask public class UserCache : ScheduledTask
{ {
private static ConcurrentDictionary<string, Tuple<User, DateTime>> _Cache = new ConcurrentDictionary<string, Tuple<User, DateTime>>(); private static ConcurrentDictionary<string, Tuple<User, DateTime>> _Cache = new ConcurrentDictionary<string, Tuple<User, DateTime>>();
private const long CacheTimeoutTicks = 6000000000; // 10 Minutes private const long CacheTimeoutTicks = 6000000000; // 10 Minutes
private const string CacheHttpRequestKey = "Disco_CurrentUser"; private const string CacheHttpRequestKey = "Disco_CurrentUser";
public static User CurrentUser public static User CurrentUser
{ {
get get
{ {
string username = null; string username = null;
User user; User user;
// Check for ASP.NET // Check for ASP.NET
if (HttpContext.Current != null) if (HttpContext.Current != null)
{ {
if (HttpContext.Current.Request.IsAuthenticated) if (HttpContext.Current.Request.IsAuthenticated)
{ {
user = (User)HttpContext.Current.Items[CacheHttpRequestKey]; user = (User)HttpContext.Current.Items[CacheHttpRequestKey];
if (user != null) if (user != null)
return user; return user;
username = HttpContext.Current.User.Identity.Name; username = HttpContext.Current.User.Identity.Name;
} }
else else
{ {
return null; return null;
//throw new PlatformNotSupportedException("ASP.NET Authentication is not correctly configured"); //throw new PlatformNotSupportedException("ASP.NET Authentication is not correctly configured");
} }
} }
// User default User // User default User
if (username == null) if (username == null)
{ {
username = System.Security.Principal.WindowsIdentity.GetCurrent().Name; username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
} }
user = GetUser(username); user = GetUser(username);
if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated)
{ {
// Cache in current request // Cache in current request
HttpContext.Current.Items[CacheHttpRequestKey] = user; HttpContext.Current.Items[CacheHttpRequestKey] = user;
} }
return user; return user;
} }
} }
public static User GetUser(string Username) public static User GetUser(string Username)
{ {
// Check Cache // Check Cache
User u = TryUserCache(Username); User u = TryUserCache(Username);
if (u == null) if (u == null)
{ {
// Load from Repository // Load from Repository
using (DiscoDataContext dbContext = new DiscoDataContext()) using (DiscoDataContext dbContext = new DiscoDataContext())
{ {
u = GetUser(Username, dbContext, true); u = GetUser(Username, dbContext, true);
} }
} }
return u; return u;
} }
public static User GetUser(string Username, DiscoDataContext dbContext, bool ForceRefresh = false) public static User GetUser(string Username, DiscoDataContext dbContext, bool ForceRefresh = false)
{ {
User u = null; User u = null;
// Check Cache // Check Cache
if (!ForceRefresh) if (!ForceRefresh)
u = TryUserCache(Username); u = TryUserCache(Username);
if (u == null) if (u == null)
{ {
string username = Username.ToLower(); string username = Username.ToLower();
u = UserBI.Utilities.LoadUser(dbContext, username); u = UserBI.Utilities.LoadUser(dbContext, username);
SetValue(username, u); SetValue(username, u);
} }
return u; return u;
} }
private static User TryUserCache(string Username) private static User TryUserCache(string Username)
{ {
string username = Username.ToLower(); string username = Username.ToLower();
Tuple<User, DateTime> userRecord; Tuple<User, DateTime> userRecord;
if (_Cache.TryGetValue(username, out userRecord)) if (_Cache.TryGetValue(username, out userRecord))
{ {
if (userRecord.Item2 > DateTime.Now) if (userRecord.Item2 > DateTime.Now)
return userRecord.Item1; return userRecord.Item1;
else else
_Cache.TryRemove(username, out userRecord); _Cache.TryRemove(username, out userRecord);
} }
return null; return null;
} }
public static bool InvalidateValue(string Key) public static bool InvalidateValue(string Key)
{ {
Tuple<User, DateTime> userRecord; Tuple<User, DateTime> userRecord;
return _Cache.TryRemove(Key.ToLower(), out userRecord); return _Cache.TryRemove(Key.ToLower(), out userRecord);
} }
private static bool SetValue(string Key, User User) private static bool SetValue(string Key, User User)
{ {
string key = Key.ToLower(); string key = Key.ToLower();
Tuple<User, DateTime> userRecord = new Tuple<User, DateTime>(User, DateTime.Now.AddTicks(CacheTimeoutTicks)); Tuple<User, DateTime> userRecord = new Tuple<User, DateTime>(User, DateTime.Now.AddTicks(CacheTimeoutTicks));
if (_Cache.ContainsKey(key)) if (_Cache.ContainsKey(key))
{ {
Tuple<User, DateTime> oldUser; Tuple<User, DateTime> oldUser;
if (_Cache.TryGetValue(key, out oldUser)) if (_Cache.TryGetValue(key, out oldUser))
{ {
return _Cache.TryUpdate(key, userRecord, oldUser); return _Cache.TryUpdate(key, userRecord, oldUser);
} }
} }
return _Cache.TryAdd(key, userRecord); return _Cache.TryAdd(key, userRecord);
} }
private static void CleanStaleCache() private static void CleanStaleCache()
{ {
var usernames = _Cache.Keys.ToArray(); var usernames = _Cache.Keys.ToArray();
foreach (string username in usernames) foreach (string username in usernames)
{ {
Tuple<User, DateTime> userRecord; Tuple<User, DateTime> userRecord;
if (_Cache.TryGetValue(username, out userRecord)) if (_Cache.TryGetValue(username, out userRecord))
{ {
if (userRecord.Item2 <= DateTime.Now) if (userRecord.Item2 <= DateTime.Now)
_Cache.TryRemove(username, out userRecord); _Cache.TryRemove(username, out userRecord);
} }
} }
} }
//public void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler) //public void InitalizeScheduledTask(DiscoDataContext dbContext, IScheduler Scheduler)
//{ //{
// // Run @ every 15mins // // Run @ every 15mins
// // Next 15min interval // // Next 15min interval
// DateTime now = DateTime.Now; // DateTime now = DateTime.Now;
// int mins = (15 - (now.Minute % 15)); // int mins = (15 - (now.Minute % 15));
// if (mins < 10) // if (mins < 10)
// mins += 15; // mins += 15;
// DateTimeOffset startAt = new DateTimeOffset(now).AddMinutes(mins).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1); // DateTimeOffset startAt = new DateTimeOffset(now).AddMinutes(mins).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1);
// IJobDetail jobDetail = new JobDetailImpl("UserCache_CleanStaleCache", typeof(UserCache)); // IJobDetail jobDetail = new JobDetailImpl("UserCache_CleanStaleCache", typeof(UserCache));
// ITrigger trigger = TriggerBuilder.Create(). // ITrigger trigger = TriggerBuilder.Create().
// WithIdentity("UserCache_CleanStaleCacheTrigger").StartAt(startAt). // WithIdentity("UserCache_CleanStaleCacheTrigger").StartAt(startAt).
// WithSchedule(SimpleScheduleBuilder.RepeatMinutelyForever(15)). // WithSchedule(SimpleScheduleBuilder.RepeatMinutelyForever(15)).
// Build(); // Build();
// Scheduler.ScheduleJob(jobDetail, trigger); // Scheduler.ScheduleJob(jobDetail, trigger);
//} //}
public override string TaskName { get { return "User Cache - Clean Stale Cache"; } } public override string TaskName { get { return "User Cache - Clean Stale Cache"; } }
public override bool SingleInstanceTask { get { return true; } } public override bool SingleInstanceTask { get { return true; } }
public override bool CancelInitiallySupported { get { return false; } } public override bool CancelInitiallySupported { get { return false; } }
public override bool LogExceptionsOnly { get { return true; } } public override bool LogExceptionsOnly { get { return true; } }
public override void InitalizeScheduledTask(DiscoDataContext dbContext) public override void InitalizeScheduledTask(DiscoDataContext dbContext)
{ {
// Run @ every 15mins // Run @ every 15mins
// Next 15min interval // Next 15min interval
DateTime now = DateTime.Now; DateTime now = DateTime.Now;
int mins = (15 - (now.Minute % 15)); int mins = (15 - (now.Minute % 15));
if (mins < 10) if (mins < 10)
mins += 15; mins += 15;
DateTimeOffset startAt = new DateTimeOffset(now).AddMinutes(mins).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1); DateTimeOffset startAt = new DateTimeOffset(now).AddMinutes(mins).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1);
TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(startAt). TriggerBuilder triggerBuilder = TriggerBuilder.Create().StartAt(startAt).
WithSchedule(SimpleScheduleBuilder.RepeatMinutelyForever(15)); WithSchedule(SimpleScheduleBuilder.RepeatMinutelyForever(15));
this.ScheduleTask(triggerBuilder); this.ScheduleTask(triggerBuilder);
} }
protected override void ExecuteTask() protected override void ExecuteTask()
{ {
CleanStaleCache(); CleanStaleCache();
} }
} }
} }
+76 -76
View File
@@ -1,76 +1,76 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.Repository; using Disco.Models.Repository;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.BI.Search; using Disco.Models.BI.Search;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.DirectoryServices.ActiveDirectory; using System.DirectoryServices.ActiveDirectory;
using Disco.Services.Logging; using Disco.Services.Logging;
namespace Disco.BI.UserBI namespace Disco.BI.UserBI
{ {
public static class Utilities public static class Utilities
{ {
public static User LoadUser(DiscoDataContext dbContext, string Username) public static User LoadUser(DiscoDataContext dbContext, string Username)
{ {
// Machine Account ? // Machine Account ?
if (Username.EndsWith("$")) if (Username.EndsWith("$"))
{ {
return Interop.ActiveDirectory.ActiveDirectory.GetMachineAccount(Username).ToRepositoryUser(); return Interop.ActiveDirectory.ActiveDirectory.GetMachineAccount(Username).ToRepositoryUser();
} }
// User Account // User Account
User user = null; User user = null;
try try
{ {
var ADUser = Interop.ActiveDirectory.ActiveDirectory.GetUserAccount(Username); var ADUser = Interop.ActiveDirectory.ActiveDirectory.GetUserAccount(Username);
if (ADUser == null) if (ADUser == null)
throw new ArgumentException(string.Format("Invalid Username: '{0}'", Username), "Username"); throw new ArgumentException(string.Format("Invalid Username: '{0}'", Username), "Username");
user = ADUser.ToRepositoryUser(); user = ADUser.ToRepositoryUser();
} }
catch (COMException ex) catch (COMException ex)
{ {
// If "Server is not operational" then Try Cache // If "Server is not operational" then Try Cache
if (ex.ErrorCode != -2147016646) if (ex.ErrorCode != -2147016646)
{ {
throw ex; throw ex;
} }
SystemLog.LogException("Primary Domain Controller Down? Disco.BI.UserBI.Utilities.LoadUser", ex); SystemLog.LogException("Primary Domain Controller Down? Disco.BI.UserBI.Utilities.LoadUser", ex);
} }
catch (ActiveDirectoryOperationException ex) catch (ActiveDirectoryOperationException ex)
{ {
// Try From Cache... // Try From Cache...
SystemLog.LogException("Primary Domain Controller Down? Disco.BI.UserBI.Utilities.LoadUser", ex); SystemLog.LogException("Primary Domain Controller Down? Disco.BI.UserBI.Utilities.LoadUser", ex);
} }
// Update Repository // Update Repository
User existingUser; User existingUser;
if (user == null) if (user == null)
{ {
string username = Username.Contains(@"\") ? Username.Substring(Username.IndexOf(@"\") + 1) : Username; string username = Username.Contains(@"\") ? Username.Substring(Username.IndexOf(@"\") + 1) : Username;
existingUser = dbContext.Users.Find(username); existingUser = dbContext.Users.Find(username);
if (existingUser == null) if (existingUser == null)
throw new ArgumentException(string.Format("Invalid User - Not In Disco DB: '{0}'", Username), "Username"); throw new ArgumentException(string.Format("Invalid User - Not In Disco DB: '{0}'", Username), "Username");
else else
return existingUser; return existingUser;
} }
existingUser = dbContext.Users.Find(user.Id); existingUser = dbContext.Users.Find(user.Id);
if (existingUser == null) if (existingUser == null)
{ {
dbContext.Users.Add(user); dbContext.Users.Add(user);
} }
else else
{ {
existingUser.UpdateSelf(user); existingUser.UpdateSelf(user);
user = existingUser; user = existingUser;
} }
dbContext.SaveChanges(); dbContext.SaveChanges();
return user; return user;
} }
} }
} }
+83 -83
View File
@@ -1,83 +1,83 @@
using Disco.BI.Wireless.eduSTAR; using Disco.BI.Wireless.eduSTAR;
using Disco.Data.Configuration; using Disco.Data.Configuration;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.BI.Extensions; using Disco.BI.Extensions;
using Disco.Models.Repository; using Disco.Models.Repository;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Threading; using System.Threading;
namespace Disco.BI.Wireless namespace Disco.BI.Wireless
{ {
public abstract class BaseWirelessProvider public abstract class BaseWirelessProvider
{ {
protected DiscoDataContext dbContext; protected DiscoDataContext dbContext;
private static object _CertificateAllocateLock = System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(new object()); private static object _CertificateAllocateLock = System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(new object());
public static BaseWirelessProvider GetProvider(DiscoDataContext dbContext) public static BaseWirelessProvider GetProvider(DiscoDataContext dbContext)
{ {
string provider = dbContext.DiscoConfiguration.Wireless.Provider; string provider = dbContext.DiscoConfiguration.Wireless.Provider;
if (provider == "eduSTAR") if (provider == "eduSTAR")
{ {
return new eduSTARWirelessProvider(dbContext); return new eduSTARWirelessProvider(dbContext);
} }
throw new System.NotSupportedException(string.Format("Wireless Provider Not Supported: '{0}'", dbContext.DiscoConfiguration.Wireless.Provider)); throw new System.NotSupportedException(string.Format("Wireless Provider Not Supported: '{0}'", dbContext.DiscoConfiguration.Wireless.Provider));
} }
protected BaseWirelessProvider(DiscoDataContext dbContext) protected BaseWirelessProvider(DiscoDataContext dbContext)
{ {
this.dbContext = dbContext; this.dbContext = dbContext;
} }
private DeviceCertificate CertificateAllocate(ref Device repoDevice) private DeviceCertificate CertificateAllocate(ref Device repoDevice)
{ {
lock (BaseWirelessProvider._CertificateAllocateLock) lock (BaseWirelessProvider._CertificateAllocateLock)
{ {
this.FillCertificateAutoBuffer(); this.FillCertificateAutoBuffer();
int timeout = 60; int timeout = 60;
int freeCertCount = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == null && c.Enabled).Count(); int freeCertCount = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == null && c.Enabled).Count();
while (!(freeCertCount > 0 | timeout <= 0)) while (!(freeCertCount > 0 | timeout <= 0))
{ {
System.Threading.Thread.Sleep(500); System.Threading.Thread.Sleep(500);
freeCertCount = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == null && c.Enabled).Count(); freeCertCount = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == null && c.Enabled).Count();
timeout--; timeout--;
} }
DeviceCertificate cert = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == null && c.Enabled).FirstOrDefault(); DeviceCertificate cert = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == null && c.Enabled).FirstOrDefault();
if (cert == null) if (cert == null)
{ {
WirelessCertificatesLog.LogAllocationFailed(repoDevice.SerialNumber); WirelessCertificatesLog.LogAllocationFailed(repoDevice.SerialNumber);
throw new System.InvalidOperationException("Unable to Allocate a Wireless Certificate"); throw new System.InvalidOperationException("Unable to Allocate a Wireless Certificate");
} }
WirelessCertificatesLog.LogAllocated(cert.Name, repoDevice.SerialNumber); WirelessCertificatesLog.LogAllocated(cert.Name, repoDevice.SerialNumber);
cert.DeviceSerialNumber = repoDevice.SerialNumber; cert.DeviceSerialNumber = repoDevice.SerialNumber;
cert.AllocatedDate = System.DateTime.Now; cert.AllocatedDate = System.DateTime.Now;
this.dbContext.SaveChanges(); this.dbContext.SaveChanges();
return cert; return cert;
} }
} }
public DeviceCertificate Enrol(Device repoDevice) public DeviceCertificate Enrol(Device repoDevice)
{ {
DeviceCertificate allocatedCert = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == repoDevice.SerialNumber && c.Enabled).FirstOrDefault(); DeviceCertificate allocatedCert = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == repoDevice.SerialNumber && c.Enabled).FirstOrDefault();
if (allocatedCert != null) if (allocatedCert != null)
{ {
return allocatedCert; return allocatedCert;
} }
// Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3. // Removed 2012-06-14 G# - Properties moved to DeviceProfile model & DB Migrated in DBv3.
//if (repoDevice.DeviceProfile.Configuration(this.dbContext).AllocateWirelessCertificate) //if (repoDevice.DeviceProfile.Configuration(this.dbContext).AllocateWirelessCertificate)
if (repoDevice.DeviceProfile.AllocateCertificate) if (repoDevice.DeviceProfile.AllocateCertificate)
{ {
allocatedCert = this.CertificateAllocate(ref repoDevice); allocatedCert = this.CertificateAllocate(ref repoDevice);
return allocatedCert; return allocatedCert;
} }
else else
{ {
return null; return null;
} }
} }
protected abstract void FillCertificateAutoBuffer(); protected abstract void FillCertificateAutoBuffer();
public abstract void FillCertificateBuffer(int Amount); public abstract void FillCertificateBuffer(int Amount);
public abstract System.Collections.Generic.List<string> RemoveExistingCertificateNames(); public abstract System.Collections.Generic.List<string> RemoveExistingCertificateNames();
} }
} }
+304 -304
View File
@@ -1,304 +1,304 @@
using Disco.Logging; using Disco.Logging;
using Disco.Logging.Models; using Disco.Logging.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
namespace Disco.BI.Wireless namespace Disco.BI.Wireless
{ {
public class WirelessCertificatesLog : LogBase public class WirelessCertificatesLog : LogBase
{ {
public enum EventTypeIds public enum EventTypeIds
{ {
RetrievalStarting = 10, RetrievalStarting = 10,
RetrievalProgress, RetrievalProgress,
RetrievalFinished, RetrievalFinished,
RetrievalWarning = 15, RetrievalWarning = 15,
RetrievalError, RetrievalError,
RetrievalCertificateStarting = 20, RetrievalCertificateStarting = 20,
RetrievalCertificateFinished = 22, RetrievalCertificateFinished = 22,
RetrievalCertificateWarning = 25, RetrievalCertificateWarning = 25,
RetrievalCertificateError, RetrievalCertificateError,
Allocated = 40, Allocated = 40,
AllocationFailed = 50 AllocationFailed = 50
} }
private const int _ModuleId = 60; private const int _ModuleId = 60;
private static bool _IsCertificateRetrievalProcessing; private static bool _IsCertificateRetrievalProcessing;
private static string _CertificateRetrievalStatus; private static string _CertificateRetrievalStatus;
private static int _CertificateRetrievalProgress; private static int _CertificateRetrievalProgress;
public static WirelessCertificatesLog Current public static WirelessCertificatesLog Current
{ {
get get
{ {
return (WirelessCertificatesLog)LogContext.LogModules[60]; return (WirelessCertificatesLog)LogContext.LogModules[60];
} }
} }
public static bool IsCertificateRetrievalProcessing public static bool IsCertificateRetrievalProcessing
{ {
get get
{ {
return WirelessCertificatesLog._IsCertificateRetrievalProcessing; return WirelessCertificatesLog._IsCertificateRetrievalProcessing;
} }
} }
public override string ModuleDescription public override string ModuleDescription
{ {
get get
{ {
return "Wireless Certificates"; return "Wireless Certificates";
} }
} }
public override int ModuleId public override int ModuleId
{ {
get get
{ {
return 60; return 60;
} }
} }
public override string ModuleName public override string ModuleName
{ {
get get
{ {
return "WirelessCertificates"; return "WirelessCertificates";
} }
} }
[System.Diagnostics.DebuggerNonUserCode] [System.Diagnostics.DebuggerNonUserCode]
public WirelessCertificatesLog() public WirelessCertificatesLog()
{ {
} }
private static void Log(WirelessCertificatesLog.EventTypeIds EventTypeId, params object[] Args) private static void Log(WirelessCertificatesLog.EventTypeIds EventTypeId, params object[] Args)
{ {
WirelessCertificatesLog.Current.Log((int)EventTypeId, Args); WirelessCertificatesLog.Current.Log((int)EventTypeId, Args);
} }
public static void LogRetrievalStarting(int CertificateCount, int CertificateIdFrom, int CertificateIdTo) public static void LogRetrievalStarting(int CertificateCount, int CertificateIdFrom, int CertificateIdTo)
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalStarting, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalStarting, new object[]
{ {
CertificateCount, CertificateCount,
CertificateIdFrom, CertificateIdFrom,
CertificateIdTo CertificateIdTo
}); });
} }
public static void LogRetrievalFinished() public static void LogRetrievalFinished()
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalFinished, new object[0]); WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalFinished, new object[0]);
} }
public static void LogRetrievalWarning(string Message) public static void LogRetrievalWarning(string Message)
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalWarning, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalWarning, new object[]
{ {
Message Message
}); });
} }
public static void LogRetrievalError(string Message) public static void LogRetrievalError(string Message)
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalError, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalError, new object[]
{ {
Message Message
}); });
} }
public static void LogRetrievalCertificateStarting(string CertificateId) public static void LogRetrievalCertificateStarting(string CertificateId)
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalCertificateStarting, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalCertificateStarting, new object[]
{ {
CertificateId CertificateId
}); });
} }
public static void LogRetrievalCertificateFinished(string CertificateId) public static void LogRetrievalCertificateFinished(string CertificateId)
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalCertificateFinished, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalCertificateFinished, new object[]
{ {
CertificateId CertificateId
}); });
} }
public static void LogRetrievalCertificateWarning(string CertificateId, string Message) public static void LogRetrievalCertificateWarning(string CertificateId, string Message)
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalCertificateWarning, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalCertificateWarning, new object[]
{ {
CertificateId, CertificateId,
Message Message
}); });
} }
public static void LogRetrievalCertificateError(string CertificateId, string Message) public static void LogRetrievalCertificateError(string CertificateId, string Message)
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalCertificateError, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalCertificateError, new object[]
{ {
CertificateId, CertificateId,
Message Message
}); });
} }
public static void LogAllocated(string CertificateId, string DeviceSerialNumber) public static void LogAllocated(string CertificateId, string DeviceSerialNumber)
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.Allocated, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.Allocated, new object[]
{ {
CertificateId, CertificateId,
DeviceSerialNumber DeviceSerialNumber
}); });
} }
public static void LogAllocationFailed(string DeviceSerialNumber) public static void LogAllocationFailed(string DeviceSerialNumber)
{ {
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.AllocationFailed, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.AllocationFailed, new object[]
{ {
DeviceSerialNumber DeviceSerialNumber
}); });
} }
public static void LogCertificateRetrievalProgress(bool? IsProcessing, int? Progress, string Status) public static void LogCertificateRetrievalProgress(bool? IsProcessing, int? Progress, string Status)
{ {
bool flag = IsProcessing.HasValue; bool flag = IsProcessing.HasValue;
if (flag) if (flag)
{ {
WirelessCertificatesLog._IsCertificateRetrievalProcessing = IsProcessing.Value; WirelessCertificatesLog._IsCertificateRetrievalProcessing = IsProcessing.Value;
} }
flag = WirelessCertificatesLog._IsCertificateRetrievalProcessing; flag = WirelessCertificatesLog._IsCertificateRetrievalProcessing;
if (flag) if (flag)
{ {
bool flag2 = Status != null; bool flag2 = Status != null;
if (flag2) if (flag2)
{ {
WirelessCertificatesLog._CertificateRetrievalStatus = Status; WirelessCertificatesLog._CertificateRetrievalStatus = Status;
} }
flag2 = Progress.HasValue; flag2 = Progress.HasValue;
if (flag2) if (flag2)
{ {
WirelessCertificatesLog._CertificateRetrievalProgress = Progress.Value; WirelessCertificatesLog._CertificateRetrievalProgress = Progress.Value;
} }
} }
else else
{ {
WirelessCertificatesLog._CertificateRetrievalStatus = null; WirelessCertificatesLog._CertificateRetrievalStatus = null;
WirelessCertificatesLog._CertificateRetrievalProgress = 0; WirelessCertificatesLog._CertificateRetrievalProgress = 0;
} }
WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalProgress, new object[] WirelessCertificatesLog.Log(WirelessCertificatesLog.EventTypeIds.RetrievalProgress, new object[]
{ {
WirelessCertificatesLog._IsCertificateRetrievalProcessing, WirelessCertificatesLog._IsCertificateRetrievalProcessing,
WirelessCertificatesLog._CertificateRetrievalProgress, WirelessCertificatesLog._CertificateRetrievalProgress,
WirelessCertificatesLog._CertificateRetrievalStatus WirelessCertificatesLog._CertificateRetrievalStatus
}); });
} }
protected override System.Collections.Generic.List<LogEventType> LoadEventTypes() protected override System.Collections.Generic.List<LogEventType> LoadEventTypes()
{ {
return new System.Collections.Generic.List<LogEventType> return new System.Collections.Generic.List<LogEventType>
{ {
new LogEventType new LogEventType
{ {
Id = 10, Id = 10,
ModuleId = 60, ModuleId = 60,
Name = "Retrieval Starting", Name = "Retrieval Starting",
Format = "Starting retrieval of {0} certificate/s ({1} to {2})", Format = "Starting retrieval of {0} certificate/s ({1} to {2})",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 11, Id = 11,
ModuleId = 60, ModuleId = 60,
Name = "Retrieval Progress", Name = "Retrieval Progress",
Format = "Processing: {0}; {1}% Complete; Status: {2}", Format = "Processing: {0}; {1}% Complete; Status: {2}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = false, UsePersist = false,
UseDisplay = false UseDisplay = false
}, },
new LogEventType new LogEventType
{ {
Id = 12, Id = 12,
ModuleId = 60, ModuleId = 60,
Name = "Retrieval Finished", Name = "Retrieval Finished",
Format = "Retrieval of Certificates Complete", Format = "Retrieval of Certificates Complete",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 15, Id = 15,
ModuleId = 60, ModuleId = 60,
Name = "Retrieval Warning", Name = "Retrieval Warning",
Format = "Retrieval Warning: {0}", Format = "Retrieval Warning: {0}",
Severity = 1, Severity = 1,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 16, Id = 16,
ModuleId = 60, ModuleId = 60,
Name = "Retrieval Error", Name = "Retrieval Error",
Format = "Retrieval Error: {0}", Format = "Retrieval Error: {0}",
Severity = 2, Severity = 2,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 20, Id = 20,
ModuleId = 60, ModuleId = 60,
Name = "Retrieval Certificate Starting", Name = "Retrieval Certificate Starting",
Format = "Retrieving Certificate: {0}", Format = "Retrieving Certificate: {0}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 22, Id = 22,
ModuleId = 60, ModuleId = 60,
Name = "Retrieval Certificate Finished", Name = "Retrieval Certificate Finished",
Format = "Certificate Retrieved: {0}", Format = "Certificate Retrieved: {0}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 25, Id = 25,
ModuleId = 60, ModuleId = 60,
Name = "Retrieval Certificate Warning", Name = "Retrieval Certificate Warning",
Format = "{0} Certificate Warning: {1}", Format = "{0} Certificate Warning: {1}",
Severity = 1, Severity = 1,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 26, Id = 26,
ModuleId = 60, ModuleId = 60,
Name = "Retrieval Certificate Error", Name = "Retrieval Certificate Error",
Format = "{0} Certificate Error: {1}", Format = "{0} Certificate Error: {1}",
Severity = 2, Severity = 2,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 40, Id = 40,
ModuleId = 60, ModuleId = 60,
Name = "Allocated", Name = "Allocated",
Format = "Certificate {0} allocated to {1}", Format = "Certificate {0} allocated to {1}",
Severity = 0, Severity = 0,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
}, },
new LogEventType new LogEventType
{ {
Id = 50, Id = 50,
ModuleId = 60, ModuleId = 60,
Name = "Allocation Failed", Name = "Allocation Failed",
Format = "No certificates available for Device: {0}", Format = "No certificates available for Device: {0}",
Severity = 2, Severity = 2,
UseLive = true, UseLive = true,
UsePersist = true, UsePersist = true,
UseDisplay = true UseDisplay = true
} }
}; };
} }
} }
} }
@@ -1,283 +1,283 @@
using Disco.BI.Wireless.eduSTAR.eduSTARWirelessCertService; using Disco.BI.Wireless.eduSTAR.eduSTARWirelessCertService;
using Disco.Data.Repository; using Disco.Data.Repository;
using Disco.Models.Repository; using Disco.Models.Repository;
using Ionic.Zip; using Ionic.Zip;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Linq.Expressions; using System.Linq.Expressions;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.ServiceModel; using System.ServiceModel;
using System.ServiceModel.Channels; using System.ServiceModel.Channels;
using System.Threading; using System.Threading;
namespace Disco.BI.Wireless.eduSTAR namespace Disco.BI.Wireless.eduSTAR
{ {
public class eduSTARWirelessProvider : BaseWirelessProvider public class eduSTARWirelessProvider : BaseWirelessProvider
{ {
private class BulkLoadCertificatesContract private class BulkLoadCertificatesContract
{ {
public int Start { get; set; } public int Start { get; set; }
public int Count { get; set; } public int Count { get; set; }
} }
private static object _BulkLoadThreadLock = new object(); private static object _BulkLoadThreadLock = new object();
private static System.Threading.Thread _BulkLoadThread; private static System.Threading.Thread _BulkLoadThread;
public eduSTARWirelessProvider(DiscoDataContext dbContext) public eduSTARWirelessProvider(DiscoDataContext dbContext)
: base(dbContext) : base(dbContext)
{ {
} }
protected override void FillCertificateAutoBuffer() protected override void FillCertificateAutoBuffer()
{ {
int freeCertCount = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == null && c.Enabled).Count(); int freeCertCount = this.dbContext.DeviceCertificates.Where(c => c.DeviceSerialNumber == null && c.Enabled).Count();
if (freeCertCount <= this.dbContext.DiscoConfiguration.Wireless.CertificateAutoBufferLow) if (freeCertCount <= this.dbContext.DiscoConfiguration.Wireless.CertificateAutoBufferLow)
{ {
this.BulkLoadCertificates(0); this.BulkLoadCertificates(0);
} }
} }
public override void FillCertificateBuffer(int Amount) public override void FillCertificateBuffer(int Amount)
{ {
this.BulkLoadCertificates(Amount); this.BulkLoadCertificates(Amount);
} }
public override System.Collections.Generic.List<string> RemoveExistingCertificateNames() public override System.Collections.Generic.List<string> RemoveExistingCertificateNames()
{ {
return new System.Collections.Generic.List<string> return new System.Collections.Generic.List<string>
{ {
"(eduPaSS)", "(eduPaSS)",
"(CN=Computers, ?DC=services, ?DC=education, ?DC=vic, ?DC=gov, ?DC=au)" "(CN=Computers, ?DC=services, ?DC=education, ?DC=vic, ?DC=gov, ?DC=au)"
}; };
} }
private void BulkLoadCertificates(int Amount = 0) private void BulkLoadCertificates(int Amount = 0)
{ {
if (eduSTARWirelessProvider._BulkLoadThread == null) if (eduSTARWirelessProvider._BulkLoadThread == null)
{ {
lock (eduSTARWirelessProvider._BulkLoadThreadLock) lock (eduSTARWirelessProvider._BulkLoadThreadLock)
{ {
if (eduSTARWirelessProvider._BulkLoadThread == null) if (eduSTARWirelessProvider._BulkLoadThread == null)
{ {
int start = 0; int start = 0;
if (this.dbContext.DeviceCertificates.Count() > 0) if (this.dbContext.DeviceCertificates.Count() > 0)
{ {
start = this.dbContext.DeviceCertificates.Max(c => c.ProviderIndex) + 1; start = this.dbContext.DeviceCertificates.Max(c => c.ProviderIndex) + 1;
} }
int buffer = this.dbContext.DeviceCertificates.Count(c => c.DeviceSerialNumber == null && c.Enabled); int buffer = this.dbContext.DeviceCertificates.Count(c => c.DeviceSerialNumber == null && c.Enabled);
int count = this.dbContext.DiscoConfiguration.Wireless.CertificateAutoBufferMax - buffer; int count = this.dbContext.DiscoConfiguration.Wireless.CertificateAutoBufferMax - buffer;
if (Amount > 0) if (Amount > 0)
{ {
count = Amount; count = Amount;
} }
if (count > 0) if (count > 0)
{ {
eduSTARWirelessProvider.BulkLoadCertificatesContract contract = new eduSTARWirelessProvider.BulkLoadCertificatesContract eduSTARWirelessProvider.BulkLoadCertificatesContract contract = new eduSTARWirelessProvider.BulkLoadCertificatesContract
{ {
Start = start, Start = start,
Count = count Count = count
}; };
System.Threading.ParameterizedThreadStart threadStart = delegate(object a0) System.Threading.ParameterizedThreadStart threadStart = delegate(object a0)
{ {
this.BulkLoadCertificatesStart((eduSTARWirelessProvider.BulkLoadCertificatesContract)a0); this.BulkLoadCertificatesStart((eduSTARWirelessProvider.BulkLoadCertificatesContract)a0);
} }
; ;
eduSTARWirelessProvider._BulkLoadThread = new System.Threading.Thread(threadStart); eduSTARWirelessProvider._BulkLoadThread = new System.Threading.Thread(threadStart);
eduSTARWirelessProvider._BulkLoadThread.Start(contract); eduSTARWirelessProvider._BulkLoadThread.Start(contract);
} }
} }
} }
} }
} }
private void BulkLoadCertificatesStart(eduSTARWirelessProvider.BulkLoadCertificatesContract contract) private void BulkLoadCertificatesStart(eduSTARWirelessProvider.BulkLoadCertificatesContract contract)
{ {
try try
{ {
WirelessCertificatesLog.LogRetrievalStarting(contract.Count, contract.Start, contract.Start + contract.Count - 1); WirelessCertificatesLog.LogRetrievalStarting(contract.Count, contract.Start, contract.Start + contract.Count - 1);
WirelessCertificatesLog.LogCertificateRetrievalProgress(true, 0, string.Format("Starting Bulk Retrieval (Loading {0} Certificate/s)", contract.Count)); WirelessCertificatesLog.LogCertificateRetrievalProgress(true, 0, string.Format("Starting Bulk Retrieval (Loading {0} Certificate/s)", contract.Count));
DiscoDataContext dbLocalContext = new DiscoDataContext(); DiscoDataContext dbLocalContext = new DiscoDataContext();
try try
{ {
WirelessCertServiceSoapClient proxy = this.GetProxy(); WirelessCertServiceSoapClient proxy = this.GetProxy();
try try
{ {
int num = contract.Start + contract.Count - 1; int num = contract.Start + contract.Count - 1;
int index = contract.Start; int index = contract.Start;
while (true) while (true)
{ {
int num2 = num; int num2 = num;
if (index > num2) if (index > num2)
{ {
break; break;
} }
WirelessCertificatesLog.LogCertificateRetrievalProgress(true, (int)System.Math.Round(unchecked(((double)checked(index - contract.Start) + 0.5) / (double)contract.Count * 100.0)), string.Format("Retrieving Certificate {0} of {1}", index - contract.Start + 1, contract.Count)); WirelessCertificatesLog.LogCertificateRetrievalProgress(true, (int)System.Math.Round(unchecked(((double)checked(index - contract.Start) + 0.5) / (double)contract.Count * 100.0)), string.Format("Retrieving Certificate {0} of {1}", index - contract.Start + 1, contract.Count));
DeviceCertificate cert = this.LoadCertificate(index, proxy, dbLocalContext); DeviceCertificate cert = this.LoadCertificate(index, proxy, dbLocalContext);
dbLocalContext.DeviceCertificates.Add(cert); dbLocalContext.DeviceCertificates.Add(cert);
dbLocalContext.SaveChanges(); dbLocalContext.SaveChanges();
WirelessCertificatesLog.LogRetrievalCertificateFinished(cert.Name); WirelessCertificatesLog.LogRetrievalCertificateFinished(cert.Name);
index++; index++;
} }
} }
finally finally
{ {
bool flag = proxy != null; bool flag = proxy != null;
if (flag) if (flag)
{ {
((System.IDisposable)proxy).Dispose(); ((System.IDisposable)proxy).Dispose();
} }
} }
} }
finally finally
{ {
bool flag = dbLocalContext != null; bool flag = dbLocalContext != null;
if (flag) if (flag)
{ {
((System.IDisposable)dbLocalContext).Dispose(); ((System.IDisposable)dbLocalContext).Dispose();
} }
} }
} }
catch (System.Exception ex) catch (System.Exception ex)
{ {
WirelessCertificatesLog.LogRetrievalError(string.Format("[{0}] {1}", ex.GetType().Name, ex.Message)); WirelessCertificatesLog.LogRetrievalError(string.Format("[{0}] {1}", ex.GetType().Name, ex.Message));
throw ex; throw ex;
} }
finally finally
{ {
lock (eduSTARWirelessProvider._BulkLoadThreadLock) lock (eduSTARWirelessProvider._BulkLoadThreadLock)
{ {
eduSTARWirelessProvider._BulkLoadThread = null; eduSTARWirelessProvider._BulkLoadThread = null;
} }
WirelessCertificatesLog.LogRetrievalFinished(); WirelessCertificatesLog.LogRetrievalFinished();
WirelessCertificatesLog.LogCertificateRetrievalProgress(false, null, null); WirelessCertificatesLog.LogCertificateRetrievalProgress(false, null, null);
} }
} }
private DeviceCertificate LoadCertificate(int Index, DiscoDataContext dbContext) private DeviceCertificate LoadCertificate(int Index, DiscoDataContext dbContext)
{ {
DeviceCertificate LoadCertificate; DeviceCertificate LoadCertificate;
try try
{ {
WirelessCertServiceSoapClient proxy = this.GetProxy(); WirelessCertServiceSoapClient proxy = this.GetProxy();
try try
{ {
LoadCertificate = this.LoadCertificate(Index, proxy, dbContext); LoadCertificate = this.LoadCertificate(Index, proxy, dbContext);
} }
finally finally
{ {
bool flag = proxy != null; bool flag = proxy != null;
if (flag) if (flag)
{ {
((System.IDisposable)proxy).Dispose(); ((System.IDisposable)proxy).Dispose();
} }
} }
} }
catch (System.Exception ex) catch (System.Exception ex)
{ {
WirelessCertificatesLog.LogRetrievalCertificateError(Index.ToString(), string.Format("[{0}] {1}", ex.GetType().Name, ex.Message)); WirelessCertificatesLog.LogRetrievalCertificateError(Index.ToString(), string.Format("[{0}] {1}", ex.GetType().Name, ex.Message));
throw ex; throw ex;
} }
return LoadCertificate; return LoadCertificate;
} }
private DeviceCertificate LoadCertificate(int Index, WirelessCertServiceSoapClient Proxy, DiscoDataContext dbContext) private DeviceCertificate LoadCertificate(int Index, WirelessCertServiceSoapClient Proxy, DiscoDataContext dbContext)
{ {
bool flag = string.IsNullOrWhiteSpace(dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountSchoolId); bool flag = string.IsNullOrWhiteSpace(dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountSchoolId);
if (flag) if (flag)
{ {
throw new System.ArgumentException("Wireless Certificates: Invalid ServiceAccount SchoolId"); throw new System.ArgumentException("Wireless Certificates: Invalid ServiceAccount SchoolId");
} }
flag = string.IsNullOrWhiteSpace(dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountUsername); flag = string.IsNullOrWhiteSpace(dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountUsername);
if (flag) if (flag)
{ {
throw new System.ArgumentException("Wireless Certificates: Invalid ServiceAccount Username"); throw new System.ArgumentException("Wireless Certificates: Invalid ServiceAccount Username");
} }
flag = string.IsNullOrWhiteSpace(dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountPassword); flag = string.IsNullOrWhiteSpace(dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountPassword);
if (flag) if (flag)
{ {
throw new System.ArgumentException("Wireless Certificates: Invalid ServiceAccount Password"); throw new System.ArgumentException("Wireless Certificates: Invalid ServiceAccount Password");
} }
DeviceCertificate cert = new DeviceCertificate DeviceCertificate cert = new DeviceCertificate
{ {
ProviderIndex = Index, ProviderIndex = Index,
Name = string.Format("{0}-{1}", dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountSchoolId, Index.ToString("00000")), Name = string.Format("{0}-{1}", dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountSchoolId, Index.ToString("00000")),
Enabled = true Enabled = true
}; };
WirelessCertificatesLog.LogRetrievalCertificateStarting(cert.Name); WirelessCertificatesLog.LogRetrievalCertificateStarting(cert.Name);
string response; string response;
try try
{ {
response = Proxy.GetWirelessCert(dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountSchoolId, cert.Name, "password", dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountUsername, dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountPassword); response = Proxy.GetWirelessCert(dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountSchoolId, cert.Name, "password", dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountUsername, dbContext.DiscoConfiguration.Wireless.eduSTAR_ServiceAccountPassword);
} }
catch (System.Exception ex) catch (System.Exception ex)
{ {
WirelessCertificatesLog.LogRetrievalCertificateError(cert.Name, ex.Message); WirelessCertificatesLog.LogRetrievalCertificateError(cert.Name, ex.Message);
throw ex; throw ex;
} }
try try
{ {
byte[] responseBytes = System.Convert.FromBase64String(response); byte[] responseBytes = System.Convert.FromBase64String(response);
System.IO.MemoryStream responseByteStream = new System.IO.MemoryStream(responseBytes); System.IO.MemoryStream responseByteStream = new System.IO.MemoryStream(responseBytes);
try try
{ {
ZipFile responseZip = ZipFile.Read(responseByteStream); ZipFile responseZip = ZipFile.Read(responseByteStream);
ZipEntry certFile = responseZip.FirstOrDefault((ZipEntry ze) => ze.FileName.EndsWith(".pfx", System.StringComparison.InvariantCultureIgnoreCase)); ZipEntry certFile = responseZip.FirstOrDefault((ZipEntry ze) => ze.FileName.EndsWith(".pfx", System.StringComparison.InvariantCultureIgnoreCase));
System.IO.MemoryStream certByteStream = new System.IO.MemoryStream(); System.IO.MemoryStream certByteStream = new System.IO.MemoryStream();
try try
{ {
certFile.Extract(certByteStream); certFile.Extract(certByteStream);
cert.Content = certByteStream.ToArray(); cert.Content = certByteStream.ToArray();
} }
finally finally
{ {
flag = (certByteStream != null); flag = (certByteStream != null);
if (flag) if (flag)
{ {
((System.IDisposable)certByteStream).Dispose(); ((System.IDisposable)certByteStream).Dispose();
} }
} }
} }
finally finally
{ {
flag = (responseByteStream != null); flag = (responseByteStream != null);
if (flag) if (flag)
{ {
((System.IDisposable)responseByteStream).Dispose(); ((System.IDisposable)responseByteStream).Dispose();
} }
} }
} }
catch (System.Exception ex2) catch (System.Exception ex2)
{ {
if (response.Contains("Computer with this name already exists")) if (response.Contains("Computer with this name already exists"))
{ {
WirelessCertificatesLog.LogRetrievalCertificateWarning(cert.Name, "Already exists on eduSTAR server, disabling and skipping."); WirelessCertificatesLog.LogRetrievalCertificateWarning(cert.Name, "Already exists on eduSTAR server, disabling and skipping.");
cert.ExpirationDate = System.DateTime.Now; cert.ExpirationDate = System.DateTime.Now;
cert.Enabled = false; cert.Enabled = false;
cert.Content = null; cert.Content = null;
return cert; return cert;
} }
throw new System.InvalidOperationException(string.Format("Unable to Uncompress (Server returned: {0})", response), ex2); throw new System.InvalidOperationException(string.Format("Unable to Uncompress (Server returned: {0})", response), ex2);
} }
try try
{ {
X509Certificate2 x509Cert = new X509Certificate2(cert.Content, "password"); X509Certificate2 x509Cert = new X509Certificate2(cert.Content, "password");
cert.ExpirationDate = x509Cert.NotAfter; cert.ExpirationDate = x509Cert.NotAfter;
} }
catch (System.Exception ex3) catch (System.Exception ex3)
{ {
throw new System.InvalidOperationException("Invalid Certificate returned by Server", ex3); throw new System.InvalidOperationException("Invalid Certificate returned by Server", ex3);
} }
return cert; return cert;
} }
private WirelessCertServiceSoapClient GetProxy() private WirelessCertServiceSoapClient GetProxy()
{ {
BasicHttpBinding binding = new BasicHttpBinding(); BasicHttpBinding binding = new BasicHttpBinding();
// Don't Use Proxy // Don't Use Proxy
binding.UseDefaultWebProxy = false; binding.UseDefaultWebProxy = false;
binding.ProxyAddress = null; binding.ProxyAddress = null;
binding.Security.Mode = BasicHttpSecurityMode.Transport; binding.Security.Mode = BasicHttpSecurityMode.Transport;
binding.MaxReceivedMessageSize = 524288L; binding.MaxReceivedMessageSize = 524288L;
binding.ReaderQuotas.MaxStringContentLength = 524288; binding.ReaderQuotas.MaxStringContentLength = 524288;
EndpointAddress endpointAddress = new EndpointAddress(new Uri("https://www.eduweb.vic.gov.au/edustar/WirelessCertWS/wirelesscertws.asmx"), new AddressHeader[0]); EndpointAddress endpointAddress = new EndpointAddress(new Uri("https://www.eduweb.vic.gov.au/edustar/WirelessCertWS/wirelesscertws.asmx"), new AddressHeader[0]);
return new WirelessCertServiceSoapClient(binding, endpointAddress); return new WirelessCertServiceSoapClient(binding, endpointAddress);
} }
} }
} }
+113 -113
View File
@@ -1,113 +1,113 @@
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// <auto-generated> // <auto-generated>
// This code was generated by a tool. // This code was generated by a tool.
// Runtime Version:4.0.30319.17929 // Runtime Version:4.0.30319.17929
// //
// Changes to this file may cause incorrect behavior and will be lost if // Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated. // the code is regenerated.
// </auto-generated> // </auto-generated>
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
namespace Disco.Properties { namespace Disco.Properties {
using System; using System;
/// <summary> /// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc. /// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary> /// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder // This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio. // class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen // To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project. // with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources { internal class Resources {
private static global::System.Resources.ResourceManager resourceMan; private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture; private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() { internal Resources() {
} }
/// <summary> /// <summary>
/// Returns the cached ResourceManager instance used by this class. /// Returns the cached ResourceManager instance used by this class.
/// </summary> /// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager { internal static global::System.Resources.ResourceManager ResourceManager {
get { get {
if (object.ReferenceEquals(resourceMan, null)) { if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Disco.Properties.Resources", typeof(Resources).Assembly); global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Disco.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp; resourceMan = temp;
} }
return resourceMan; return resourceMan;
} }
} }
/// <summary> /// <summary>
/// Overrides the current thread's CurrentUICulture property for all /// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class. /// resource lookups using this strongly typed resource class.
/// </summary> /// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture { internal static global::System.Globalization.CultureInfo Culture {
get { get {
return resourceCulture; return resourceCulture;
} }
set { set {
resourceCulture = value; resourceCulture = value;
} }
} }
/// <summary> /// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap MimeType_doc48 { internal static System.Drawing.Bitmap MimeType_doc48 {
get { get {
object obj = ResourceManager.GetObject("MimeType_doc48", resourceCulture); object obj = ResourceManager.GetObject("MimeType_doc48", resourceCulture);
return ((System.Drawing.Bitmap)(obj)); return ((System.Drawing.Bitmap)(obj));
} }
} }
/// <summary> /// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap MimeType_img16 { internal static System.Drawing.Bitmap MimeType_img16 {
get { get {
object obj = ResourceManager.GetObject("MimeType_img16", resourceCulture); object obj = ResourceManager.GetObject("MimeType_img16", resourceCulture);
return ((System.Drawing.Bitmap)(obj)); return ((System.Drawing.Bitmap)(obj));
} }
} }
/// <summary> /// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap MimeType_pdf16 { internal static System.Drawing.Bitmap MimeType_pdf16 {
get { get {
object obj = ResourceManager.GetObject("MimeType_pdf16", resourceCulture); object obj = ResourceManager.GetObject("MimeType_pdf16", resourceCulture);
return ((System.Drawing.Bitmap)(obj)); return ((System.Drawing.Bitmap)(obj));
} }
} }
/// <summary> /// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap MimeType_pdf48 { internal static System.Drawing.Bitmap MimeType_pdf48 {
get { get {
object obj = ResourceManager.GetObject("MimeType_pdf48", resourceCulture); object obj = ResourceManager.GetObject("MimeType_pdf48", resourceCulture);
return ((System.Drawing.Bitmap)(obj)); return ((System.Drawing.Bitmap)(obj));
} }
} }
/// <summary> /// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap. /// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary> /// </summary>
internal static System.Drawing.Bitmap MimeType_unknown48 { internal static System.Drawing.Bitmap MimeType_unknown48 {
get { get {
object obj = ResourceManager.GetObject("MimeType_unknown48", resourceCulture); object obj = ResourceManager.GetObject("MimeType_unknown48", resourceCulture);
return ((System.Drawing.Bitmap)(obj)); return ((System.Drawing.Bitmap)(obj));
} }
} }
} }
} }
+135 -135
View File
@@ -1,136 +1,136 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value> <value>[base64 mime encoded serialized .NET Framework object]</value>
</data> </data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType> <xsd:complexType>
<xsd:choice maxOccurs="unbounded"> <xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata"> <xsd:element name="metadata">
<xsd:complexType> <xsd:complexType>
<xsd:sequence> <xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" /> <xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence> </xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" /> <xsd:attribute ref="xml:space" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="assembly"> <xsd:element name="assembly">
<xsd:complexType> <xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="data"> <xsd:element name="data">
<xsd:complexType> <xsd:complexType>
<xsd:sequence> <xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence> </xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" /> <xsd:attribute ref="xml:space" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="resheader"> <xsd:element name="resheader">
<xsd:complexType> <xsd:complexType>
<xsd:sequence> <xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence> </xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" /> <xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
</xsd:choice> </xsd:choice>
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
</xsd:schema> </xsd:schema>
<resheader name="resmimetype"> <resheader name="resmimetype">
<value>text/microsoft-resx</value> <value>text/microsoft-resx</value>
</resheader> </resheader>
<resheader name="version"> <resheader name="version">
<value>2.0</value> <value>2.0</value>
</resheader> </resheader>
<resheader name="reader"> <resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="MimeType_doc48" type="System.Resources.ResXFileRef, System.Windows.Forms"> <data name="MimeType_doc48" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-doc48.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value> <value>..\Resources\MimeType-doc48.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data> </data>
<data name="MimeType_img16" type="System.Resources.ResXFileRef, System.Windows.Forms"> <data name="MimeType_img16" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-img16.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value> <value>..\Resources\MimeType-img16.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data> </data>
<data name="MimeType_pdf16" type="System.Resources.ResXFileRef, System.Windows.Forms"> <data name="MimeType_pdf16" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-pdf16.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value> <value>..\Resources\MimeType-pdf16.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data> </data>
<data name="MimeType_pdf48" type="System.Resources.ResXFileRef, System.Windows.Forms"> <data name="MimeType_pdf48" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-pdf48.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value> <value>..\Resources\MimeType-pdf48.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data> </data>
<data name="MimeType_unknown48" type="System.Resources.ResXFileRef, System.Windows.Forms"> <data name="MimeType_unknown48" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\MimeType-unknown48.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value> <value>..\Resources\MimeType-unknown48.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data> </data>
</root> </root>
+20 -20
View File
@@ -1,21 +1,21 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<configSections> <configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections> </configSections>
<system.serviceModel> <system.serviceModel>
<bindings /> <bindings />
<client /> <client />
</system.serviceModel> </system.serviceModel>
<entityFramework> <entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters> <parameters>
<parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" /> <parameter value="Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters> </parameters>
</defaultConnectionFactory> </defaultConnectionFactory>
</entityFramework> </entityFramework>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup> </startup>
</configuration> </configuration>
+8 -8
View File
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="EntityFramework" version="5.0.0" targetFramework="net45" /> <package id="EntityFramework" version="5.0.0" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" /> <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" />
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" /> <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" />
<package id="SignalR.Hosting.AspNet" version="0.5.3" targetFramework="net45" /> <package id="SignalR.Hosting.AspNet" version="0.5.3" targetFramework="net45" />
<package id="SignalR.Hosting.Common" version="0.5.3" targetFramework="net45" /> <package id="SignalR.Hosting.Common" version="0.5.3" targetFramework="net45" />
<package id="SignalR.Server" version="0.5.3" targetFramework="net45" /> <package id="SignalR.Server" version="0.5.3" targetFramework="net45" />
</packages> </packages>
+6 -6
View File
@@ -1,6 +1,6 @@
<?xml version="1.0"?> <?xml version="1.0"?>
<configuration> <configuration>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/>
</startup> </startup>
</configuration> </configuration>
+140 -140
View File
@@ -1,141 +1,141 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D6B85A86-0FAA-4B04-BC9E-D01A08C03387}</ProjectGuid> <ProjectGuid>{D6B85A86-0FAA-4B04-BC9E-D01A08C03387}</ProjectGuid>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Disco.Client</RootNamespace> <RootNamespace>Disco.Client</RootNamespace>
<AssemblyName>Disco.Client</AssemblyName> <AssemblyName>Disco.Client</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<TargetFrameworkProfile>Client</TargetFrameworkProfile> <TargetFrameworkProfile>Client</TargetFrameworkProfile>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir> <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages> <RestorePackages>true</RestorePackages>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<StartupObject>Disco.Client.Program</StartupObject> <StartupObject>Disco.Client.Program</StartupObject>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent> <RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<ApplicationIcon>Icon.ico</ApplicationIcon> <ApplicationIcon>Icon.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>
<PropertyGroup /> <PropertyGroup />
<PropertyGroup> <PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest> <ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> <Reference Include="Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath> <HintPath>..\packages\Newtonsoft.Json.4.5.11\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.DirectoryServices" /> <Reference Include="System.DirectoryServices" />
<Reference Include="System.Management" /> <Reference Include="System.Management" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="..\Disco.Models\ClientServices\Enrol.cs"> <Compile Include="..\Disco.Models\ClientServices\Enrol.cs">
<Link>Models\ClientServices\Enrol.cs</Link> <Link>Models\ClientServices\Enrol.cs</Link>
</Compile> </Compile>
<Compile Include="..\Disco.Models\ClientServices\EnrolResponse.cs"> <Compile Include="..\Disco.Models\ClientServices\EnrolResponse.cs">
<Link>Models\ClientServices\EnrolResponse.cs</Link> <Link>Models\ClientServices\EnrolResponse.cs</Link>
</Compile> </Compile>
<Compile Include="..\Disco.Models\ClientServices\MacEnrol.cs"> <Compile Include="..\Disco.Models\ClientServices\MacEnrol.cs">
<Link>Models\ClientServices\MacEnrol.cs</Link> <Link>Models\ClientServices\MacEnrol.cs</Link>
</Compile> </Compile>
<Compile Include="..\Disco.Models\ClientServices\MacEnrolResponse.cs"> <Compile Include="..\Disco.Models\ClientServices\MacEnrolResponse.cs">
<Link>Models\ClientServices\MacEnrolResponse.cs</Link> <Link>Models\ClientServices\MacEnrolResponse.cs</Link>
</Compile> </Compile>
<Compile Include="..\Disco.Models\ClientServices\MacSecureEnrolResponse.cs"> <Compile Include="..\Disco.Models\ClientServices\MacSecureEnrolResponse.cs">
<Link>Models\ClientServices\MacSecureEnrolResponse.cs</Link> <Link>Models\ClientServices\MacSecureEnrolResponse.cs</Link>
</Compile> </Compile>
<Compile Include="..\Disco.Models\ClientServices\ServiceBase.cs"> <Compile Include="..\Disco.Models\ClientServices\ServiceBase.cs">
<Link>Models\ClientServices\ServiceBase.cs</Link> <Link>Models\ClientServices\ServiceBase.cs</Link>
</Compile> </Compile>
<Compile Include="..\Disco.Models\ClientServices\WhoAmI.cs"> <Compile Include="..\Disco.Models\ClientServices\WhoAmI.cs">
<Link>Models\ClientServices\WhoAmI.cs</Link> <Link>Models\ClientServices\WhoAmI.cs</Link>
</Compile> </Compile>
<Compile Include="..\Disco.Models\ClientServices\WhoAmIResponse.cs"> <Compile Include="..\Disco.Models\ClientServices\WhoAmIResponse.cs">
<Link>Models\ClientServices\WhoAmIResponse.cs</Link> <Link>Models\ClientServices\WhoAmIResponse.cs</Link>
</Compile> </Compile>
<Compile Include="ErrorReporting.cs" /> <Compile Include="ErrorReporting.cs" />
<Compile Include="Extensions\ClientServiceException.cs" /> <Compile Include="Extensions\ClientServiceException.cs" />
<Compile Include="Extensions\ClientServicesExtensions.cs" /> <Compile Include="Extensions\ClientServicesExtensions.cs" />
<Compile Include="Extensions\EnrolExtensions.cs" /> <Compile Include="Extensions\EnrolExtensions.cs" />
<Compile Include="Extensions\WhoAmIExtensions.cs" /> <Compile Include="Extensions\WhoAmIExtensions.cs" />
<Compile Include="Interop\Certificates.cs" /> <Compile Include="Interop\Certificates.cs" />
<Compile Include="Interop\LocalAuthentication.cs" /> <Compile Include="Interop\LocalAuthentication.cs" />
<Compile Include="Interop\Network.cs" /> <Compile Include="Interop\Network.cs" />
<Compile Include="Presentation.cs" /> <Compile Include="Presentation.cs" />
<Compile Include="Interop\SystemAudit.cs" /> <Compile Include="Interop\SystemAudit.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="App.config" /> <None Include="App.config" />
<None Include="Package Creation\PreparationClient.zip" /> <None Include="Package Creation\PreparationClient.zip" />
<None Include="packages.config" /> <None Include="packages.config" />
<None Include="Properties\app.manifest" /> <None Include="Properties\app.manifest" />
<None Include="Start.bat"> <None Include="Start.bat">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="PsExec.exe"> <None Include="PsExec.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Include="Icon.ico" /> <Content Include="Icon.ico" />
<None Include="Package Creation\7z.dll" /> <None Include="Package Creation\7z.dll" />
<None Include="Package Creation\7z.exe" /> <None Include="Package Creation\7z.exe" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<ProjectExtensions> <ProjectExtensions>
<VisualStudio> <VisualStudio>
<UserProperties BuildVersion_UseGlobalSettings="True" BuildVersion_DetectChanges="False" BuildVersion_StartDate="2001/1/1" BuildVersion_BuildAction="ReBuild" /> <UserProperties BuildVersion_UseGlobalSettings="True" BuildVersion_DetectChanges="False" BuildVersion_StartDate="2001/1/1" BuildVersion_BuildAction="ReBuild" />
</VisualStudio> </VisualStudio>
</ProjectExtensions> </ProjectExtensions>
<PropertyGroup> <PropertyGroup>
<PostBuildEvent>DEL "$(ProjectDir)Package Creation\PreparationClient.zip" <PostBuildEvent>DEL "$(ProjectDir)Package Creation\PreparationClient.zip"
"$(ProjectDir)Package Creation\7z.exe" a -tzip "$(ProjectDir)Package Creation\PreparationClient.zip" "$(TargetDir)*.*" -x!*.tmp -x!*.vshost.* -x!Newtonsoft.Json.xml -x!*.pdb "$(ProjectDir)Package Creation\7z.exe" a -tzip "$(ProjectDir)Package Creation\PreparationClient.zip" "$(TargetDir)*.*" -x!*.tmp -x!*.vshost.* -x!Newtonsoft.Json.xml -x!*.pdb
COPY "$(ProjectDir)Package Creation\PreparationClient.zip" "$(ProjectDir)..\Disco.Web\ClientBin"</PostBuildEvent> COPY "$(ProjectDir)Package Creation\PreparationClient.zip" "$(ProjectDir)..\Disco.Web\ClientBin"</PostBuildEvent>
</PropertyGroup> </PropertyGroup>
<Import Project="$(SolutionDir)\.nuget\nuget.targets" /> <Import Project="$(SolutionDir)\.nuget\nuget.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">
</Target> </Target>
<Target Name="AfterBuild"> <Target Name="AfterBuild">
</Target> </Target>
--> -->
</Project> </Project>
+192 -192
View File
@@ -1,192 +1,192 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using Disco.Client.Extensions; using Disco.Client.Extensions;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Disco.Client namespace Disco.Client
{ {
public static class ErrorReporting public static class ErrorReporting
{ {
private const string ServicePathTemplate = "http://DISCO:9292/Services/Client/ClientError"; private const string ServicePathTemplate = "http://DISCO:9292/Services/Client/ClientError";
public static string DeviceIdentifier { get; set; } public static string DeviceIdentifier { get; set; }
public static string EnrolmentSessionId { get; set; } public static string EnrolmentSessionId { get; set; }
public static void ReportError(Exception Ex, bool ReportToServer) public static void ReportError(Exception Ex, bool ReportToServer)
{ {
bool isClientServiceException = Ex is ClientServiceException; bool isClientServiceException = Ex is ClientServiceException;
ErrorReport report = new ErrorReport() ErrorReport report = new ErrorReport()
{ {
DeviceIdentifier = DeviceIdentifier, DeviceIdentifier = DeviceIdentifier,
SessionId = EnrolmentSessionId, SessionId = EnrolmentSessionId,
JsonException = Ex.IntenseExceptionSerialization() JsonException = Ex.IntenseExceptionSerialization()
}; };
try try
{ {
LogToFile(report); LogToFile(report);
} }
catch (Exception) { } catch (Exception) { }
try try
{ {
LogToEventLog(report); LogToEventLog(report);
} }
catch (Exception) { } catch (Exception) { }
// Don't log server errors back to the server // Don't log server errors back to the server
if (!isClientServiceException && ReportToServer) if (!isClientServiceException && ReportToServer)
{ {
try try
{ {
LogToServer(report); LogToServer(report);
} }
catch (Exception) { } catch (Exception) { }
} }
try try
{ {
Presentation.WriteFatalError(Ex); Presentation.WriteFatalError(Ex);
} }
catch (Exception) { } catch (Exception) { }
} }
#region Log Actions #region Log Actions
private static void LogToFile(ErrorReport report) private static void LogToFile(ErrorReport report)
{ {
var logPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ErrorLog.csv"); var logPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ErrorLog.csv");
using (var streamWriter = File.AppendText(logPath)) using (var streamWriter = File.AppendText(logPath))
{ {
streamWriter.Write(DateTime.Now.ToString("s")); streamWriter.Write(DateTime.Now.ToString("s"));
streamWriter.Write(","); streamWriter.Write(",");
streamWriter.Write(report.DeviceIdentifier); streamWriter.Write(report.DeviceIdentifier);
streamWriter.Write(",\""); streamWriter.Write(",\"");
streamWriter.Write(report.JsonException); streamWriter.Write(report.JsonException);
streamWriter.Write("\""); streamWriter.Write("\"");
streamWriter.Flush(); streamWriter.Flush();
} }
} }
private static void LogToEventLog(ErrorReport report) private static void LogToEventLog(ErrorReport report)
{ {
string eventSource = "Disco Client"; string eventSource = "Disco Client";
if (!EventLog.SourceExists(eventSource)) if (!EventLog.SourceExists(eventSource))
EventLog.CreateEventSource(eventSource, "Application"); EventLog.CreateEventSource(eventSource, "Application");
EventLog.WriteEntry(eventSource, report.JsonException, EventLogEntryType.Error, 400); EventLog.WriteEntry(eventSource, report.JsonException, EventLogEntryType.Error, 400);
} }
private static void LogToServer(ErrorReport report) private static void LogToServer(ErrorReport report)
{ {
string reportJson = JsonConvert.SerializeObject(report); string reportJson = JsonConvert.SerializeObject(report);
string reportResponse; string reportResponse;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServicePathTemplate); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServicePathTemplate);
request.UserAgent = string.Format("Disco-Client/{0}", Assembly.GetExecutingAssembly().GetName().Version.ToString(3)); request.UserAgent = string.Format("Disco-Client/{0}", Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
request.ContentType = "application/json"; request.ContentType = "application/json";
request.Method = WebRequestMethods.Http.Post; request.Method = WebRequestMethods.Http.Post;
request.UseDefaultCredentials = true; request.UseDefaultCredentials = true;
request.Timeout = 300000; // 5 Minutes request.Timeout = 300000; // 5 Minutes
using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream())) using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream()))
{ {
requestWriter.Write(reportJson); requestWriter.Write(reportJson);
} }
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{ {
using (StreamReader responseReader = new StreamReader(response.GetResponseStream())) using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
{ {
reportResponse = responseReader.ReadToEnd(); reportResponse = responseReader.ReadToEnd();
} }
} }
System.Diagnostics.Debug.WriteLine("Error Report Logged to Server; Response: {0}", reportResponse); System.Diagnostics.Debug.WriteLine("Error Report Logged to Server; Response: {0}", reportResponse);
} }
#endregion #endregion
public class ErrorReport public class ErrorReport
{ {
public string SessionId { get; set; } public string SessionId { get; set; }
public string DeviceIdentifier { get; set; } public string DeviceIdentifier { get; set; }
public string JsonException { get; set; } public string JsonException { get; set; }
} }
public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) public static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{ {
try try
{ {
var ex = e.ExceptionObject as Exception; var ex = e.ExceptionObject as Exception;
if (ex != null) if (ex != null)
{ {
ReportError(ex, true); ReportError(ex, true);
} }
} }
catch (Exception) catch (Exception)
{ {
// Igore failure to Log Errors // Igore failure to Log Errors
} }
} }
#region Exception Serialization #region Exception Serialization
private static string IntenseExceptionSerialization(this Exception Ex) private static string IntenseExceptionSerialization(this Exception Ex)
{ {
try try
{ {
return JsonConvert.SerializeObject(Ex); return JsonConvert.SerializeObject(Ex);
} }
catch (Exception) catch (Exception)
{ {
try try
{ {
var encapsulatedEx = Ex.ToEncapsulatedException(); var encapsulatedEx = Ex.ToEncapsulatedException();
return JsonConvert.SerializeObject(encapsulatedEx); return JsonConvert.SerializeObject(encapsulatedEx);
} }
catch (Exception) catch (Exception)
{ {
try try
{ {
var encapsulatedEx = Ex.ToEncapsulatedException(0); var encapsulatedEx = Ex.ToEncapsulatedException(0);
return JsonConvert.SerializeObject(encapsulatedEx); return JsonConvert.SerializeObject(encapsulatedEx);
} }
catch (Exception) catch (Exception)
{ {
return JsonConvert.SerializeObject(Ex.Message); return JsonConvert.SerializeObject(Ex.Message);
} }
} }
} }
} }
private static EncapsulatedException ToEncapsulatedException(this Exception ex, int InnerRecursionDepth = 4) private static EncapsulatedException ToEncapsulatedException(this Exception ex, int InnerRecursionDepth = 4)
{ {
EncapsulatedException inner = null; EncapsulatedException inner = null;
if (InnerRecursionDepth > 0 && ex.InnerException != null) if (InnerRecursionDepth > 0 && ex.InnerException != null)
inner = ex.InnerException.ToEncapsulatedException(--InnerRecursionDepth); inner = ex.InnerException.ToEncapsulatedException(--InnerRecursionDepth);
return new EncapsulatedException() return new EncapsulatedException()
{ {
EncapsulatedType = ex.GetType().Name, EncapsulatedType = ex.GetType().Name,
Message = ex.Message, Message = ex.Message,
StackTrace = ex.StackTrace, StackTrace = ex.StackTrace,
InnerException = inner InnerException = inner
}; };
} }
public class EncapsulatedException public class EncapsulatedException
{ {
public string Message { get; set; } public string Message { get; set; }
public string EncapsulatedType { get; set; } public string EncapsulatedType { get; set; }
public string StackTrace { get; set; } public string StackTrace { get; set; }
public EncapsulatedException InnerException { get; set; } public EncapsulatedException InnerException { get; set; }
} }
#endregion #endregion
} }
} }
@@ -1,18 +1,18 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Disco.Client.Extensions namespace Disco.Client.Extensions
{ {
public class ClientServiceException : Exception public class ClientServiceException : Exception
{ {
public string ServiceFeature { get; private set; } public string ServiceFeature { get; private set; }
public ClientServiceException(string ServiceFeature, string ServerMessage) : base(ServerMessage) public ClientServiceException(string ServiceFeature, string ServerMessage) : base(ServerMessage)
{ {
this.ServiceFeature = ServiceFeature; this.ServiceFeature = ServiceFeature;
} }
} }
} }
@@ -1,56 +1,56 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Disco.Models.ClientServices; using Disco.Models.ClientServices;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Disco.Client.Extensions namespace Disco.Client.Extensions
{ {
public static class ClientServicesExtensions public static class ClientServicesExtensions
{ {
public const string ServicePathAuthenticatedTemplate = "http://DISCO:9292/Services/Client/Authenticated/{0}"; public const string ServicePathAuthenticatedTemplate = "http://DISCO:9292/Services/Client/Authenticated/{0}";
public const string ServicePathUnauthenticatedTemplate = "http://DISCO:9292/Services/Client/Unauthenticated/{0}"; public const string ServicePathUnauthenticatedTemplate = "http://DISCO:9292/Services/Client/Unauthenticated/{0}";
public static ResponseType Post<ResponseType>(this ServiceBase<ResponseType> Service, bool Authenticated) public static ResponseType Post<ResponseType>(this ServiceBase<ResponseType> Service, bool Authenticated)
{ {
string jsonResponse; string jsonResponse;
string serviceUrl; string serviceUrl;
if (Authenticated) if (Authenticated)
serviceUrl = string.Format(ServicePathAuthenticatedTemplate, Service.Feature); serviceUrl = string.Format(ServicePathAuthenticatedTemplate, Service.Feature);
else else
serviceUrl = string.Format(ServicePathUnauthenticatedTemplate, Service.Feature); serviceUrl = string.Format(ServicePathUnauthenticatedTemplate, Service.Feature);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceUrl); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceUrl);
request.UserAgent = string.Format("Disco-Client/{0}", Assembly.GetExecutingAssembly().GetName().Version.ToString(3)); request.UserAgent = string.Format("Disco-Client/{0}", Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
request.ContentType = "application/json"; request.ContentType = "application/json";
request.Method = WebRequestMethods.Http.Post; request.Method = WebRequestMethods.Http.Post;
request.UseDefaultCredentials = true; request.UseDefaultCredentials = true;
request.Timeout = 300000; // 5 Minutes request.Timeout = 300000; // 5 Minutes
string jsonRequest = JsonConvert.SerializeObject(Service); string jsonRequest = JsonConvert.SerializeObject(Service);
using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream())) using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream()))
{ {
requestWriter.Write(jsonRequest); requestWriter.Write(jsonRequest);
} }
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{ {
using (StreamReader responseReader = new StreamReader(response.GetResponseStream())) using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
{ {
jsonResponse = responseReader.ReadToEnd(); jsonResponse = responseReader.ReadToEnd();
} }
} }
if (string.IsNullOrEmpty(jsonResponse)) if (string.IsNullOrEmpty(jsonResponse))
return default(ResponseType); return default(ResponseType);
else else
return JsonConvert.DeserializeObject<ResponseType>(jsonResponse); return JsonConvert.DeserializeObject<ResponseType>(jsonResponse);
} }
} }
} }
+188 -188
View File
@@ -1,188 +1,188 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Disco.Models.ClientServices; using Disco.Models.ClientServices;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.IO; using System.IO;
using System.Diagnostics; using System.Diagnostics;
using Microsoft.Win32; using Microsoft.Win32;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Disco.Client.Extensions namespace Disco.Client.Extensions
{ {
public static class EnrolExtensions public static class EnrolExtensions
{ {
public static void Build(this Enrol enrol) public static void Build(this Enrol enrol)
{ {
enrol.DeviceUUID = Interop.SystemAudit.DeviceUUID; enrol.DeviceUUID = Interop.SystemAudit.DeviceUUID;
enrol.DeviceSerialNumber = Interop.SystemAudit.DeviceSerialNumber; enrol.DeviceSerialNumber = Interop.SystemAudit.DeviceSerialNumber;
enrol.DeviceComputerName = Interop.LocalAuthentication.ComputerName; enrol.DeviceComputerName = Interop.LocalAuthentication.ComputerName;
enrol.DeviceManufacturer = Interop.SystemAudit.DeviceManufacturer; enrol.DeviceManufacturer = Interop.SystemAudit.DeviceManufacturer;
enrol.DeviceModel = Interop.SystemAudit.DeviceModel; enrol.DeviceModel = Interop.SystemAudit.DeviceModel;
enrol.DeviceModelType = Interop.SystemAudit.DeviceType; enrol.DeviceModelType = Interop.SystemAudit.DeviceType;
enrol.DeviceIsPartOfDomain = Interop.SystemAudit.DeviceIsPartOfDomain; enrol.DeviceIsPartOfDomain = Interop.SystemAudit.DeviceIsPartOfDomain;
// LAN // LAN
enrol.DeviceLanMacAddress = Interop.Network.PrimaryLanMacAddress; enrol.DeviceLanMacAddress = Interop.Network.PrimaryLanMacAddress;
// WAN // WAN
enrol.DeviceWlanMacAddress = Interop.Network.PrimaryWlanMacAddress; enrol.DeviceWlanMacAddress = Interop.Network.PrimaryWlanMacAddress;
// Certificates // Certificates
enrol.DeviceCertificates = Interop.Certificates.GetCertificateSubjects(StoreName.My, StoreLocation.LocalMachine); enrol.DeviceCertificates = Interop.Certificates.GetCertificateSubjects(StoreName.My, StoreLocation.LocalMachine);
} }
public static void Process(this EnrolResponse enrolResponse) public static void Process(this EnrolResponse enrolResponse)
{ {
if (enrolResponse == null) if (enrolResponse == null)
throw new ClientServiceException("Enrolment", "Server denied enrolment (Empty Response)"); throw new ClientServiceException("Enrolment", "Server denied enrolment (Empty Response)");
ErrorReporting.EnrolmentSessionId = enrolResponse.SessionId; ErrorReporting.EnrolmentSessionId = enrolResponse.SessionId;
if (!string.IsNullOrEmpty(enrolResponse.ErrorMessage)) if (!string.IsNullOrEmpty(enrolResponse.ErrorMessage))
throw new ClientServiceException("Enrolment", enrolResponse.ErrorMessage); throw new ClientServiceException("Enrolment", enrolResponse.ErrorMessage);
// Offline Domain Join // Offline Domain Join
bool requireReboot = enrolResponse.ApplyOfflineDomainJoin(); bool requireReboot = enrolResponse.ApplyOfflineDomainJoin();
// Certificates // Certificates
enrolResponse.ApplyDeviceCertificates(); enrolResponse.ApplyDeviceCertificates();
// Device Owner // Device Owner
enrolResponse.ApplyDeviceAssignedUser(); enrolResponse.ApplyDeviceAssignedUser();
Presentation.UpdateStatus("Enrolling Device", "Device Enrolment Successfully Completed", false, 0, 1500); Presentation.UpdateStatus("Enrolling Device", "Device Enrolment Successfully Completed", false, 0, 1500);
Program.RebootRequired = requireReboot; Program.RebootRequired = requireReboot;
Program.AllowUninstall = enrolResponse.AllowBootstrapperUninstall; Program.AllowUninstall = enrolResponse.AllowBootstrapperUninstall;
} }
/// <summary> /// <summary>
/// Processes a Client Service Enrol Response for Offline Domain Join Actions /// Processes a Client Service Enrol Response for Offline Domain Join Actions
/// </summary> /// </summary>
/// <param name="enrolResponse"></param> /// <param name="enrolResponse"></param>
/// <returns>Boolean indicating whether a reboot is required.</returns> /// <returns>Boolean indicating whether a reboot is required.</returns>
private static bool ApplyOfflineDomainJoin(this EnrolResponse enrolResponse) private static bool ApplyOfflineDomainJoin(this EnrolResponse enrolResponse)
{ {
if (!string.IsNullOrWhiteSpace(enrolResponse.OfflineDomainJoin)) if (!string.IsNullOrWhiteSpace(enrolResponse.OfflineDomainJoin))
{ {
Presentation.UpdateStatus("Enrolling Device", string.Format("Performing Offline Domain Join:{0}Renaming Computer: {1} -> {2}", Environment.NewLine, Interop.LocalAuthentication.ComputerName, enrolResponse.DeviceComputerName), true, -1, 1500); Presentation.UpdateStatus("Enrolling Device", string.Format("Performing Offline Domain Join:{0}Renaming Computer: {1} -> {2}", Environment.NewLine, Interop.LocalAuthentication.ComputerName, enrolResponse.DeviceComputerName), true, -1, 1500);
string odjFile = Path.GetTempFileName(); string odjFile = Path.GetTempFileName();
File.WriteAllBytes(odjFile, Convert.FromBase64String(enrolResponse.OfflineDomainJoin)); File.WriteAllBytes(odjFile, Convert.FromBase64String(enrolResponse.OfflineDomainJoin));
string odjWindowsPath = Environment.GetEnvironmentVariable("SystemRoot"); string odjWindowsPath = Environment.GetEnvironmentVariable("SystemRoot");
string odjProcessArguments = string.Format("/REQUESTODJ /LOADFILE \"{0}\" /WINDOWSPATH \"{1}\" /LOCALOS", odjFile, odjWindowsPath); string odjProcessArguments = string.Format("/REQUESTODJ /LOADFILE \"{0}\" /WINDOWSPATH \"{1}\" /LOCALOS", odjFile, odjWindowsPath);
ProcessStartInfo odjProcessStartInfo = new ProcessStartInfo("DJOIN.EXE", odjProcessArguments) ProcessStartInfo odjProcessStartInfo = new ProcessStartInfo("DJOIN.EXE", odjProcessArguments)
{ {
CreateNoWindow = true, CreateNoWindow = true,
ErrorDialog = false, ErrorDialog = false,
LoadUserProfile = true, LoadUserProfile = true,
RedirectStandardOutput = true, RedirectStandardOutput = true,
UseShellExecute = false UseShellExecute = false
}; };
string odjResult; string odjResult;
using (Process odjProcess = System.Diagnostics.Process.Start(odjProcessStartInfo)) using (Process odjProcess = System.Diagnostics.Process.Start(odjProcessStartInfo))
{ {
odjResult = odjProcess.StandardOutput.ReadToEnd(); odjResult = odjProcess.StandardOutput.ReadToEnd();
odjProcess.WaitForExit(20000); // 20 Seconds odjProcess.WaitForExit(20000); // 20 Seconds
} }
Presentation.UpdateStatus("Enrolling Device", string.Format("Offline Domain Join Result:{0}{1}", Environment.NewLine, odjResult), true, -1, 3000); Presentation.UpdateStatus("Enrolling Device", string.Format("Offline Domain Join Result:{0}{1}", Environment.NewLine, odjResult), true, -1, 3000);
if (File.Exists(odjFile)) if (File.Exists(odjFile))
File.Delete(odjFile); File.Delete(odjFile);
// Flush Logged-On History // Flush Logged-On History
if (!string.IsNullOrEmpty(enrolResponse.DeviceDomainName)) if (!string.IsNullOrEmpty(enrolResponse.DeviceDomainName))
{ {
using (RegistryKey regWinlogon = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true)){ using (RegistryKey regWinlogon = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true)){
regWinlogon.SetValue("DefaultDomainName", enrolResponse.DeviceDomainName, RegistryValueKind.String); regWinlogon.SetValue("DefaultDomainName", enrolResponse.DeviceDomainName, RegistryValueKind.String);
regWinlogon.SetValue("DefaultUserName", String.Empty, RegistryValueKind.String); regWinlogon.SetValue("DefaultUserName", String.Empty, RegistryValueKind.String);
} }
using (RegistryKey regLogonUI = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI", true)) using (RegistryKey regLogonUI = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI", true))
{ {
regLogonUI.DeleteValue("LastLoggedOnUser", false); regLogonUI.DeleteValue("LastLoggedOnUser", false);
} }
} }
return true; // Reboot required return true; // Reboot required
} }
else else
{ {
// No Domain Join // No Domain Join
return false; // Reboot not required return false; // Reboot not required
} }
} }
/// <summary> /// <summary>
/// Processes a Client Service Enrol Response for Device Assigned User Actions /// Processes a Client Service Enrol Response for Device Assigned User Actions
/// </summary> /// </summary>
/// <param name="enrolResponse"></param> /// <param name="enrolResponse"></param>
private static void ApplyDeviceAssignedUser(this EnrolResponse enrolResponse) private static void ApplyDeviceAssignedUser(this EnrolResponse enrolResponse)
{ {
// Only run task if Assigned User was specified // Only run task if Assigned User was specified
if (!string.IsNullOrWhiteSpace(enrolResponse.DeviceAssignedUserSID)) if (!string.IsNullOrWhiteSpace(enrolResponse.DeviceAssignedUserSID))
{ {
Presentation.UpdateStatus("Enrolling Device", string.Format(@"Configuring permissions for the device owner:{0}{1} ({2}\{3})", Environment.NewLine, enrolResponse.DeviceAssignedUserName, enrolResponse.DeviceAssignedUserDomain, enrolResponse.DeviceAssignedUserUsername), true, -1, 3000); Presentation.UpdateStatus("Enrolling Device", string.Format(@"Configuring permissions for the device owner:{0}{1} ({2}\{3})", Environment.NewLine, enrolResponse.DeviceAssignedUserName, enrolResponse.DeviceAssignedUserDomain, enrolResponse.DeviceAssignedUserUsername), true, -1, 3000);
Interop.LocalAuthentication.AddLocalGroupMembership("Administrators", enrolResponse.DeviceAssignedUserSID, enrolResponse.DeviceAssignedUserUsername, enrolResponse.DeviceAssignedUserDomain); Interop.LocalAuthentication.AddLocalGroupMembership("Administrators", enrolResponse.DeviceAssignedUserSID, enrolResponse.DeviceAssignedUserUsername, enrolResponse.DeviceAssignedUserDomain);
// Make Windows think this user was the last to logon // Make Windows think this user was the last to logon
using (RegistryKey regWinlogon = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true)) using (RegistryKey regWinlogon = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true))
{ {
regWinlogon.SetValue("DefaultDomainName", enrolResponse.DeviceAssignedUserDomain, RegistryValueKind.String); regWinlogon.SetValue("DefaultDomainName", enrolResponse.DeviceAssignedUserDomain, RegistryValueKind.String);
regWinlogon.SetValue("DefaultUserName", enrolResponse.DeviceAssignedUserUsername, RegistryValueKind.String); regWinlogon.SetValue("DefaultUserName", enrolResponse.DeviceAssignedUserUsername, RegistryValueKind.String);
} }
using (RegistryKey regLogonUI = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI", true)) using (RegistryKey regLogonUI = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI", true))
{ {
regLogonUI.SetValue("LastLoggedOnUser", string.Format(@"{0}\{1}", enrolResponse.DeviceAssignedUserDomain, enrolResponse.DeviceAssignedUserUsername), RegistryValueKind.String); regLogonUI.SetValue("LastLoggedOnUser", string.Format(@"{0}\{1}", enrolResponse.DeviceAssignedUserDomain, enrolResponse.DeviceAssignedUserUsername), RegistryValueKind.String);
} }
} }
} }
/// <summary> /// <summary>
/// Processes a Client Service Enrol Response for Device Certificate Actions /// Processes a Client Service Enrol Response for Device Certificate Actions
/// </summary> /// </summary>
/// <param name="enrolResponse"></param> /// <param name="enrolResponse"></param>
private static void ApplyDeviceCertificates(this EnrolResponse enrolResponse) private static void ApplyDeviceCertificates(this EnrolResponse enrolResponse)
{ {
// Only run if a Certificate was supplied // Only run if a Certificate was supplied
if (!string.IsNullOrEmpty(enrolResponse.DeviceCertificate)) if (!string.IsNullOrEmpty(enrolResponse.DeviceCertificate))
{ {
Presentation.UpdateStatus("Enrolling Device", "Configuring Wireless Certificates", true, -1, 1000); Presentation.UpdateStatus("Enrolling Device", "Configuring Wireless Certificates", true, -1, 1000);
var certPersonalBytes = Convert.FromBase64String(enrolResponse.DeviceCertificate); var certPersonalBytes = Convert.FromBase64String(enrolResponse.DeviceCertificate);
var certPersonal = new X509Certificate2(certPersonalBytes, "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); var certPersonal = new X509Certificate2(certPersonalBytes, "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
if (certPersonal == null) if (certPersonal == null)
throw new ClientServiceException("Enrolment > Device Certificate", "Unable to Import Device Certificate Provided, possibly check password."); throw new ClientServiceException("Enrolment > Device Certificate", "Unable to Import Device Certificate Provided, possibly check password.");
// Certificate Removal // Certificate Removal
if (enrolResponse.DeviceCertificateRemoveExisting != null && enrolResponse.DeviceCertificateRemoveExisting.Count > 0) if (enrolResponse.DeviceCertificateRemoveExisting != null && enrolResponse.DeviceCertificateRemoveExisting.Count > 0)
{ {
List<Regex> regExMatchesSubject = new List<Regex>(); List<Regex> regExMatchesSubject = new List<Regex>();
foreach (var subjectRegEx in enrolResponse.DeviceCertificateRemoveExisting) foreach (var subjectRegEx in enrolResponse.DeviceCertificateRemoveExisting)
regExMatchesSubject.Add(new Regex(subjectRegEx, RegexOptions.IgnoreCase)); regExMatchesSubject.Add(new Regex(subjectRegEx, RegexOptions.IgnoreCase));
// Remove from 'My' Store // Remove from 'My' Store
Interop.Certificates.RemoveCertificates(StoreName.My, StoreLocation.LocalMachine, regExMatchesSubject, certPersonal); Interop.Certificates.RemoveCertificates(StoreName.My, StoreLocation.LocalMachine, regExMatchesSubject, certPersonal);
// Remove from 'Root' Store // Remove from 'Root' Store
Interop.Certificates.RemoveCertificates(StoreName.Root, StoreLocation.LocalMachine, regExMatchesSubject, certPersonal); Interop.Certificates.RemoveCertificates(StoreName.Root, StoreLocation.LocalMachine, regExMatchesSubject, certPersonal);
// Remove from 'CertificateAuthority' Store // Remove from 'CertificateAuthority' Store
Interop.Certificates.RemoveCertificates(StoreName.CertificateAuthority, StoreLocation.LocalMachine, regExMatchesSubject, certPersonal); Interop.Certificates.RemoveCertificates(StoreName.CertificateAuthority, StoreLocation.LocalMachine, regExMatchesSubject, certPersonal);
} }
// Add Certificate // Add Certificate
Presentation.UpdateStatus("Enrolling Device", string.Format("Configuring Wireless Certificates{0}Installing Certificate: {1}", Environment.NewLine, Interop.Certificates.GetCertificateFriendlyName(certPersonal)), true, -1); Presentation.UpdateStatus("Enrolling Device", string.Format("Configuring Wireless Certificates{0}Installing Certificate: {1}", Environment.NewLine, Interop.Certificates.GetCertificateFriendlyName(certPersonal)), true, -1);
Interop.Certificates.AddCertificate(StoreName.My, StoreLocation.LocalMachine, certPersonal); Interop.Certificates.AddCertificate(StoreName.My, StoreLocation.LocalMachine, certPersonal);
} }
} }
} }
} }
+36 -36
View File
@@ -1,36 +1,36 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Disco.Models.ClientServices; using Disco.Models.ClientServices;
namespace Disco.Client.Extensions namespace Disco.Client.Extensions
{ {
public static class WhoAmIExtensions public static class WhoAmIExtensions
{ {
public static void Process(this WhoAmIResponse whoAmIResponse) public static void Process(this WhoAmIResponse whoAmIResponse)
{ {
Program.IsAuthenticated = true; Program.IsAuthenticated = true;
whoAmIResponse.PresentResponse(); whoAmIResponse.PresentResponse();
} }
private static void PresentResponse(this WhoAmIResponse whoAmIResponse) private static void PresentResponse(this WhoAmIResponse whoAmIResponse)
{ {
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
message.AppendLine("Authenticated Connection:"); message.AppendLine("Authenticated Connection:");
message.Append("Username: ").AppendLine(whoAmIResponse.Username); message.Append("Username: ").AppendLine(whoAmIResponse.Username);
message.Append("Name: ").Append(whoAmIResponse.DisplayName); message.Append("Name: ").Append(whoAmIResponse.DisplayName);
message.Append(" (").Append(whoAmIResponse.Type).AppendLine(")"); message.Append(" (").Append(whoAmIResponse.Type).AppendLine(")");
Presentation.UpdateStatus("Connection Established to Preparation Server", message.ToString(), false, 0, 1500); Presentation.UpdateStatus("Connection Established to Preparation Server", message.ToString(), false, 0, 1500);
} }
public static void UnauthenticatedResponse() public static void UnauthenticatedResponse()
{ {
Program.IsAuthenticated = false; Program.IsAuthenticated = false;
Presentation.UpdateStatus("Connection Established to Preparation Server", "Unauthenticated connection to the server...", false, 0, 1500); Presentation.UpdateStatus("Connection Established to Preparation Server", "Unauthenticated connection to the server...", false, 0, 1500);
} }
} }
} }
+103 -103
View File
@@ -1,103 +1,103 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace Disco.Client.Interop namespace Disco.Client.Interop
{ {
public static class Certificates public static class Certificates
{ {
public static string GetCertificateFriendlyName(X509Certificate2 Certificate) public static string GetCertificateFriendlyName(X509Certificate2 Certificate)
{ {
string subject = Certificate.Subject; string subject = Certificate.Subject;
return subject.Substring(subject.IndexOf("=") + 1, subject.IndexOf(",") - subject.IndexOf("=") - 1); return subject.Substring(subject.IndexOf("=") + 1, subject.IndexOf(",") - subject.IndexOf("=") - 1);
} }
public static List<string> GetCertificateSubjects(StoreName StoreName, StoreLocation StoreLocation) public static List<string> GetCertificateSubjects(StoreName StoreName, StoreLocation StoreLocation)
{ {
X509Store certStore = new X509Store(StoreName, StoreLocation); X509Store certStore = new X509Store(StoreName, StoreLocation);
certStore.Open(OpenFlags.ReadOnly); certStore.Open(OpenFlags.ReadOnly);
var certSubjects = certStore.Certificates.Cast<X509Certificate2>().Select(c => c.Subject).ToList(); var certSubjects = certStore.Certificates.Cast<X509Certificate2>().Select(c => c.Subject).ToList();
certStore.Close(); certStore.Close();
return certSubjects; return certSubjects;
} }
public static bool AddCertificate(StoreName StoreName, StoreLocation StoreLocation, X509Certificate2 Certificate) public static bool AddCertificate(StoreName StoreName, StoreLocation StoreLocation, X509Certificate2 Certificate)
{ {
X509Store certStore = new X509Store(StoreName, StoreLocation); X509Store certStore = new X509Store(StoreName, StoreLocation);
bool certAlreadyAdded = false; bool certAlreadyAdded = false;
certStore.Open(OpenFlags.ReadWrite); certStore.Open(OpenFlags.ReadWrite);
try try
{ {
foreach (X509Certificate2 cert in certStore.Certificates) foreach (X509Certificate2 cert in certStore.Certificates)
{ {
if (cert.SerialNumber.Equals(Certificate.SerialNumber)) if (cert.SerialNumber.Equals(Certificate.SerialNumber))
{ {
certAlreadyAdded = true; certAlreadyAdded = true;
break; break;
} }
} }
if (!certAlreadyAdded) if (!certAlreadyAdded)
{ {
Presentation.UpdateStatus("Enrolling Device", string.Format("Configuring Wireless Certificates{0}Adding Certificate: '{1}' from {2}@{3}", Environment.NewLine, GetCertificateFriendlyName(Certificate), StoreName.ToString(), StoreLocation.ToString()), true, -1, 3000); Presentation.UpdateStatus("Enrolling Device", string.Format("Configuring Wireless Certificates{0}Adding Certificate: '{1}' from {2}@{3}", Environment.NewLine, GetCertificateFriendlyName(Certificate), StoreName.ToString(), StoreLocation.ToString()), true, -1, 3000);
certStore.Add(Certificate); certStore.Add(Certificate);
} }
} }
catch (Exception) { throw; } catch (Exception) { throw; }
finally finally
{ {
certStore.Close(); certStore.Close();
} }
return !certAlreadyAdded; return !certAlreadyAdded;
} }
public static List<string> RemoveCertificates(StoreName StoreName, StoreLocation StoreLocation, List<Regex> RegExMatchesSubject, X509Certificate2 CertificateException) public static List<string> RemoveCertificates(StoreName StoreName, StoreLocation StoreLocation, List<Regex> RegExMatchesSubject, X509Certificate2 CertificateException)
{ {
X509Store certStore = new X509Store(StoreName, StoreLocation); X509Store certStore = new X509Store(StoreName, StoreLocation);
List<string> results = new List<string>(); List<string> results = new List<string>();
List<X509Certificate2> certStoreRemove = new List<X509Certificate2>(); List<X509Certificate2> certStoreRemove = new List<X509Certificate2>();
certStore.Open(OpenFlags.ReadWrite); certStore.Open(OpenFlags.ReadWrite);
try try
{ {
foreach (X509Certificate2 cert in certStore.Certificates) foreach (X509Certificate2 cert in certStore.Certificates)
{ {
if (!cert.SerialNumber.Equals(CertificateException.SerialNumber)) if (!cert.SerialNumber.Equals(CertificateException.SerialNumber))
{ {
foreach (var subjectRegEx in RegExMatchesSubject) foreach (var subjectRegEx in RegExMatchesSubject)
{ {
if (subjectRegEx.IsMatch(cert.Subject)) if (subjectRegEx.IsMatch(cert.Subject))
{ {
certStoreRemove.Add(cert); certStoreRemove.Add(cert);
break; break;
} }
} }
} }
} }
foreach (var cert in certStoreRemove) foreach (var cert in certStoreRemove)
{ {
results.Add(cert.Subject); results.Add(cert.Subject);
Presentation.UpdateStatus("Enrolling Device", string.Format("Configuring Wireless Certificates{0}Removing Certificate: '{1}' from {2}@{3}", Environment.NewLine, GetCertificateFriendlyName(cert), StoreName.ToString(), StoreLocation.ToString()), true, -1, 1500); Presentation.UpdateStatus("Enrolling Device", string.Format("Configuring Wireless Certificates{0}Removing Certificate: '{1}' from {2}@{3}", Environment.NewLine, GetCertificateFriendlyName(cert), StoreName.ToString(), StoreLocation.ToString()), true, -1, 1500);
certStore.Remove(cert); certStore.Remove(cert);
} }
} }
catch (Exception) { throw; } catch (Exception) { throw; }
finally finally
{ {
certStore.Close(); certStore.Close();
} }
return results; return results;
} }
} }
} }
+59 -59
View File
@@ -1,59 +1,59 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.DirectoryServices; using System.DirectoryServices;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Disco.Client.Interop namespace Disco.Client.Interop
{ {
public static class LocalAuthentication public static class LocalAuthentication
{ {
public static bool AddLocalGroupMembership(string GroupName, string UserSID, string Username, string UserDomain) public static bool AddLocalGroupMembership(string GroupName, string UserSID, string Username, string UserDomain)
{ {
using (DirectoryEntry group = new DirectoryEntry(string.Format("WinNT://./{0},group", GroupName))) using (DirectoryEntry group = new DirectoryEntry(string.Format("WinNT://./{0},group", GroupName)))
{ {
// Check to see if the User is already a member // Check to see if the User is already a member
foreach (object memberRef in (IEnumerable)group.Invoke("Members")) foreach (object memberRef in (IEnumerable)group.Invoke("Members"))
{ {
using (DirectoryEntry member = new DirectoryEntry(memberRef)) using (DirectoryEntry member = new DirectoryEntry(memberRef))
{ {
var memberPath = member.Path; var memberPath = member.Path;
if (memberPath.Equals(string.Format("WinNT://{0}/{1}", UserDomain, Username), StringComparison.InvariantCultureIgnoreCase) || if (memberPath.Equals(string.Format("WinNT://{0}/{1}", UserDomain, Username), StringComparison.InvariantCultureIgnoreCase) ||
memberPath.Equals(string.Format("WinNT://{0}", UserSID), StringComparison.InvariantCultureIgnoreCase)) memberPath.Equals(string.Format("WinNT://{0}", UserSID), StringComparison.InvariantCultureIgnoreCase))
return false; return false;
} }
} }
group.Invoke("Add", string.Format("WinNT://{0}", UserSID)); group.Invoke("Add", string.Format("WinNT://{0}", UserSID));
} }
return true; return true;
} }
public static string CurrentUserDomain public static string CurrentUserDomain
{ {
get get
{ {
return Environment.UserDomainName; return Environment.UserDomainName;
} }
} }
public static string CurrentUserName public static string CurrentUserName
{ {
get get
{ {
return Environment.UserName; return Environment.UserName;
} }
} }
public static string ComputerName public static string ComputerName
{ {
get get
{ {
return Environment.MachineName; return Environment.MachineName;
} }
} }
} }
} }
+327 -327
View File
@@ -1,327 +1,327 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Management; using System.Management;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
namespace Disco.Client.Interop namespace Disco.Client.Interop
{ {
public static class Network public static class Network
{ {
private static List<NetworkAdapterInfo> NetworkAdapters { get; set; } private static List<NetworkAdapterInfo> NetworkAdapters { get; set; }
private static NetworkAdapterInfo PrimaryLanNetworkAdapter { get; set; } private static NetworkAdapterInfo PrimaryLanNetworkAdapter { get; set; }
private static NetworkAdapterInfo PrimaryWlanNetworkAdapter { get; set; } private static NetworkAdapterInfo PrimaryWlanNetworkAdapter { get; set; }
static Network() static Network()
{ {
// Get All Adapters // Get All Adapters
RetrieveLanAdapters(); RetrieveLanAdapters();
if (NetworkAdapters.Count > 0) if (NetworkAdapters.Count > 0)
{ {
// Only Retrieve Wlan Adapters if at least one adapter was found by WMI // Only Retrieve Wlan Adapters if at least one adapter was found by WMI
RetrieveWlanAdapters(); RetrieveWlanAdapters();
// Determine Primary Adapters // Determine Primary Adapters
// Lan // Lan
PrimaryLanNetworkAdapter = NetworkAdapters.Where(n => !n.IsWLanAdapter && n.NetConnectionId.StartsWith("Local Area Connection", StringComparison.InvariantCultureIgnoreCase)).OrderByDescending(n => n.Speed).FirstOrDefault(); PrimaryLanNetworkAdapter = NetworkAdapters.Where(n => !n.IsWLanAdapter && n.NetConnectionId.StartsWith("Local Area Connection", StringComparison.InvariantCultureIgnoreCase)).OrderByDescending(n => n.Speed).FirstOrDefault();
// Might be too restrictive - remove name restriction just in case. // Might be too restrictive - remove name restriction just in case.
if (PrimaryLanNetworkAdapter == null) if (PrimaryLanNetworkAdapter == null)
PrimaryLanNetworkAdapter = NetworkAdapters.Where(n => !n.IsWLanAdapter).OrderByDescending(n => n.Speed).FirstOrDefault(); PrimaryLanNetworkAdapter = NetworkAdapters.Where(n => !n.IsWLanAdapter).OrderByDescending(n => n.Speed).FirstOrDefault();
// Wan // Wan
PrimaryWlanNetworkAdapter = NetworkAdapters.Where(n => n.IsWLanAdapter).OrderByDescending(n => n.Speed).FirstOrDefault(); PrimaryWlanNetworkAdapter = NetworkAdapters.Where(n => n.IsWLanAdapter).OrderByDescending(n => n.Speed).FirstOrDefault();
} }
} }
private static void RetrieveLanAdapters() private static void RetrieveLanAdapters()
{ {
// Get NetworkAdapter Information // Get NetworkAdapter Information
try try
{ {
using (ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("SELECT Index, GUID, MACAddress, Name, NetConnectionID, Speed FROM Win32_NetworkAdapter WHERE PhysicalAdapter=true AND MACAddress IS NOT NULL AND Name IS NOT NULL AND NetConnectionID IS NOT NULL AND Speed IS NOT NULL")) using (ManagementObjectSearcher mSearcher = new ManagementObjectSearcher("SELECT Index, GUID, MACAddress, Name, NetConnectionID, Speed FROM Win32_NetworkAdapter WHERE PhysicalAdapter=true AND MACAddress IS NOT NULL AND Name IS NOT NULL AND NetConnectionID IS NOT NULL AND Speed IS NOT NULL"))
{ {
using (ManagementObjectCollection mResults = mSearcher.Get()) using (ManagementObjectCollection mResults = mSearcher.Get())
{ {
NetworkAdapters = new List<NetworkAdapterInfo>(); NetworkAdapters = new List<NetworkAdapterInfo>();
foreach (var mResult in mResults.Cast<ManagementObject>()) foreach (var mResult in mResults.Cast<ManagementObject>())
{ {
NetworkAdapterInfo nic = new NetworkAdapterInfo() NetworkAdapterInfo nic = new NetworkAdapterInfo()
{ {
Index = (UInt32)mResult.GetPropertyValue("Index"), Index = (UInt32)mResult.GetPropertyValue("Index"),
Guid = Guid.Parse((string)mResult.GetPropertyValue("GUID")), Guid = Guid.Parse((string)mResult.GetPropertyValue("GUID")),
MacAddress = mResult.GetPropertyValue("MACAddress").ToString(), MacAddress = mResult.GetPropertyValue("MACAddress").ToString(),
Name = mResult.GetPropertyValue("Name").ToString(), Name = mResult.GetPropertyValue("Name").ToString(),
NetConnectionId = mResult.GetPropertyValue("NetConnectionID").ToString(), NetConnectionId = mResult.GetPropertyValue("NetConnectionID").ToString(),
Speed = Convert.ToUInt64(mResult.GetPropertyValue("Speed")), Speed = Convert.ToUInt64(mResult.GetPropertyValue("Speed")),
IsWLanAdapter = false IsWLanAdapter = false
}; };
NetworkAdapters.Add(nic); NetworkAdapters.Add(nic);
} }
} }
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
throw new Exception("Disco Client was unable to retrieve NetworkAdapter information from WMI", ex); throw new Exception("Disco Client was unable to retrieve NetworkAdapter information from WMI", ex);
} }
} }
private static void RetrieveWlanAdapters() private static void RetrieveWlanAdapters()
{ {
WLAN_INTERFACE_INFO_LIST wlanApiInterfaceList; WLAN_INTERFACE_INFO_LIST wlanApiInterfaceList;
IntPtr wlanApiHandle = IntPtr.Zero; IntPtr wlanApiHandle = IntPtr.Zero;
uint wlanApiServiceVersion = 0; uint wlanApiServiceVersion = 0;
if (WlanOpenHandle(WLAN_API_VERSION_2_0, IntPtr.Zero, out wlanApiServiceVersion, ref wlanApiHandle) == ERROR_SUCCESS) if (WlanOpenHandle(WLAN_API_VERSION_2_0, IntPtr.Zero, out wlanApiServiceVersion, ref wlanApiHandle) == ERROR_SUCCESS)
{ {
IntPtr wlanApiInterfaceListPointer = IntPtr.Zero; IntPtr wlanApiInterfaceListPointer = IntPtr.Zero;
if (WlanEnumInterfaces(wlanApiHandle, IntPtr.Zero, ref wlanApiInterfaceListPointer) == ERROR_SUCCESS) if (WlanEnumInterfaces(wlanApiHandle, IntPtr.Zero, ref wlanApiInterfaceListPointer) == ERROR_SUCCESS)
{ {
wlanApiInterfaceList = new WLAN_INTERFACE_INFO_LIST(wlanApiInterfaceListPointer); wlanApiInterfaceList = new WLAN_INTERFACE_INFO_LIST(wlanApiInterfaceListPointer);
WlanFreeMemory(wlanApiInterfaceListPointer); WlanFreeMemory(wlanApiInterfaceListPointer);
} }
else else
{ {
// Error - No Wlan Adapters Reported // Error - No Wlan Adapters Reported
WlanCloseHandle(wlanApiHandle, IntPtr.Zero); WlanCloseHandle(wlanApiHandle, IntPtr.Zero);
return; return;
} }
WlanCloseHandle(wlanApiHandle, IntPtr.Zero); WlanCloseHandle(wlanApiHandle, IntPtr.Zero);
} }
else else
{ {
// Error - No Wlan Adapters Reported // Error - No Wlan Adapters Reported
return; return;
} }
if (wlanApiInterfaceList.InterfaceInfo != null) if (wlanApiInterfaceList.InterfaceInfo != null)
{ {
foreach (var wlanApiAdapter in wlanApiInterfaceList.InterfaceInfo) foreach (var wlanApiAdapter in wlanApiInterfaceList.InterfaceInfo)
{ {
var wlanApiAdapterInfo = wlanApiAdapter; var wlanApiAdapterInfo = wlanApiAdapter;
var wmiAdapterInfo = NetworkAdapters.FirstOrDefault(n => n.Guid == wlanApiAdapterInfo.InterfaceGuid); var wmiAdapterInfo = NetworkAdapters.FirstOrDefault(n => n.Guid == wlanApiAdapterInfo.InterfaceGuid);
if (wmiAdapterInfo != null) if (wmiAdapterInfo != null)
{ {
wmiAdapterInfo.IsWLanAdapter = true; wmiAdapterInfo.IsWLanAdapter = true;
wmiAdapterInfo.WlanState = wlanApiAdapterInfo.isState; wmiAdapterInfo.WlanState = wlanApiAdapterInfo.isState;
} }
} }
} }
} }
public static string PrimaryLanMacAddress public static string PrimaryLanMacAddress
{ {
get get
{ {
// Return null if no Primary LAN Network Adapter found on this Device // Return null if no Primary LAN Network Adapter found on this Device
return (PrimaryLanNetworkAdapter == null) ? null : PrimaryLanNetworkAdapter.MacAddress; return (PrimaryLanNetworkAdapter == null) ? null : PrimaryLanNetworkAdapter.MacAddress;
} }
} }
public static string PrimaryWlanMacAddress public static string PrimaryWlanMacAddress
{ {
get get
{ {
// Return null if no Primary WLAN Network Adapter found on this Device // Return null if no Primary WLAN Network Adapter found on this Device
return (PrimaryWlanNetworkAdapter == null) ? null : PrimaryWlanNetworkAdapter.MacAddress; return (PrimaryWlanNetworkAdapter == null) ? null : PrimaryWlanNetworkAdapter.MacAddress;
} }
} }
private class NetworkAdapterInfo private class NetworkAdapterInfo
{ {
public UInt32 Index { get; set; } public UInt32 Index { get; set; }
public Guid Guid { get; set; } public Guid Guid { get; set; }
public string Name { get; set; } public string Name { get; set; }
public string NetConnectionId { get; set; } public string NetConnectionId { get; set; }
public string MacAddress { get; set; } public string MacAddress { get; set; }
public UInt64 Speed { get; set; } public UInt64 Speed { get; set; }
public bool IsWLanAdapter { get; set; } public bool IsWLanAdapter { get; set; }
public WLAN_INTERFACE_STATE WlanState { get; set; } public WLAN_INTERFACE_STATE WlanState { get; set; }
public string WlanStateDescription public string WlanStateDescription
{ {
get get
{ {
switch (WlanState) switch (WlanState)
{ {
case WLAN_INTERFACE_STATE.wlan_interface_state_not_ready: case WLAN_INTERFACE_STATE.wlan_interface_state_not_ready:
return "Not Ready"; return "Not Ready";
case WLAN_INTERFACE_STATE.wlan_interface_state_connected: case WLAN_INTERFACE_STATE.wlan_interface_state_connected:
return "Connected"; return "Connected";
case WLAN_INTERFACE_STATE.wlan_interface_state_ad_hoc_network_formed: case WLAN_INTERFACE_STATE.wlan_interface_state_ad_hoc_network_formed:
return "Ad Hoc Network Formed"; return "Ad Hoc Network Formed";
case WLAN_INTERFACE_STATE.wlan_interface_state_disconnecting: case WLAN_INTERFACE_STATE.wlan_interface_state_disconnecting:
return "Disconnecting"; return "Disconnecting";
case WLAN_INTERFACE_STATE.wlan_interface_state_disconnected: case WLAN_INTERFACE_STATE.wlan_interface_state_disconnected:
return "Disconnected"; return "Disconnected";
case WLAN_INTERFACE_STATE.wlan_interface_state_associating: case WLAN_INTERFACE_STATE.wlan_interface_state_associating:
return "Associating"; return "Associating";
case WLAN_INTERFACE_STATE.wlan_interface_state_discovering: case WLAN_INTERFACE_STATE.wlan_interface_state_discovering:
return "Discovering"; return "Discovering";
case WLAN_INTERFACE_STATE.wlan_interface_state_authenticating: case WLAN_INTERFACE_STATE.wlan_interface_state_authenticating:
return "Authenticating"; return "Authenticating";
default: default:
return "Unknown"; return "Unknown";
} }
} }
} }
} }
#region Wlan Win32 Interop #region Wlan Win32 Interop
private const uint WLAN_API_VERSION_2_0 = 2; // Windows Vista WiFi API Version private const uint WLAN_API_VERSION_2_0 = 2; // Windows Vista WiFi API Version
private const int ERROR_SUCCESS = 0; private const int ERROR_SUCCESS = 0;
/// <summary > /// <summary >
/// Opens a connection to the server /// Opens a connection to the server
/// </summary > /// </summary >
[DllImport("Wlanapi.dll")] [DllImport("Wlanapi.dll")]
private static extern int WlanOpenHandle( private static extern int WlanOpenHandle(
uint dwClientVersion, uint dwClientVersion,
IntPtr pReserved, //not in MSDN but required IntPtr pReserved, //not in MSDN but required
[Out] out uint pdwNegotiatedVersion, [Out] out uint pdwNegotiatedVersion,
ref IntPtr ClientHandle); ref IntPtr ClientHandle);
/// <summary > /// <summary >
/// Closes a connection to the server /// Closes a connection to the server
/// </summary > /// </summary >
[DllImport("Wlanapi", EntryPoint = "WlanCloseHandle")] [DllImport("Wlanapi", EntryPoint = "WlanCloseHandle")]
private static extern uint WlanCloseHandle( private static extern uint WlanCloseHandle(
[In] IntPtr hClientHandle, [In] IntPtr hClientHandle,
IntPtr pReserved); IntPtr pReserved);
/// <summary > /// <summary >
/// Enumerates all wireless interfaces in the laptop /// Enumerates all wireless interfaces in the laptop
/// </summary > /// </summary >
[DllImport("Wlanapi", EntryPoint = "WlanEnumInterfaces")] [DllImport("Wlanapi", EntryPoint = "WlanEnumInterfaces")]
private static extern uint WlanEnumInterfaces( private static extern uint WlanEnumInterfaces(
[In] IntPtr hClientHandle, [In] IntPtr hClientHandle,
IntPtr pReserved, IntPtr pReserved,
ref IntPtr ppInterfaceList); ref IntPtr ppInterfaceList);
/// <summary > /// <summary >
/// Frees memory returned by native WiFi functions /// Frees memory returned by native WiFi functions
/// </summary > /// </summary >
[DllImport("Wlanapi", EntryPoint = "WlanFreeMemory")] [DllImport("Wlanapi", EntryPoint = "WlanFreeMemory")]
private static extern void WlanFreeMemory([In] IntPtr pMemory); private static extern void WlanFreeMemory([In] IntPtr pMemory);
/// <summary> /// <summary>
/// Defines the state of the interface. e.g. connected, disconnected. /// Defines the state of the interface. e.g. connected, disconnected.
/// </summary> /// </summary>
private enum WLAN_INTERFACE_STATE private enum WLAN_INTERFACE_STATE
{ {
/// <summary> /// <summary>
/// wlan_interface_state_not_ready -> 0 /// wlan_interface_state_not_ready -> 0
/// </summary> /// </summary>
wlan_interface_state_not_ready = 0, wlan_interface_state_not_ready = 0,
/// <summary> /// <summary>
/// wlan_interface_state_connected -> 1 /// wlan_interface_state_connected -> 1
/// </summary> /// </summary>
wlan_interface_state_connected = 1, wlan_interface_state_connected = 1,
/// <summary> /// <summary>
/// wlan_interface_state_ad_hoc_network_formed -> 2 /// wlan_interface_state_ad_hoc_network_formed -> 2
/// </summary> /// </summary>
wlan_interface_state_ad_hoc_network_formed = 2, wlan_interface_state_ad_hoc_network_formed = 2,
/// <summary> /// <summary>
/// wlan_interface_state_disconnecting -> 3 /// wlan_interface_state_disconnecting -> 3
/// </summary> /// </summary>
wlan_interface_state_disconnecting = 3, wlan_interface_state_disconnecting = 3,
/// <summary> /// <summary>
/// wlan_interface_state_disconnected -> 4 /// wlan_interface_state_disconnected -> 4
/// </summary> /// </summary>
wlan_interface_state_disconnected = 4, wlan_interface_state_disconnected = 4,
/// <summary> /// <summary>
/// wlan_interface_state_associating -> 5 /// wlan_interface_state_associating -> 5
/// </summary> /// </summary>
wlan_interface_state_associating = 5, wlan_interface_state_associating = 5,
/// <summary> /// <summary>
/// wlan_interface_state_discovering -> 6 /// wlan_interface_state_discovering -> 6
/// </summary> /// </summary>
wlan_interface_state_discovering = 6, wlan_interface_state_discovering = 6,
/// <summary> /// <summary>
/// wlan_interface_state_authenticating -> 7 /// wlan_interface_state_authenticating -> 7
/// </summary> /// </summary>
wlan_interface_state_authenticating = 7, wlan_interface_state_authenticating = 7,
} }
/// <summary > /// <summary >
/// Stores interface info /// Stores interface info
/// </summary > /// </summary >
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct WLAN_INTERFACE_INFO private struct WLAN_INTERFACE_INFO
{ {
/// GUID->_GUID /// GUID->_GUID
public Guid InterfaceGuid; public Guid InterfaceGuid;
/// WCHAR[256] /// WCHAR[256]
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string strInterfaceDescription; public string strInterfaceDescription;
/// WLAN_INTERFACE_STATE->_WLAN_INTERFACE_STATE /// WLAN_INTERFACE_STATE->_WLAN_INTERFACE_STATE
public WLAN_INTERFACE_STATE isState; public WLAN_INTERFACE_STATE isState;
} }
/// <summary> /// <summary>
/// Contains an array of NIC information /// Contains an array of NIC information
/// </summary> /// </summary>
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
private struct WLAN_INTERFACE_INFO_LIST private struct WLAN_INTERFACE_INFO_LIST
{ {
/// <summary> /// <summary>
/// Length of <see cref="InterfaceInfo"/> array /// Length of <see cref="InterfaceInfo"/> array
/// </summary> /// </summary>
public Int32 dwNumberOfItems; public Int32 dwNumberOfItems;
/// <summary> /// <summary>
/// This member is not used by the wireless service. Applications can use this member when processing individual interfaces. /// This member is not used by the wireless service. Applications can use this member when processing individual interfaces.
/// </summary> /// </summary>
public Int32 dwIndex; public Int32 dwIndex;
/// <summary> /// <summary>
/// Array of WLAN interfaces. /// Array of WLAN interfaces.
/// </summary> /// </summary>
public WLAN_INTERFACE_INFO[] InterfaceInfo; public WLAN_INTERFACE_INFO[] InterfaceInfo;
/// <summary> /// <summary>
/// Constructor for WLAN_INTERFACE_INFO_LIST. /// Constructor for WLAN_INTERFACE_INFO_LIST.
/// Constructor is needed because the InterfaceInfo member varies based on how many adapters are in the system. /// Constructor is needed because the InterfaceInfo member varies based on how many adapters are in the system.
/// </summary> /// </summary>
/// <param name="pList">the unmanaged pointer containing the list.</param> /// <param name="pList">the unmanaged pointer containing the list.</param>
public WLAN_INTERFACE_INFO_LIST(IntPtr pList) public WLAN_INTERFACE_INFO_LIST(IntPtr pList)
{ {
// The first 4 bytes are the number of WLAN_INTERFACE_INFO structures. // The first 4 bytes are the number of WLAN_INTERFACE_INFO structures.
dwNumberOfItems = Marshal.ReadInt32(pList, 0); dwNumberOfItems = Marshal.ReadInt32(pList, 0);
// The next 4 bytes are the index of the current item in the unmanaged API. // The next 4 bytes are the index of the current item in the unmanaged API.
dwIndex = Marshal.ReadInt32(pList, 4); dwIndex = Marshal.ReadInt32(pList, 4);
// Construct the array of WLAN_INTERFACE_INFO structures. // Construct the array of WLAN_INTERFACE_INFO structures.
InterfaceInfo = new WLAN_INTERFACE_INFO[dwNumberOfItems]; InterfaceInfo = new WLAN_INTERFACE_INFO[dwNumberOfItems];
for (int i = 0; i <= dwNumberOfItems - 1; i++) for (int i = 0; i <= dwNumberOfItems - 1; i++)
{ {
// The offset of the array of structures is 8 bytes past the beginning. // The offset of the array of structures is 8 bytes past the beginning.
// Then, take the index and multiply it by the number of bytes in the // Then, take the index and multiply it by the number of bytes in the
// structure. // structure.
// The length of the WLAN_INTERFACE_INFO structure is 532 bytes - this // The length of the WLAN_INTERFACE_INFO structure is 532 bytes - this
// was determined by doing a Marshall.SizeOf(WLAN_INTERFACE_INFO) // was determined by doing a Marshall.SizeOf(WLAN_INTERFACE_INFO)
IntPtr pItemList = new IntPtr(pList.ToInt64() + (i * 532) + 8); IntPtr pItemList = new IntPtr(pList.ToInt64() + (i * 532) + 8);
// Construct the WLAN_INTERFACE_INFO structure, marshal the unmanaged // Construct the WLAN_INTERFACE_INFO structure, marshal the unmanaged
// structure into it, then copy it to the array of structures. // structure into it, then copy it to the array of structures.
InterfaceInfo[i] = (WLAN_INTERFACE_INFO)Marshal.PtrToStructure(pItemList, typeof(WLAN_INTERFACE_INFO)); InterfaceInfo[i] = (WLAN_INTERFACE_INFO)Marshal.PtrToStructure(pItemList, typeof(WLAN_INTERFACE_INFO));
} }
} }
} }
#endregion #endregion
} }
} }
+104 -104
View File
@@ -1,104 +1,104 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using Disco.Client.Extensions; using Disco.Client.Extensions;
namespace Disco.Client namespace Disco.Client
{ {
public static class Presentation public static class Presentation
{ {
public static bool DelayUI { get; set; } public static bool DelayUI { get; set; }
private static string EscapeMessage(this string Message) private static string EscapeMessage(this string Message)
{ {
if (!string.IsNullOrEmpty(Message)) if (!string.IsNullOrEmpty(Message))
return Message.Replace(",", "{comma}").Replace(Environment.NewLine, "{newline}"); return Message.Replace(",", "{comma}").Replace(Environment.NewLine, "{newline}");
else else
return null; return null;
} }
public static void UpdateStatus(string SubHeading, string Message, bool ShowProgress, int Progress, int TryDelay) public static void UpdateStatus(string SubHeading, string Message, bool ShowProgress, int Progress, int TryDelay)
{ {
Presentation.UpdateStatus(SubHeading, Message, ShowProgress, Progress); Presentation.UpdateStatus(SubHeading, Message, ShowProgress, Progress);
if (TryDelay > 0) if (TryDelay > 0)
Presentation.TryDelay(TryDelay); Presentation.TryDelay(TryDelay);
} }
public static void UpdateStatus(string SubHeading, string Message, bool ShowProgress, int Progress) public static void UpdateStatus(string SubHeading, string Message, bool ShowProgress, int Progress)
{ {
Console.WriteLine("#{0},{1},{2},{3}", SubHeading.EscapeMessage(), Message.EscapeMessage(), ShowProgress.ToString(), Progress.ToString()); Console.WriteLine("#{0},{1},{2},{3}", SubHeading.EscapeMessage(), Message.EscapeMessage(), ShowProgress.ToString(), Progress.ToString());
} }
public static void TryDelay(int Milliseconds) public static void TryDelay(int Milliseconds)
{ {
if (DelayUI) if (DelayUI)
Thread.Sleep(Milliseconds); Thread.Sleep(Milliseconds);
} }
public static void WriteBanner() public static void WriteBanner()
{ {
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
message.Append("Version: ").AppendLine(Assembly.GetExecutingAssembly().GetName().Version.ToString(3)); message.Append("Version: ").AppendLine(Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
message.Append("Device: ").Append(Interop.SystemAudit.DeviceSerialNumber).Append(" (").Append(Interop.SystemAudit.DeviceManufacturer).Append(" ").Append(Interop.SystemAudit.DeviceModel).AppendLine(")"); message.Append("Device: ").Append(Interop.SystemAudit.DeviceSerialNumber).Append(" (").Append(Interop.SystemAudit.DeviceManufacturer).Append(" ").Append(Interop.SystemAudit.DeviceModel).AppendLine(")");
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
UpdateStatus("Preparation Client Started", message.ToString(), false, 0); UpdateStatus("Preparation Client Started", message.ToString(), false, 0);
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
TryDelay(3000); TryDelay(3000);
} }
public static void WriteFatalError(Exception ex) public static void WriteFatalError(Exception ex)
{ {
Console.ForegroundColor = ConsoleColor.Magenta; Console.ForegroundColor = ConsoleColor.Magenta;
ClientServiceException clientServiceException = ex as ClientServiceException; ClientServiceException clientServiceException = ex as ClientServiceException;
if (clientServiceException != null) if (clientServiceException != null)
{ {
UpdateStatus(string.Format("An error occurred during {0}", clientServiceException.ServiceFeature), UpdateStatus(string.Format("An error occurred during {0}", clientServiceException.ServiceFeature),
clientServiceException.Message, false, 0); clientServiceException.Message, false, 0);
} }
else else
{ {
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
message.Append("Type: ").AppendLine(ex.GetType().Name); message.Append("Type: ").AppendLine(ex.GetType().Name);
message.Append("Message: ").AppendLine(ex.Message); message.Append("Message: ").AppendLine(ex.Message);
message.Append("Source: ").AppendLine(ex.Source); message.Append("Source: ").AppendLine(ex.Source);
message.Append("Stack: ").AppendLine(ex.StackTrace); message.Append("Stack: ").AppendLine(ex.StackTrace);
UpdateStatus("An error occurred", message.ToString(), false, 0); UpdateStatus("An error occurred", message.ToString(), false, 0);
} }
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
TryDelay(30000); TryDelay(30000);
} }
public static void WriteFooter(bool RebootRequired, bool AllowUninstall, bool ErrorEncountered) public static void WriteFooter(bool RebootRequired, bool AllowUninstall, bool ErrorEncountered)
{ {
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
if (ErrorEncountered) if (ErrorEncountered)
{ {
UpdateStatus("Client Finished due to Error", "An error occurred which caused the Preparation Client to stop running.", false, 0); UpdateStatus("Client Finished due to Error", "An error occurred which caused the Preparation Client to stop running.", false, 0);
TryDelay(5000); TryDelay(5000);
} }
else else
{ {
UpdateStatus("Client Finished Successfully", "The Preparation Client finished successfully.", false, 0); UpdateStatus("Client Finished Successfully", "The Preparation Client finished successfully.", false, 0);
TryDelay(1000); TryDelay(1000);
} }
if (RebootRequired) if (RebootRequired)
RegisterBootstrapperPostActions(ShutdownActions.Reboot, AllowUninstall && !ErrorEncountered); RegisterBootstrapperPostActions(ShutdownActions.Reboot, AllowUninstall && !ErrorEncountered);
else else
RegisterBootstrapperPostActions(ShutdownActions.None, AllowUninstall && !ErrorEncountered); RegisterBootstrapperPostActions(ShutdownActions.None, AllowUninstall && !ErrorEncountered);
} }
public static void RegisterBootstrapperPostActions(ShutdownActions ShutdownAction, bool Uninstall) public static void RegisterBootstrapperPostActions(ShutdownActions ShutdownAction, bool Uninstall)
{ {
Console.WriteLine("!{0},{1}", Enum.GetName(typeof(ShutdownActions), ShutdownAction), Uninstall ? "UninstallBootstrapper" : "DontUninstallBootstrapper"); Console.WriteLine("!{0},{1}", Enum.GetName(typeof(ShutdownActions), ShutdownAction), Uninstall ? "UninstallBootstrapper" : "DontUninstallBootstrapper");
} }
public enum ShutdownActions public enum ShutdownActions
{ {
None, None,
Shutdown, Shutdown,
Reboot Reboot
} }
} }
} }
+137 -137
View File
@@ -1,137 +1,137 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Disco.Models.ClientServices; using Disco.Models.ClientServices;
using Disco.Client.Extensions; using Disco.Client.Extensions;
namespace Disco.Client namespace Disco.Client
{ {
public static class Program public static class Program
{ {
public static bool IsAuthenticated { get; set; } public static bool IsAuthenticated { get; set; }
public static bool RebootRequired { get; set; } public static bool RebootRequired { get; set; }
public static bool AllowUninstall { get; set; } public static bool AllowUninstall { get; set; }
[STAThread] [STAThread]
public static void Main(string[] args) public static void Main(string[] args)
{ {
bool keepProcessing; bool keepProcessing;
// Initialize Environment Settings // Initialize Environment Settings
SetupEnvironment(); SetupEnvironment();
// Report to Bootstrapper // Report to Bootstrapper
Presentation.WriteBanner(); Presentation.WriteBanner();
// WhoAmI Phase // WhoAmI Phase
keepProcessing = Program.WhoAmI(); keepProcessing = Program.WhoAmI();
// Enrol Phase // Enrol Phase
if (keepProcessing) if (keepProcessing)
keepProcessing = Program.Enrol(); keepProcessing = Program.Enrol();
// End conversation with Bootstrapper // End conversation with Bootstrapper
Presentation.WriteFooter(Program.RebootRequired, Program.AllowUninstall, !keepProcessing); Presentation.WriteFooter(Program.RebootRequired, Program.AllowUninstall, !keepProcessing);
} }
public static void SetupEnvironment() public static void SetupEnvironment()
{ {
// Hookup Unhandled Error Handling // Hookup Unhandled Error Handling
AppDomain.CurrentDomain.UnhandledException += ErrorReporting.CurrentDomain_UnhandledException; AppDomain.CurrentDomain.UnhandledException += ErrorReporting.CurrentDomain_UnhandledException;
// Ignore Local Proxies // Ignore Local Proxies
WebRequest.DefaultWebProxy = new WebProxy(); WebRequest.DefaultWebProxy = new WebProxy();
// Override Http 100 Continue Behavour // Override Http 100 Continue Behavour
ServicePointManager.Expect100Continue = false; ServicePointManager.Expect100Continue = false;
// Assume success unless otherwise notified // Assume success unless otherwise notified
AllowUninstall = true; AllowUninstall = true;
// Detect Disco.Bootstrapper - Create Enable UI Delay if Running // Detect Disco.Bootstrapper - Create Enable UI Delay if Running
try try
{ {
Presentation.DelayUI = (System.Diagnostics.Process.GetProcessesByName("Disco.ClientBootstrapper").Length > 0); Presentation.DelayUI = (System.Diagnostics.Process.GetProcessesByName("Disco.ClientBootstrapper").Length > 0);
} }
catch (Exception) catch (Exception)
{ {
Presentation.DelayUI = true; // Add Delays on Error Presentation.DelayUI = true; // Add Delays on Error
} }
} }
public static bool WhoAmI() public static bool WhoAmI()
{ {
try try
{ {
WhoAmIResponse response; WhoAmIResponse response;
WhoAmI request; WhoAmI request;
// Build Request // Build Request
request = new WhoAmI(); request = new WhoAmI();
// Send Request // Send Request
Presentation.UpdateStatus("Connecting to Preparation Server", "Determining connection authentication, please wait...", true, -1); Presentation.UpdateStatus("Connecting to Preparation Server", "Determining connection authentication, please wait...", true, -1);
response = request.Post(true); response = request.Post(true);
// Process Response // Process Response
response.Process(); response.Process();
// Complete // Complete
return true; return true;
} }
catch (WebException webEx) catch (WebException webEx)
{ {
// Check for 'Unauthenticated' Connection // Check for 'Unauthenticated' Connection
if ((webEx.Status == WebExceptionStatus.ProtocolError) && ((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.Unauthorized) if ((webEx.Status == WebExceptionStatus.ProtocolError) && ((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.Unauthorized)
{ {
WhoAmIExtensions.UnauthenticatedResponse(); WhoAmIExtensions.UnauthenticatedResponse();
return true; return true;
} }
else else
{ {
// Some other Web Error // Some other Web Error
ErrorReporting.ReportError(webEx, false); ErrorReporting.ReportError(webEx, false);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
ErrorReporting.ReportError(ex, true); ErrorReporting.ReportError(ex, true);
} }
return false; return false;
} }
public static bool Enrol() public static bool Enrol()
{ {
try try
{ {
Enrol request; Enrol request;
EnrolResponse response = null; EnrolResponse response = null;
// Build Request // Build Request
Presentation.UpdateStatus("Enrolling Device", "Building enrolment request and preparing to send data to the server.", true, -1); Presentation.UpdateStatus("Enrolling Device", "Building enrolment request and preparing to send data to the server.", true, -1);
request = new Enrol(); request = new Enrol();
request.Build(); request.Build();
// Send Request // Send Request
Presentation.UpdateStatus("Enrolling Device", "Sending the enrolment request to the server.", true, -1); Presentation.UpdateStatus("Enrolling Device", "Sending the enrolment request to the server.", true, -1);
response = request.Post(Program.IsAuthenticated); response = request.Post(Program.IsAuthenticated);
// Process Response // Process Response
Presentation.UpdateStatus("Enrolling Device", "Processing the enrolment response from the server.", true, -1); Presentation.UpdateStatus("Enrolling Device", "Processing the enrolment response from the server.", true, -1);
response.Process(); response.Process();
// Complete // Complete
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
{ {
ErrorReporting.ReportError(ex, true); ErrorReporting.ReportError(ex, true);
return false; return false;
} }
} }
} }
} }
+48 -48
View File
@@ -1,48 +1,48 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<assemblyIdentity version="1.0.0.0" name="DiscoClientBootstrapper.app"/> <assemblyIdentity version="1.0.0.0" name="DiscoClientBootstrapper.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security> <security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC Manifest Options <!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following. requestedExecutionLevel node with one of the following.
<requestedExecutionLevel level="asInvoker" uiAccess="false" /> <requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" /> <requestedExecutionLevel level="highestAvailable" uiAccess="false" />
Specifying requestedExecutionLevel node will disable file and registry virtualization. Specifying requestedExecutionLevel node will disable file and registry virtualization.
If you want to utilize File and Registry Virtualization for backward If you want to utilize File and Registry Virtualization for backward
compatibility then delete the requestedExecutionLevel node. compatibility then delete the requestedExecutionLevel node.
--> -->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges> </requestedPrivileges>
</security> </security>
</trustInfo> </trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application> <application>
<!-- A list of all Windows versions that this application is designed to work with. Windows will automatically select the most compatible environment.--> <!-- A list of all Windows versions that this application is designed to work with. Windows will automatically select the most compatible environment.-->
<!-- If your application is designed to work with Windows 7, uncomment the following supportedOS node--> <!-- If your application is designed to work with Windows 7, uncomment the following supportedOS node-->
<!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>--> <!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>-->
</application> </application>
</compatibility> </compatibility>
<!-- Enable themes for Windows common controls and dialogs (Windows XP and later) --> <!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
<!-- <dependency> <!-- <dependency>
<dependentAssembly> <dependentAssembly>
<assemblyIdentity <assemblyIdentity
type="win32" type="win32"
name="Microsoft.Windows.Common-Controls" name="Microsoft.Windows.Common-Controls"
version="6.0.0.0" version="6.0.0.0"
processorArchitecture="*" processorArchitecture="*"
publicKeyToken="6595b64144ccf1df" publicKeyToken="6595b64144ccf1df"
language="*" language="*"
/> />
</dependentAssembly> </dependentAssembly>
</dependency>--> </dependency>-->
</asmv1:assembly> </asmv1:assembly>
+8 -8
View File
@@ -1,9 +1,9 @@
@ECHO OFF @ECHO OFF
IF /I "%USERDOMAIN%"=="NT AUTHORITY" GOTO RunAsNetworkService IF /I "%USERDOMAIN%"=="NT AUTHORITY" GOTO RunAsNetworkService
Disco.Client.exe Disco.Client.exe
EXIT /B 0 EXIT /B 0
:RunAsNetworkService :RunAsNetworkService
ECHO #Running,Launching Preparation Client, Please wait...{newline}Starting client as 'NT AUTHORITY\Network Service',true,-1 ECHO #Running,Launching Preparation Client, Please wait...{newline}Starting client as 'NT AUTHORITY\Network Service',true,-1
PsExec -acceptula -i -u "NT AUTHORITY\Network Service" -w "%CD%" "%CD%\Start.bat" PsExec -acceptula -i -u "NT AUTHORITY\Network Service" -w "%CD%" "%CD%\Start.bat"
EXIT /B 0 EXIT /B 0
+3 -3
View File
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="Newtonsoft.Json" version="4.5.11" targetFramework="net40-Client" /> <package id="Newtonsoft.Json" version="4.5.11" targetFramework="net40-Client" />
</packages> </packages>
+252 -252
View File
@@ -1,252 +1,252 @@
//#define Debug //#define Debug
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Net; using System.Net;
using System.IO; using System.IO;
using System.Diagnostics; using System.Diagnostics;
namespace Disco.ClientBootstrapper namespace Disco.ClientBootstrapper
{ {
class BootstrapperLoop class BootstrapperLoop
{ {
public Thread LoopThread; public Thread LoopThread;
public delegate void LoopCompleteCallback(); public delegate void LoopCompleteCallback();
private LoopCompleteCallback mLoopCompleteCallback; private LoopCompleteCallback mLoopCompleteCallback;
private IStatus statusUI; private IStatus statusUI;
private string tempWorkingDirectory; private string tempWorkingDirectory;
private StringBuilder errorMessage; private StringBuilder errorMessage;
private Process clientProcess; private Process clientProcess;
public BootstrapperLoop(IStatus StatusUI, LoopCompleteCallback Callback) public BootstrapperLoop(IStatus StatusUI, LoopCompleteCallback Callback)
{ {
this.statusUI = StatusUI; this.statusUI = StatusUI;
this.mLoopCompleteCallback = Callback; this.mLoopCompleteCallback = Callback;
this.errorMessage = new StringBuilder(); this.errorMessage = new StringBuilder();
} }
public void Start() public void Start()
{ {
this.LoopThread = new Thread(new ThreadStart(loopHost)); this.LoopThread = new Thread(new ThreadStart(loopHost));
this.LoopThread.Start(); this.LoopThread.Start();
} }
private void loopHost() private void loopHost()
{ {
try try
{ {
loop(); loop();
} }
catch (Exception ex) catch (Exception ex)
{ {
if (ex.GetType() == typeof(ThreadAbortException)) if (ex.GetType() == typeof(ThreadAbortException))
return; return;
if (ex.GetType() == typeof(ThreadInterruptedException)) if (ex.GetType() == typeof(ThreadInterruptedException))
return; return;
Program.WriteAppError(ex); Program.WriteAppError(ex);
throw; throw;
} }
} }
private void loop() private void loop()
{ {
#if Debug #if Debug
statusUI.UpdateStatus("Waiting for Debugger", "Please wait...", true, -1); statusUI.UpdateStatus("Waiting for Debugger", "Please wait...", true, -1);
try try
{ {
do do
{ {
System.Threading.Thread.Sleep(10); System.Threading.Thread.Sleep(10);
} while (!System.Diagnostics.Debugger.IsAttached); } while (!System.Diagnostics.Debugger.IsAttached);
} }
catch (Exception ex) catch (Exception ex)
{ {
statusUI.UpdateStatus("Error", ex.Message, true, -1); statusUI.UpdateStatus("Error", ex.Message, true, -1);
return; return;
} }
#else #else
statusUI.UpdateStatus("System Preparation (Bootstrapper)", "Starting", "Please wait...", true, -1); statusUI.UpdateStatus("System Preparation (Bootstrapper)", "Starting", "Please wait...", true, -1);
#endif #endif
tempWorkingDirectory = Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), "Disco\\Temp"); tempWorkingDirectory = Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), "Disco\\Temp");
if (!Directory.Exists(tempWorkingDirectory)) if (!Directory.Exists(tempWorkingDirectory))
Directory.CreateDirectory(tempWorkingDirectory); Directory.CreateDirectory(tempWorkingDirectory);
// Check for Network Connectivity // Check for Network Connectivity
statusUI.UpdateStatus(null, "Detecting Network", "Checking network connectivity, Please wait...", true, -1); statusUI.UpdateStatus(null, "Detecting Network", "Checking network connectivity, Please wait...", true, -1);
if (!Interop.NetworkInterop.PingDisco()) if (!Interop.NetworkInterop.PingDisco())
{ {
statusUI.UpdateStatus(null, "Detecting Network", "No network connectivity detected, Diagnosing...", true, -1); statusUI.UpdateStatus(null, "Detecting Network", "No network connectivity detected, Diagnosing...", true, -1);
statusUI_WriteAdapterInfo(); statusUI_WriteAdapterInfo();
if (!Interop.NetworkInterop.PingDisco()) if (!Interop.NetworkInterop.PingDisco())
{ {
// Check for Wireless // Check for Wireless
var hasWireless = (Interop.NetworkInterop.NetworkAdapters.Count(na => na.IsWireless) > 0); var hasWireless = (Interop.NetworkInterop.NetworkAdapters.Count(na => na.IsWireless) > 0);
if (hasWireless) if (hasWireless)
{ {
// True: Do wireless loop // True: Do wireless loop
statusUI.UpdateStatus(null, "Configuring Wireless Network", "Wireless adapter detected, Configuring...", true, -1); statusUI.UpdateStatus(null, "Configuring Wireless Network", "Wireless adapter detected, Configuring...", true, -1);
Interop.NetworkInterop.ConfigureWireless(); Interop.NetworkInterop.ConfigureWireless();
statusUI.UpdateStatus(null, "Waiting for Wireless Network", null, true, 0); statusUI.UpdateStatus(null, "Waiting for Wireless Network", null, true, 0);
for (int i = 0; i < 100; i++) for (int i = 0; i < 100; i++)
{ {
statusUI_WriteAdapterInfo(); statusUI_WriteAdapterInfo();
statusUI.UpdateStatus(null, null, null, true, i); statusUI.UpdateStatus(null, null, null, true, i);
Program.SleepThread(500, false); Program.SleepThread(500, false);
if (Interop.NetworkInterop.PingDisco()) if (Interop.NetworkInterop.PingDisco())
break; break;
} }
if (!Interop.NetworkInterop.PingDisco()) if (!Interop.NetworkInterop.PingDisco())
{ {
statusUI.UpdateStatus(null, "Wireless Network Failed", "Unable to connect to the wireless network, please connect the network cable...", false); statusUI.UpdateStatus(null, "Wireless Network Failed", "Unable to connect to the wireless network, please connect the network cable...", false);
Program.SleepThread(3000, false); Program.SleepThread(3000, false);
} }
} }
if (!Interop.NetworkInterop.PingDisco()) if (!Interop.NetworkInterop.PingDisco())
{ {
// Instruct user to connect network cable // Instruct user to connect network cable
statusUI.UpdateStatus(null, "Please connect the network cable", null); statusUI.UpdateStatus(null, "Please connect the network cable", null);
for (int i = 0; i < 100; i++) for (int i = 0; i < 100; i++)
{ {
statusUI_WriteAdapterInfo(); statusUI_WriteAdapterInfo();
statusUI.UpdateStatus(null, null, null, true, i); statusUI.UpdateStatus(null, null, null, true, i);
Program.SleepThread(500, false); Program.SleepThread(500, false);
if (Interop.NetworkInterop.PingDisco()) if (Interop.NetworkInterop.PingDisco())
break; break;
} }
} }
} }
if (!Interop.NetworkInterop.PingDisco()) if (!Interop.NetworkInterop.PingDisco())
{ {
// Client Failed // Client Failed
if (this.mLoopCompleteCallback != null) if (this.mLoopCompleteCallback != null)
{ {
this.mLoopCompleteCallback.BeginInvoke(null, null); this.mLoopCompleteCallback.BeginInvoke(null, null);
} }
return; return;
} }
} }
// Download Client // Download Client
statusUI.UpdateStatus(null, "Downloading", "Retrieving Preparation Client, Please wait...", true, -1); statusUI.UpdateStatus(null, "Downloading", "Retrieving Preparation Client, Please wait...", true, -1);
string clientSourceLocation = Path.Combine(tempWorkingDirectory, "PreparationClient.zip"); string clientSourceLocation = Path.Combine(tempWorkingDirectory, "PreparationClient.zip");
using (var webClient = new WebClient()) using (var webClient = new WebClient())
{ {
webClient.DownloadFile("http://disco:9292/Services/Client/PreparationClient", clientSourceLocation); webClient.DownloadFile("http://disco:9292/Services/Client/PreparationClient", clientSourceLocation);
} }
// Unzip Client // Unzip Client
statusUI.UpdateStatus(null, "Extracting", "Retrieving Preparation Client, Please wait...", true, -1); statusUI.UpdateStatus(null, "Extracting", "Retrieving Preparation Client, Please wait...", true, -1);
string clientLocation = Path.Combine(tempWorkingDirectory, "PreparationClient"); string clientLocation = Path.Combine(tempWorkingDirectory, "PreparationClient");
if (!Directory.Exists(clientLocation)) if (!Directory.Exists(clientLocation))
Directory.CreateDirectory(clientLocation); Directory.CreateDirectory(clientLocation);
using (var clientSource = Ionic.Zip.ZipFile.Read(clientSourceLocation)) using (var clientSource = Ionic.Zip.ZipFile.Read(clientSourceLocation))
{ {
clientSource.ExtractAll(clientLocation, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently); clientSource.ExtractAll(clientLocation, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
} }
// Launch Client // Launch Client
statusUI.UpdateStatus("System Preparation (Client)", "Running", "Launching Preparation Client, Please wait...", true, -1); statusUI.UpdateStatus("System Preparation (Client)", "Running", "Launching Preparation Client, Please wait...", true, -1);
ProcessStartInfo clientProcessStart = new ProcessStartInfo(Path.Combine(clientLocation, "Start.bat")) ProcessStartInfo clientProcessStart = new ProcessStartInfo(Path.Combine(clientLocation, "Start.bat"))
{ {
WorkingDirectory = clientLocation, WorkingDirectory = clientLocation,
CreateNoWindow = true, CreateNoWindow = true,
RedirectStandardOutput = true, RedirectStandardOutput = true,
UseShellExecute = false, UseShellExecute = false,
}; };
using (clientProcess = Process.Start(clientProcessStart)) using (clientProcess = Process.Start(clientProcessStart))
{ {
// Read StdOutput until End // Read StdOutput until End
try try
{ {
clientProcess.OutputDataReceived += new DataReceivedEventHandler(clientProcess_OutputDataReceived); clientProcess.OutputDataReceived += new DataReceivedEventHandler(clientProcess_OutputDataReceived);
clientProcess.BeginOutputReadLine(); clientProcess.BeginOutputReadLine();
clientProcess.WaitForExit(); clientProcess.WaitForExit();
} }
catch (Exception) { throw; } catch (Exception) { throw; }
finally finally
{ {
try { clientProcess.CloseMainWindow(); } try { clientProcess.CloseMainWindow(); }
catch (Exception) { } catch (Exception) { }
} }
} }
clientProcess = null; clientProcess = null;
// Cleanup // Cleanup
if (Directory.Exists(tempWorkingDirectory)) if (Directory.Exists(tempWorkingDirectory))
Directory.Delete(tempWorkingDirectory, true); Directory.Delete(tempWorkingDirectory, true);
Interop.CertificateInterop.RemoveTempCerts(); Interop.CertificateInterop.RemoveTempCerts();
// Pause if Error // Pause if Error
if (this.errorMessage.Length > 0) if (this.errorMessage.Length > 0)
{ {
Program.SleepThread(10000, true); Program.SleepThread(10000, true);
} }
// End Of Loop // End Of Loop
if (this.mLoopCompleteCallback != null) if (this.mLoopCompleteCallback != null)
{ {
this.mLoopCompleteCallback.BeginInvoke(null, null); this.mLoopCompleteCallback.BeginInvoke(null, null);
} }
} }
void statusUI_WriteAdapterInfo() void statusUI_WriteAdapterInfo()
{ {
var info = new StringBuilder(); var info = new StringBuilder();
foreach (var na in Interop.NetworkInterop.NetworkAdapters) foreach (var na in Interop.NetworkInterop.NetworkAdapters)
{ {
if (na.IsWireless) if (na.IsWireless)
{ {
info.AppendLine(string.Format("{0}: {1}", na.NetConnectionID, na.WirelessConnectionStatusMeaning(na.WirelessConnectionStatus))); info.AppendLine(string.Format("{0}: {1}", na.NetConnectionID, na.WirelessConnectionStatusMeaning(na.WirelessConnectionStatus)));
} }
else else
{ {
info.AppendLine(string.Format("{0}: {1}", na.NetConnectionID, na.ConnectionStatusMeaning(na.ConnectionStatus))); info.AppendLine(string.Format("{0}: {1}", na.NetConnectionID, na.ConnectionStatusMeaning(na.ConnectionStatus)));
} }
} }
statusUI.UpdateStatus(null, null, info.ToString()); statusUI.UpdateStatus(null, null, info.ToString());
} }
void clientProcess_OutputDataReceived(object sender, DataReceivedEventArgs e) void clientProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{ {
if (!string.IsNullOrWhiteSpace(e.Data)) if (!string.IsNullOrWhiteSpace(e.Data))
{ {
System.Diagnostics.Debug.WriteLine(string.Format("OUTPUT: {0}", e.Data)); System.Diagnostics.Debug.WriteLine(string.Format("OUTPUT: {0}", e.Data));
var data = e.Data.Substring(1).Split(new char[] { ',' }); var data = e.Data.Substring(1).Split(new char[] { ',' });
switch (e.Data[0]) switch (e.Data[0])
{ {
case '#': case '#':
if (data.Length == 4) if (data.Length == 4)
{ {
statusUI.UpdateStatus(null, data[0].Replace("{comma}", ","), data[1].Replace("{comma}", ",").Replace("{newline}", Environment.NewLine), bool.Parse(data[2]), int.Parse(data[3])); statusUI.UpdateStatus(null, data[0].Replace("{comma}", ","), data[1].Replace("{comma}", ",").Replace("{newline}", Environment.NewLine), bool.Parse(data[2]), int.Parse(data[3]));
} }
break; break;
case '!': case '!':
Program.PostBootstrapperActions = new List<string>(data); Program.PostBootstrapperActions = new List<string>(data);
break; break;
} }
} }
} }
//void clientProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e) //void clientProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
//{ //{
// if (!string.IsNullOrEmpty(e.Data)) // if (!string.IsNullOrEmpty(e.Data))
// { // {
// System.Diagnostics.Debug.WriteLine(string.Format("ERROR: {0}", e.Data)); // System.Diagnostics.Debug.WriteLine(string.Format("ERROR: {0}", e.Data));
// this.errorMessage.AppendLine(e.Data); // this.errorMessage.AppendLine(e.Data);
// statusUI.UpdateStatus(null, "An Error Occurred", this.errorMessage.ToString(), false); // statusUI.UpdateStatus(null, "An Error Occurred", this.errorMessage.ToString(), false);
// } // }
//} //}
} }
} }
@@ -1,11 +1,11 @@
Option Explicit Option Explicit
Dim objShell, BootstrapperLocation Dim objShell, BootstrapperLocation
Set objShell = CreateObject("WScript.Shell") Set objShell = CreateObject("WScript.Shell")
BootstrapperLocation = Mid(WScript.ScriptFullName, 1, InStrRev(WScript.ScriptFullName, "\")) & "\Disco.ClientBootstrapper.exe" BootstrapperLocation = Mid(WScript.ScriptFullName, 1, InStrRev(WScript.ScriptFullName, "\")) & "\Disco.ClientBootstrapper.exe"
Call objShell.Run("""" & BootstrapperLocation & """ /Install", , True) Call objShell.Run("""" & BootstrapperLocation & """ /Install", , True)
WScript.Echo "Disco Client Bootstrapper Installed" WScript.Echo "Disco Client Bootstrapper Installed"
@@ -1,335 +1,335 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform> <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion> <ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{15BD9561-A3C7-4608-9F7E-F1A1CFB60055}</ProjectGuid> <ProjectGuid>{15BD9561-A3C7-4608-9F7E-F1A1CFB60055}</ProjectGuid>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Disco.ClientBootstrapper</RootNamespace> <RootNamespace>Disco.ClientBootstrapper</RootNamespace>
<AssemblyName>Disco.ClientBootstrapper</AssemblyName> <AssemblyName>Disco.ClientBootstrapper</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile> <TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<PublishUrl>publish\</PublishUrl> <PublishUrl>publish\</PublishUrl>
<Install>true</Install> <Install>true</Install>
<InstallFrom>Disk</InstallFrom> <InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled> <UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode> <UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval> <UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits> <UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically> <UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired> <UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions> <MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision> <ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion> <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper> <IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust> <UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled> <BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget> <PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest> <ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets> <CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules> <CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'">
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets> <CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules> <CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<ApplicationIcon>Icon.ico</ApplicationIcon> <ApplicationIcon>Icon.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent> <RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Management" /> <Reference Include="System.Management" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Deployment" /> <Reference Include="System.Deployment" />
<Reference Include="System.Drawing" /> <Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" /> <Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\BitWriter.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\BitWriter.cs">
<Link>DotNetZip\BZip2\BitWriter.cs</Link> <Link>DotNetZip\BZip2\BitWriter.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\BZip2Compressor.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\BZip2Compressor.cs">
<Link>DotNetZip\BZip2\BZip2Compressor.cs</Link> <Link>DotNetZip\BZip2\BZip2Compressor.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\BZip2InputStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\BZip2InputStream.cs">
<Link>DotNetZip\BZip2\BZip2InputStream.cs</Link> <Link>DotNetZip\BZip2\BZip2InputStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\BZip2OutputStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\BZip2OutputStream.cs">
<Link>DotNetZip\BZip2\BZip2OutputStream.cs</Link> <Link>DotNetZip\BZip2\BZip2OutputStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\ParallelBZip2OutputStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\ParallelBZip2OutputStream.cs">
<Link>DotNetZip\BZip2\ParallelBZip2OutputStream.cs</Link> <Link>DotNetZip\BZip2\ParallelBZip2OutputStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\Rand.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\BZip2\Rand.cs">
<Link>DotNetZip\BZip2\Rand.cs</Link> <Link>DotNetZip\BZip2\Rand.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\CommonSrc\CRC32.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\CommonSrc\CRC32.cs">
<Link>DotNetZip\CRC32.cs</Link> <Link>DotNetZip\CRC32.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ComHelper.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ComHelper.cs">
<Link>DotNetZip\Zip\ComHelper.cs</Link> <Link>DotNetZip\Zip\ComHelper.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\EncryptionAlgorithm.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\EncryptionAlgorithm.cs">
<Link>DotNetZip\Zip\EncryptionAlgorithm.cs</Link> <Link>DotNetZip\Zip\EncryptionAlgorithm.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\Events.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\Events.cs">
<Link>DotNetZip\Zip\Events.cs</Link> <Link>DotNetZip\Zip\Events.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\Exceptions.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\Exceptions.cs">
<Link>DotNetZip\Zip\Exceptions.cs</Link> <Link>DotNetZip\Zip\Exceptions.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ExtractExistingFileAction.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ExtractExistingFileAction.cs">
<Link>DotNetZip\Zip\ExtractExistingFileAction.cs</Link> <Link>DotNetZip\Zip\ExtractExistingFileAction.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\FileSelector.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\FileSelector.cs">
<Link>DotNetZip\Zip\FileSelector.cs</Link> <Link>DotNetZip\Zip\FileSelector.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\OffsetStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\OffsetStream.cs">
<Link>DotNetZip\Zip\OffsetStream.cs</Link> <Link>DotNetZip\Zip\OffsetStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\Shared.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\Shared.cs">
<Link>DotNetZip\Zip\Shared.cs</Link> <Link>DotNetZip\Zip\Shared.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\WinZipAes.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\WinZipAes.cs">
<Link>DotNetZip\Zip\WinZipAes.cs</Link> <Link>DotNetZip\Zip\WinZipAes.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipConstants.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipConstants.cs">
<Link>DotNetZip\Zip\ZipConstants.cs</Link> <Link>DotNetZip\Zip\ZipConstants.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipCrypto.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipCrypto.cs">
<Link>DotNetZip\Zip\ZipCrypto.cs</Link> <Link>DotNetZip\Zip\ZipCrypto.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipDirEntry.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipDirEntry.cs">
<Link>DotNetZip\Zip\ZipDirEntry.cs</Link> <Link>DotNetZip\Zip\ZipDirEntry.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntry.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntry.cs">
<Link>DotNetZip\Zip\ZipEntry.cs</Link> <Link>DotNetZip\Zip\ZipEntry.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntry.Extract.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntry.Extract.cs">
<Link>DotNetZip\Zip\ZipEntry.Extract.cs</Link> <Link>DotNetZip\Zip\ZipEntry.Extract.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntry.Read.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntry.Read.cs">
<Link>DotNetZip\Zip\ZipEntry.Read.cs</Link> <Link>DotNetZip\Zip\ZipEntry.Read.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntry.Write.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntry.Write.cs">
<Link>DotNetZip\Zip\ZipEntry.Write.cs</Link> <Link>DotNetZip\Zip\ZipEntry.Write.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntrySource.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipEntrySource.cs">
<Link>DotNetZip\Zip\ZipEntrySource.cs</Link> <Link>DotNetZip\Zip\ZipEntrySource.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipErrorAction.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipErrorAction.cs">
<Link>DotNetZip\Zip\ZipErrorAction.cs</Link> <Link>DotNetZip\Zip\ZipErrorAction.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.AddUpdate.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.AddUpdate.cs">
<Link>DotNetZip\Zip\ZipFile.AddUpdate.cs</Link> <Link>DotNetZip\Zip\ZipFile.AddUpdate.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Check.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Check.cs">
<Link>DotNetZip\Zip\ZipFile.Check.cs</Link> <Link>DotNetZip\Zip\ZipFile.Check.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.cs">
<Link>DotNetZip\Zip\ZipFile.cs</Link> <Link>DotNetZip\Zip\ZipFile.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Events.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Events.cs">
<Link>DotNetZip\Zip\ZipFile.Events.cs</Link> <Link>DotNetZip\Zip\ZipFile.Events.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Extract.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Extract.cs">
<Link>DotNetZip\Zip\ZipFile.Extract.cs</Link> <Link>DotNetZip\Zip\ZipFile.Extract.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Read.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Read.cs">
<Link>DotNetZip\Zip\ZipFile.Read.cs</Link> <Link>DotNetZip\Zip\ZipFile.Read.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Save.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Save.cs">
<Link>DotNetZip\Zip\ZipFile.Save.cs</Link> <Link>DotNetZip\Zip\ZipFile.Save.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.SaveSelfExtractor.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.SaveSelfExtractor.cs">
<Link>DotNetZip\Zip\ZipFile.SaveSelfExtractor.cs</Link> <Link>DotNetZip\Zip\ZipFile.SaveSelfExtractor.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Selector.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.Selector.cs">
<Link>DotNetZip\Zip\ZipFile.Selector.cs</Link> <Link>DotNetZip\Zip\ZipFile.Selector.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.x-IEnumerable.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipFile.x-IEnumerable.cs">
<Link>DotNetZip\Zip\ZipFile.x-IEnumerable.cs</Link> <Link>DotNetZip\Zip\ZipFile.x-IEnumerable.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipInputStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipInputStream.cs">
<Link>DotNetZip\Zip\ZipInputStream.cs</Link> <Link>DotNetZip\Zip\ZipInputStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipOutputStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipOutputStream.cs">
<Link>DotNetZip\Zip\ZipOutputStream.cs</Link> <Link>DotNetZip\Zip\ZipOutputStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipSegmentedStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zip\ZipSegmentedStream.cs">
<Link>DotNetZip\Zip\ZipSegmentedStream.cs</Link> <Link>DotNetZip\Zip\ZipSegmentedStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\Deflate.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\Deflate.cs">
<Link>DotNetZip\Zlib\Deflate.cs</Link> <Link>DotNetZip\Zlib\Deflate.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\DeflateStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\DeflateStream.cs">
<Link>DotNetZip\Zlib\DeflateStream.cs</Link> <Link>DotNetZip\Zlib\DeflateStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\GZipStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\GZipStream.cs">
<Link>DotNetZip\Zlib\GZipStream.cs</Link> <Link>DotNetZip\Zlib\GZipStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\Inflate.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\Inflate.cs">
<Link>DotNetZip\Zlib\Inflate.cs</Link> <Link>DotNetZip\Zlib\Inflate.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\InfTree.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\InfTree.cs">
<Link>DotNetZip\Zlib\InfTree.cs</Link> <Link>DotNetZip\Zlib\InfTree.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ParallelDeflateOutputStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ParallelDeflateOutputStream.cs">
<Link>DotNetZip\Zlib\ParallelDeflateOutputStream.cs</Link> <Link>DotNetZip\Zlib\ParallelDeflateOutputStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\Tree.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\Tree.cs">
<Link>DotNetZip\Zlib\Tree.cs</Link> <Link>DotNetZip\Zlib\Tree.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\Zlib.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\Zlib.cs">
<Link>DotNetZip\Zlib\Zlib.cs</Link> <Link>DotNetZip\Zlib\Zlib.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ZlibBaseStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ZlibBaseStream.cs">
<Link>DotNetZip\Zlib\ZlibBaseStream.cs</Link> <Link>DotNetZip\Zlib\ZlibBaseStream.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ZlibCodec.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ZlibCodec.cs">
<Link>DotNetZip\Zlib\ZlibCodec.cs</Link> <Link>DotNetZip\Zlib\ZlibCodec.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ZlibConstants.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ZlibConstants.cs">
<Link>DotNetZip\Zlib\ZlibConstants.cs</Link> <Link>DotNetZip\Zlib\ZlibConstants.cs</Link>
</Compile> </Compile>
<Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ZlibStream.cs"> <Compile Include="..\Resources\Libraries\DotNetZip\Source\Zlib\ZlibStream.cs">
<Link>DotNetZip\Zlib\ZlibStream.cs</Link> <Link>DotNetZip\Zlib\ZlibStream.cs</Link>
</Compile> </Compile>
<Compile Include="BootstrapperLoop.cs" /> <Compile Include="BootstrapperLoop.cs" />
<Compile Include="InstallLoop.cs" /> <Compile Include="InstallLoop.cs" />
<Compile Include="Interop\CertificateInterop.cs" /> <Compile Include="Interop\CertificateInterop.cs" />
<Compile Include="FormStatus.cs"> <Compile Include="FormStatus.cs">
<SubType>Form</SubType> <SubType>Form</SubType>
</Compile> </Compile>
<Compile Include="FormStatus.Designer.cs"> <Compile Include="FormStatus.Designer.cs">
<DependentUpon>FormStatus.cs</DependentUpon> <DependentUpon>FormStatus.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="Interop\NetworkAdapter.cs" /> <Compile Include="Interop\NetworkAdapter.cs" />
<Compile Include="Interop\NetworkInterop.cs" /> <Compile Include="Interop\NetworkInterop.cs" />
<Compile Include="Interop\RegistryInterop.cs" /> <Compile Include="Interop\RegistryInterop.cs" />
<Compile Include="Interop\ShutdownInterop.cs" /> <Compile Include="Interop\ShutdownInterop.cs" />
<Compile Include="Interop\InstallInterop.cs" /> <Compile Include="Interop\InstallInterop.cs" />
<Compile Include="Interop\WIMInterop.cs" /> <Compile Include="Interop\WIMInterop.cs" />
<Compile Include="IStatus.cs" /> <Compile Include="IStatus.cs" />
<Compile Include="NullStatus.cs" /> <Compile Include="NullStatus.cs" />
<Compile Include="Program.cs" /> <Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="FormStatus.resx"> <EmbeddedResource Include="FormStatus.resx">
<DependentUpon>FormStatus.cs</DependentUpon> <DependentUpon>FormStatus.cs</DependentUpon>
</EmbeddedResource> </EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx"> <EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator> <Generator>ResXFileCodeGenerator</Generator>
<SubType>Designer</SubType> <SubType>Designer</SubType>
<LastGenOutput>Resources.Designer.cs</LastGenOutput> <LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource> </EmbeddedResource>
<None Include="Properties\app.manifest" /> <None Include="Properties\app.manifest" />
<None Include="Properties\Settings.settings"> <None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator> <Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput> <LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None> </None>
<Compile Include="Properties\Resources.Designer.cs"> <Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen> <AutoGen>True</AutoGen>
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon> <DependentUpon>Resources.resx</DependentUpon>
</Compile> </Compile>
<Compile Include="Properties\Settings.Designer.cs"> <Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen> <AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon> <DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput> <DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile> </Compile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.0,Profile=Client"> <BootstrapperPackage Include=".NETFramework,Version=v4.0,Profile=Client">
<Visible>False</Visible> <Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4 Client Profile %28x86 and x64%29</ProductName> <ProductName>Microsoft .NET Framework 4 Client Profile %28x86 and x64%29</ProductName>
<Install>true</Install> <Install>true</Install>
</BootstrapperPackage> </BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5"> <BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible> <Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName> <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install> <Install>false</Install>
</BootstrapperPackage> </BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1"> <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible> <Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName> <ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install> <Install>false</Install>
</BootstrapperPackage> </BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1"> <BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible> <Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName> <ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install> <Install>true</Install>
</BootstrapperPackage> </BootstrapperPackage>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Include="BootstrapperWorkstationInstall.vbs"> <Content Include="BootstrapperWorkstationInstall.vbs">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
<Content Include="Icon.ico" /> <Content Include="Icon.ico" />
<Content Include="InstallBootstrapper.vbs" /> <Content Include="InstallBootstrapper.vbs" />
<None Include="Resources\Background-BW.png" /> <None Include="Resources\Background-BW.png" />
<Content Include="UninstallBootstrapper.vbs" /> <Content Include="UninstallBootstrapper.vbs" />
</ItemGroup> </ItemGroup>
<ItemGroup /> <ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<ProjectExtensions> <ProjectExtensions>
<VisualStudio> <VisualStudio>
<UserProperties BuildVersion_StartDate="2001/1/1" BuildVersion_DetectChanges="False" BuildVersion_UpdateAssemblyVersion="False" BuildVersion_UpdateFileVersion="False" BuildVersion_UseGlobalSettings="True" BuildVersion_BuildAction="ReBuild" /> <UserProperties BuildVersion_StartDate="2001/1/1" BuildVersion_DetectChanges="False" BuildVersion_UpdateAssemblyVersion="False" BuildVersion_UpdateFileVersion="False" BuildVersion_UseGlobalSettings="True" BuildVersion_BuildAction="ReBuild" />
</VisualStudio> </VisualStudio>
</ProjectExtensions> </ProjectExtensions>
<PropertyGroup> <PropertyGroup>
<PostBuildEvent>COPY "$(TargetPath)" "$(ProjectDir)..\Disco.Web\ClientBin"</PostBuildEvent> <PostBuildEvent>COPY "$(TargetPath)" "$(ProjectDir)..\Disco.Web\ClientBin"</PostBuildEvent>
</PropertyGroup> </PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">
</Target> </Target>
<Target Name="AfterBuild"> <Target Name="AfterBuild">
</Target> </Target>
--> -->
</Project> </Project>
+125 -125
View File
@@ -1,125 +1,125 @@
namespace Disco.ClientBootstrapper namespace Disco.ClientBootstrapper
{ {
partial class FormStatus partial class FormStatus
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.labelHeading = new System.Windows.Forms.Label(); this.labelHeading = new System.Windows.Forms.Label();
this.progressBar = new System.Windows.Forms.ProgressBar(); this.progressBar = new System.Windows.Forms.ProgressBar();
this.labelSubHeading = new System.Windows.Forms.Label(); this.labelSubHeading = new System.Windows.Forms.Label();
this.labelMessage = new System.Windows.Forms.Label(); this.labelMessage = new System.Windows.Forms.Label();
this.labelVersion = new System.Windows.Forms.Label(); this.labelVersion = new System.Windows.Forms.Label();
this.SuspendLayout(); this.SuspendLayout();
// //
// labelHeading // labelHeading
// //
this.labelHeading.BackColor = System.Drawing.Color.Transparent; this.labelHeading.BackColor = System.Drawing.Color.Transparent;
this.labelHeading.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelHeading.Font = new System.Drawing.Font("Microsoft Sans Serif", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelHeading.Location = new System.Drawing.Point(15, 15); this.labelHeading.Location = new System.Drawing.Point(15, 15);
this.labelHeading.Name = "labelHeading"; this.labelHeading.Name = "labelHeading";
this.labelHeading.Size = new System.Drawing.Size(270, 20); this.labelHeading.Size = new System.Drawing.Size(270, 20);
this.labelHeading.TabIndex = 0; this.labelHeading.TabIndex = 0;
this.labelHeading.Text = "System Preparation"; this.labelHeading.Text = "System Preparation";
// //
// progressBar // progressBar
// //
this.progressBar.BackColor = System.Drawing.Color.White; this.progressBar.BackColor = System.Drawing.Color.White;
this.progressBar.Location = new System.Drawing.Point(15, 100); this.progressBar.Location = new System.Drawing.Point(15, 100);
this.progressBar.Margin = new System.Windows.Forms.Padding(2); this.progressBar.Margin = new System.Windows.Forms.Padding(2);
this.progressBar.MarqueeAnimationSpeed = 50; this.progressBar.MarqueeAnimationSpeed = 50;
this.progressBar.Name = "progressBar"; this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(381, 15); this.progressBar.Size = new System.Drawing.Size(381, 15);
this.progressBar.Style = System.Windows.Forms.ProgressBarStyle.Marquee; this.progressBar.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
this.progressBar.TabIndex = 1; this.progressBar.TabIndex = 1;
this.progressBar.Visible = false; this.progressBar.Visible = false;
// //
// labelSubHeading // labelSubHeading
// //
this.labelSubHeading.BackColor = System.Drawing.Color.White; this.labelSubHeading.BackColor = System.Drawing.Color.White;
this.labelSubHeading.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelSubHeading.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelSubHeading.Location = new System.Drawing.Point(15, 35); this.labelSubHeading.Location = new System.Drawing.Point(15, 35);
this.labelSubHeading.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labelSubHeading.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelSubHeading.Name = "labelSubHeading"; this.labelSubHeading.Name = "labelSubHeading";
this.labelSubHeading.Size = new System.Drawing.Size(381, 20); this.labelSubHeading.Size = new System.Drawing.Size(381, 20);
this.labelSubHeading.TabIndex = 2; this.labelSubHeading.TabIndex = 2;
// //
// labelMessage // labelMessage
// //
this.labelMessage.BackColor = System.Drawing.Color.White; this.labelMessage.BackColor = System.Drawing.Color.White;
this.labelMessage.Location = new System.Drawing.Point(15, 55); this.labelMessage.Location = new System.Drawing.Point(15, 55);
this.labelMessage.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labelMessage.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.labelMessage.Name = "labelMessage"; this.labelMessage.Name = "labelMessage";
this.labelMessage.Size = new System.Drawing.Size(381, 60); this.labelMessage.Size = new System.Drawing.Size(381, 60);
this.labelMessage.TabIndex = 3; this.labelMessage.TabIndex = 3;
// //
// labelVersion // labelVersion
// //
this.labelVersion.BackColor = System.Drawing.Color.White; this.labelVersion.BackColor = System.Drawing.Color.White;
this.labelVersion.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelVersion.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelVersion.ForeColor = System.Drawing.Color.Gray; this.labelVersion.ForeColor = System.Drawing.Color.Gray;
this.labelVersion.Location = new System.Drawing.Point(229, 15); this.labelVersion.Location = new System.Drawing.Point(229, 15);
this.labelVersion.Name = "labelVersion"; this.labelVersion.Name = "labelVersion";
this.labelVersion.Size = new System.Drawing.Size(167, 20); this.labelVersion.Size = new System.Drawing.Size(167, 20);
this.labelVersion.TabIndex = 0; this.labelVersion.TabIndex = 0;
this.labelVersion.Text = "Disco Bootstrapper v"; this.labelVersion.Text = "Disco Bootstrapper v";
this.labelVersion.TextAlign = System.Drawing.ContentAlignment.TopRight; this.labelVersion.TextAlign = System.Drawing.ContentAlignment.TopRight;
// //
// FormStatus // FormStatus
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::Disco.ClientBootstrapper.Properties.Resources.Background_BW; this.BackgroundImage = global::Disco.ClientBootstrapper.Properties.Resources.Background_BW;
this.ClientSize = new System.Drawing.Size(411, 130); this.ClientSize = new System.Drawing.Size(411, 130);
this.Controls.Add(this.labelHeading); this.Controls.Add(this.labelHeading);
this.Controls.Add(this.labelSubHeading); this.Controls.Add(this.labelSubHeading);
this.Controls.Add(this.progressBar); this.Controls.Add(this.progressBar);
this.Controls.Add(this.labelVersion); this.Controls.Add(this.labelVersion);
this.Controls.Add(this.labelMessage); this.Controls.Add(this.labelMessage);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false; this.MaximizeBox = false;
this.MinimizeBox = false; this.MinimizeBox = false;
this.Name = "FormStatus"; this.Name = "FormStatus";
this.ShowIcon = false; this.ShowIcon = false;
this.ShowInTaskbar = false; this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Disco - Client Bootstrapper"; this.Text = "Disco - Client Bootstrapper";
this.TopMost = true; this.TopMost = true;
this.TransparencyKey = System.Drawing.Color.Magenta; this.TransparencyKey = System.Drawing.Color.Magenta;
this.ResumeLayout(false); this.ResumeLayout(false);
} }
#endregion #endregion
private System.Windows.Forms.Label labelHeading; private System.Windows.Forms.Label labelHeading;
private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.ProgressBar progressBar;
private System.Windows.Forms.Label labelSubHeading; private System.Windows.Forms.Label labelSubHeading;
private System.Windows.Forms.Label labelMessage; private System.Windows.Forms.Label labelMessage;
private System.Windows.Forms.Label labelVersion; private System.Windows.Forms.Label labelVersion;
} }
} }
+82 -82
View File
@@ -1,82 +1,82 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Data; using System.Data;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
namespace Disco.ClientBootstrapper namespace Disco.ClientBootstrapper
{ {
public partial class FormStatus : Form, IStatus public partial class FormStatus : Form, IStatus
{ {
private delegate void dUpdateStatus(string Heading, string SubHeading, string Message, Nullable<bool> ShowProgress, Nullable<int> Progress); private delegate void dUpdateStatus(string Heading, string SubHeading, string Message, Nullable<bool> ShowProgress, Nullable<int> Progress);
private dUpdateStatus mUpdateStatus; private dUpdateStatus mUpdateStatus;
public FormStatus() public FormStatus()
{ {
InitializeComponent(); InitializeComponent();
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
this.labelVersion.Text = string.Format("v{0}", version.ToString(3)); this.labelVersion.Text = string.Format("v{0}", version.ToString(3));
this.FormClosed += new FormClosedEventHandler(FormStatus_FormClosed); this.FormClosed += new FormClosedEventHandler(FormStatus_FormClosed);
mUpdateStatus = new dUpdateStatus(UpdateStatusDo); mUpdateStatus = new dUpdateStatus(UpdateStatusDo);
Cursor.Hide(); Cursor.Hide();
} }
void FormStatus_FormClosed(object sender, FormClosedEventArgs e) void FormStatus_FormClosed(object sender, FormClosedEventArgs e)
{ {
Cursor.Show(); Cursor.Show();
Program.ExitApplication(); Program.ExitApplication();
} }
public void UpdateStatus(string Heading, string SubHeading, string Message, Nullable<bool> ShowProgress = null, Nullable<int> Progress = null) public void UpdateStatus(string Heading, string SubHeading, string Message, Nullable<bool> ShowProgress = null, Nullable<int> Progress = null)
{ {
try try
{ {
this.Invoke(mUpdateStatus, Heading, SubHeading, Message, ShowProgress, Progress); this.Invoke(mUpdateStatus, Heading, SubHeading, Message, ShowProgress, Progress);
} }
catch (Exception) { } catch (Exception) { }
} }
private void UpdateStatusDo(string Heading, string SubHeading, string Message, Nullable<bool> ShowProgress, Nullable<int> Progress) private void UpdateStatusDo(string Heading, string SubHeading, string Message, Nullable<bool> ShowProgress, Nullable<int> Progress)
{ {
if (Heading != null) if (Heading != null)
if (this.labelHeading.Text != Heading) if (this.labelHeading.Text != Heading)
this.labelHeading.Text = Heading; this.labelHeading.Text = Heading;
if (SubHeading != null) if (SubHeading != null)
if (this.labelSubHeading.Text != SubHeading) if (this.labelSubHeading.Text != SubHeading)
this.labelSubHeading.Text = SubHeading; this.labelSubHeading.Text = SubHeading;
if (Message != null) if (Message != null)
if (this.labelMessage.Text != Message) if (this.labelMessage.Text != Message)
this.labelMessage.Text = Message; this.labelMessage.Text = Message;
if (ShowProgress.HasValue) if (ShowProgress.HasValue)
{ {
if (ShowProgress.Value) if (ShowProgress.Value)
{ {
this.progressBar.Visible = true; this.progressBar.Visible = true;
if (Progress.HasValue) if (Progress.HasValue)
{ {
if (Progress.Value > 0) if (Progress.Value > 0)
{ {
this.progressBar.Value = Math.Min(Progress.Value, 100); this.progressBar.Value = Math.Min(Progress.Value, 100);
this.progressBar.Style = ProgressBarStyle.Continuous; this.progressBar.Style = ProgressBarStyle.Continuous;
} }
else else
{ {
this.progressBar.Style = ProgressBarStyle.Marquee; this.progressBar.Style = ProgressBarStyle.Marquee;
} }
} }
} }
else else
{ {
this.progressBar.Visible = false; this.progressBar.Visible = false;
} }
} }
} }
} }
} }
+119 -119
View File
@@ -1,120 +1,120 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value> <value>[base64 mime encoded serialized .NET Framework object]</value>
</data> </data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType> <xsd:complexType>
<xsd:choice maxOccurs="unbounded"> <xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata"> <xsd:element name="metadata">
<xsd:complexType> <xsd:complexType>
<xsd:sequence> <xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" /> <xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence> </xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" /> <xsd:attribute ref="xml:space" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="assembly"> <xsd:element name="assembly">
<xsd:complexType> <xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="data"> <xsd:element name="data">
<xsd:complexType> <xsd:complexType>
<xsd:sequence> <xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence> </xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" /> <xsd:attribute ref="xml:space" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="resheader"> <xsd:element name="resheader">
<xsd:complexType> <xsd:complexType>
<xsd:sequence> <xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence> </xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" /> <xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
</xsd:choice> </xsd:choice>
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
</xsd:schema> </xsd:schema>
<resheader name="resmimetype"> <resheader name="resmimetype">
<value>text/microsoft-resx</value> <value>text/microsoft-resx</value>
</resheader> </resheader>
<resheader name="version"> <resheader name="version">
<value>2.0</value> <value>2.0</value>
</resheader> </resheader>
<resheader name="reader"> <resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
</root> </root>
+12 -12
View File
@@ -1,12 +1,12 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
namespace Disco.ClientBootstrapper namespace Disco.ClientBootstrapper
{ {
interface IStatus interface IStatus
{ {
void UpdateStatus(string Heading, string SubHeading, string Message, Nullable<bool> ShowProgress = null, Nullable<int> Progress = null); void UpdateStatus(string Heading, string SubHeading, string Message, Nullable<bool> ShowProgress = null, Nullable<int> Progress = null);
} }
} }
@@ -1,62 +1,62 @@
Option Explicit Option Explicit
Dim objFSO, objReg, objShell, objFile Dim objFSO, objReg, objShell, objFile
Dim SourceFolder, DestinationFolder, GroupPolicyScriptLocation Dim SourceFolder, DestinationFolder, GroupPolicyScriptLocation
Const HKLM = &H80000002 Const HKLM = &H80000002
DestinationFolder = "C:\Disco" DestinationFolder = "C:\Disco"
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objReg = GetObject("winmgmts:root\default:StdRegProv") Set objReg = GetObject("winmgmts:root\default:StdRegProv")
Set objShell = CreateObject("WScript.Shell") Set objShell = CreateObject("WScript.Shell")
If objFSO.FolderExists(DestinationFolder) Then If objFSO.FolderExists(DestinationFolder) Then
Call objFSO.DeleteFolder(DestinationFolder) Call objFSO.DeleteFolder(DestinationFolder)
End If End If
Call objFSO.CreateFolder(DestinationFolder) Call objFSO.CreateFolder(DestinationFolder)
SourceFolder = Mid(WScript.ScriptFullName, 1, InStrRev(WScript.ScriptFullName, "\")) SourceFolder = Mid(WScript.ScriptFullName, 1, InStrRev(WScript.ScriptFullName, "\"))
Call objFSO.CopyFile(SourceFolder & "*.*", DestinationFolder, True) Call objFSO.CopyFile(SourceFolder & "*.*", DestinationFolder, True)
GroupPolicyScriptLocation = objShell.ExpandEnvironmentStrings("%WinDir%\System32\GroupPolicy\Machine\Scripts\scripts.ini") GroupPolicyScriptLocation = objShell.ExpandEnvironmentStrings("%WinDir%\System32\GroupPolicy\Machine\Scripts\scripts.ini")
If objFSO.FileExists(GroupPolicyScriptLocation) Then If objFSO.FileExists(GroupPolicyScriptLocation) Then
Call objFSO.DeleteFile(GroupPolicyScriptLocation) Call objFSO.DeleteFile(GroupPolicyScriptLocation)
End If End If
Set objFile = objFSO.CreateTextFile(GroupPolicyScriptLocation, True, True) Set objFile = objFSO.CreateTextFile(GroupPolicyScriptLocation, True, True)
Call objFile.WriteLine() Call objFile.WriteLine()
Call objFile.WriteLine("[Startup]") Call objFile.WriteLine("[Startup]")
Call objFile.WriteLine("0CmdLine=C:\Disco\Disco.ClientBootstrapper.exe") Call objFile.WriteLine("0CmdLine=C:\Disco\Disco.ClientBootstrapper.exe")
Call objFile.WriteLine("0Parameters=/Uninstall") Call objFile.WriteLine("0Parameters=/Uninstall")
Call objFile.Close() Call objFile.Close()
Set objFile = Nothing Set objFile = Nothing
Set objFSO = Nothing Set objFSO = Nothing
Call objReg.SetDWORDValue(HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "HideStartupScripts", 0) Call objReg.SetDWORDValue(HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "HideStartupScripts", 0)
Call objReg.SetDWORDValue (HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "RunStartupScriptSync", 1) Call objReg.SetDWORDValue (HKLM, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", "RunStartupScriptSync", 1)
Call objReg.CreateKey(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown") Call objReg.CreateKey(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown")
Call objReg.CreateKey(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0") Call objReg.CreateKey(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "GPO-ID", "LocalGPO") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "GPO-ID", "LocalGPO")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "SOM-ID", "Local") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "SOM-ID", "Local")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "FileSysPath", "C:\WINDOWS\System32\GroupPolicy\Machine") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "FileSysPath", "C:\WINDOWS\System32\GroupPolicy\Machine")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "DisplayName", "Local Group Policy") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "DisplayName", "Local Group Policy")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "GPOName", "Local Group Policy") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "GPOName", "Local Group Policy")
Call objReg.SetDWORDValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "PSScriptOrder", 1) Call objReg.SetDWORDValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0", "PSScriptOrder", 1)
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0", "Script", DestinationFolder & "\Disco.ClientBootstrapper.exe") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0", "Script", DestinationFolder & "\Disco.ClientBootstrapper.exe")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0", "Parameters", "/Uninstall") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0", "Parameters", "/Uninstall")
Call objReg.SetDWORDValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0", "IsPowershell", 0) Call objReg.SetDWORDValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0", "IsPowershell", 0)
Call objReg.SetBinaryValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0", "ExecTime", array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)) Call objReg.SetBinaryValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup\0\0", "ExecTime", array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))
Call objReg.CreateKey(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown") Call objReg.CreateKey(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown")
Call objReg.CreateKey(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0") Call objReg.CreateKey(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "GPO-ID", "LocalGPO") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "GPO-ID", "LocalGPO")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "SOM-ID", "Local") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "SOM-ID", "Local")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "FileSysPath", "C:\Windows\System32\GroupPolicy\Machine") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "FileSysPath", "C:\Windows\System32\GroupPolicy\Machine")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "DisplayName", "Local Group Policy") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "DisplayName", "Local Group Policy")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "GPOName", "Local Group Policy") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "GPOName", "Local Group Policy")
Call objReg.SetDWORDValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "PSScriptOrder", 1) Call objReg.SetDWORDValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0", "PSScriptOrder", 1)
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0", "Script", DestinationFolder & "\Disco.ClientBootstrapper.exe") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0", "Script", DestinationFolder & "\Disco.ClientBootstrapper.exe")
Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0", "Parameters", "/Uninstall") Call objReg.SetStringValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0", "Parameters", "/Uninstall")
Call objReg.SetBinaryValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0", "ExecTime", array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)) Call objReg.SetBinaryValue(HKLM, "SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup\0\0", "ExecTime", array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0))
Set objReg = Nothing Set objReg = Nothing
+55 -55
View File
@@ -1,55 +1,55 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
namespace Disco.ClientBootstrapper namespace Disco.ClientBootstrapper
{ {
class InstallLoop class InstallLoop
{ {
public Thread LoopThread; public Thread LoopThread;
public delegate void CompleteCallback(); public delegate void CompleteCallback();
private CompleteCallback mCompleteCallback; private CompleteCallback mCompleteCallback;
private string InstallLocation; private string InstallLocation;
private string WimImageId; private string WimImageId;
public InstallLoop(string InstallLocation, string WimImageId = null) public InstallLoop(string InstallLocation, string WimImageId = null)
{ {
this.InstallLocation = InstallLocation; this.InstallLocation = InstallLocation;
this.WimImageId = WimImageId; this.WimImageId = WimImageId;
} }
public void Start(CompleteCallback Callback) public void Start(CompleteCallback Callback)
{ {
this.mCompleteCallback = Callback; this.mCompleteCallback = Callback;
this.LoopThread = new Thread(new ThreadStart(loopHost)); this.LoopThread = new Thread(new ThreadStart(loopHost));
this.LoopThread.Start(); this.LoopThread.Start();
} }
private void loopHost() private void loopHost()
{ {
try try
{ {
//Program.Status.UpdateStatus(null, null, "Testing UI"); //Program.Status.UpdateStatus(null, null, "Testing UI");
//Program.SleepThread(5000, false); //Program.SleepThread(5000, false);
Interop.InstallInterop.Install(this.InstallLocation, this.WimImageId); Interop.InstallInterop.Install(this.InstallLocation, this.WimImageId);
if (this.mCompleteCallback != null) if (this.mCompleteCallback != null)
{ {
this.mCompleteCallback.BeginInvoke(null, null); this.mCompleteCallback.BeginInvoke(null, null);
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
if (ex.GetType() == typeof(ThreadAbortException)) if (ex.GetType() == typeof(ThreadAbortException))
return; return;
if (ex.GetType() == typeof(ThreadInterruptedException)) if (ex.GetType() == typeof(ThreadInterruptedException))
return; return;
Program.WriteAppError(ex); Program.WriteAppError(ex);
throw; throw;
} }
} }
} }
} }
@@ -1,180 +1,180 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.IO; using System.IO;
namespace Disco.ClientBootstrapper.Interop namespace Disco.ClientBootstrapper.Interop
{ {
public static class CertificateInterop public static class CertificateInterop
{ {
private static List<string> _tempCerts; private static List<string> _tempCerts;
public static void RemoveTempCerts() public static void RemoveTempCerts()
{ {
if (_tempCerts != null && _tempCerts.Count > 0) if (_tempCerts != null && _tempCerts.Count > 0)
{ {
Remove(StoreName.My, StoreLocation.LocalMachine, _tempCerts); Remove(StoreName.My, StoreLocation.LocalMachine, _tempCerts);
Remove(StoreName.CertificateAuthority, StoreLocation.LocalMachine, _tempCerts); Remove(StoreName.CertificateAuthority, StoreLocation.LocalMachine, _tempCerts);
Remove(StoreName.Root, StoreLocation.LocalMachine, _tempCerts); Remove(StoreName.Root, StoreLocation.LocalMachine, _tempCerts);
} }
} }
public static void AddTempCerts() public static void AddTempCerts()
{ {
if (_tempCerts == null) if (_tempCerts == null)
_tempCerts = new List<string>(); _tempCerts = new List<string>();
var inlineCertificateLocation = Program.InlinePath.Value; var inlineCertificateLocation = Program.InlinePath.Value;
// Root Certificates // Root Certificates
try try
{ {
var CertFiles = Directory.EnumerateFiles(inlineCertificateLocation, "WLAN_Cert_Root_*.*").ToList(); var CertFiles = Directory.EnumerateFiles(inlineCertificateLocation, "WLAN_Cert_Root_*.*").ToList();
if (CertFiles.Count > 0) if (CertFiles.Count > 0)
{ {
foreach (var certFile in CertFiles) foreach (var certFile in CertFiles)
{ {
var cert = new X509Certificate2(File.ReadAllBytes(certFile), "password"); var cert = new X509Certificate2(File.ReadAllBytes(certFile), "password");
var result = Add(StoreName.Root, StoreLocation.LocalMachine, cert); var result = Add(StoreName.Root, StoreLocation.LocalMachine, cert);
if (result) if (result)
{ {
if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp")) if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp"))
_tempCerts.Add(cert.SerialNumber); _tempCerts.Add(cert.SerialNumber);
Program.Status.UpdateStatus(null, null, string.Format("Added Root Certificate: {0}", cert.ShortSubjectName())); Program.Status.UpdateStatus(null, null, string.Format("Added Root Certificate: {0}", cert.ShortSubjectName()));
Program.SleepThread(500, false); Program.SleepThread(500, false);
} }
} }
} }
} }
catch (Exception) catch (Exception)
{ {
throw; throw;
} }
// Intermediate Certificates // Intermediate Certificates
try try
{ {
var CertFiles = Directory.EnumerateFiles(inlineCertificateLocation, "WLAN_Cert_Intermediate_*.*").ToList(); var CertFiles = Directory.EnumerateFiles(inlineCertificateLocation, "WLAN_Cert_Intermediate_*.*").ToList();
if (CertFiles.Count > 0) if (CertFiles.Count > 0)
{ {
foreach (var certFile in CertFiles) foreach (var certFile in CertFiles)
{ {
var cert = new X509Certificate2(File.ReadAllBytes(certFile), "password"); var cert = new X509Certificate2(File.ReadAllBytes(certFile), "password");
var result = Add(StoreName.CertificateAuthority, StoreLocation.LocalMachine, cert); var result = Add(StoreName.CertificateAuthority, StoreLocation.LocalMachine, cert);
if (result) if (result)
{ {
if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp")) if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp"))
_tempCerts.Add(cert.SerialNumber); _tempCerts.Add(cert.SerialNumber);
Program.Status.UpdateStatus(null, null, string.Format("Added Intermediate Certificate: {0}", cert.ShortSubjectName())); Program.Status.UpdateStatus(null, null, string.Format("Added Intermediate Certificate: {0}", cert.ShortSubjectName()));
Program.SleepThread(500, false); Program.SleepThread(500, false);
} }
} }
} }
} }
catch (Exception) catch (Exception)
{ {
throw; throw;
} }
// Host/Personal Certificates // Host/Personal Certificates
try try
{ {
var CertFiles = Directory.EnumerateFiles(inlineCertificateLocation, "WLAN_Cert_Personal_*.*").ToList(); var CertFiles = Directory.EnumerateFiles(inlineCertificateLocation, "WLAN_Cert_Personal_*.*").ToList();
if (CertFiles.Count > 0) if (CertFiles.Count > 0)
{ {
foreach (var certFile in CertFiles) foreach (var certFile in CertFiles)
{ {
var cert = new X509Certificate2(File.ReadAllBytes(certFile), "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); var cert = new X509Certificate2(File.ReadAllBytes(certFile), "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
var result = Add(StoreName.My, StoreLocation.LocalMachine, cert); var result = Add(StoreName.My, StoreLocation.LocalMachine, cert);
if (result) if (result)
{ {
if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp")) if (Path.GetFileNameWithoutExtension(certFile).ToLower().Contains("temp"))
_tempCerts.Add(cert.SerialNumber); _tempCerts.Add(cert.SerialNumber);
Program.Status.UpdateStatus(null, null, string.Format("Added Host Certificate: {0}", cert.ShortSubjectName())); Program.Status.UpdateStatus(null, null, string.Format("Added Host Certificate: {0}", cert.ShortSubjectName()));
Program.SleepThread(500, false); Program.SleepThread(500, false);
} }
} }
} }
} }
catch (Exception) catch (Exception)
{ {
throw; throw;
} }
} }
public static string ShortSubjectName(this X509Certificate2 Certificate) public static string ShortSubjectName(this X509Certificate2 Certificate)
{ {
string s = Certificate.Subject; string s = Certificate.Subject;
return s.Substring(s.IndexOf("=") + 1, s.IndexOf(",") - s.IndexOf("=") - 1); return s.Substring(s.IndexOf("=") + 1, s.IndexOf(",") - s.IndexOf("=") - 1);
} }
public static bool Add(StoreName StoreName, StoreLocation StoreLocation, X509Certificate2 Certificate) public static bool Add(StoreName StoreName, StoreLocation StoreLocation, X509Certificate2 Certificate)
{ {
var certStore = new X509Store(StoreName, StoreLocation); var certStore = new X509Store(StoreName, StoreLocation);
bool certAlreadyExists = false; bool certAlreadyExists = false;
certStore.Open(OpenFlags.ReadWrite); certStore.Open(OpenFlags.ReadWrite);
foreach (var cert in certStore.Certificates) foreach (var cert in certStore.Certificates)
{ {
if (cert.SerialNumber.Equals(Certificate.SerialNumber)) if (cert.SerialNumber.Equals(Certificate.SerialNumber))
{ {
certAlreadyExists = true; certAlreadyExists = true;
break; break;
} }
} }
if (!certAlreadyExists) if (!certAlreadyExists)
{ {
certStore.Add(Certificate); certStore.Add(Certificate);
} }
certStore.Close(); certStore.Close();
return !certAlreadyExists; return !certAlreadyExists;
} }
public static bool Remove(StoreName StoreName, StoreLocation StoreLocation, List<Regex> RegexMatches, string SerialException) public static bool Remove(StoreName StoreName, StoreLocation StoreLocation, List<Regex> RegexMatches, string SerialException)
{ {
var certStore = new X509Store(StoreName, StoreLocation); var certStore = new X509Store(StoreName, StoreLocation);
var removeCerts = new List<X509Certificate2>(); var removeCerts = new List<X509Certificate2>();
certStore.Open(OpenFlags.ReadWrite); certStore.Open(OpenFlags.ReadWrite);
foreach (var cert in certStore.Certificates) foreach (var cert in certStore.Certificates)
{ {
if (!cert.SerialNumber.Equals(SerialException)) if (!cert.SerialNumber.Equals(SerialException))
{ {
foreach (var subjectRegex in RegexMatches) foreach (var subjectRegex in RegexMatches)
{ {
if (subjectRegex.IsMatch(cert.Subject)) if (subjectRegex.IsMatch(cert.Subject))
{ {
removeCerts.Add(cert); removeCerts.Add(cert);
break; break;
} }
} }
} }
} }
foreach (var cert in removeCerts) foreach (var cert in removeCerts)
{ {
certStore.Remove(cert); certStore.Remove(cert);
} }
certStore.Close(); certStore.Close();
return (removeCerts.Count > 0); return (removeCerts.Count > 0);
} }
public static bool Remove(StoreName StoreName, StoreLocation StoreLocation, List<string> CertificateSerials) public static bool Remove(StoreName StoreName, StoreLocation StoreLocation, List<string> CertificateSerials)
{ {
var certStore = new X509Store(StoreName, StoreLocation); var certStore = new X509Store(StoreName, StoreLocation);
var removeCerts = new List<X509Certificate2>(); var removeCerts = new List<X509Certificate2>();
certStore.Open(OpenFlags.ReadWrite); certStore.Open(OpenFlags.ReadWrite);
foreach (var cert in certStore.Certificates) foreach (var cert in certStore.Certificates)
{ {
if (CertificateSerials.Contains(cert.SerialNumber)) if (CertificateSerials.Contains(cert.SerialNumber))
{ {
removeCerts.Add(cert); removeCerts.Add(cert);
} }
} }
foreach (var cert in removeCerts) foreach (var cert in removeCerts)
{ {
certStore.Remove(cert); certStore.Remove(cert);
} }
certStore.Close(); certStore.Close();
return (removeCerts.Count > 0); return (removeCerts.Count > 0);
} }
} }
} }
File diff suppressed because it is too large Load Diff
+164 -164
View File
@@ -1,164 +1,164 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Management; using System.Management;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace Disco.ClientBootstrapper.Interop namespace Disco.ClientBootstrapper.Interop
{ {
class NetworkAdapter class NetworkAdapter
{ {
public uint Index { get; set; } public uint Index { get; set; }
public string WmiPath { get; set; } public string WmiPath { get; set; }
public Guid Guid { get; set; } public Guid Guid { get; set; }
public string Name { get; set; } public string Name { get; set; }
public string NetConnectionID { get; set; } public string NetConnectionID { get; set; }
public string MACAddress { get; set; } public string MACAddress { get; set; }
public UInt64 Speed { get; set; } public UInt64 Speed { get; set; }
public UInt16 LastConnectionStatus { get; set; } public UInt16 LastConnectionStatus { get; set; }
public bool IsWireless { get; set; } public bool IsWireless { get; set; }
public string WirelessInterfaceDescription { get; set; } public string WirelessInterfaceDescription { get; set; }
public int LastWirelessConnectionStatus { get; set; } public int LastWirelessConnectionStatus { get; set; }
public NetworkAdapter(ManagementObject wmiObject) public NetworkAdapter(ManagementObject wmiObject)
{ {
UpdateFromWmi(wmiObject); UpdateFromWmi(wmiObject);
} }
private void UpdateFromWmi(ManagementObject wmiObject) private void UpdateFromWmi(ManagementObject wmiObject)
{ {
this.WmiPath = (string)wmiObject.GetPropertyValue("__PATH"); this.WmiPath = (string)wmiObject.GetPropertyValue("__PATH");
this.Index = (UInt32)wmiObject.GetPropertyValue("Index"); this.Index = (UInt32)wmiObject.GetPropertyValue("Index");
this.Guid = Guid.Parse((string)wmiObject.GetPropertyValue("GUID")); this.Guid = Guid.Parse((string)wmiObject.GetPropertyValue("GUID"));
this.MACAddress = (string)wmiObject.GetPropertyValue("MACAddress"); this.MACAddress = (string)wmiObject.GetPropertyValue("MACAddress");
this.Name = (string)wmiObject.GetPropertyValue("Name"); this.Name = (string)wmiObject.GetPropertyValue("Name");
this.NetConnectionID = (string)wmiObject.GetPropertyValue("NetConnectionID"); this.NetConnectionID = (string)wmiObject.GetPropertyValue("NetConnectionID");
this.Speed = (UInt64)wmiObject.GetPropertyValue("Speed"); this.Speed = (UInt64)wmiObject.GetPropertyValue("Speed");
var connectionStatus = ConnectionStatus; var connectionStatus = ConnectionStatus;
this.IsWireless = true; this.IsWireless = true;
try try
{ {
var wirelessConnectionStatus = WirelessConnectionStatus; var wirelessConnectionStatus = WirelessConnectionStatus;
} }
catch (Exception) { catch (Exception) {
this.IsWireless = false; this.IsWireless = false;
}; };
} }
public int WirelessConnectionStatus public int WirelessConnectionStatus
{ {
get { get {
if (this.IsWireless) if (this.IsWireless)
{ {
IntPtr handle = IntPtr.Zero; IntPtr handle = IntPtr.Zero;
uint negotiatedVersion; uint negotiatedVersion;
try try
{ {
if (NetworkInterop.WlanOpenHandle(1, IntPtr.Zero, out negotiatedVersion, ref handle) != 0) if (NetworkInterop.WlanOpenHandle(1, IntPtr.Zero, out negotiatedVersion, ref handle) != 0)
throw new NotSupportedException("This network adapter does not support Wireless"); throw new NotSupportedException("This network adapter does not support Wireless");
IntPtr ptr = new IntPtr(); IntPtr ptr = new IntPtr();
uint dataSize; uint dataSize;
var interfaceGuid = this.Guid; var interfaceGuid = this.Guid;
if (NetworkInterop.WlanQueryInterface(handle, ref interfaceGuid, NetworkInterop.WLAN_INTF_OPCODE.wlan_intf_opcode_interface_state, IntPtr.Zero, out dataSize, ref ptr, IntPtr.Zero) != 0) if (NetworkInterop.WlanQueryInterface(handle, ref interfaceGuid, NetworkInterop.WLAN_INTF_OPCODE.wlan_intf_opcode_interface_state, IntPtr.Zero, out dataSize, ref ptr, IntPtr.Zero) != 0)
throw new NotSupportedException("This network adapter does not support Wireless"); throw new NotSupportedException("This network adapter does not support Wireless");
this.LastWirelessConnectionStatus = Marshal.ReadInt32(ptr); this.LastWirelessConnectionStatus = Marshal.ReadInt32(ptr);
NetworkInterop.WlanFreeMemory(ptr); NetworkInterop.WlanFreeMemory(ptr);
return this.LastWirelessConnectionStatus; return this.LastWirelessConnectionStatus;
} }
finally finally
{ {
if (handle != IntPtr.Zero) if (handle != IntPtr.Zero)
NetworkInterop.WlanCloseHandle(handle, IntPtr.Zero); NetworkInterop.WlanCloseHandle(handle, IntPtr.Zero);
} }
} }
else else
{ {
throw new NotSupportedException("This network adapter does not support Wireless"); throw new NotSupportedException("This network adapter does not support Wireless");
} }
} }
} }
public string WirelessConnectionStatusMeaning(int status) public string WirelessConnectionStatusMeaning(int status)
{ {
switch ((NetworkInterop.WLAN_INTERFACE_STATE)status) switch ((NetworkInterop.WLAN_INTERFACE_STATE)status)
{ {
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_ad_hoc_network_formed: case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_ad_hoc_network_formed:
return "Ad Hoc Network Formed"; return "Ad Hoc Network Formed";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_associating: case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_associating:
return "Associating"; return "Associating";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_authenticating: case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_authenticating:
return "Authenticating"; return "Authenticating";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_connected: case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_connected:
return "Connected"; return "Connected";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_disconnected: case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_disconnected:
return "Disconnected"; return "Disconnected";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_disconnecting: case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_disconnecting:
return "Disconnecting"; return "Disconnecting";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_discovering: case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_discovering:
return "Discovering"; return "Discovering";
case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_not_ready: case NetworkInterop.WLAN_INTERFACE_STATE.wlan_interface_state_not_ready:
return "Not Ready"; return "Not Ready";
default: default:
return "Unknown"; return "Unknown";
} }
} }
public UInt16 ConnectionStatus public UInt16 ConnectionStatus
{ {
get get
{ {
using (var wmiObject = new ManagementObject(this.WmiPath)) using (var wmiObject = new ManagementObject(this.WmiPath))
{ {
this.LastConnectionStatus = (UInt16)wmiObject.GetPropertyValue("NetConnectionStatus"); this.LastConnectionStatus = (UInt16)wmiObject.GetPropertyValue("NetConnectionStatus");
} }
return this.LastConnectionStatus; return this.LastConnectionStatus;
} }
} }
public string ConnectionStatusMeaning(UInt16 status) public string ConnectionStatusMeaning(UInt16 status)
{ {
switch (status) switch (status)
{ {
case (UInt16)0: case (UInt16)0:
return "Disconnected"; return "Disconnected";
case (UInt16)1: case (UInt16)1:
return "Connecting"; return "Connecting";
case (UInt16)2: case (UInt16)2:
return "Connected"; return "Connected";
case (UInt16)3: case (UInt16)3:
return "Disconnecting"; return "Disconnecting";
case (UInt16)4: case (UInt16)4:
return "Hardware not present"; return "Hardware not present";
case (UInt16)5: case (UInt16)5:
return "Hardware disabled"; return "Hardware disabled";
case (UInt16)6: case (UInt16)6:
return "Hardware malfunction"; return "Hardware malfunction";
case (UInt16)7: case (UInt16)7:
return "Media disconnected"; return "Media disconnected";
case (UInt16)8: case (UInt16)8:
return "Authenticating"; return "Authenticating";
case (UInt16)9: case (UInt16)9:
return "Authentication succeeded"; return "Authentication succeeded";
case (UInt16)10: case (UInt16)10:
return "Authentication failed"; return "Authentication failed";
case (UInt16)11: case (UInt16)11:
return "Invalid address"; return "Invalid address";
case (UInt16)12: case (UInt16)12:
return "Credentials required"; return "Credentials required";
default: default:
return "Unknown"; return "Unknown";
} }
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More