diff --git a/Microsoft.Toolkit.HighPerformance/Buffers/Internals/RawObjectMemoryManager{T}.cs b/Microsoft.Toolkit.HighPerformance/Buffers/Internals/RawObjectMemoryManager{T}.cs
index 89ce81ea208..1a173c7ce3b 100644
--- a/Microsoft.Toolkit.HighPerformance/Buffers/Internals/RawObjectMemoryManager{T}.cs
+++ b/Microsoft.Toolkit.HighPerformance/Buffers/Internals/RawObjectMemoryManager{T}.cs
@@ -9,6 +9,7 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Toolkit.HighPerformance.Extensions;
+using Microsoft.Toolkit.HighPerformance.Helpers;
namespace Microsoft.Toolkit.HighPerformance.Buffers.Internals
{
@@ -49,7 +50,7 @@ public RawObjectMemoryManager(object instance, IntPtr offset, int length)
///
public override Span GetSpan()
{
- ref T r0 = ref this.instance.DangerousGetObjectDataReferenceAt(this.offset);
+ ref T r0 = ref ObjectMarshal.DangerousGetObjectDataReferenceAt(this.instance, this.offset);
return MemoryMarshal.CreateSpan(ref r0, this.length);
}
@@ -68,7 +69,7 @@ public override unsafe MemoryHandle Pin(int elementIndex = 0)
// traditional means (eg. via the implicit T[] array conversion), if T is a
// reference type or a type containing some references.
GCHandle handle = GCHandle.Alloc(this.instance, GCHandleType.Pinned);
- ref T r0 = ref this.instance.DangerousGetObjectDataReferenceAt(this.offset);
+ ref T r0 = ref ObjectMarshal.DangerousGetObjectDataReferenceAt(this.instance, this.offset);
ref T r1 = ref Unsafe.Add(ref r0, (nint)(uint)elementIndex);
void* p = Unsafe.AsPointer(ref r1);
diff --git a/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.1D.cs b/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.1D.cs
index 75b292d4208..6f851c7a968 100644
--- a/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.1D.cs
+++ b/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.1D.cs
@@ -9,6 +9,9 @@
using System.Runtime.InteropServices;
#endif
using Microsoft.Toolkit.HighPerformance.Enumerables;
+#if !NETCORE_RUNTIME && !NET5_0
+using Microsoft.Toolkit.HighPerformance.Helpers;
+#endif
using Microsoft.Toolkit.HighPerformance.Helpers.Internals;
using RuntimeHelpers = Microsoft.Toolkit.HighPerformance.Helpers.Internals.RuntimeHelpers;
@@ -40,7 +43,7 @@ public static ref T DangerousGetReference(this T[] array)
#else
IntPtr offset = RuntimeHelpers.GetArrayDataByteOffset();
- return ref array.DangerousGetObjectDataReferenceAt(offset);
+ return ref ObjectMarshal.DangerousGetObjectDataReferenceAt(array, offset);
#endif
}
@@ -69,7 +72,7 @@ public static ref T DangerousGetReferenceAt(this T[] array, int i)
return ref ri;
#else
IntPtr offset = RuntimeHelpers.GetArrayDataByteOffset();
- ref T r0 = ref array.DangerousGetObjectDataReferenceAt(offset);
+ ref T r0 = ref ObjectMarshal.DangerousGetObjectDataReferenceAt(array, offset);
ref T ri = ref Unsafe.Add(ref r0, (nint)(uint)i);
return ref ri;
diff --git a/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.2D.cs b/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.2D.cs
index 6b571a68ef1..635451b9c53 100644
--- a/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.2D.cs
+++ b/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.2D.cs
@@ -10,6 +10,7 @@
using Microsoft.Toolkit.HighPerformance.Buffers.Internals;
#endif
using Microsoft.Toolkit.HighPerformance.Enumerables;
+using Microsoft.Toolkit.HighPerformance.Helpers;
using Microsoft.Toolkit.HighPerformance.Helpers.Internals;
using RuntimeHelpers = Microsoft.Toolkit.HighPerformance.Helpers.Internals.RuntimeHelpers;
@@ -39,7 +40,7 @@ public static ref T DangerousGetReference(this T[,] array)
#else
IntPtr offset = RuntimeHelpers.GetArray2DDataByteOffset();
- return ref array.DangerousGetObjectDataReferenceAt(offset);
+ return ref ObjectMarshal.DangerousGetObjectDataReferenceAt(array, offset);
#endif
}
@@ -72,7 +73,7 @@ public static ref T DangerousGetReferenceAt(this T[,] array, int i, int j)
int width = array.GetLength(1);
nint index = ((nint)(uint)i * (nint)(uint)width) + (nint)(uint)j;
IntPtr offset = RuntimeHelpers.GetArray2DDataByteOffset();
- ref T r0 = ref array.DangerousGetObjectDataReferenceAt(offset);
+ ref T r0 = ref ObjectMarshal.DangerousGetObjectDataReferenceAt(array, offset);
ref T ri = ref Unsafe.Add(ref r0, index);
return ref ri;
@@ -137,7 +138,7 @@ public static RefEnumerable GetRow(this T[,] array, int row)
return new RefEnumerable(ref r0, width, 1);
#else
ref T r0 = ref array.DangerousGetReferenceAt(row, 0);
- IntPtr offset = array.DangerousGetObjectDataByteOffset(ref r0);
+ IntPtr offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref r0);
return new RefEnumerable(array, offset, width, 1);
#endif
@@ -191,7 +192,7 @@ public static RefEnumerable GetColumn(this T[,] array, int column)
return new RefEnumerable(ref r0, height, width);
#else
ref T r0 = ref array.DangerousGetReferenceAt(0, column);
- IntPtr offset = array.DangerousGetObjectDataByteOffset(ref r0);
+ IntPtr offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref r0);
return new RefEnumerable(array, offset, height, width);
#endif
@@ -324,7 +325,7 @@ public static Memory GetRowMemory(this T[,] array, int row)
}
ref T r0 = ref array.DangerousGetReferenceAt(row, 0);
- IntPtr offset = array.DangerousGetObjectDataByteOffset(ref r0);
+ IntPtr offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref r0);
return new RawObjectMemoryManager(array, offset, array.GetLength(1)).Memory;
}
diff --git a/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.3D.cs b/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.3D.cs
index ba4f0bd498d..b5671469da9 100644
--- a/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.3D.cs
+++ b/Microsoft.Toolkit.HighPerformance/Extensions/ArrayExtensions.3D.cs
@@ -5,6 +5,7 @@
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
+using Microsoft.Toolkit.HighPerformance.Helpers;
#if SPAN_RUNTIME_SUPPORT
using System.Runtime.InteropServices;
using Microsoft.Toolkit.HighPerformance.Buffers.Internals;
@@ -38,7 +39,7 @@ public static ref T DangerousGetReference(this T[,,] array)
#else
IntPtr offset = RuntimeHelpers.GetArray3DDataByteOffset();
- return ref array.DangerousGetObjectDataReferenceAt(offset);
+ return ref ObjectMarshal.DangerousGetObjectDataReferenceAt(array, offset);
#endif
}
@@ -78,7 +79,7 @@ public static ref T DangerousGetReferenceAt(this T[,,] array, int i, int j, i
((nint)(uint)i * (nint)(uint)height * (nint)(uint)width) +
((nint)(uint)j * (nint)(uint)width) + (nint)(uint)k;
IntPtr offset = RuntimeHelpers.GetArray3DDataByteOffset();
- ref T r0 = ref array.DangerousGetObjectDataReferenceAt(offset);
+ ref T r0 = ref ObjectMarshal.DangerousGetObjectDataReferenceAt(array, offset);
ref T ri = ref Unsafe.Add(ref r0, index);
return ref ri;
@@ -212,7 +213,7 @@ public static Memory AsMemory(this T[,,] array, int depth)
}
ref T r0 = ref array.DangerousGetReferenceAt(depth, 0, 0);
- IntPtr offset = array.DangerousGetObjectDataByteOffset(ref r0);
+ IntPtr offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref r0);
int length = checked(array.GetLength(1) * array.GetLength(2));
return new RawObjectMemoryManager(array, offset, length).Memory;
diff --git a/Microsoft.Toolkit.HighPerformance/Extensions/BoolExtensions.cs b/Microsoft.Toolkit.HighPerformance/Extensions/BoolExtensions.cs
index e4fa0a6df73..388529f15dc 100644
--- a/Microsoft.Toolkit.HighPerformance/Extensions/BoolExtensions.cs
+++ b/Microsoft.Toolkit.HighPerformance/Extensions/BoolExtensions.cs
@@ -33,20 +33,6 @@ public static unsafe byte ToByte(this bool flag)
return *(byte*)©
}
- ///
- /// Converts the given value into an .
- ///
- /// The input value to convert.
- /// 1 if is , 0 otherwise.
- /// This method does not contain branching instructions.
- [Pure]
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- [Obsolete("Use ToByte instead.")]
- public static unsafe int ToInt(this bool flag)
- {
- return *(byte*)&flag;
- }
-
///
/// Converts the given value to an mask with
/// all bits representing the value of the input flag (either 0xFFFFFFFF or 0x00000000).
diff --git a/Microsoft.Toolkit.HighPerformance/Helpers/Internals/RuntimeHelpers.cs b/Microsoft.Toolkit.HighPerformance/Helpers/Internals/RuntimeHelpers.cs
index 4a0d464b0af..49817edc31a 100644
--- a/Microsoft.Toolkit.HighPerformance/Helpers/Internals/RuntimeHelpers.cs
+++ b/Microsoft.Toolkit.HighPerformance/Helpers/Internals/RuntimeHelpers.cs
@@ -13,7 +13,6 @@
using System.Reflection;
#endif
using System.Runtime.CompilerServices;
-using Microsoft.Toolkit.HighPerformance.Extensions;
namespace Microsoft.Toolkit.HighPerformance.Helpers.Internals
{
@@ -152,7 +151,7 @@ public static unsafe IntPtr GetObjectDataOrReferenceByteOffset(object? obj, r
return (IntPtr)Unsafe.AsPointer(ref data);
}
- return obj.DangerousGetObjectDataByteOffset(ref data);
+ return ObjectMarshal.DangerousGetObjectDataByteOffset(obj, ref data);
}
///
@@ -174,7 +173,7 @@ public static unsafe ref T GetObjectDataAtOffsetOrPointerReference(object? ob
return ref Unsafe.AsRef((void*)offset);
}
- return ref obj.DangerousGetObjectDataReferenceAt(offset);
+ return ref ObjectMarshal.DangerousGetObjectDataReferenceAt(obj, offset);
}
///
@@ -274,7 +273,7 @@ private static IntPtr MeasureArrayDataByteOffset()
{
var array = new T[1];
- return array.DangerousGetObjectDataByteOffset(ref array[0]);
+ return ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array[0]);
}
///
@@ -286,7 +285,7 @@ private static IntPtr MeasureArray2DDataByteOffset()
{
var array = new T[1, 1];
- return array.DangerousGetObjectDataByteOffset(ref array[0, 0]);
+ return ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array[0, 0]);
}
///
@@ -298,7 +297,7 @@ private static IntPtr MeasureArray3DDataByteOffset()
{
var array = new T[1, 1, 1];
- return array.DangerousGetObjectDataByteOffset(ref array[0, 0, 0]);
+ return ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array[0, 0, 0]);
}
}
}
diff --git a/Microsoft.Toolkit.HighPerformance/Extensions/ObjectExtensions.cs b/Microsoft.Toolkit.HighPerformance/Helpers/ObjectMarshal.cs
similarity index 95%
rename from Microsoft.Toolkit.HighPerformance/Extensions/ObjectExtensions.cs
rename to Microsoft.Toolkit.HighPerformance/Helpers/ObjectMarshal.cs
index 0a61350a17e..9e451917a7e 100644
--- a/Microsoft.Toolkit.HighPerformance/Extensions/ObjectExtensions.cs
+++ b/Microsoft.Toolkit.HighPerformance/Helpers/ObjectMarshal.cs
@@ -7,12 +7,12 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-namespace Microsoft.Toolkit.HighPerformance.Extensions
+namespace Microsoft.Toolkit.HighPerformance.Helpers
{
///
/// Helpers for working with instances.
///
- public static class ObjectExtensions
+ public static class ObjectMarshal
{
///
/// Calculates the byte offset to a specific field within a given .
@@ -29,7 +29,7 @@ public static class ObjectExtensions
///
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static IntPtr DangerousGetObjectDataByteOffset(this object obj, ref T data)
+ public static IntPtr DangerousGetObjectDataByteOffset(object obj, ref T data)
{
var rawObj = Unsafe.As(obj)!;
ref byte r0 = ref rawObj.Data;
@@ -53,7 +53,7 @@ public static IntPtr DangerousGetObjectDataByteOffset(this object obj, ref T
///
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static ref T DangerousGetObjectDataReferenceAt(this object obj, IntPtr offset)
+ public static ref T DangerousGetObjectDataReferenceAt(object obj, IntPtr offset)
{
var rawObj = Unsafe.As(obj)!;
ref byte r0 = ref rawObj.Data;
@@ -97,7 +97,7 @@ private sealed class RawObjectData
///
/// This extension behaves just like the following method:
///
- /// public static bool TryUnbox<T>(this object obj, out T value)
+ /// public static bool TryUnbox<T>(object obj, out T value)
/// {
/// if (obj is T)
/// {
@@ -139,7 +139,7 @@ public static bool TryUnbox(this object obj, out T value)
/// Thrown when is not of type .
[Pure]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static ref T DangerousUnbox(this object obj)
+ public static ref T DangerousUnbox(object obj)
where T : struct
{
return ref Unsafe.Unbox(obj);
diff --git a/Microsoft.Toolkit.HighPerformance/Memory/Memory2D{T}.cs b/Microsoft.Toolkit.HighPerformance/Memory/Memory2D{T}.cs
index 6f6a7262222..3bc114a380d 100644
--- a/Microsoft.Toolkit.HighPerformance/Memory/Memory2D{T}.cs
+++ b/Microsoft.Toolkit.HighPerformance/Memory/Memory2D{T}.cs
@@ -13,6 +13,7 @@
using Microsoft.Toolkit.HighPerformance.Buffers.Internals;
#endif
using Microsoft.Toolkit.HighPerformance.Extensions;
+using Microsoft.Toolkit.HighPerformance.Helpers;
using Microsoft.Toolkit.HighPerformance.Memory.Internals;
using Microsoft.Toolkit.HighPerformance.Memory.Views;
using static Microsoft.Toolkit.HighPerformance.Helpers.Internals.RuntimeHelpers;
@@ -129,7 +130,7 @@ public Memory2D(T[] array, int offset, int height, int width, int pitch)
}
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(offset));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(offset));
this.height = height;
this.width = width;
this.pitch = pitch;
@@ -222,7 +223,7 @@ public Memory2D(T[,]? array, int row, int column, int height, int width)
}
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(row, column));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(row, column));
this.height = height;
this.width = width;
this.pitch = columns - width;
@@ -250,7 +251,7 @@ public Memory2D(T[,,] array, int depth)
}
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(depth, 0, 0));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, 0, 0));
this.height = array.GetLength(1);
this.width = array.GetLength(2);
this.pitch = 0;
@@ -306,7 +307,7 @@ public Memory2D(T[,,] array, int depth, int row, int column, int height, int wid
}
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(depth, row, column));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, row, column));
this.height = height;
this.width = width;
this.pitch = columns - width;
@@ -465,7 +466,7 @@ internal Memory2D(Memory memory, int offset, int height, int width, int pitch
ref char r0 = ref text.DangerousGetReferenceAt(textStart + offset);
this.instance = text;
- this.offset = text.DangerousGetObjectDataByteOffset(ref r0);
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(text, ref r0);
}
else if (MemoryMarshal.TryGetArray(memory, out ArraySegment segment))
{
@@ -477,7 +478,7 @@ internal Memory2D(Memory memory, int offset, int height, int width, int pitch
T[] array = segment.Array!;
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(segment.Offset + offset));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(segment.Offset + offset));
}
else if (MemoryMarshal.TryGetMemoryManager>(memory, out var memoryManager, out int memoryManagerStart, out _))
{
@@ -549,7 +550,7 @@ public static Memory2D DangerousCreate(object instance, ref T value, int heig
OverflowHelper.EnsureIsInNativeIntRange(height, width, pitch);
- IntPtr offset = instance.DangerousGetObjectDataByteOffset(ref value);
+ IntPtr offset = ObjectMarshal.DangerousGetObjectDataByteOffset(instance, ref value);
return new Memory2D(instance, offset, height, width, pitch);
}
@@ -615,7 +616,7 @@ public Span2D Span
}
else
{
- ref T r0 = ref this.instance.DangerousGetObjectDataReferenceAt(this.offset);
+ ref T r0 = ref ObjectMarshal.DangerousGetObjectDataReferenceAt(this.instance, this.offset);
return new Span2D(ref r0, this.height, this.width, this.pitch);
}
@@ -749,7 +750,7 @@ public unsafe MemoryHandle Pin()
GCHandle handle = GCHandle.Alloc(this.instance, GCHandleType.Pinned);
- void* pointer = Unsafe.AsPointer(ref this.instance.DangerousGetObjectDataReferenceAt(this.offset));
+ void* pointer = Unsafe.AsPointer(ref ObjectMarshal.DangerousGetObjectDataReferenceAt(this.instance, this.offset));
return new MemoryHandle(pointer, handle);
}
@@ -775,7 +776,7 @@ public bool TryGetMemory(out Memory memory)
else if (typeof(T) == typeof(char) && this.instance.GetType() == typeof(string))
{
string text = Unsafe.As(this.instance)!;
- int index = text.AsSpan().IndexOf(in text.DangerousGetObjectDataReferenceAt(this.offset));
+ int index = text.AsSpan().IndexOf(in ObjectMarshal.DangerousGetObjectDataReferenceAt(text, this.offset));
ReadOnlyMemory temp = text.AsMemory(index, (int)Length);
// The string type could still be present if a user ends up creating a
@@ -795,7 +796,7 @@ public bool TryGetMemory(out Memory memory)
{
// If it's a T[] array, also handle the initial offset
T[] array = Unsafe.As(this.instance)!;
- int index = array.AsSpan().IndexOf(ref array.DangerousGetObjectDataReferenceAt(this.offset));
+ int index = array.AsSpan().IndexOf(ref ObjectMarshal.DangerousGetObjectDataReferenceAt(array, this.offset));
memory = array.AsMemory(index, this.height * this.width);
}
diff --git a/Microsoft.Toolkit.HighPerformance/Memory/ReadOnlyMemory2D{T}.cs b/Microsoft.Toolkit.HighPerformance/Memory/ReadOnlyMemory2D{T}.cs
index 80e8839cb85..3666755e533 100644
--- a/Microsoft.Toolkit.HighPerformance/Memory/ReadOnlyMemory2D{T}.cs
+++ b/Microsoft.Toolkit.HighPerformance/Memory/ReadOnlyMemory2D{T}.cs
@@ -13,6 +13,7 @@
using Microsoft.Toolkit.HighPerformance.Buffers.Internals;
#endif
using Microsoft.Toolkit.HighPerformance.Extensions;
+using Microsoft.Toolkit.HighPerformance.Helpers;
using Microsoft.Toolkit.HighPerformance.Memory.Internals;
using Microsoft.Toolkit.HighPerformance.Memory.Views;
using static Microsoft.Toolkit.HighPerformance.Helpers.Internals.RuntimeHelpers;
@@ -115,7 +116,7 @@ public ReadOnlyMemory2D(string text, int offset, int height, int width, int pitc
}
this.instance = text;
- this.offset = text.DangerousGetObjectDataByteOffset(ref text.DangerousGetReferenceAt(offset));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(text, ref text.DangerousGetReferenceAt(offset));
this.height = height;
this.width = width;
this.pitch = pitch;
@@ -182,7 +183,7 @@ public ReadOnlyMemory2D(T[] array, int offset, int height, int width, int pitch)
}
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(offset));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(offset));
this.height = height;
this.width = width;
this.pitch = pitch;
@@ -259,7 +260,7 @@ public ReadOnlyMemory2D(T[,]? array, int row, int column, int height, int width)
}
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(row, column));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(row, column));
this.height = height;
this.width = width;
this.pitch = columns - width;
@@ -279,7 +280,7 @@ public ReadOnlyMemory2D(T[,,] array, int depth)
}
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(depth, 0, 0));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, 0, 0));
this.height = array.GetLength(1);
this.width = array.GetLength(2);
this.pitch = 0;
@@ -327,7 +328,7 @@ public ReadOnlyMemory2D(T[,,] array, int depth, int row, int column, int height,
}
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(depth, row, column));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, row, column));
this.height = height;
this.width = width;
this.pitch = columns - width;
@@ -484,14 +485,14 @@ internal ReadOnlyMemory2D(ReadOnlyMemory memory, int offset, int height, int
ref char r0 = ref text.DangerousGetReferenceAt(textStart + offset);
this.instance = text;
- this.offset = text.DangerousGetObjectDataByteOffset(ref r0);
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(text, ref r0);
}
else if (MemoryMarshal.TryGetArray(memory, out ArraySegment segment))
{
T[] array = segment.Array!;
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(segment.Offset + offset));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(segment.Offset + offset));
}
else if (MemoryMarshal.TryGetMemoryManager>(memory, out var memoryManager, out int memoryManagerStart, out _))
{
@@ -563,7 +564,7 @@ public static ReadOnlyMemory2D DangerousCreate(object instance, ref T value,
OverflowHelper.EnsureIsInNativeIntRange(height, width, pitch);
- IntPtr offset = instance.DangerousGetObjectDataByteOffset(ref value);
+ IntPtr offset = ObjectMarshal.DangerousGetObjectDataByteOffset(instance, ref value);
return new ReadOnlyMemory2D(instance, offset, height, width, pitch);
}
@@ -630,7 +631,7 @@ public ReadOnlySpan2D Span
else
{
// This handles both arrays and strings
- ref T r0 = ref this.instance.DangerousGetObjectDataReferenceAt(this.offset);
+ ref T r0 = ref ObjectMarshal.DangerousGetObjectDataReferenceAt(this.instance, this.offset);
return new ReadOnlySpan2D(in r0, this.height, this.width, this.pitch);
}
@@ -764,7 +765,7 @@ public unsafe MemoryHandle Pin()
GCHandle handle = GCHandle.Alloc(this.instance, GCHandleType.Pinned);
- void* pointer = Unsafe.AsPointer(ref this.instance.DangerousGetObjectDataReferenceAt(this.offset));
+ void* pointer = Unsafe.AsPointer(ref ObjectMarshal.DangerousGetObjectDataReferenceAt(this.instance, this.offset));
return new MemoryHandle(pointer, handle);
}
@@ -797,7 +798,7 @@ public bool TryGetMemory(out ReadOnlyMemory memory)
// within the string), and the input reference, which we can get from the byte offset in use. The result
// is the character index which we can use to create the final Memory instance.
string text = Unsafe.As(this.instance)!;
- int index = text.AsSpan().IndexOf(in text.DangerousGetObjectDataReferenceAt(this.offset));
+ int index = text.AsSpan().IndexOf(in ObjectMarshal.DangerousGetObjectDataReferenceAt(text, this.offset));
ReadOnlyMemory temp = text.AsMemory(index, (int)Length);
memory = Unsafe.As, ReadOnlyMemory>(ref temp);
@@ -811,7 +812,7 @@ public bool TryGetMemory(out ReadOnlyMemory memory)
{
// If it's a T[] array, also handle the initial offset
T[] array = Unsafe.As(this.instance)!;
- int index = array.AsSpan().IndexOf(ref array.DangerousGetObjectDataReferenceAt(this.offset));
+ int index = array.AsSpan().IndexOf(ref ObjectMarshal.DangerousGetObjectDataReferenceAt(array, this.offset));
memory = array.AsMemory(index, this.height * this.width);
}
diff --git a/Microsoft.Toolkit.HighPerformance/Memory/ReadOnlySpan2D{T}.cs b/Microsoft.Toolkit.HighPerformance/Memory/ReadOnlySpan2D{T}.cs
index 17c9f5df51b..cd38069dad4 100644
--- a/Microsoft.Toolkit.HighPerformance/Memory/ReadOnlySpan2D{T}.cs
+++ b/Microsoft.Toolkit.HighPerformance/Memory/ReadOnlySpan2D{T}.cs
@@ -9,6 +9,9 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Toolkit.HighPerformance.Extensions;
+#if !SPAN_RUNTIME_SUPPORT
+using Microsoft.Toolkit.HighPerformance.Helpers;
+#endif
using Microsoft.Toolkit.HighPerformance.Memory.Internals;
using Microsoft.Toolkit.HighPerformance.Memory.Views;
#if !SPAN_RUNTIME_SUPPORT
@@ -210,7 +213,7 @@ public ReadOnlySpan2D(T[] array, int offset, int height, int width, int pitch)
this.span = MemoryMarshal.CreateReadOnlySpan(ref array.DangerousGetReferenceAt(offset), height);
#else
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(offset));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(offset));
this.height = height;
#endif
this.width = width;
@@ -234,7 +237,7 @@ public ReadOnlySpan2D(T[,]? array)
this.span = MemoryMarshal.CreateReadOnlySpan(ref array.DangerousGetReference(), array.GetLength(0));
#else
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(0, 0));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(0, 0));
this.height = array.GetLength(0);
#endif
this.width = this.stride = array.GetLength(1);
@@ -294,7 +297,7 @@ public ReadOnlySpan2D(T[,]? array, int row, int column, int height, int width)
this.span = MemoryMarshal.CreateReadOnlySpan(ref array.DangerousGetReferenceAt(row, column), height);
#else
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(row, column));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(row, column));
this.height = height;
#endif
this.width = width;
@@ -318,7 +321,7 @@ public ReadOnlySpan2D(T[,,] array, int depth)
this.span = MemoryMarshal.CreateReadOnlySpan(ref array.DangerousGetReferenceAt(depth, 0, 0), array.GetLength(1));
#else
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(depth, 0, 0));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, 0, 0));
this.height = array.GetLength(1);
#endif
this.width = this.stride = array.GetLength(2);
@@ -369,7 +372,7 @@ public ReadOnlySpan2D(T[,,] array, int depth, int row, int column, int height, i
this.span = MemoryMarshal.CreateReadOnlySpan(ref array.DangerousGetReferenceAt(depth, row, column), height);
#else
this.instance = array;
- this.offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(depth, row, column));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, row, column));
this.height = height;
#endif
this.width = width;
diff --git a/Microsoft.Toolkit.HighPerformance/Memory/Span2D{T}.cs b/Microsoft.Toolkit.HighPerformance/Memory/Span2D{T}.cs
index ecdeeccfb58..88ac3c2c214 100644
--- a/Microsoft.Toolkit.HighPerformance/Memory/Span2D{T}.cs
+++ b/Microsoft.Toolkit.HighPerformance/Memory/Span2D{T}.cs
@@ -9,6 +9,9 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Toolkit.HighPerformance.Extensions;
+#if !SPAN_RUNTIME_SUPPORT
+using Microsoft.Toolkit.HighPerformance.Helpers;
+#endif
using Microsoft.Toolkit.HighPerformance.Memory.Internals;
using Microsoft.Toolkit.HighPerformance.Memory.Views;
#if !SPAN_RUNTIME_SUPPORT
@@ -249,7 +252,7 @@ public Span2D(T[] array, int offset, int height, int width, int pitch)
this.span = MemoryMarshal.CreateSpan(ref array.DangerousGetReferenceAt(offset), height);
#else
this.Instance = array;
- this.Offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(offset));
+ this.Offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(offset));
this.height = height;
#endif
this.width = width;
@@ -281,7 +284,7 @@ public Span2D(T[,]? array)
this.span = MemoryMarshal.CreateSpan(ref array.DangerousGetReference(), array.GetLength(0));
#else
this.Instance = array;
- this.Offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(0, 0));
+ this.Offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(0, 0));
this.height = array.GetLength(0);
#endif
this.width = this.Stride = array.GetLength(1);
@@ -349,7 +352,7 @@ public Span2D(T[,]? array, int row, int column, int height, int width)
this.span = MemoryMarshal.CreateSpan(ref array.DangerousGetReferenceAt(row, column), height);
#else
this.Instance = array;
- this.Offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(row, column));
+ this.Offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(row, column));
this.height = height;
#endif
this.width = width;
@@ -381,7 +384,7 @@ public Span2D(T[,,] array, int depth)
this.span = MemoryMarshal.CreateSpan(ref array.DangerousGetReferenceAt(depth, 0, 0), array.GetLength(1));
#else
this.Instance = array;
- this.Offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(depth, 0, 0));
+ this.Offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, 0, 0));
this.height = array.GetLength(1);
#endif
this.width = this.Stride = array.GetLength(2);
@@ -440,7 +443,7 @@ public Span2D(T[,,] array, int depth, int row, int column, int height, int width
this.span = MemoryMarshal.CreateSpan(ref array.DangerousGetReferenceAt(depth, row, column), height);
#else
this.Instance = array;
- this.Offset = array.DangerousGetObjectDataByteOffset(ref array.DangerousGetReferenceAt(depth, row, column));
+ this.Offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, row, column));
this.height = height;
#endif
this.width = width;
diff --git a/Microsoft.Toolkit.HighPerformance/ReadOnlyRef{T}.cs b/Microsoft.Toolkit.HighPerformance/ReadOnlyRef{T}.cs
index 37401184821..4ca386500a2 100644
--- a/Microsoft.Toolkit.HighPerformance/ReadOnlyRef{T}.cs
+++ b/Microsoft.Toolkit.HighPerformance/ReadOnlyRef{T}.cs
@@ -7,7 +7,7 @@
#if SPAN_RUNTIME_SUPPORT
using System.Runtime.InteropServices;
#else
-using Microsoft.Toolkit.HighPerformance.Extensions;
+using Microsoft.Toolkit.HighPerformance.Helpers;
#endif
namespace Microsoft.Toolkit.HighPerformance
@@ -98,7 +98,7 @@ private ReadOnlyRef(object owner, IntPtr offset)
public ReadOnlyRef(object owner, in T value)
{
this.owner = owner;
- this.offset = owner.DangerousGetObjectDataByteOffset(ref Unsafe.AsRef(value));
+ this.offset = ObjectMarshal.DangerousGetObjectDataByteOffset(owner, ref Unsafe.AsRef(value));
}
///
@@ -107,7 +107,7 @@ public ReadOnlyRef(object owner, in T value)
public ref readonly T Value
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- get => ref this.owner.DangerousGetObjectDataReferenceAt(this.offset);
+ get => ref ObjectMarshal.DangerousGetObjectDataReferenceAt(this.owner, this.offset);
}
///
diff --git a/Microsoft.Toolkit.HighPerformance/Ref{T}.cs b/Microsoft.Toolkit.HighPerformance/Ref{T}.cs
index e821a365969..1ba880437d7 100644
--- a/Microsoft.Toolkit.HighPerformance/Ref{T}.cs
+++ b/Microsoft.Toolkit.HighPerformance/Ref{T}.cs
@@ -7,7 +7,7 @@
#if SPAN_RUNTIME_SUPPORT
using System.Runtime.InteropServices;
#else
-using Microsoft.Toolkit.HighPerformance.Extensions;
+using Microsoft.Toolkit.HighPerformance.Helpers;
#endif
namespace Microsoft.Toolkit.HighPerformance
@@ -77,7 +77,7 @@ public ref T Value
public Ref(object owner, ref T value)
{
Owner = owner;
- Offset = owner.DangerousGetObjectDataByteOffset(ref value);
+ Offset = ObjectMarshal.DangerousGetObjectDataByteOffset(owner, ref value);
}
///
@@ -86,7 +86,7 @@ public Ref(object owner, ref T value)
public ref T Value
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- get => ref Owner.DangerousGetObjectDataReferenceAt(Offset);
+ get => ref ObjectMarshal.DangerousGetObjectDataReferenceAt(Owner, Offset);
}
#endif
diff --git a/Microsoft.Toolkit.Services/Core/AuthenticationResult.cs b/Microsoft.Toolkit.Services/Core/AuthenticationResult.cs
deleted file mode 100644
index 0378093c05e..00000000000
--- a/Microsoft.Toolkit.Services/Core/AuthenticationResult.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.Core
-{
- ///
- /// AuthenticationResult class, parameters: ResponseErrorDetail(uint), ResponseData(string) and ResponseStatus(AuthenticationResultStatus)
- ///
- public class AuthenticationResult
- {
- ///
- /// Gets or sets the authentication error detail
- ///
- public uint ResponseErrorDetail { get; set; }
-
- ///
- /// Gets or sets the authentication result data
- ///
- public string ResponseData { get; set; }
-
- ///
- /// Gets or sets the authentication status, could be UserCancel, ErrorHttp and Success.
- ///
- public AuthenticationResultStatus ResponseStatus { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Core/AuthenticationResultStatus.cs b/Microsoft.Toolkit.Services/Core/AuthenticationResultStatus.cs
deleted file mode 100644
index 439caceffd6..00000000000
--- a/Microsoft.Toolkit.Services/Core/AuthenticationResultStatus.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.Core
-{
- ///
- /// Contains the status of the authentication operation
- ///
- public enum AuthenticationResultStatus
- {
- ///
- /// The operation succeeded, and the response data is available.
- ///
- Success,
-
- ///
- /// The operation was canceled by the user
- ///
- UserCancel,
-
- ///
- /// The operation failed because a specific HTTP error was returned, for example 404
- ///
- ErrorHttp
- }
-}
diff --git a/Microsoft.Toolkit.Services/Core/DataProviderBase.cs b/Microsoft.Toolkit.Services/Core/DataProviderBase.cs
deleted file mode 100644
index ff8f320af42..00000000000
--- a/Microsoft.Toolkit.Services/Core/DataProviderBase.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net.Http;
-using System.Threading.Tasks;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Base class for data providers in this library.
- ///
- /// Query configuration type for given provider.
- public abstract class DataProviderBase
- {
- ///
- /// Initializes a new instance of the class.
- ///
- public DataProviderBase()
- {
- }
-
- ///
- /// Load data from provider endpoint.
- ///
- /// Strong typed object to parse the response items into.
- /// Query configuration.
- /// Upper record limit.
- /// The zero-based index of the page that corresponds to the items to retrieve.
- /// Parser to use for results.
- /// Strong typed list of results.
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an async method, so nesting generic types is necessary.")]
- public async Task> LoadDataAsync(TConfig config, int maxRecords, int pageIndex, Parsers.IParser parser)
- where TSchema : Parsers.SchemaBase
- {
- if (config == null)
- {
- throw new ConfigNullException();
- }
-
- if (parser == null)
- {
- throw new ParserNullException();
- }
-
- ValidateConfig(config);
-
- var result = await GetDataAsync(config, maxRecords, pageIndex, parser);
- if (result != null)
- {
- return result
- .Take(maxRecords)
- .ToList();
- }
-
- return Array.Empty();
- }
-
- private static HttpClient httpClient;
-
- ///
- /// Gets or sets static instance of HttpClient.
- ///
- public static HttpClient HttpClient
- {
- get { return httpClient ?? (httpClient = new HttpClient()); }
- set { httpClient = value; }
- }
-
- ///
- /// Derived classes will have to implement this method to return provider data
- ///
- /// Configuration to use
- /// Maximum number of records to return
- /// The zero-based index of the page that corresponds to the items to retrieve.
- /// Parser to use
- /// Schema defining data returned
- /// List of data
- protected abstract Task> GetDataAsync(TConfig config, int maxRecords, int pageIndex, Parsers.IParser parser)
- where TSchema : Parsers.SchemaBase;
-
- ///
- /// Method provided by derived class to validate specified configuration
- ///
- /// Configuration to validate
- protected abstract void ValidateConfig(TConfig config);
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Core/DataProviderBase{TConfig,TSchema}.cs b/Microsoft.Toolkit.Services/Core/DataProviderBase{TConfig,TSchema}.cs
deleted file mode 100644
index 4115623aa16..00000000000
--- a/Microsoft.Toolkit.Services/Core/DataProviderBase{TConfig,TSchema}.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Base class for data providers in this library.
- ///
- /// Strong typed query configuration object.
- /// Strong typed object to parse the response items into.
- public abstract class DataProviderBase : DataProviderBase
- where TSchema : Parsers.SchemaBase
- {
- ///
- /// Load data from provider endpoint.
- ///
- /// Query configuration.
- /// Upper record limit.
- /// The zero-based index of the page that corresponds to the items to retrieve.
- /// List of strong typed objects.
- public Task> LoadDataAsync(TConfig config, int maxRecords = 20, int pageIndex = 0)
- {
- return LoadDataAsync(config, maxRecords, pageIndex, GetDefaultParser(config));
- }
-
- ///
- /// Default parser abstract method.
- ///
- /// Query configuration object.
- /// Strong typed default parser.
- protected abstract Parsers.IParser GetDefaultParser(TConfig config);
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Core/ExtensionMethods.cs b/Microsoft.Toolkit.Services/Core/ExtensionMethods.cs
deleted file mode 100644
index 49124ac625b..00000000000
--- a/Microsoft.Toolkit.Services/Core/ExtensionMethods.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Reflection;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// This class offers general purpose methods.
- ///
- internal static class ExtensionMethods
- {
- ///
- /// Converts between enumeration value and string value.
- ///
- /// Enumeration.
- /// Returns string value.
- private static string GetStringValue(Enum value)
- {
- string output = null;
- Type type = value.GetType();
-
- FieldInfo fi = type.GetRuntimeField(value.ToString());
- Parsers.Core.StringValueAttribute[] attrs = fi.GetCustomAttributes(typeof(Parsers.Core.StringValueAttribute), false) as Parsers.Core.StringValueAttribute[];
- if (attrs != null && attrs.Length > 0)
- {
- output = attrs[0].Value;
- }
-
- return output;
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Core/IAuthenticationBroker.cs b/Microsoft.Toolkit.Services/Core/IAuthenticationBroker.cs
deleted file mode 100644
index 1c56147e7c8..00000000000
--- a/Microsoft.Toolkit.Services/Core/IAuthenticationBroker.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Microsoft.Toolkit.Services.Core
-{
- ///
- /// This gets an Uri value.
- ///
- public interface IAuthenticationBroker
- {
- ///
- /// Returns the authentication status, it could be UserCancel, ErrorHttp and Success.
- ///
- /// Authorization base url
- /// LinkedInOAuthTokens callbackUri
- /// Returns a status
- Task Authenticate(Uri requestUri, Uri callbackUri);
- }
-}
diff --git a/Microsoft.Toolkit.Services/Core/IDataService{T,U,V}.cs b/Microsoft.Toolkit.Services/Core/IDataService{T,U,V}.cs
deleted file mode 100644
index c24144b82de..00000000000
--- a/Microsoft.Toolkit.Services/Core/IDataService{T,U,V}.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Generic interface that all deployed service providers implement.
- ///
- /// Reference to underlying data service provider.
- /// Strongly-typed schema for data returned in list query.
- /// Configuration type specifying query parameters.
- public interface IDataService
- {
- ///
- /// Gets the underlying data service provider.
- ///
- T Provider { get; }
-
- ///
- /// Makes a request for a list of data from the given service provider.
- ///
- /// Describes the query on the list data request.
- /// Specifies an upper limit to the number of records returned.
- /// The zero-based index of the page that corresponds to the items to retrieve.
- /// Returns a strongly typed list of results from the service.
- Task> RequestAsync(V config, int maxRecords, int pageIndex = 0);
- }
-}
diff --git a/Microsoft.Toolkit.Services/Core/IPasswordManager.cs b/Microsoft.Toolkit.Services/Core/IPasswordManager.cs
deleted file mode 100644
index 33aff970698..00000000000
--- a/Microsoft.Toolkit.Services/Core/IPasswordManager.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.Core
-{
- ///
- /// This interface gets a PasswordCredential, store the credential and remove the key.
- ///
- public interface IPasswordManager
- {
- ///
- /// Gets the user credentials.
- ///
- /// Receive the storage key user and the access token
- /// Returns user credential.
- PasswordCredential Get(string key);
-
- ///
- /// Store users credential.
- ///
- /// Resource
- /// Username and password.
- void Store(string resource, PasswordCredential credential);
-
- ///
- /// Remove users credential.
- ///
- /// Credential unique key
- void Remove(string key);
- }
-}
diff --git a/Microsoft.Toolkit.Services/Core/ISignatureManager.cs b/Microsoft.Toolkit.Services/Core/ISignatureManager.cs
deleted file mode 100644
index d35af9d20ca..00000000000
--- a/Microsoft.Toolkit.Services/Core/ISignatureManager.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.Core
-{
- ///
- /// Provides platform specific logic to sign request for OAuth communication
- ///
- public interface ISignatureManager
- {
- ///
- /// Generate request signature
- ///
- /// String to sign
- /// Secret to use to sign
- /// If true append & to the base string
- /// The signed baseString to use in the OAuth requests
- string GetSignature(string baseString, string secret, bool append = false);
- }
-}
diff --git a/Microsoft.Toolkit.Services/Core/IStorageManager.cs b/Microsoft.Toolkit.Services/Core/IStorageManager.cs
deleted file mode 100644
index eab9f81ff10..00000000000
--- a/Microsoft.Toolkit.Services/Core/IStorageManager.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Threading.Tasks;
-
-namespace Microsoft.Toolkit.Services.Core
-{
- ///
- /// This interface store the key value
- ///
- public interface IStorageManager
- {
- ///
- /// Gets the key value
- ///
- /// Token value
- /// Returns a string value
- Task GetAsync(string key);
-
- ///
- /// Sets the key value
- ///
- /// Token key
- /// String value
- /// A representing the asynchronous operation.
- Task SetAsync(string key, string value);
- }
-}
diff --git a/Microsoft.Toolkit.Services/Core/PasswordCredential.cs b/Microsoft.Toolkit.Services/Core/PasswordCredential.cs
deleted file mode 100644
index 67bb96641f7..00000000000
--- a/Microsoft.Toolkit.Services/Core/PasswordCredential.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.Core
-{
- ///
- /// PasswordCredential class composed of UserName and Password, both strings.
- ///
- public class PasswordCredential
- {
- ///
- /// Gets or sets the username from login form
- ///
- public string UserName { get; set; }
-
- ///
- /// Gets or sets the password from login form
- ///
- public string Password { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Exceptions/ConfigNullException.cs b/Microsoft.Toolkit.Services/Exceptions/ConfigNullException.cs
deleted file mode 100644
index f32b19b731a..00000000000
--- a/Microsoft.Toolkit.Services/Exceptions/ConfigNullException.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Exception for null Config.
- ///
- public class ConfigNullException : Exception
- {
- ///
- /// Initializes a new instance of the class.
- /// Default constructor.
- ///
- public ConfigNullException()
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor accepting additional message string.
- ///
- /// Additional error information.
- public ConfigNullException(string message)
- : base(message)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor accepting additional message string and inner exception
- ///
- /// Additional error information.
- /// Reference to inner exception.
- public ConfigNullException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Exceptions/ConfigParameterNullException.cs b/Microsoft.Toolkit.Services/Exceptions/ConfigParameterNullException.cs
deleted file mode 100644
index 8a4f1cdddcb..00000000000
--- a/Microsoft.Toolkit.Services/Exceptions/ConfigParameterNullException.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Exception for config parameter being null.
- ///
- public class ConfigParameterNullException : Exception
- {
- ///
- /// Initializes a new instance of the class.
- /// Default constructor.
- ///
- public ConfigParameterNullException()
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Accepts parameter name.
- ///
- /// Name of the parameter.
- public ConfigParameterNullException(string parameter)
- : base(string.Format("The parameter '{0}' in config is null.", parameter))
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Accepts parameter name and inner exception.
- ///
- /// Name of the parameter.
- /// Reference to the inner exception.
- public ConfigParameterNullException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Exceptions/OAuthKeysNotPresentException.cs b/Microsoft.Toolkit.Services/Exceptions/OAuthKeysNotPresentException.cs
deleted file mode 100644
index 06b13dfe38c..00000000000
--- a/Microsoft.Toolkit.Services/Exceptions/OAuthKeysNotPresentException.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Exception for no OAuth keys being present.
- ///
- public class OAuthKeysNotPresentException : Exception
- {
- ///
- /// Initializes a new instance of the class.
- /// Default constructor.
- ///
- public OAuthKeysNotPresentException()
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with information on missing key.
- ///
- /// Name of the missing key.
- public OAuthKeysNotPresentException(string key)
- : base(string.Format("Open Authentication Key '{0}' not present", key))
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with additional message and inner exception.
- ///
- /// Additional exception message.
- /// Reference to inner exception.
- public OAuthKeysNotPresentException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Exceptions/OAuthKeysRevokedException.cs b/Microsoft.Toolkit.Services/Exceptions/OAuthKeysRevokedException.cs
deleted file mode 100644
index f9126448ada..00000000000
--- a/Microsoft.Toolkit.Services/Exceptions/OAuthKeysRevokedException.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Exception for revoked OAuth keys.
- ///
- public class OAuthKeysRevokedException : Exception
- {
- ///
- /// Initializes a new instance of the class.
- /// Default constructor.
- ///
- public OAuthKeysRevokedException()
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with additional message.
- ///
- /// Additional message
- public OAuthKeysRevokedException(string message)
- : base(message)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with additional message and inner exception.
- ///
- /// Additional message.
- /// Reference to inner exception.
- public OAuthKeysRevokedException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Exceptions/ParserNullException.cs b/Microsoft.Toolkit.Services/Exceptions/ParserNullException.cs
deleted file mode 100644
index 24da1f64e11..00000000000
--- a/Microsoft.Toolkit.Services/Exceptions/ParserNullException.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Exception for null Parser.
- ///
- public class ParserNullException : Exception
- {
- ///
- /// Initializes a new instance of the class.
- /// Default constructor.
- ///
- public ParserNullException()
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with additional message.
- ///
- /// Additional message
- public ParserNullException(string message)
- : base(message)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with additional message and inner exception.
- ///
- /// Additional message.
- /// Reference to inner exception.
- public ParserNullException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Exceptions/RequestFailedException.cs b/Microsoft.Toolkit.Services/Exceptions/RequestFailedException.cs
deleted file mode 100644
index 6bfd16057f0..00000000000
--- a/Microsoft.Toolkit.Services/Exceptions/RequestFailedException.cs
+++ /dev/null
@@ -1,55 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Net;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Exception for failed requests.
- ///
- public class RequestFailedException : Exception
- {
- ///
- /// Initializes a new instance of the class.
- /// Default constructor.
- ///
- public RequestFailedException()
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with additional message.
- ///
- /// Additional message.
- public RequestFailedException(string message)
- : base(message)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with status code and reason for request failure.
- ///
- /// Failure status code.
- /// Failure reason.
- public RequestFailedException(HttpStatusCode statusCode, string reason)
- : base(string.Format("Request failed with status code {0} and reason '{1}'", (int)statusCode, reason))
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with additional message and inner exception.
- ///
- /// Additional message.
- /// Reference to inner exception.
- public RequestFailedException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Exceptions/TooManyRequestsException.cs b/Microsoft.Toolkit.Services/Exceptions/TooManyRequestsException.cs
deleted file mode 100644
index 7b66c23d59b..00000000000
--- a/Microsoft.Toolkit.Services/Exceptions/TooManyRequestsException.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Exception for too many requests.
- ///
- public class TooManyRequestsException : Exception
- {
- ///
- /// Initializes a new instance of the class.
- /// Default constructor.
- ///
- public TooManyRequestsException()
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with additional message.
- ///
- /// Additional message.
- public TooManyRequestsException(string message)
- : base(message)
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with additional message and reference to inner exception.
- ///
- /// Additional message.
- /// Reference to inner exception.
- public TooManyRequestsException(string message, Exception innerException)
- : base(message, innerException)
- {
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Exceptions/UserNotFoundException.cs b/Microsoft.Toolkit.Services/Exceptions/UserNotFoundException.cs
deleted file mode 100644
index afa74efc90a..00000000000
--- a/Microsoft.Toolkit.Services/Exceptions/UserNotFoundException.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services
-{
- ///
- /// Exception for user not found.
- ///
- public class UserNotFoundException : Exception
- {
- ///
- /// Initializes a new instance of the class.
- /// Default constructor.
- ///
- public UserNotFoundException()
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with screen/user name information.
- ///
- /// Name of user not found.
- public UserNotFoundException(string screenName)
- : base("User " + screenName + " not found.")
- {
- }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor with screen/user name information and inner exception.
- ///
- /// Name of user not found.
- /// Reference to inner exception.
- public UserNotFoundException(string screenName, Exception innerException)
- : base("User " + screenName + " not found.", innerException)
- {
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Microsoft.Toolkit.Services.csproj b/Microsoft.Toolkit.Services/Microsoft.Toolkit.Services.csproj
deleted file mode 100644
index e1f1a13d6fb..00000000000
--- a/Microsoft.Toolkit.Services/Microsoft.Toolkit.Services.csproj
+++ /dev/null
@@ -1,53 +0,0 @@
-
-
-
- uap10.0.17763;netstandard2.0;NET462
- Windows Community Toolkit .NET Standard Services
-
- This .NET standard library enables access to different data sources such as Microsoft Graph, OneDrive, Twitter, Microsoft Translator, and LinkedIn. It is part of the Windows Community Toolkit.
-
- UWP Community Toolkit Windows Microsoft Graph OneDrive Twitter Translator LinkedIn service login OAuth
- 8.0
- CS8002;CS0618
- false
-
-
-
- $(DefineConstants);WINRT
-
-
-
- true
- false
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Microsoft.Toolkit.Services/OAuth/OAuthEncoder.cs b/Microsoft.Toolkit.Services/OAuth/OAuthEncoder.cs
deleted file mode 100644
index d8987614550..00000000000
--- a/Microsoft.Toolkit.Services/OAuth/OAuthEncoder.cs
+++ /dev/null
@@ -1,78 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text.RegularExpressions;
-
-#if WINRT
-using Windows.Security.Cryptography;
-using Windows.Security.Cryptography.Core;
-using Windows.Storage.Streams;
-
-#endif
-namespace Microsoft.Toolkit.Services.OAuth
-{
- ///
- /// OAuth Encoder.
- ///
- internal static class OAuthEncoder
- {
- ///
- /// Url encode input string.
- ///
- /// Input string.
- /// Encoded string.
- public static string UrlEncode(string value)
- {
- if (string.IsNullOrEmpty(value))
- {
- return string.Empty;
- }
-
- var result = Uri.EscapeDataString(value);
-
- // UrlEncode escapes with lowercase characters (e.g. %2f) but oAuth needs %2F
- result = Regex.Replace(result, "(%[0-9a-f][0-9a-f])", c => c.Value.ToUpper());
-
- // these characters are not escaped by UrlEncode() but needed to be escaped
- result = result
- .Replace("(", "%28")
- .Replace(")", "%29")
- .Replace("$", "%24")
- .Replace("!", "%21")
- .Replace("*", "%2A")
- .Replace("'", "%27");
-
- // these characters are escaped by UrlEncode() but will fail if unescaped!
- result = result.Replace("%7E", "~");
-
- return result;
- }
-
- ///
- /// Encode list of parameters.
- ///
- /// List of parameters.
- /// Encoded string of parameters.
- public static string UrlEncode(IEnumerable parameters)
- {
- string rawUrl = string.Join("&", parameters.OrderBy(p => p.Key).Select(p => p.ToString()).ToArray());
- return UrlEncode(rawUrl);
- }
-
-#if WINRT
- public static string GenerateHash(string input, string key)
- {
- MacAlgorithmProvider mac = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
- IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
- CryptographicKey cryptoKey = mac.CreateKey(keyMaterial);
- IBuffer hash = CryptographicEngine.Sign(cryptoKey, CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8));
- return CryptographicBuffer.EncodeToBase64String(hash);
- }
-#endif
-
- }
-}
diff --git a/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs b/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs
deleted file mode 100644
index be93787e951..00000000000
--- a/Microsoft.Toolkit.Services/OAuth/OAuthParameter.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Globalization;
-
-namespace Microsoft.Toolkit.Services.OAuth
-{
- ///
- /// OAuth parameter.
- ///
- internal class OAuthParameter
- {
- ///
- /// Gets or sets key property.
- ///
- public string Key { get; set; }
-
- ///
- /// Gets or sets value property.
- ///
- public string Value { get; set; }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor accepting key and value.
- ///
- /// Key.
- /// Value.
- public OAuthParameter(string key, string value)
- {
- Key = key;
- Value = value;
- }
-
- ///
- /// ToString override.
- ///
- /// String representation
- public override string ToString()
- {
- return ToString(false);
- }
-
- ///
- /// Format key / value into string.
- ///
- /// Whether to create quotes in string.
- /// Formatted string of key / value.
- public string ToString(bool withQuotes)
- {
- string format;
- if (withQuotes)
- {
- format = "{0}=\"{1}\"";
- }
- else
- {
- format = "{0}={1}";
- }
-
- return string.Format(CultureInfo.InvariantCulture, format, OAuthEncoder.UrlEncode(Key), OAuthEncoder.UrlEncode(Value));
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/OAuth/OAuthUriExtensions.cs b/Microsoft.Toolkit.Services/OAuth/OAuthUriExtensions.cs
deleted file mode 100644
index c269279994e..00000000000
--- a/Microsoft.Toolkit.Services/OAuth/OAuthUriExtensions.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Text;
-
-namespace Microsoft.Toolkit.Services.OAuth
-{
- ///
- /// OAuth Uri extensions.
- ///
- internal static class OAuthUriExtensions
- {
- ///
- /// Get query parameters from Uri.
- ///
- /// Uri to process.
- /// Dictionary of query parameters.
- public static IDictionary GetQueryParams(this Uri uri)
- {
- var dict = uri.Query.Remove(0, 1).Split('&').ToDictionary(c => c.Split('=')[0], c => Uri.UnescapeDataString(c.Split('=')[1]));
- return dict;
- }
-
- ///
- /// Get absolute Uri.
- ///
- /// Uri to process.
- /// Uri without query string.
- public static string AbsoluteWithoutQuery(this Uri uri)
- {
- if (string.IsNullOrEmpty(uri.Query))
- {
- return uri.AbsoluteUri;
- }
-
- return uri.AbsoluteUri.Replace(uri.Query, string.Empty);
- }
-
- ///
- /// Normalize the Uri into string.
- ///
- /// Uri to process.
- /// Normalized string.
- public static string Normalize(this Uri uri)
- {
- var result = new StringBuilder(string.Format(CultureInfo.InvariantCulture, "{0}://{1}", uri.Scheme, uri.Host));
- if (!((uri.Scheme == "http" && uri.Port == 80) || (uri.Scheme == "https" && uri.Port == 443)))
- {
- result.Append(string.Concat(":", uri.Port));
- }
-
- result.Append(uri.AbsolutePath);
-
- return result.ToString();
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkAuthenticationBroker.cs b/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkAuthenticationBroker.cs
deleted file mode 100644
index a182c84902b..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkAuthenticationBroker.cs
+++ /dev/null
@@ -1,81 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Threading.Tasks;
-using System.Windows;
-using Microsoft.Toolkit.Services.Core;
-using ApplicationForm = System.Windows.Forms.Application;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.NetFramework
-{
- internal class NetFrameworkAuthenticationBroker : IAuthenticationBroker
- {
- public Task Authenticate(Uri requestUri, Uri callbackUri)
- {
- int numberForms = ApplicationForm.OpenForms.Count;
- if (numberForms > 0)
- {
- return this.AuthenticateForm(requestUri, callbackUri);
- }
- else if (Application.Current != null)
- {
- return this.AuthenticateWindow(requestUri, callbackUri);
- }
- else
- {
- // Your code shouldn't reach this exception.
- throw new Exception("Cannot identify the current application. Please review your main app");
- }
- }
-
- public async Task AuthenticateWindow(Uri requestUri, Uri callbackUri)
- {
- PopupWPF popupWindow;
- var taskCompletionSource = new TaskCompletionSource();
- popupWindow = new PopupWPF(callbackUri);
- popupWindow.Closed += (sender, e) =>
- {
- taskCompletionSource.SetResult(HandleExit(popupWindow.ActualUrl));
- };
-
- popupWindow.Show();
- popupWindow.NavigateTo(requestUri.AbsoluteUri);
- return await taskCompletionSource.Task;
- }
-
- public async Task AuthenticateForm(Uri requestUri, Uri callbackUri)
- {
- PopupForm popupForm;
- var taskCompletionSource = new TaskCompletionSource();
- popupForm = new PopupForm(callbackUri);
- popupForm.FormClosed += (sender, e) =>
- {
- taskCompletionSource.SetResult(HandleExit(popupForm.ActualUrl));
- };
-
- popupForm.Show();
- popupForm.NavigateTo(requestUri.AbsoluteUri);
- return await taskCompletionSource.Task;
- }
-
- private AuthenticationResult HandleExit(Uri actualUrl)
- {
- var result = new AuthenticationResult();
- if (actualUrl != null)
- {
- var query = System.Web.HttpUtility.ParseQueryString(actualUrl.Query);
-
- result.ResponseData = query.ToString();
- result.ResponseStatus = AuthenticationResultStatus.Success;
- }
- else
- {
- result.ResponseStatus = AuthenticationResultStatus.ErrorHttp;
- }
-
- return result;
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkPasswordManager.cs b/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkPasswordManager.cs
deleted file mode 100644
index bca8353a8b1..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkPasswordManager.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Runtime.InteropServices;
-using System.Text;
-using Microsoft.Toolkit.Services.Core;
-using static Microsoft.Toolkit.Services.PlatformSpecific.NetFramework.PasswordManagerNativeMethods;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.NetFramework
-{
- internal class NetFrameworkPasswordManager : IPasswordManager
- {
- public void Store(string resource, PasswordCredential credential)
- {
- // Validations.
- byte[] byteArray = Encoding.Unicode.GetBytes(credential.Password);
-
- // Go ahead with what we have are stuff it into the CredMan structures.
- Credential cred = new Credential
- {
- TargetName = resource,
- UserName = credential.UserName,
- CredentialBlob = credential.Password,
- CredentialBlobSize = (uint)byteArray.Length,
- AttributeCount = 0,
- Attributes = IntPtr.Zero,
- Comment = null,
- TargetAlias = null,
- Type = CRED_TYPE.GENERIC,
- Persist = CRED_PERSIST.LOCAL_MACHINE
- };
- NativeCredential userCredential = NativeCredential.GetNativeCredential(cred);
-
- // Write the info into the CredMan storage.
- bool written = CredWrite(ref userCredential, 0);
- int lastError = Marshal.GetLastWin32Error();
- if (!written)
- {
- string message = "CredWrite failed with the error code " + lastError.ToString();
- throw new InvalidOperationException(message);
- }
- }
-
- public PasswordCredential Get(string key)
- {
- int lastError = Marshal.GetHRForLastWin32Error();
-
- if (!CredRead(key, CRED_TYPE.GENERIC, 0, out var nCredPtr))
- {
- return null;
- }
-
- CriticalCredentialHandle credentialHandle = new CriticalCredentialHandle(nCredPtr);
-
- Credential credential = credentialHandle.GetCredential();
- return new PasswordCredential
- {
- UserName = credential.UserName,
- Password = credential.CredentialBlob
- };
- }
-
- public void Remove(string key)
- {
- CredDelete(key, CRED_TYPE.GENERIC, 0);
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkSignatureManager.cs b/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkSignatureManager.cs
deleted file mode 100644
index 61dfd1c08f6..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkSignatureManager.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Security.Cryptography;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.Toolkit.Services.Core;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.NetFramework
-{
- internal class NetFrameworkSignatureManager : ISignatureManager
- {
- ///
- /// Generate request signature.
- ///
- /// String to sign
- /// Secret to use to sign
- /// If true append & to the base string
- /// Signature.
- public string GetSignature(string baseString, string secret, bool append = false)
- {
- var key = append ? secret + "&" : secret;
-
- var baseStringByte = Encoding.UTF8.GetBytes(baseString);
- var keyByte = Encoding.UTF8.GetBytes(key);
-
- using (HMACSHA1 hmac = new HMACSHA1(keyByte))
- {
- hmac.Initialize();
- var hash = hmac.ComputeHash(baseStringByte);
- string base64 = Convert.ToBase64String(hash);
- return base64;
- }
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkStorageManager.cs b/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkStorageManager.cs
deleted file mode 100644
index c5a4b186820..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/NetFrameworkStorageManager.cs
+++ /dev/null
@@ -1,57 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.IO.IsolatedStorage;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.Toolkit.Services.Core;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.NetFramework
-{
- internal class NetFrameworkStorageManager : IStorageManager
- {
- private const string FileName = "credential_service_data.txt";
- private const char Separator = ':';
-
- public async Task GetAsync(string key)
- {
- var isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
-
- using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(FileName, FileMode.OpenOrCreate, isoStore))
- {
- using (StreamReader reader = new StreamReader(isoStream))
- {
- while (!reader.EndOfStream)
- {
- var line = (await reader.ReadLineAsync()).Split(Separator);
- var currentKey = line.First();
- if (currentKey == key)
- {
- return line.Last();
- }
- }
- }
- }
-
- return null;
- }
-
- public Task SetAsync(string key, string value)
- {
- var isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
-
- using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(FileName, FileMode.Append, isoStore))
- {
- using (StreamWriter writer = new StreamWriter(isoStream))
- {
- return writer.WriteLineAsync(string.Concat(key, Separator, value));
- }
- }
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PasswordManagerNativeMethods.cs b/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PasswordManagerNativeMethods.cs
deleted file mode 100644
index d4f9a993fd3..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PasswordManagerNativeMethods.cs
+++ /dev/null
@@ -1,161 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Runtime.InteropServices;
-
-using Microsoft.Win32.SafeHandles;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.NetFramework
-{
- internal class PasswordManagerNativeMethods
- {
- [DllImport("Advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
- internal static extern bool CredRead(string target, CRED_TYPE type, int reservedFlag, out IntPtr credentialPtr);
-
- [DllImport("Advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)]
- internal static extern bool CredWrite([In] ref NativeCredential userCredential, [In] uint flags);
-
- [DllImport("Advapi32.dll", EntryPoint = "CredFree", SetLastError = true)]
- internal static extern bool CredFree([In] IntPtr cred);
-
- [DllImport("advapi32.dll", EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode)]
- internal static extern bool CredDelete(string target, CRED_TYPE type, int flags);
-
- internal enum CRED_TYPE : uint
- {
- GENERIC = 1,
- DOMAIN_PASSWORD = 2,
- DOMAIN_CERTIFICATE = 3,
- DOMAIN_VISIBLE_PASSWORD = 4,
- GENERIC_CERTIFICATE = 5,
- DOMAIN_EXTENDED = 6,
- MAXIMUM = 7, // Maximum supported cred type
- MAXIMUM_EX = MAXIMUM + 1000, // Allow new applications to run on old OSes
- }
-
- internal enum CRED_PERSIST : uint
- {
- SESSION = 1,
- LOCAL_MACHINE = 2,
- ENTERPRISE = 3,
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- internal struct NativeCredential
- {
- internal uint Flags;
- internal CRED_TYPE Type;
- internal IntPtr TargetName;
- internal IntPtr Comment;
- internal System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
- internal uint CredentialBlobSize;
- internal IntPtr CredentialBlob;
- internal uint Persist;
- internal uint AttributeCount;
- internal IntPtr Attributes;
- internal IntPtr TargetAlias;
- internal IntPtr UserName;
-
- ///
- /// This method derives a NativeCredential instance from a given Credential instance.
- ///
- /// The managed Credential counterpart containing data to be stored.
- /// A NativeCredential instance that is derived from the given Credential
- /// instance.
- internal static NativeCredential GetNativeCredential(Credential cred)
- {
- return new NativeCredential
- {
- AttributeCount = 0,
- Attributes = IntPtr.Zero,
- Comment = IntPtr.Zero,
- TargetAlias = IntPtr.Zero,
- Type = CRED_TYPE.GENERIC,
- Persist = (uint)cred.Persist,
- CredentialBlobSize = (uint)cred.CredentialBlobSize,
- TargetName = Marshal.StringToCoTaskMemUni(cred.TargetName),
- CredentialBlob = Marshal.StringToCoTaskMemUni(cred.CredentialBlob),
- UserName = Marshal.StringToCoTaskMemUni(cred.UserName)
- };
- }
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- internal struct Credential
- {
- internal uint Flags;
- internal CRED_TYPE Type;
- internal string TargetName;
- internal string Comment;
- internal System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
- internal uint CredentialBlobSize;
- internal string CredentialBlob;
- internal CRED_PERSIST Persist;
- internal uint AttributeCount;
- internal IntPtr Attributes;
- internal string TargetAlias;
- internal string UserName;
- }
-
- ///
- /// Handle and create the credential.
- ///
- internal sealed class CriticalCredentialHandle : CriticalHandleZeroOrMinusOneIsInvalid
- {
- // Set the handle.
- internal CriticalCredentialHandle(IntPtr preexistingHandle)
- {
- SetHandle(preexistingHandle);
- }
-
- internal Credential GetCredential()
- {
- if (!IsInvalid)
- {
- // Get the Credential from the mem location
- NativeCredential nativeCredential = (NativeCredential)Marshal.PtrToStructure(handle, typeof(NativeCredential));
-
- // Create a managed Credential type and fill it with data from the native counterpart.
- return new Credential
- {
- CredentialBlobSize = nativeCredential.CredentialBlobSize,
- CredentialBlob = Marshal.PtrToStringUni(nativeCredential.CredentialBlob, (int)nativeCredential.CredentialBlobSize / 2),
- UserName = Marshal.PtrToStringUni(nativeCredential.UserName),
- TargetName = Marshal.PtrToStringUni(nativeCredential.TargetName),
- TargetAlias = Marshal.PtrToStringUni(nativeCredential.TargetAlias),
- Type = nativeCredential.Type,
- Flags = nativeCredential.Flags,
- Persist = (CRED_PERSIST)nativeCredential.Persist
- };
- }
- else
- {
- throw new InvalidOperationException("Invalid CriticalHandle!");
- }
- }
-
- // Perform any specific actions to release the handle in the ReleaseHandle method.
- // Often, you need to use PInvoke to make a call into the Win32 API to release the
- // handle. In this case, however, we can use the Marshal class to release the unmanaged memory.
- protected override bool ReleaseHandle()
- {
- // If the handle was set, free it. Return success.
- if (!IsInvalid)
- {
- // NOTE: We should also ZERO out the memory allocated to the handle, before freeing it
- // so there are no traces of the sensitive data left in memory.
- CredFree(handle);
-
- // Mark the handle as invalid for future users.
- SetHandleAsInvalid();
- return true;
- }
-
- // Return false.
- return false;
- }
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupForm.Designer.cs b/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupForm.Designer.cs
deleted file mode 100644
index 85562563dd5..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupForm.Designer.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.NetFramework
-{
-
- partial class PopupForm
- {
- ///
- /// Required designer variable.
- ///
- private System.ComponentModel.IContainer components = null;
-
- ///
- /// Clean up any resources being used.
- ///
- /// true if managed resources should be disposed; otherwise, false.
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
-
- #region Windows Form Designer generated code
-
- ///
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- ///
- private void InitializeComponent()
- {
- this.webView1 = new Microsoft.Toolkit.Forms.UI.Controls.WebView();
- ((System.ComponentModel.ISupportInitialize)(this.webView1)).BeginInit();
- this.SuspendLayout();
- //
- // webView1
- //
- this.webView1.Dock = System.Windows.Forms.DockStyle.Fill;
- this.webView1.Location = new System.Drawing.Point(0, 0);
- this.webView1.MinimumSize = new System.Drawing.Size(20, 20);
- this.webView1.Name = "webView1";
- this.webView1.Size = new System.Drawing.Size(800, 450);
- this.webView1.TabIndex = 0;
- //
- // Form1
- //
- this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
- this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
- this.ClientSize = new System.Drawing.Size(800, 450);
- this.Controls.Add(this.webView1);
- this.Name = "Form1";
- this.Text = "Form1";
- ((System.ComponentModel.ISupportInitialize)(this.webView1)).EndInit();
- this.ResumeLayout(false);
-
- }
-
- #endregion
-
- private Microsoft.Toolkit.Forms.UI.Controls.WebView webView1;
- }
-}
-
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupForm.cs b/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupForm.cs
deleted file mode 100644
index 2c4e6a2ac41..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupForm.cs
+++ /dev/null
@@ -1,77 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Data;
-using System.Drawing;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows.Forms;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.NetFramework
-{
- ///
- /// Service WebView for windows forms
- ///
- public partial class PopupForm : Form
- {
- private string initialHost;
- private string callbackHost;
-
- ///
- /// Gets or sets the current URL before closing the form
- ///
- public Uri ActualUrl { get; set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Uri callback url
- public PopupForm(Uri callbackUrl)
- {
- InitializeComponent();
- webView1.NavigationStarting += (s, e) => WebViewNavigationStartingHandler(e.Uri);
- callbackHost = GetTopLevelDomain(callbackUrl);
- }
-
- private void WebViewNavigationStartingHandler(Uri uri)
- {
- var topLevelDomain = GetTopLevelDomain(uri);
- if (initialHost != topLevelDomain && topLevelDomain == callbackHost)
- {
- ActualUrl = uri;
- this.Close();
- }
- }
-
- ///
- /// Loads a given url in the WebView
- ///
- /// Url string to navigate to.
- public void NavigateTo(string url)
- {
- initialHost = GetTopLevelDomain(url);
- webView1.Navigate(url);
- }
-
- private string GetTopLevelDomain(string url)
- {
- return GetTopLevelDomain(new Uri(url));
- }
-
- private string GetTopLevelDomain(Uri url)
- {
- var hostParts = url.Host.Split('.').Select(x => x.ToString());
- if (hostParts.Count() > 1)
- {
- return hostParts.ElementAt(1);
- }
-
- return hostParts.ElementAt(0);
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupWPF.xaml b/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupWPF.xaml
deleted file mode 100644
index 4783beba528..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupWPF.xaml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupWPF.xaml.cs b/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupWPF.xaml.cs
deleted file mode 100644
index 75b958ca6cd..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/NETFramework/PopupWPF.xaml.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-using System.Windows;
-using System.Windows.Controls;
-using System.Windows.Data;
-using System.Windows.Documents;
-using System.Windows.Forms;
-using System.Windows.Input;
-using System.Windows.Media;
-using System.Windows.Media.Imaging;
-using System.Windows.Shapes;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.NetFramework
-{
- ///
- /// Interaction logic for PopupWPF.xaml
- ///
- public partial class PopupWPF : Window
- {
- private string initialHost;
- private string callbackHost;
-
- ///
- /// Gets or sets the current URL before closing the form
- ///
- public Uri ActualUrl { get; set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Uri callback url
- public PopupWPF(Uri callbackUrl)
- {
- InitializeComponent();
-
- WebView1.NavigationStarting += (s, e) => WebViewNavigationStartingHandler(e.Uri);
- callbackHost = GetTopLevelDomain(callbackUrl);
- }
-
- private void WebViewNavigationStartingHandler(Uri uri)
- {
- var topLevelDomain = GetTopLevelDomain(uri);
- if (initialHost != topLevelDomain && topLevelDomain == callbackHost)
- {
- ActualUrl = uri;
- this.Close();
- }
- }
-
- ///
- /// Loads a given url in the WebView
- ///
- /// Url string to navigate to.
- public void NavigateTo(string url)
- {
- initialHost = GetTopLevelDomain(url);
- WebView1.Navigate(url);
- }
-
- private string GetTopLevelDomain(string url)
- {
- return GetTopLevelDomain(new Uri(url));
- }
-
- private string GetTopLevelDomain(Uri url)
- {
- var hostParts = url.Host.Split('.').Select(x => x.ToString());
- if (hostParts.Count() > 1)
- {
- return hostParts.ElementAt(1);
- }
-
- return hostParts.ElementAt(0);
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpAuthenticationBroker.cs b/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpAuthenticationBroker.cs
deleted file mode 100644
index 0d73af1c914..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpAuthenticationBroker.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Threading.Tasks;
-using Microsoft.Toolkit.Services.Core;
-using Windows.Security.Authentication.Web;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.Uwp
-{
- ///
- /// Authentication Broker
- ///
- internal class UwpAuthenticationBroker : IAuthenticationBroker
- {
- ///
- /// Authentication process
- ///
- /// Request Uri
- /// Uri result
- /// Returns login status
- public async Task Authenticate(Uri requestUri, Uri callbackUri)
- {
- WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync(
- WebAuthenticationOptions.None,
- requestUri,
- callbackUri);
-
- switch (result.ResponseStatus)
- {
- case WebAuthenticationStatus.Success:
- return new AuthenticationResult { ResponseData = result.ResponseData, ResponseStatus = AuthenticationResultStatus.Success };
- case WebAuthenticationStatus.UserCancel:
- return new AuthenticationResult { ResponseData = result.ResponseData, ResponseStatus = AuthenticationResultStatus.UserCancel, ResponseErrorDetail = result.ResponseErrorDetail };
- case WebAuthenticationStatus.ErrorHttp:
- return new AuthenticationResult { ResponseData = result.ResponseData, ResponseStatus = AuthenticationResultStatus.ErrorHttp, ResponseErrorDetail = result.ResponseErrorDetail };
- default:
- // TODO: Change with correct name;
- throw new ArgumentException("error");
- }
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpPasswordManager.cs b/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpPasswordManager.cs
deleted file mode 100644
index 4d7b3f77fee..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpPasswordManager.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Linq;
-using Microsoft.Toolkit.Services.Core;
-using Windows.Security.Credentials;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.Uwp
-{
- ///
- /// Password Manager
- ///
- internal class UwpPasswordManager : IPasswordManager
- {
- ///
- /// Password vault used to store access tokens
- ///
- private readonly PasswordVault _vault;
-
- ///
- /// Initializes a new instance of the class.
- ///
- public UwpPasswordManager()
- {
- _vault = new PasswordVault();
- }
-
- ///
- public Toolkit.Services.Core.PasswordCredential Get(string key)
- {
- var credentials = RetrievePasswordCredential(key);
- if (credentials == null)
- {
- return null;
- }
-
- return new Toolkit.Services.Core.PasswordCredential { Password = credentials.Password, UserName = credentials.UserName };
- }
-
- private Windows.Security.Credentials.PasswordCredential RetrievePasswordCredential(string key)
- {
- var passwordCredentials = _vault.RetrieveAll();
- var temp = passwordCredentials.FirstOrDefault(c => c.Resource == key);
-
- if (temp == null)
- {
- return null;
- }
-
- return _vault.Retrieve(temp.Resource, temp.UserName);
- }
-
- ///
- public void Remove(string key)
- {
- _vault.Remove(RetrievePasswordCredential(key));
- }
-
- ///
- public void Store(string resource, Toolkit.Services.Core.PasswordCredential credentials)
- {
- var passwordCredential = new Windows.Security.Credentials.PasswordCredential(resource, credentials.UserName, credentials.Password);
- _vault.Add(passwordCredential);
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpSignatureManager.cs b/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpSignatureManager.cs
deleted file mode 100644
index f257995031c..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpSignatureManager.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Microsoft.Toolkit.Services.Core;
-
-using Windows.Security.Cryptography;
-using Windows.Security.Cryptography.Core;
-using Windows.Storage.Streams;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.Uwp
-{
- ///
- /// UWP specific signature generator using cryptographic library
- ///
- internal class UwpSignatureManager : ISignatureManager
- {
- ///
- /// Generate request signature.
- ///
- /// String to sign
- /// Secret to use to sign
- /// If true append & to the base string
- /// Signature.
- public string GetSignature(string baseString, string secret, bool append = false)
- {
- var key = append ? secret + "&" : secret;
-
- IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
- MacAlgorithmProvider mac = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
- CryptographicKey cryptoKey = mac.CreateKey(keyMaterial);
- IBuffer dataToBeSigned = CryptographicBuffer.ConvertStringToBinary(baseString, BinaryStringEncoding.Utf8);
- IBuffer hash = CryptographicEngine.Sign(cryptoKey, dataToBeSigned);
- return CryptographicBuffer.EncodeToBase64String(hash);
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpStorageManager.cs b/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpStorageManager.cs
deleted file mode 100644
index 9fbfc6be3bd..00000000000
--- a/Microsoft.Toolkit.Services/PlatformSpecific/Uwp/UwpStorageManager.cs
+++ /dev/null
@@ -1,40 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Linq;
-using System.Threading.Tasks;
-using Microsoft.Toolkit.Services.Core;
-using Windows.Security.Credentials;
-using Windows.Storage;
-
-namespace Microsoft.Toolkit.Services.PlatformSpecific.Uwp
-{
- ///
- /// UWP specific implementation for IStorageManager using ApplicationData and LocalSettings
- ///
- internal class UwpStorageManager : IStorageManager
- {
- ///
- /// Read the storage to return the key if exists if not null;
- ///
- /// Key to lookup
- /// Return string value if exists if not null
- public Task GetAsync(string key)
- {
- return Task.FromResult(ApplicationData.Current.LocalSettings.Values[key]?.ToString());
- }
-
- ///
- /// Save the value in the key inside the storage
- ///
- /// Key name in storage
- /// Value associated to the storage
- /// A representing the asynchronous operation.
- public Task SetAsync(string key, string value)
- {
- ApplicationData.Current.LocalSettings.Values[key] = value;
- return Task.CompletedTask;
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Properties/Microsoft.Toolkit.Services.rd.xml b/Microsoft.Toolkit.Services/Properties/Microsoft.Toolkit.Services.rd.xml
deleted file mode 100644
index 9f5b9bd9498..00000000000
--- a/Microsoft.Toolkit.Services/Properties/Microsoft.Toolkit.Services.rd.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
-
-
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInConstants.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInConstants.cs
deleted file mode 100644
index af8b0679955..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInConstants.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Constant strings for LinkedIn Service.
- ///
- public static class LinkedInConstants
- {
- ///
- /// Storage key name for access token.
- ///
- public static readonly string STORAGEKEYACCESSTOKEN = "LinkedInAccessToken";
-
- ///
- /// Storage key name for user name.
- ///
- public static readonly string STORAGEKEYUSER = "LinkedInUser";
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInContent.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInContent.cs
deleted file mode 100644
index cafd0e4562e..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInContent.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Strong type representation of Content.
- ///
- public class LinkedInContent
- {
- ///
- /// Gets or sets title property.
- ///
- public string Title { get; set; }
-
- ///
- /// Gets or sets description property.
- ///
- public string Description { get; set; }
-
- ///
- /// Gets or sets submitted url property.
- ///
- public string SubmittedUrl { get; set; }
-
- ///
- /// Gets or sets submitted image url property.
- ///
- public string SubmittedImageUrl { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInDataConfig.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInDataConfig.cs
deleted file mode 100644
index 1bd294d35a6..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInDataConfig.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Configuration object for specifying richer query information.
- ///
- public class LinkedInDataConfig
- {
- ///
- /// Gets or sets the query string for filtering service results.
- ///
- public string Query { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInDataProvider.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInDataProvider.cs
deleted file mode 100644
index b7977d0d092..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInDataProvider.cs
+++ /dev/null
@@ -1,334 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Net.Http;
-using System.Text;
-using System.Text.Json;
-using System.Threading.Tasks;
-using Microsoft.Toolkit.Services.Core;
-
-#if WINRT
-using Microsoft.Toolkit.Services.PlatformSpecific.Uwp;
-#endif
-
-#if NET462
-using Microsoft.Toolkit.Services.PlatformSpecific.NetFramework;
-#endif
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Data Provider for connecting to LinkedIn service.
- ///
- public class LinkedInDataProvider
- {
- private const string _oAuthBaseUrl = "https://www.linkedin.com/uas/oauth2/";
- private const string _baseUrl = "https://api.linkedin.com/v1";
-
- private static HttpClient client = new HttpClient();
-
- ///
- /// Gets or sets logged in user information.
- ///
- public string Username { get; set; }
-
- ///
- /// Gets a value indicating whether the provider is already logged in
- ///
- public bool LoggedIn { get; private set; }
-
- ///
- /// Gets or sets requiredPermissions property.
- ///
- public LinkedInPermissions RequiredPermissions { get; set; }
-
- private readonly IAuthenticationBroker _authentication;
- private readonly IPasswordManager _passwordManager;
- private readonly IStorageManager _storageManager;
-
- ///
- /// Gets or sets tokens property.
- ///
- public LinkedInOAuthTokens Tokens { get; set; }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor.
- ///
- /// OAuth tokens for request.
- /// Required permissions for the session.
- /// Authentication result interface.
- /// Password Manager interface, store the password.
- /// Storage Manager interface.
- public LinkedInDataProvider(LinkedInOAuthTokens tokens, LinkedInPermissions requiredPermissions, IAuthenticationBroker authentication, IPasswordManager passwordManager, IStorageManager storageManager)
- {
- if (string.IsNullOrEmpty(tokens.ClientSecret))
- {
- throw new ArgumentException("Missing client secret key");
- }
-
- if (string.IsNullOrEmpty(tokens.ClientId))
- {
- throw new ArgumentException("Missing client ID");
- }
-
- if (string.IsNullOrEmpty(tokens.CallbackUri))
- {
- throw new ArgumentException("Missing callback uri");
- }
-
- // Check if its a valid combination of LinkedInPermissions
- if ((~(int)LinkedInPermissionsHelpers.AllPermissions & (int)requiredPermissions) != 0)
- {
- throw new ArgumentException("Error retrieving required permissions");
- }
-
- Tokens = tokens;
- RequiredPermissions = requiredPermissions;
- _authentication = authentication ?? throw new ArgumentException("Invalid AuthenticationBroker");
- _storageManager = storageManager ?? throw new ArgumentException("Invalid StorageManager");
- _passwordManager = passwordManager ?? throw new ArgumentException("Invalid PasswordManager");
- }
-#if WINRT
- ///
- /// Initializes a new instance of the class.
- /// Constructor.
- ///
- /// OAuth tokens for request.
- /// Required permissions for the session.
- public LinkedInDataProvider(LinkedInOAuthTokens tokens, LinkedInPermissions requiredPermissions)
- : this(tokens, requiredPermissions, new UwpAuthenticationBroker(), new UwpPasswordManager(), new UwpStorageManager())
- {
- }
-#endif
-
-#if NET462
- ///
- /// Initializes a new instance of the class.
- /// Constructor.
- ///
- /// OAuth tokens for request.
- /// Required permissions for the session.
- public LinkedInDataProvider(LinkedInOAuthTokens tokens, LinkedInPermissions requiredPermissions)
- : this(tokens, requiredPermissions, new NetFrameworkAuthenticationBroker(), new NetFrameworkPasswordManager(), new NetFrameworkStorageManager())
- {
- }
-#endif
-
- ///
- /// Log user in to LinkedIn.
- ///
- /// Boolean indicating login success.
- public async Task LoginAsync()
- {
- var user = await _storageManager.GetAsync(LinkedInConstants.STORAGEKEYUSER);
- var credential = _passwordManager.Get(LinkedInConstants.STORAGEKEYACCESSTOKEN);
- if (!string.IsNullOrEmpty(user) && credential != null)
- {
- Tokens.AccessToken = credential.Password;
- Username = user;
- LoggedIn = true;
- return true;
- }
-
- string authorizeCode = await GetAuthorizeCodeAsync(Tokens, RequiredPermissions);
-
- if (!string.IsNullOrEmpty(authorizeCode))
- {
- var accessToken = await GetAccessTokenAsync(Tokens, authorizeCode);
-
- if (!string.IsNullOrEmpty(accessToken))
- {
- Tokens.AccessToken = accessToken;
-
- _passwordManager.Store(LinkedInConstants.STORAGEKEYACCESSTOKEN, new PasswordCredential { UserName = LinkedInConstants.STORAGEKEYUSER, Password = accessToken });
- await _storageManager.SetAsync(LinkedInConstants.STORAGEKEYUSER, LinkedInConstants.STORAGEKEYUSER);
- return true;
- }
- }
-
- LoggedIn = false;
- return false;
- }
-
- ///
- /// Log user out of LinkedIn.
- ///
- /// A representing the asynchronous operation.
- public async Task LogoutAsync()
- {
- var credential = _passwordManager.Get(LinkedInConstants.STORAGEKEYACCESSTOKEN);
-
- if (credential != null)
- {
- _passwordManager.Remove(LinkedInConstants.STORAGEKEYACCESSTOKEN);
- await _storageManager.SetAsync(LinkedInConstants.STORAGEKEYUSER, null);
- }
-
- LoggedIn = false;
- }
-
- ///
- /// Wrapper around REST API for making data request.
- ///
- /// Schema to use
- /// Query configuration.
- /// Upper limit for records returned.
- /// Index of paged results.
- /// A comma separated string of required fields, which will have strongly typed representation in the model passed in.
- /// Strongly typed list of results.
- public async Task> GetDataAsync(LinkedInDataConfig config, int maxRecords, int startRecord = 0, string fields = "id")
- {
- var parser = new LinkedInParser();
-
- var url = $"{_baseUrl}{config.Query}/~:({fields})?oauth2_access_token={Tokens.AccessToken}&format=json&count={maxRecords}&start={startRecord}";
-
- using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
- request.Headers.Connection.TryParseAdd("Keep-Alive");
-
- using var response = await client.SendAsync(request).ConfigureAwait(false);
- var data = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
-
- if (response.IsSuccessStatusCode && !string.IsNullOrEmpty(data))
- {
- return parser.Parse(data);
- }
-
- throw new RequestFailedException((System.Net.HttpStatusCode)response.StatusCode, data);
- }
-
- ///
- /// Share data to LinkedIn.
- ///
- /// Schema of data to share.
- /// Type of response object.
- /// Share request content.
- /// Boolean indicating success or failure.
- public async Task ShareDataAsync(T dataToShare)
- {
- var shareRequest = dataToShare as LinkedInShareRequest;
- if (shareRequest != null)
- {
- LinkedInVisibility.ParseVisibilityStringToEnum(shareRequest.Visibility.Code);
-
- var requestParser = new LinkedInParser();
-
- var url = $"{_baseUrl}/people/~/shares?oauth2_access_token={Tokens.AccessToken}&format=json";
-
- using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
- request.Headers.Add("x-li-format", "json");
- var stringContent = requestParser.Parse(shareRequest);
- request.Content = new StringContent(stringContent, Encoding.UTF8, "application/json");
-
- using var response = await client.SendAsync(request).ConfigureAwait(false);
- var data = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
-
- var responseParser = new LinkedInParser();
-
- var listResults = responseParser.Parse(data) as List;
- return listResults[0];
- }
-
- return default(U);
- }
-
- ///
- /// Check validity of configuration.
- ///
- /// Query configuration.
- protected void ValidateConfig(LinkedInDataConfig config)
- {
- if (config?.Query == null)
- {
- throw new ConfigParameterNullException(nameof(config.Query));
- }
- }
-
- private async Task GetAccessTokenAsync(LinkedInOAuthTokens tokens, string authorizeCode)
- {
- var url = $"{_oAuthBaseUrl}accessToken?grant_type=authorization_code"
- + "&code=" + authorizeCode
- + "&redirect_uri=" + Uri.EscapeDataString(tokens.CallbackUri)
- + "&client_id=" + tokens.ClientId
- + "&client_secret=" + tokens.ClientSecret;
-
- using var request = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
- using var response = await client.SendAsync(request).ConfigureAwait(false);
- using var jsonStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
- using var jsonDoc = await JsonDocument.ParseAsync(jsonStream).ConfigureAwait(false);
-
- var value = jsonDoc.RootElement.GetProperty("access_token");
- return value.GetString();
- }
-
- private async Task GetAuthorizeCodeAsync(LinkedInOAuthTokens tokens, LinkedInPermissions permissions)
- {
- string scopes = ConvertPermissionsToEncodedScopeString(permissions);
-
- var url = $"{_oAuthBaseUrl}authorization?response_type=code"
- + "&client_id=" + tokens.ClientId
- + "&state=STATE"
- + "&redirect_uri=" + Uri.EscapeDataString(tokens.CallbackUri)
- + "&" + scopes;
-
- var startUri = new Uri(url);
- var endUri = new Uri(tokens.CallbackUri);
-
- var result = await _authentication.Authenticate(startUri, endUri);
- switch (result.ResponseStatus)
- {
- case AuthenticationResultStatus.Success:
- {
- var response = result.ResponseData;
- IDictionary dictionary = new Dictionary();
- var split = response.Split('?');
- foreach (var keyValue in split[split.Length - 1].Split('&'))
- {
- var keyValueSplit = keyValue.Split('=');
- if (keyValueSplit.Length == 2)
- {
- dictionary.Add(keyValueSplit[0], keyValueSplit[1]);
- }
- }
-
- return dictionary["code"];
- }
-
- case AuthenticationResultStatus.ErrorHttp:
- Debug.WriteLine("WAB failed, message={0}", result.ResponseErrorDetail.ToString());
- return string.Empty;
-
- case AuthenticationResultStatus.UserCancel:
- Debug.WriteLine("WAB user aborted.");
- return string.Empty;
- }
-
- return string.Empty;
- }
-
- private string ConvertPermissionsToEncodedScopeString(LinkedInPermissions requiredPermissions)
- {
- StringBuilder scope = new StringBuilder();
-
- foreach (LinkedInPermissions value in Enum.GetValues(typeof(LinkedInPermissions)))
- {
- if ((requiredPermissions & value) != LinkedInPermissions.NotSet)
- {
- var name = value.ToString().ToLower();
- name = name.Replace("readwrite", "rw_");
- name = name.Replace("read", "r_");
- name = name.Replace("write", "w_");
- name = name.Replace("companyadmin", "company_admin");
-
- scope.Append($"{name} ");
- }
- }
-
- return "scope=" + Uri.EscapeDataString(scope.ToString());
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInOAuthTokens.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInOAuthTokens.cs
deleted file mode 100644
index 0014425afa4..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInOAuthTokens.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// LinkedIn OAuth tokens.
- ///
- public class LinkedInOAuthTokens
- {
- ///
- /// Gets or sets clientId.
- ///
- public string ClientId { get; set; }
-
- ///
- /// Gets or sets clientSecret.
- ///
- public string ClientSecret { get; set; }
-
- ///
- /// Gets or sets callback Uri.
- ///
- public string CallbackUri { get; set; }
-
- ///
- /// Gets or sets access token.
- ///
- public string AccessToken { get; set; }
-
- ///
- /// Gets or sets access token Secret.
- ///
- public string AccessTokenSecret { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInParser.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInParser.cs
deleted file mode 100644
index 4e145764452..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInParser.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Text.Json;
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Parse results into strong type.
- ///
- /// Type to parse into.
- public class LinkedInParser
- {
- ///
- /// Take string data and parse into strong data type.
- ///
- /// String data.
- /// Returns strong type.
- public IEnumerable Parse(string data)
- {
- List results;
-
- try
- {
- results = JsonSerializer.Deserialize>(data);
- }
- catch (JsonException)
- {
- T linkedInResult = JsonSerializer.Deserialize(data);
- results = new List { linkedInResult };
- }
-
- return results;
- }
-
- ///
- /// Take strong type and return corresponding JSON string.
- ///
- /// Strong typed instance.
- /// Returns string data.
- public string Parse(T dataToShare)
- {
- return JsonSerializer.Serialize(dataToShare, typeof(T), new JsonSerializerOptions { IgnoreNullValues = true });
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInPermissions.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInPermissions.cs
deleted file mode 100644
index 6d2d2fe756a..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInPermissions.cs
+++ /dev/null
@@ -1,54 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// List of user related data permissions
- ///
- [Flags]
- public enum LinkedInPermissions
- {
- ///
- /// Not set
- ///
- NotSet = 0,
-
- ///
- /// Read - Basic profile (r_basicprofile)
- ///
- ReadBasicProfile = 1,
-
- ///
- /// Read - Email Address (r_emailaddress)
- ///
- ReadEmailAddress = 2,
-
- ///
- /// Read / Write - Company Admin (rw_company_admin)
- ///
- ReadWriteCompanyAdmin = 4,
-
- ///
- /// Write - Share (w_share)
- ///
- WriteShare = 8
- }
-
-#pragma warning disable SA1649 // File name should match first type name
- internal static class LinkedInPermissionsHelpers
- {
- ///
- /// Internal AllPermissions for LinkedInPermissions, so we don't expose it. Keep it in sync with
- ///
- internal const LinkedInPermissions AllPermissions =
- LinkedInPermissions.ReadBasicProfile |
- LinkedInPermissions.ReadEmailAddress |
- LinkedInPermissions.ReadWriteCompanyAdmin |
- LinkedInPermissions.WriteShare;
- }
-#pragma warning restore SA1649 // File name should match first type name
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInProfile.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInProfile.cs
deleted file mode 100644
index 84dc6f0edc9..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInProfile.cs
+++ /dev/null
@@ -1,67 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Strongly typed LinkedIn Basic Profile. More details here https://developer.linkedin.com/docs/fields/basic-profile.
- ///
- public partial class LinkedInProfile
- {
- ///
- /// Gets a string description of the strongly typed properties in this model.
- ///
- public static string Fields => "first-name,last-name,headline,id,picture-url,site-standard-profile-request,num-connections,summary,public-profile-url";
-
- ///
- /// Gets or sets firstName property.
- ///
- public string FirstName { get; set; }
-
- ///
- /// Gets or sets headline property.
- ///
- public string Headline { get; set; }
-
- ///
- /// Gets or sets id property.
- ///
- public string Id { get; set; }
-
- ///
- /// Gets or sets lastname property.
- ///
- public string LastName { get; set; }
-
- ///
- /// Gets or sets picture-url property.
- ///
- public string PictureUrl { get; set; }
-
- ///
- /// Gets or sets num-connections property.
- ///
- public string NumConnections { get; set; }
-
- ///
- /// Gets or sets summary property.
- ///
- public string Summary { get; set; }
-
- ///
- /// Gets or sets public-profile-url property.
- ///
- public string PublicProfileUrl { get; set; }
-
- ///
- /// Gets or sets email-address property. Requires r_emailaddress permission.
- ///
- public string EmailAddress { get; set; }
-
- ///
- /// Gets or sets siteStandardProfileRequest property.
- ///
- public LinkedInProfileRequest SiteStandardProfileRequest { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInProfileRequest.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInProfileRequest.cs
deleted file mode 100644
index ac8e238c5db..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInProfileRequest.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Strongly typed SiteStandardProfileRequest class.
- ///
- public class LinkedInProfileRequest
- {
- ///
- /// Gets or sets url property.
- ///
- public string Url { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInService.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInService.cs
deleted file mode 100644
index 977419ebefa..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInService.cs
+++ /dev/null
@@ -1,276 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using Microsoft.Toolkit.Services.Core;
-#if WINRT
-using Microsoft.Toolkit.Services.PlatformSpecific.Uwp;
-#endif
-
-#if NET462
-using Microsoft.Toolkit.Services.PlatformSpecific.NetFramework;
-#endif
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Class for connecting to LinkedIn.
- ///
- public class LinkedInService
- {
- ///
- /// Private singleton field.
- ///
- private static LinkedInService _instance;
-
- ///
- /// Gets public singleton property.
- ///
- public static LinkedInService Instance => _instance ?? (_instance = new LinkedInService());
-
- private LinkedInDataProvider _provider;
-
- private LinkedInOAuthTokens _oAuthTokens;
-
- private LinkedInPermissions _requiredPermissions;
-
- private IAuthenticationBroker _authenticationBroker;
- private IPasswordManager _passwordManager;
- private IStorageManager _storageManager;
- private bool _isInitialized = false;
-
- ///
- /// Gets a reference to an instance of the underlying data provider.
- ///
- public LinkedInDataProvider Provider => _provider ?? (_provider = new LinkedInDataProvider(_oAuthTokens, _requiredPermissions, _authenticationBroker, _passwordManager, _storageManager));
-
- private LinkedInService()
- {
- }
-
- ///
- /// Log user in to LinkedIn.
- ///
- /// Returns success or failure of login attempt.
- public Task LoginAsync()
- {
- if (!_isInitialized)
- {
- throw new InvalidOperationException("Initialized needs to be called first.");
- }
-
- return Provider.LoginAsync();
- }
-
- ///
- /// Share content to LinkedIn.
- ///
- /// Comment containing a Url.
- /// Code for who to share with.
- /// Boolean indicating success or failure.
- public Task ShareActivityAsync(string commentContainingUrl, LinkedInShareVisibility visibilityCode = LinkedInShareVisibility.ConnectionsOnly)
- {
- var shareRequest = new LinkedInShareRequest
- {
- Comment = commentContainingUrl,
- Visibility = new LinkedInVisibility { Code = LinkedInVisibility.ParseVisibilityEnumToString(visibilityCode) }
- };
-
- return ShareActivityAsync(shareRequest);
- }
-
- ///
- /// Share content to LinkedIn.
- ///
- /// Share request.
- /// Boolean indicating success or failure.
- public Task ShareActivityAsync(LinkedInShareRequest shareRequest)
- {
- return Provider.ShareDataAsync(shareRequest);
- }
-
- ///
- /// Log user out of LinkedIn.
- ///
- /// A representing the asynchronous operation.
- public Task LogoutAsync()
- {
- _isInitialized = false;
- return Provider.LogoutAsync();
- }
-
-#if WINRT
- ///
- /// Initialize underlying provider with relevant token information for UWP.
- ///
- /// Token instance.
- /// Scope / permissions app requires user to sign up for.
- /// Success or failure.
- public bool Initialize(LinkedInOAuthTokens oAuthTokens, LinkedInPermissions requiredPermissions = LinkedInPermissions.NotSet)
- {
- return Initialize(oAuthTokens, new UwpAuthenticationBroker(), new UwpPasswordManager(), new UwpStorageManager(), requiredPermissions);
- }
-
- ///
- /// Initialize underlying provider with relevant token information.
- ///
- /// Client Id.
- /// Client secret.
- /// Callback URI. Has to match callback URI defined at www.linkedin.com/developer/apps/ (can be arbitrary).
- /// Success or failure.
- public bool Initialize(string clientId, string clientSecret, string callbackUri)
- {
- return Initialize(clientId, clientSecret, callbackUri, new UwpAuthenticationBroker(), new UwpPasswordManager(), new UwpStorageManager());
- }
-#endif
-
-#if NET462
- ///
- /// Initialize underlying provider with relevant token information for UWP.
- ///
- /// Token instance.
- /// Scope / permissions app requires user to sign up for.
- /// Success or failure.
- public bool Initialize(LinkedInOAuthTokens oAuthTokens, LinkedInPermissions requiredPermissions = LinkedInPermissions.NotSet)
- {
- return Initialize(oAuthTokens, new NetFrameworkAuthenticationBroker(), new NetFrameworkPasswordManager(), new NetFrameworkStorageManager(), requiredPermissions);
- }
-
- ///
- /// Initialize underlying provider with relevant token information.
- ///
- /// Client Id.
- /// Client secret.
- /// Callback URI. Has to match callback URI defined at www.linkedin.com/developer/apps/ (can be arbitrary).
- /// Success or failure.
- public bool Initialize(string clientId, string clientSecret, string callbackUri)
- {
- return Initialize(clientId, clientSecret, callbackUri, new NetFrameworkAuthenticationBroker(), new NetFrameworkPasswordManager(), new NetFrameworkStorageManager());
- }
-#endif
-
- ///
- /// Initialize underlying provider with relevant token information.
- ///
- /// Client Id.
- /// Client secret.
- /// Callback URI. Has to match callback URI defined at www.linkedin.com/developer/apps/ (can be arbitrary).
- /// Authentication result interface.
- /// Password Manager interface, store the password.
- /// Storage Manager interface.
- /// Success or failure.
- public bool Initialize(string clientId, string clientSecret, string callbackUri, IAuthenticationBroker authentication, IPasswordManager passwordManager, IStorageManager storageManager)
- {
- if (string.IsNullOrEmpty(clientId))
- {
- throw new ArgumentNullException(nameof(clientId));
- }
-
- if (string.IsNullOrEmpty(clientSecret))
- {
- throw new ArgumentNullException(nameof(clientSecret));
- }
-
- if (string.IsNullOrEmpty(callbackUri))
- {
- throw new ArgumentNullException(nameof(callbackUri));
- }
-
- var oAuthTokens = new LinkedInOAuthTokens
- {
- ClientId = clientId,
- ClientSecret = clientSecret,
- CallbackUri = callbackUri
- };
-
- return Initialize(oAuthTokens, authentication, passwordManager, storageManager, LinkedInPermissions.ReadBasicProfile);
- }
-
- ///
- /// Initialize underlying provider with relevant token information.
- ///
- /// Token instance.
- /// Authentication result interface.
- /// Password Manager interface, store the password.
- /// Storage Manager interface.
- /// Scope / permissions app requires user to sign up for.
- /// Success or failure.
- public bool Initialize(LinkedInOAuthTokens oAuthTokens, IAuthenticationBroker authentication, IPasswordManager passwordManager, IStorageManager storageManager, LinkedInPermissions requiredPermissions = LinkedInPermissions.NotSet)
- {
- _oAuthTokens = oAuthTokens ?? throw new ArgumentNullException(nameof(oAuthTokens));
- _authenticationBroker = authentication ?? throw new ArgumentNullException(nameof(authentication));
- _storageManager = storageManager ?? throw new ArgumentNullException(nameof(storageManager));
- _passwordManager = passwordManager ?? throw new ArgumentNullException(nameof(passwordManager));
-
- _requiredPermissions = requiredPermissions;
-
- Provider.RequiredPermissions = requiredPermissions;
- Provider.Tokens = oAuthTokens;
-
- _isInitialized = true;
-
- return true;
- }
-
- ///
- /// Request list data from service provider based upon a given config / query.
- ///
- /// Strong type of model.
- /// LinkedInDataConfig instance.
- /// Upper limit of records to return.
- /// Index of paged results.
- /// A comma separated string of required fields, which will have strongly typed representation in the model passed in.
- /// Strongly typed list of data returned from the service.
- public async Task> RequestAsync(LinkedInDataConfig config, int maxRecords = 20, int startRecord = 0, string fields = "id")
- {
- List queryResults = new List();
-
- var results = await Provider.GetDataAsync(config, maxRecords, startRecord, fields);
-
- foreach (var result in results)
- {
- queryResults.Add(result);
- }
-
- return queryResults;
- }
-
- ///
- /// Retrieve logged in users profile details.
- ///
- /// Require email address - which needs user consensus.
- /// Strongly typed profile.
- public async Task GetUserProfileAsync(bool requireEmailAddress = false)
- {
- var fields = LinkedInProfile.Fields;
-
- if (requireEmailAddress)
- {
- if (!_requiredPermissions.HasFlag(LinkedInPermissions.ReadEmailAddress))
- {
- throw new InvalidOperationException("Please re-initialize with email permission and call LoginAsync again so user may grant access.");
- }
-
- fields += ",email-address";
- }
-
- if (Provider.LoggedIn)
- {
- var results = await LinkedInService.Instance.RequestAsync(new LinkedInDataConfig { Query = "/people" }, 1, 0, fields);
-
- return results[0];
- }
-
- var isLoggedIn = await LoginAsync();
- if (isLoggedIn)
- {
- return await GetUserProfileAsync();
- }
-
- return null;
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInShareRequest.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInShareRequest.cs
deleted file mode 100644
index 07bfd76b1e9..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInShareRequest.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Strong type for sharing data to LinkedIn.
- ///
- public partial class LinkedInShareRequest
- {
- ///
- /// Gets or sets comment property.
- ///
- public string Comment { get; set; }
-
- ///
- /// Gets or sets visibility property.
- ///
- public LinkedInVisibility Visibility { get; set; }
-
- ///
- /// Gets or sets content property.
- ///
- public LinkedInContent Content { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInShareResponse.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInShareResponse.cs
deleted file mode 100644
index 294511da5a4..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInShareResponse.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Strong type for Share Response.
- ///
- public class LinkedInShareResponse
- {
- ///
- /// Gets or sets UpdateKey property.
- ///
- public string UpdateKey { get; set; }
-
- ///
- /// Gets or sets UpdateUrl property.
- ///
- public string UpdateUrl { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInShareVisibility.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInShareVisibility.cs
deleted file mode 100644
index 0ddf125cefa..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInShareVisibility.cs
+++ /dev/null
@@ -1,25 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// List of user related data permissions
- ///
- [Flags]
- public enum LinkedInShareVisibility
- {
- ///
- /// Connections only
- ///
- ConnectionsOnly = 1,
-
- ///
- /// Anyone
- ///
- Anyone = 2
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInVisibility.cs b/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInVisibility.cs
deleted file mode 100644
index f592352717e..00000000000
--- a/Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInVisibility.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services.LinkedIn
-{
- ///
- /// Strong type representation of Visibility.
- ///
- public class LinkedInVisibility
- {
- private const string ANYONE = "anyone";
- private const string CONNECTIONSONLY = "connections-only";
-
- ///
- /// Gets or sets code property.
- ///
- public string Code { get; set; }
-
- ///
- /// Converts enum counterpart to appropriate data string.
- ///
- /// Enumeration.
- /// String representation
- public static string ParseVisibilityEnumToString(LinkedInShareVisibility visibility)
- {
- switch (visibility)
- {
- case LinkedInShareVisibility.Anyone:
- return ANYONE;
- case LinkedInShareVisibility.ConnectionsOnly:
- return CONNECTIONSONLY;
- }
-
- return string.Empty;
- }
-
- ///
- /// Converts string to enum counterpart.
- ///
- /// String.
- /// Enumeration.
- public static LinkedInShareVisibility ParseVisibilityStringToEnum(string visibility)
- {
- switch (visibility.ToLower())
- {
- case ANYONE:
- return LinkedInShareVisibility.Anyone;
- case CONNECTIONSONLY:
- return LinkedInShareVisibility.ConnectionsOnly;
- }
-
- throw new ArgumentException("Invalid visibility string supplied.");
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/AzureAuthToken.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/AzureAuthToken.cs
deleted file mode 100644
index a2607423256..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/AzureAuthToken.cs
+++ /dev/null
@@ -1,114 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Net.Http;
-using System.Text.Json;
-using System.Threading.Tasks;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// Client to call Cognitive Services Azure Auth Token service in order to get an access token.
- ///
- internal class AzureAuthToken
- {
- ///
- /// Name of header used to pass the subscription key to the token service
- ///
- private const string OcpApimSubscriptionKeyHeader = "Ocp-Apim-Subscription-Key";
-
- ///
- /// URL of the token service
- ///
- private static readonly Uri ServiceUrl = new Uri("https://api.cognitive.microsoft.com/sts/v1.0/issueToken");
-
- // TODO
- // private static readonly Uri ServiceUrl = new Uri(THIS SHOULD BE A PARAMETER NOW);
-
- ///
- /// After obtaining a valid token, this class will cache it for this duration.
- /// Use a duration of 8 minutes, which is less than the actual token lifetime of 10 minutes.
- ///
- private static readonly TimeSpan TokenCacheDuration = new TimeSpan(0, 8, 0);
-
- private static HttpClient client = new HttpClient();
-
- private string _storedTokenValue = string.Empty;
- private DateTime _storedTokenTime = DateTime.MinValue;
- private string _subscriptionKey;
-
- ///
- /// Gets or sets the Service Subscription Key.
- ///
- public string SubscriptionKey
- {
- get
- {
- return _subscriptionKey;
- }
-
- set
- {
- if (_subscriptionKey != value)
- {
- // If the subscription key is changed, the token is no longer valid.
- _subscriptionKey = value;
- _storedTokenValue = string.Empty;
- }
- }
- }
-
- ///
- /// Initializes a new instance of the class, that is used to obtain access token
- ///
- /// Subscription key to use to get an authentication token.
- public AzureAuthToken(string key)
- {
- SubscriptionKey = key;
- }
-
- ///
- /// Gets a token for the specified subscription.
- ///
- /// The encoded JWT token prefixed with the string "Bearer ".
- ///
- /// This method uses a cache to limit the number of request to the token service.
- /// A fresh token can be re-used during its lifetime of 10 minutes. After a successful
- /// request to the token service, this method caches the access token. Subsequent
- /// invocations of the method return the cached token for the next 8 minutes. After
- /// 8 minutes, a new token is fetched from the token service and the cache is updated.
- ///
- public async Task GetAccessTokenAsync()
- {
- if (string.IsNullOrEmpty(_subscriptionKey))
- {
- throw new ArgumentNullException(nameof(SubscriptionKey), "A subscription key is required. Go to Azure Portal and sign up for Microsoft Translator: https://portal.azure.com/#create/Microsoft.CognitiveServices/apitype/TextTranslation");
- }
-
- // Re-use the cached token if there is one.
- if ((DateTime.Now - _storedTokenTime) < TokenCacheDuration && !string.IsNullOrWhiteSpace(_storedTokenValue))
- {
- return _storedTokenValue;
- }
-
- using var request = new HttpRequestMessage(HttpMethod.Post, ServiceUrl);
- request.Headers.Add(OcpApimSubscriptionKeyHeader, SubscriptionKey);
-
- var response = await client.SendAsync(request).ConfigureAwait(false);
- var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
-
- if (!response.IsSuccessStatusCode)
- {
- var error = JsonSerializer.Deserialize(content);
- throw new TranslatorServiceException(error?.Error?.Message);
- }
-
- _storedTokenTime = DateTime.Now;
- _storedTokenValue = $"Bearer {content}";
-
- return _storedTokenValue;
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/DetectedLanguage.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/DetectedLanguage.cs
deleted file mode 100644
index 66cd9cc6b5a..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/DetectedLanguage.cs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// Strong type for Detected Language
- ///
- ///
- ///
- public class DetectedLanguage : DetectedLanguageBase
- {
- ///
- /// Gets a value indicating whether the detected language is one of the languages supported for text translation.
- ///
- public bool IsTranslationSupported { get; }
-
- ///
- /// Gets a value indicating whether the detected language is one of the languages supported for transliteration.
- ///
- public bool IsTransliterationSupported { get; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The code of the detected language.
- /// A float value indicating the confidence in the result. The score is between zero and one and a low score indicates a low confidence.
- /// A value indicating whether the detected language is one of the languages supported for text translation.
- /// A value indicating whether the detected language is one of the languages supported for transliteration.
- ///
- public DetectedLanguage(string language, float score, bool isTranslationSupported, bool isTransliterationSupported)
- : base(language, score)
- {
- IsTranslationSupported = isTranslationSupported;
- IsTransliterationSupported = isTransliterationSupported;
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/DetectedLanguageBase.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/DetectedLanguageBase.cs
deleted file mode 100644
index 7cfa46c1b30..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/DetectedLanguageBase.cs
+++ /dev/null
@@ -1,48 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// Strong type for Base Detected Language
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- ///
- public class DetectedLanguageBase
- {
- ///
- /// Gets the code of the detected language.
- ///
- public string Language { get; }
-
- ///
- /// Gets a float value indicating the confidence in the result. The score is between zero and one and a low score indicates a low confidence.
- ///
- public float Score { get; }
-
- ///
- public override string ToString() => Language;
-
- ///
- /// Initializes a new instance of the class.
- /// Returns the language friendly name.
- ///
- /// the code of the detected language.
- /// a float value indicating the confidence in the result. The score is between zero and one and a low score indicates a low confidence.
- public DetectedLanguageBase(string language, float score)
- {
- Language = language;
- Score = score;
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/DetectedLanguageResponse.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/DetectedLanguageResponse.cs
deleted file mode 100644
index ee4d88975f4..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/DetectedLanguageResponse.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// Strong type for Detect Language Response
- ///
- ///
- ///
- public class DetectedLanguageResponse : DetectedLanguage
- {
- ///
- /// Gets an array of other possible languages.
- ///
- public IEnumerable Alternatives { get; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// The code of the detected language.
- /// A float value indicating the confidence in the result. The score is between zero and one and a low score indicates a low confidence.
- /// A value indicating whether the detected language is one of the languages supported for text translation.
- /// A value indicating whether the detected language is one of the languages supported for transliteration.
- /// An array of other possible languages
- ///
- public DetectedLanguageResponse(string language, float score, bool isTranslationSupported, bool isTransliterationSupported, IEnumerable alternatives)
- : base(language, score, isTranslationSupported, isTransliterationSupported)
- {
- Alternatives = alternatives;
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ErrorResponse.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ErrorResponse.cs
deleted file mode 100644
index 870ee897f0e..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ErrorResponse.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Text.Json.Serialization;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
-#pragma warning disable SA1402 // File may only contain a single type
- ///
- /// Holds information about an error occurred while accessing Microsoft Translator Service.
- ///
- internal class ErrorResponse
- {
- [JsonPropertyName("error")]
- public Error Error { get; set; }
- }
-
- internal class Error
- {
- ///
- /// Gets or sets the error message.
- ///
- [JsonPropertyName("message")]
- public string Message { get; set; }
- }
-#pragma warning restore SA1402 // File may only contain a single type
-}
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ITranslatorService.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ITranslatorService.cs
deleted file mode 100644
index 984a74d6646..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ITranslatorService.cs
+++ /dev/null
@@ -1,372 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// The ITranslatorServiceClient interface specifies properties and methods to translate text in various supported languages.
- ///
- public interface ITranslatorService
- {
- ///
- /// Gets or sets the Subscription key that is necessary to use Microsoft Translator Service.
- ///
- /// The Subscription Key.
- ///
- /// You must register Microsoft Translator on https://portal.azure.com/#create/Microsoft.CognitiveServices/apitype/TextTranslation to obtain the Subscription key needed to use the service.
- ///
- string SubscriptionKey { get; set; }
-
- ///
- /// Gets or sets the string representing the supported language code to translate the text in.
- ///
- /// The string representing the supported language code to translate the text in. The code must be present in the list of codes returned from the method .
- ///
- string Language { get; set; }
-
- ///
- /// Initializes the class by getting an access token for the service.
- ///
- /// A that represents the initialize operation.
- /// The property hasn't been set.
- /// The provided isn't valid or has expired.
- /// Calling this method isn't mandatory, because the token is get/refreshed every time is needed. However, it is called at startup, it can speed-up subsequent requests.
- Task InitializeAsync();
-
- ///
- /// Initializes the class by getting an access token for the service.
- ///
- /// The subscription key for the Microsoft Translator Service on Azure.
- /// A string representing the supported language code to speak the text in. The code must be present in the list of codes returned from the method .
- /// A that represents the initialize operation.
- /// The property hasn't been set.
- /// The provided isn't valid or has expired.
- ///
- /// Calling this method isn't mandatory, because the token is get/refreshed every time is needed. However, it is called at startup, it can speed-up subsequent requests.
- /// You must register Microsoft Translator on https://portal.azure.com to obtain the Subscription key needed to use the service.
- ///
- Task InitializeAsync(string subscriptionKey, string language = null);
-
- ///
- /// Detects the language of a text.
- ///
- /// A string representing the text whose language must be detected.
- /// A string containing a two-character Language code for the given text.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic) or empty.
- ///
- ///
- /// The provided isn't valid or has expired.
- /// This method performs a non-blocking request for language detection.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-detect.
- ///
- ///
- ///
- Task DetectLanguageAsync(string input);
-
- ///
- /// Detects the language of a text.
- ///
- /// A string representing the text whose language must be detected.
- /// A object containing information about the detected language.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic) or empty.
- ///
- ///
- /// The provided isn't valid or has expired.
- /// This method performs a non-blocking request for language detection.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-detect.
- ///
- ///
- ///
- Task DetectLanguageWithResponseAsync(string input);
-
- ///
- /// Detects the language of a text.
- ///
- /// A string array containing the sentences whose language must be detected.
- /// A array with one result for each string in the input array. Each object contains information about the detected language.
- ///
- ///
- /// The parameter doesn't contain any element.
- /// The array contains more than 100 elements.
- ///
- ///
- ///
- ///
- /// The property hasn't been set.
- /// The array is null (Nothing in Visual Basic).
- ///
- ///
- /// The provided isn't valid or has expired.
- /// This method performs a non-blocking request for language detection.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-detect.
- ///
- ///
- ///
- Task> DetectLanguagesWithResponseAsync(IEnumerable input);
-
- ///
- /// Retrieves the languages available for translation.
- ///
- /// A string array containing the language codes supported for translation by Microsoft Translator Service. /// The property hasn't been set.
- /// The provided isn't valid or has expired.
- /// This method performs a non-blocking request for language codes.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-languages.
- ///
- ///
- ///
- Task> GetLanguagesAsync();
-
- ///
- /// Retrieves friendly names for the languages available for text translation.
- ///
- /// The language used to localize the language names. If the parameter is set to null, the language specified in the property will be used.
- /// An array of containing the language codes and names supported for translation by Microsoft Translator Service.
- /// The property hasn't been set.
- /// The provided isn't valid or has expired.
- /// This method performs a non-blocking request for language names.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-languages.
- ///
- ///
- ///
- Task> GetLanguageNamesAsync(string language = null);
-
- ///
- /// Translates a text string into the specified language.
- ///
- /// A string representing the translated text.
- /// A string representing the text to translate.
- /// A string representing the language code to translate the text into. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic) or empty.
- ///
- ///
- /// The parameter is longer than 1000 characters.
- /// The provided isn't valid or has expired.
- /// This method perform a non-blocking request for text translation.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate.
- ///
- ///
- ///
- ///
- Task TranslateAsync(string input, string to = null);
-
- ///
- /// Translates a text string into the specified language.
- ///
- /// A string representing the translated text.
- /// A string representing the text to translate.
- /// A string representing the language code of the original text. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- /// A string representing the language code to translate the text into. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic) or empty.
- ///
- ///
- /// The parameter is longer than 1000 characters.
- /// The provided isn't valid or has expired.
- /// This method perform a non-blocking request for text translation.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate.
- ///
- ///
- ///
- ///
- Task TranslateAsync(string input, string from, string to);
-
- ///
- /// Translates a text string into the specified language.
- ///
- /// A object containing translated text and information.
- /// A string representing the text to translate.
- /// A string representing the language code to translate the text into. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic) or empty.
- ///
- ///
- /// The parameter is longer than 1000 characters.
- /// The provided isn't valid or has expired.
- /// This method perform a non-blocking request for text translation.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate.
- ///
- ///
- ///
- ///
- Task TranslateWithResponseAsync(string input, string to = null);
-
- ///
- /// Translates a text string into the specified languages.
- ///
- /// A object containing translated text and information.
- /// A string representing the text to translate.
- /// A string representing the language code of the original text. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- /// A string representing the language code to translate the text into. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic) or empty.
- ///
- ///
- /// The parameter is longer than 1000 characters.
- /// The provided isn't valid or has expired.
- /// This method perform a non-blocking request for text translation.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate.
- ///
- ///
- ///
- ///
- Task TranslateWithResponseAsync(string input, string from, string to);
-
- ///
- /// Translates a list of sentences into the specified language.
- ///
- /// A array with one result for each language code in the array. Each object contains translated text and information.
- /// A string array containing the sentences to translate.
- /// A string representing the language code of the original text. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- /// A string representing the language code to translate the text into. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic).
- ///
- ///
- ///
- ///
- /// The parameter is longer than 1000 characters.
- /// The array contains more than 25 elements.
- ///
- ///
- /// The provided isn't valid or has expired.
- /// This method perform a non-blocking request for text translation.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate.
- ///
- ///
- ///
- ///
- Task> TranslateWithResponseAsync(IEnumerable input, string from, string to);
-
- ///
- /// Translates a text into the specified languages.
- ///
- /// A object containing translated text and information.
- /// A string representing the text to translate.
- /// A string representing the language code of the original text. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- /// A string array representing the language codes to translate the text into. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic) or empty.
- ///
- ///
- ///
- ///
- /// The parameter is longer than 1000 characters.
- /// The array contains more than 25 elements.
- ///
- ///
- /// The provided isn't valid or has expired.
- /// This method perform a non-blocking request for text translation.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate.
- ///
- ///
- ///
- ///
- Task TranslateWithResponseAsync(string input, string from, IEnumerable to);
-
- ///
- /// Translates a text string into the specified languages.
- ///
- /// A object containing translated text and information.
- /// A string representing the text to translate.
- /// A string array representing the language codes to translate the text into. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic) or empty.
- ///
- ///
- ///
- ///
- /// The parameter is longer than 1000 characters.
- /// The array contains more than 25 elements.
- ///
- ///
- /// The provided isn't valid or has expired.
- /// This method perform a non-blocking request for text translation.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate.
- ///
- ///
- ///
- ///
- Task TranslateWithResponseAsync(string input, IEnumerable to);
-
- ///
- /// Translates a list of sentences into the specified languages.
- ///
- /// A array with one result for each language code in the array. Each object contains translated text and information.
- /// A string array containing the sentences to translate.
- /// A string array representing the language codes to translate the text into. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic).
- ///
- ///
- ///
- ///
- /// The parameter is longer than 1000 characters.
- /// The array contains more than 25 elements.
- ///
- ///
- /// The provided isn't valid or has expired.
- /// This method perform a non-blocking request for text translation.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate.
- ///
- ///
- ///
- ///
- Task> TranslateWithResponseAsync(IEnumerable input, IEnumerable to = null);
-
- ///
- /// Translates a list of sentences into the specified languages.
- ///
- /// A array with one result for each language code in the array. Each object contains translated text and information.
- /// A string array containing the sentences to translate.
- /// A string representing the language code of the original text. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- /// A string array representing the language codes to translate the text into. The code must be present in the list of codes returned from the method. If the parameter is set to null, the language specified in the property will be used.
- ///
- ///
- /// The property hasn't been set.
- /// The parameter is null (Nothing in Visual Basic).
- ///
- ///
- ///
- ///
- /// The parameter is longer than 1000 characters.
- /// The array contains more than 25 elements.
- ///
- ///
- /// The provided isn't valid or has expired.
- /// This method perform a non-blocking request for text translation.
- /// For more information, go to https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate.
- ///
- ///
- ///
- ///
- Task> TranslateWithResponseAsync(IEnumerable input, string from, IEnumerable to);
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ServiceLanguage.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ServiceLanguage.cs
deleted file mode 100644
index abed597f9bd..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ServiceLanguage.cs
+++ /dev/null
@@ -1,58 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Text.Json.Serialization;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// Holds information about languages supported for text translation and speech synthesis.
- ///
- ///
- public class ServiceLanguage
- {
- ///
- /// Gets the language code.
- ///
- public string Code { get; internal set; }
-
- ///
- /// Gets the language friendly name.
- ///
- public string Name { get; }
-
- ///
- /// Gets the display name of the language in the locale native for this language.
- ///
- public string NativeName { get; }
-
- ///
- /// Gets the directionality, which is rtl for right-to-left languages or ltr for left-to-right languages.
- ///
- [JsonPropertyName("dir")]
- public string Directionality { get; }
-
- ///
- /// Returns the language friendly name.
- ///
- /// The language friendly name.
- public override string ToString() => Name;
-
- ///
- /// Initializes a new instance of the class.
- /// Returns the language friendly name.
- ///
- /// The language code.
- /// The language friendly name.
- /// The display name of the language in the locale native for this language.
- /// The directionality, which is rtl for right-to-left languages or ltr for left-to-right languages
- public ServiceLanguage(string code, string name, string nativeName = null, string directionality = null)
- {
- Code = code;
- Name = name;
- NativeName = nativeName ?? name;
- Directionality = directionality ?? "ltr";
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/Translation.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/Translation.cs
deleted file mode 100644
index b8dc3bf220d..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/Translation.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// Strong type for Translation
- ///
- ///
- public class Translation
- {
- ///
- /// Gets a string giving the translated text.
- ///
- public string Text { get; }
-
- ///
- /// Gets a string representing the language code of the target language.
- ///
- public string To { get; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// A string giving the translated text.
- /// a string representing the language code of the target language.
- public Translation(string text, string to)
- {
- Text = text;
- To = to;
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslationResponse.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslationResponse.cs
deleted file mode 100644
index 8046108bcb0..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslationResponse.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Linq;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// Strong type for Translate Response
- ///
- ///
- public class TranslationResponse
- {
- ///
- /// Gets a object describing the detected language.
- ///
- /// This property has a value only when the method is invoked without the from parameter, so that automatic language detection is applied to determine the source language.
- ///
- public DetectedLanguageBase DetectedLanguage { get; }
-
- ///
- /// Gets an array of results.
- ///
- public IEnumerable Translations { get; }
-
- ///
- /// Gets the first translation result.
- ///
- public Translation Translation => Translations?.FirstOrDefault();
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// A object describing the detected language.
- /// an array of results.
- ///
- ///
- public TranslationResponse(DetectedLanguageBase detectedLanguage, IEnumerable translations)
- {
- DetectedLanguage = detectedLanguage;
- Translations = translations;
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslatorService.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslatorService.cs
deleted file mode 100644
index aec1fb5841e..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslatorService.cs
+++ /dev/null
@@ -1,261 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Text.Json;
-using System.Threading.Tasks;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// The TranslatorService class provides methods to translate text in various supported languages.
- ///
- ///
- /// To use this library, you must register Microsoft Translator on https://portal.azure.com/#create/Microsoft.CognitiveServices/apitype/TextTranslation to obtain the Subscription key.
- ///
- ///
- public class TranslatorService : ITranslatorService
- {
- private const string BaseUrl = "https://api.cognitive.microsofttranslator.com/";
- private const string ApiVersion = "api-version=3.0";
- private const string AuthorizationUri = "Authorization";
- private const string JsonMediaType = "application/json";
-
- private const int _MaxArrayLengthForTranslation = 25;
- private const int _MaxTextLengthForTranslation = 5000;
- private const int _MaxArrayLengthForDetection = 100;
- private const int _MaxTextLengthForDetection = 10000;
-
- private static HttpClient client = new HttpClient();
-
- ///
- /// Private singleton field.
- ///
- private static TranslatorService instance;
-
- ///
- /// Gets public singleton property.
- ///
- public static TranslatorService Instance => instance ?? (instance = new TranslatorService());
-
- private AzureAuthToken _authToken;
- private string _authorizationHeaderValue = string.Empty;
-
- ///
- /// Gets a reference to an instance of the underlying data provider.
- ///
- public object Provider
- {
- get { throw new NotImplementedException(); }
- }
-
- private TranslatorService()
- {
- _authToken = new AzureAuthToken(string.Empty);
- Language = CultureInfo.CurrentCulture.Name.ToLower();
- }
-
- ///
- public string SubscriptionKey
- {
- get { return _authToken.SubscriptionKey; }
- set { _authToken.SubscriptionKey = value; }
- }
-
- ///
- public string Language { get; set; }
-
- ///
- public async Task DetectLanguageAsync(string input)
- {
- var response = await DetectLanguageWithResponseAsync(input).ConfigureAwait(false);
- return response?.Language;
- }
-
- ///
- public async Task DetectLanguageWithResponseAsync(string input)
- {
- var response = await DetectLanguagesWithResponseAsync(new string[] { input }).ConfigureAwait(false);
- return response.FirstOrDefault();
- }
-
- ///
- public async Task> DetectLanguagesWithResponseAsync(IEnumerable input)
- {
- if (input == null)
- {
- throw new ArgumentNullException(nameof(input));
- }
-
- if (!input.Any())
- {
- throw new ArgumentException($"{nameof(input)} array must contain at least 1 element");
- }
-
- if (input.Count() > _MaxArrayLengthForDetection)
- {
- throw new ArgumentException($"{nameof(input)} array can have at most {_MaxArrayLengthForDetection} elements");
- }
-
- // Checks if it is necessary to obtain/update access token.
- await CheckUpdateTokenAsync().ConfigureAwait(false);
-
- var uriString = $"{BaseUrl}detect?{ApiVersion}";
- using var request = CreateHttpRequest(uriString, HttpMethod.Post, input.Select(t => new { Text = t.Substring(0, Math.Min(t.Length, _MaxTextLengthForDetection)) }));
-
- var response = await client.SendAsync(request).ConfigureAwait(false);
- var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
-
- var responseContent = JsonSerializer.Deserialize>(content);
- return responseContent;
- }
-
- ///
- public async Task> GetLanguagesAsync()
- {
- var languages = await GetLanguageNamesAsync();
- return languages.OrderBy(l => l.Code).Select(l => l.Code).ToList();
- }
-
- ///
- public async Task> GetLanguageNamesAsync(string language = null)
- {
- // Check if it is necessary to obtain/update access token.
- await CheckUpdateTokenAsync().ConfigureAwait(false);
-
- var uriString = $"{BaseUrl}languages?scope=translation&{ApiVersion}";
- using var request = CreateHttpRequest(uriString);
-
- language = language ?? Language;
- if (!string.IsNullOrWhiteSpace(language))
- {
- // If necessary, adds the Accept-Language header in order to get localized language names.
- request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(language));
- }
-
- var response = await client.SendAsync(request).ConfigureAwait(false);
- var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
-
- var jsonContent = JsonDocument.Parse(content).RootElement.GetProperty("translation");
- var responseContent = JsonSerializer.Deserialize>(jsonContent.ToString()).ToList();
- responseContent.ForEach(r => r.Value.Code = r.Key);
-
- return responseContent.Select(r => r.Value).OrderBy(r => r.Name).ToList();
- }
-
- ///
- public Task TranslateAsync(string input, string to = null) => TranslateAsync(input, null, to ?? Language);
-
- ///
- public async Task TranslateAsync(string input, string from, string to)
- {
- var response = await TranslateWithResponseAsync(new string[] { input }, from, new string[] { to }).ConfigureAwait(false);
- return response.FirstOrDefault()?.Translation.Text;
- }
-
- ///
- public Task TranslateWithResponseAsync(string input, string to = null) => TranslateWithResponseAsync(input, null, to ?? Language);
-
- ///
- public async Task TranslateWithResponseAsync(string input, string from, string to)
- {
- var response = await TranslateWithResponseAsync(new string[] { input }, from, new string[] { to }).ConfigureAwait(false);
- return response.FirstOrDefault();
- }
-
- ///
- public Task> TranslateWithResponseAsync(IEnumerable input, string from, string to) => TranslateWithResponseAsync(input, from, new string[] { to });
-
- ///
- public Task TranslateWithResponseAsync(string input, IEnumerable to) => TranslateWithResponseAsync(input, null, to);
-
- ///
- public async Task TranslateWithResponseAsync(string input, string from, IEnumerable to)
- {
- var response = await TranslateWithResponseAsync(new string[] { input }, from, to).ConfigureAwait(false);
- return response.FirstOrDefault();
- }
-
- ///
- public Task> TranslateWithResponseAsync(IEnumerable input, IEnumerable to = null) => TranslateWithResponseAsync(input, null, to);
-
- ///
- public async Task> TranslateWithResponseAsync(IEnumerable input, string from, IEnumerable to)
- {
- if (input == null)
- {
- throw new ArgumentNullException(nameof(input));
- }
-
- if (input.Count() > _MaxArrayLengthForTranslation)
- {
- throw new ArgumentException($"{nameof(input)} array can have at most {_MaxArrayLengthForTranslation} elements");
- }
-
- if (input.Any(str => string.IsNullOrWhiteSpace(str) || str.Length > _MaxTextLengthForTranslation))
- {
- throw new ArgumentException($"Each sentence cannot be null and longer than {_MaxTextLengthForTranslation} characters");
- }
-
- if (to == null || !to.Any())
- {
- to = new string[] { Language };
- }
-
- // Checks if it is necessary to obtain/update access token.
- await CheckUpdateTokenAsync().ConfigureAwait(false);
-
- var toQueryString = string.Join("&", to.Select(t => $"to={t}"));
- var uriString = (string.IsNullOrWhiteSpace(from) ? $"{BaseUrl}translate?{toQueryString}" : $"{BaseUrl}translate?from={from}&{toQueryString}") + $"&{ApiVersion}";
- using var request = CreateHttpRequest(uriString, HttpMethod.Post, input.Select(t => new { Text = t }));
-
- var response = await client.SendAsync(request).ConfigureAwait(false);
- var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
-
- var responseContent = JsonSerializer.Deserialize>(content);
- return responseContent;
- }
-
- ///
- public Task InitializeAsync() => CheckUpdateTokenAsync();
-
- ///
- public Task InitializeAsync(string subscriptionKey, string language = null)
- {
- _authToken = new AzureAuthToken(subscriptionKey);
- Language = language ?? CultureInfo.CurrentCulture.Name.ToLower();
-
- return InitializeAsync();
- }
-
- private async Task CheckUpdateTokenAsync()
- {
- // If necessary, updates the access token.
- _authorizationHeaderValue = await _authToken.GetAccessTokenAsync().ConfigureAwait(false);
- }
-
- private HttpRequestMessage CreateHttpRequest(string uriString)
- => CreateHttpRequest(uriString, HttpMethod.Get);
-
- private HttpRequestMessage CreateHttpRequest(string uriString, HttpMethod method, object content = null)
- {
- var request = new HttpRequestMessage(method, new Uri(uriString));
- request.Headers.Add(AuthorizationUri, _authorizationHeaderValue);
-
- if (content != null)
- {
- var jsonRequest = JsonSerializer.Serialize(content);
- var requestContent = new StringContent(jsonRequest, System.Text.Encoding.UTF8, JsonMediaType);
- request.Content = requestContent;
- }
-
- return request;
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslatorServiceException.cs b/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslatorServiceException.cs
deleted file mode 100644
index f16374287e9..00000000000
--- a/Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslatorServiceException.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-
-namespace Microsoft.Toolkit.Services.MicrosoftTranslator
-{
- ///
- /// The TranslatorServiceException class holds information about Exception related to .
- ///
- ///
- public class TranslatorServiceException : Exception
- {
- ///
- /// Initializes a new instance of the class using the specified error message.
- ///
- /// Message that describes the error
- public TranslatorServiceException(string message)
- : base(message)
- {
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/Twitter/ITwitterResult.cs b/Microsoft.Toolkit.Services/Services/Twitter/ITwitterResult.cs
deleted file mode 100644
index 65fc5d93dc1..00000000000
--- a/Microsoft.Toolkit.Services/Services/Twitter/ITwitterResult.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.Twitter
-{
- ///
- /// Any kind of twitter object.
- ///
- public interface ITwitterResult
- {
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/Twitter/Tweet.cs b/Microsoft.Toolkit.Services/Services/Twitter/Tweet.cs
deleted file mode 100644
index c0dea2d0092..00000000000
--- a/Microsoft.Toolkit.Services/Services/Twitter/Tweet.cs
+++ /dev/null
@@ -1,213 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Globalization;
-using System.Text.Json.Serialization;
-
-namespace Microsoft.Toolkit.Services.Twitter
-{
- ///
- /// Twitter Timeline item.
- ///
- public class Tweet : Toolkit.Parsers.SchemaBase, ITwitterResult
- {
- private string _text;
-
- ///
- /// Gets or sets time item was created.
- ///
- [JsonPropertyName("created_at")]
- public string CreatedAt { get; set; }
-
- ///
- /// Gets or sets item Id.
- ///
- [JsonPropertyName("id_str")]
- public string Id { get; set; }
-
- ///
- /// Gets or sets text of the tweet (handles both 140 and 280 characters)
- ///
- [JsonPropertyName("text")]
- public string Text
- {
- get { return _text ?? FullText; }
- set { _text = value; }
- }
-
- ///
- /// Gets or sets text of the tweet (280 characters).
- ///
- [JsonPropertyName("full_text")]
- private string FullText { get; set; }
-
- ///
- /// Gets or sets display text range (indexes of tweet text without RT and leading user mentions)
- ///
- [JsonPropertyName("display_text_range")]
- public int[] DisplayTextRange { get; set; }
-
- ///
- /// Gets or sets a value indicating whether tweet is truncated
- /// (true when tweet is longer than 140 characters)
- /// This entity may be deprecated - it never seems to be set to true.
- ///
- [JsonPropertyName("truncated")]
- public bool IsTruncated { get; set; }
-
- ///
- /// Gets or sets attached content of the tweet
- ///
- [JsonPropertyName("entities")]
- public TwitterEntities Entities { get; set; }
-
- ///
- /// Gets or sets extended attached content of the tweet
- ///
- [JsonPropertyName("extended_entities")]
- public TwitterExtendedEntities ExtendedEntities { get; set; }
-
- ///
- /// Gets or sets tweet source (client or website used)
- ///
- [JsonPropertyName("source")]
- public string Source { get; set; }
-
- ///
- /// Gets or sets in_reply_to_screen_name
- ///
- [JsonPropertyName("in_reply_to_screen_name")]
- public string InReplyToScreenName { get; set; }
-
- ///
- /// Gets or sets in_reply_to_status_id_str
- ///
- [JsonPropertyName("in_reply_to_status_id_str")]
- public string InReplyToStatusId { get; set; }
-
- ///
- /// Gets or sets in_reply_to_user_id_str
- ///
- [JsonPropertyName("in_reply_to_user_id_str")]
- public string InReplyToUserId { get; set; }
-
- ///
- /// Gets or sets user who posted the status.
- ///
- [JsonPropertyName("user")]
- public TwitterUser User { get; set; }
-
- ///
- /// Gets or sets geo coordinates (latitude and longitude) returned by Twitter for some locations
- ///
- [JsonPropertyName("coordinates")]
- [JsonConverter(typeof(TwitterCoordinatesConverter))]
- public TwitterCoordinates Coordinates { get; set; }
-
- ///
- /// Gets or sets the Place object returned by Twitter for some locations
- ///
- [JsonPropertyName("place")]
- public TwitterPlace Place { get; set; }
-
- ///
- /// Gets or sets the Retweeted Tweet
- ///
- [JsonPropertyName("retweeted_status")]
- public Tweet RetweetedStatus { get; set; }
-
- ///
- /// Gets the creation date
- ///
- public DateTime CreationDate
- {
- get
- {
- DateTime dt;
- if (!DateTime.TryParseExact(CreatedAt, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
- {
- dt = DateTime.Today;
- }
-
- return dt;
- }
- }
-
- ///
- /// Gets or sets quoted_status
- ///
- [JsonPropertyName("quoted_status")]
- public Tweet QuotedStatus { get; set; }
-
- ///
- /// Gets or sets quoted_status_id_str
- ///
- [JsonPropertyName("quoted_status_id_str")]
- public string QuotedStatusId { get; set; }
-
- ///
- /// Gets or sets quoted_status_permalink
- ///
- [JsonPropertyName("quoted_status_permalink")]
- public TwitterUrl QuotedStatusPermalink { get; set; }
-
- ///
- /// Gets or sets approximate count of tweets quoting tweet
- ///
- [JsonPropertyName("quote_count")]
- public int QuoteCount { get; set; }
-
- ///
- /// Gets or sets number of replies to tweet
- ///
- ///
- /// Premium and Enterprise API access only
- ///
- [JsonPropertyName("reply_count")]
- public int ReplyCount { get; set; }
-
- ///
- /// Gets or sets number of times tweet has been retweeted
- ///
- [JsonPropertyName("retweet_count")]
- public int RetweetCount { get; set; }
-
- ///
- /// Gets or sets number of times tweet has been liked
- ///
- [JsonPropertyName("favorite_count")]
- public int FavoriteCount { get; set; }
-
- ///
- /// Gets or sets a value indicating whether or not logged-in user has liked tweet
- ///
- [JsonPropertyName("favorited")]
- public bool Favorited { get; set; }
-
- ///
- /// Gets or sets a value indicating whether or not logged-in user has retweeted tweet
- ///
- [JsonPropertyName("retweeted")]
- public bool Retweeted { get; set; }
-
- ///
- /// Gets or sets a value indicating whether URL in tweet has been flagged for sensitive content
- ///
- [JsonPropertyName("possibly_sensitive")]
- public bool Sensitive { get; set; }
-
- ///
- /// Gets or sets stream filter of tweet
- ///
- [JsonPropertyName("filter_level")]
- public string FilterLevel { get; set; }
-
- ///
- /// Gets or sets BCP 47 language identifier of tweet content
- ///
- [JsonPropertyName("lang")]
- public string Language { get; set; }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Services/Twitter/TweetParser.cs b/Microsoft.Toolkit.Services/Services/Twitter/TweetParser.cs
deleted file mode 100644
index 26a544cb6f8..00000000000
--- a/Microsoft.Toolkit.Services/Services/Twitter/TweetParser.cs
+++ /dev/null
@@ -1,30 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections.Generic;
-using System.Text.Json;
-
-namespace Microsoft.Toolkit.Services.Twitter
-{
- ///
- /// Twitter Timeline Parser.
- ///
- public class TweetParser : Parsers.IParser
- {
- ///
- /// Parse string data into strongly typed list.
- ///
- /// Input string.
- /// List of strongly typed objects.
- public IEnumerable Parse(string data)
- {
- if (string.IsNullOrEmpty(data))
- {
- return null;
- }
-
- return JsonSerializer.Deserialize>(data);
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Services/Twitter/TwitterCoordinates.cs b/Microsoft.Toolkit.Services/Services/Twitter/TwitterCoordinates.cs
deleted file mode 100644
index 4369619ae66..00000000000
--- a/Microsoft.Toolkit.Services/Services/Twitter/TwitterCoordinates.cs
+++ /dev/null
@@ -1,28 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.Twitter
-{
- ///
- /// Longitude and Latitude for a tweet
- ///
- public class TwitterCoordinates
- {
- ///
- /// Gets the numeric latitude (null if the value could not be converted)
- ///
- public double Latitude { get; internal set; }
-
- ///
- /// Gets the numeric longitude (null if the value could not be converted)
- ///
- public double Longitude { get; internal set; }
-
- ///
- public override string ToString()
- {
- return $"({Latitude}, {Longitude})";
- }
- }
-}
\ No newline at end of file
diff --git a/Microsoft.Toolkit.Services/Services/Twitter/TwitterCoordinatesConverter.cs b/Microsoft.Toolkit.Services/Services/Twitter/TwitterCoordinatesConverter.cs
deleted file mode 100644
index 3e459a1cfee..00000000000
--- a/Microsoft.Toolkit.Services/Services/Twitter/TwitterCoordinatesConverter.cs
+++ /dev/null
@@ -1,115 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Text.Json;
-using System.Text.Json.Serialization;
-
-namespace Microsoft.Toolkit.Services.Twitter
-{
- internal class TwitterCoordinatesConverter : JsonConverter
- {
- private readonly JsonEncodedText latitudeName = JsonEncodedText.Encode("Latitude");
- private readonly JsonEncodedText longitudeName = JsonEncodedText.Encode("Longitude");
-
- public override bool CanConvert(Type objectType)
- {
- return false;
- }
-
- private readonly JsonConverter doubleConverter;
-
- public TwitterCoordinatesConverter(JsonSerializerOptions options)
- {
- doubleConverter = options?.GetConverter(typeof(double)) as JsonConverter ?? throw new InvalidOperationException();
- }
-
- public override TwitterCoordinates Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
- {
- try
- {
- if (reader.TokenType != JsonTokenType.StartObject)
- {
- return null;
- }
-
- double latitude = default;
- bool latitudeSet = false;
-
- double longitude = default;
- bool longitudeSet = false;
-
- // Get the first property.
- reader.Read();
- if (reader.TokenType != JsonTokenType.PropertyName)
- {
- throw new JsonException();
- }
-
- if (reader.ValueTextEquals(latitudeName.EncodedUtf8Bytes))
- {
- latitude = ReadProperty(ref reader, options);
- latitudeSet = true;
- }
- else if (reader.ValueTextEquals(longitudeName.EncodedUtf8Bytes))
- {
- longitude = ReadProperty(ref reader, options);
- longitudeSet = true;
- }
- else
- {
- throw new JsonException();
- }
-
- // Get the second property.
- reader.Read();
- if (reader.TokenType != JsonTokenType.PropertyName)
- {
- throw new JsonException();
- }
-
- if (latitudeSet && reader.ValueTextEquals(longitudeName.EncodedUtf8Bytes))
- {
- longitude = ReadProperty(ref reader, options);
- }
- else if (longitudeSet && reader.ValueTextEquals(latitudeName.EncodedUtf8Bytes))
- {
- latitude = ReadProperty(ref reader, options);
- }
- else
- {
- throw new JsonException();
- }
-
- reader.Read();
-
- if (reader.TokenType != JsonTokenType.EndObject)
- {
- throw new JsonException();
- }
-
- return new TwitterCoordinates
- {
- Latitude = latitude,
- Longitude = longitude
- };
- }
- catch
- {
- return null;
- }
- }
-
- private double ReadProperty(ref Utf8JsonReader reader, JsonSerializerOptions options)
- {
- reader.Read();
- return doubleConverter.Read(ref reader, typeof(double), options);
- }
-
- public override void Write(Utf8JsonWriter writer, TwitterCoordinates value, JsonSerializerOptions options)
- {
- throw new NotImplementedException();
- }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/Twitter/TwitterDataConfig.cs b/Microsoft.Toolkit.Services/Services/Twitter/TwitterDataConfig.cs
deleted file mode 100644
index 96735e3d2b4..00000000000
--- a/Microsoft.Toolkit.Services/Services/Twitter/TwitterDataConfig.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Toolkit.Services.Twitter
-{
- ///
- /// Query string configuration.
- ///
- public class TwitterDataConfig
- {
- ///
- /// Gets or sets twitter query type.
- ///
- public TwitterQueryType QueryType { get; set; }
-
- ///
- /// Gets or sets query parameters.
- ///
- public string Query { get; set; }
- }
-}
diff --git a/Microsoft.Toolkit.Services/Services/Twitter/TwitterDataProvider.cs b/Microsoft.Toolkit.Services/Services/Twitter/TwitterDataProvider.cs
deleted file mode 100644
index 3ba3d3627c8..00000000000
--- a/Microsoft.Toolkit.Services/Services/Twitter/TwitterDataProvider.cs
+++ /dev/null
@@ -1,705 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Text.Json;
-using System.Threading.Tasks;
-using Microsoft.Toolkit.Services.Core;
-
-#if WINRT
-using System.Runtime.InteropServices.WindowsRuntime;
-using Microsoft.Toolkit.Services.PlatformSpecific.Uwp;
-using Windows.Storage.Streams;
-#endif
-
-#if NET462
-using Microsoft.Toolkit.Services.PlatformSpecific.NetFramework;
-#endif
-
-namespace Microsoft.Toolkit.Services.Twitter
-{
- ///
- /// Data Provider for connecting to Twitter service.
- ///
- public class TwitterDataProvider : Toolkit.Services.DataProviderBase
- {
- ///
- /// Base Url for service.
- ///
- private const string BaseUrl = "https://api.twitter.com/1.1";
- private const string OAuthBaseUrl = "https://api.twitter.com/oauth";
- private const string PublishUrl = "https://upload.twitter.com/1.1";
- private const string UserStreamUrl = "https://userstream.twitter.com/1.1";
-
- private static HttpClient _client;
-
- ///
- /// Base Url for service.
- ///
- private readonly TwitterOAuthTokens _tokens;
- private readonly IAuthenticationBroker _authenticationBroker;
- private readonly IPasswordManager _passwordManager;
- private readonly IStorageManager _storageManager;
- private readonly ISignatureManager _signatureManager;
- private TwitterOAuthRequest _streamRequest;
-
- ///
- /// Gets or sets logged in user information.
- ///
- public string UserScreenName { get; set; }
-
- ///
- /// Gets a value indicating whether the provider is already logged in
- ///
- public bool LoggedIn { get; private set; }
-
- ///
- /// Initializes a new instance of the class.
- /// Constructor.
- ///
- /// OAuth tokens for request.
- /// Authentication result interface.
- /// Platform password manager
- /// Platform storage provider
- /// Platform signature manager
- public TwitterDataProvider(TwitterOAuthTokens tokens, IAuthenticationBroker authenticationBroker, IPasswordManager passwordManager, IStorageManager storageManager, ISignatureManager signatureManager)
- {
- if (string.IsNullOrEmpty(tokens.ConsumerSecret))
- {
- throw new ArgumentException("Missing consumer secret");
- }
-
- if (string.IsNullOrEmpty(tokens.ConsumerKey))
- {
- throw new ArgumentException("Missing consumer key");
- }
-
- if (string.IsNullOrEmpty(tokens.CallbackUri))
- {
- throw new ArgumentException("Missing callback uri");
- }
-
- _tokens = tokens;
- _authenticationBroker = authenticationBroker ?? throw new ArgumentException("Missing AuthenticationBroker");
- _passwordManager = passwordManager ?? throw new ArgumentException("Missing PasswordManager");
- _storageManager = storageManager ?? throw new ArgumentException("Missing StorageManager");
- _signatureManager = signatureManager ?? throw new ArgumentException("Missing SignatureManager");
-
- if (_client == null)
- {
- HttpClientHandler handler = new HttpClientHandler();
- handler.AutomaticDecompression = DecompressionMethods.GZip;
- _client = new HttpClient(handler);
- }
- }
-
-#if WINRT
- ///
- /// Initializes a new instance of the class.
- /// Constructor.
- ///
- /// OAuth tokens for request.
- public TwitterDataProvider(TwitterOAuthTokens tokens)
- : this(tokens, new UwpAuthenticationBroker(), new UwpPasswordManager(), new UwpStorageManager(), new UwpSignatureManager())
- {
- }
-#endif
-
-#if NET462
- ///
- /// Initializes a new instance of the class.
- /// Constructor.
- ///
- /// OAuth tokens for request.
- public TwitterDataProvider(TwitterOAuthTokens tokens)
- : this(tokens, new NetFrameworkAuthenticationBroker(), new NetFrameworkPasswordManager(), new NetFrameworkStorageManager(), new NetFrameworkSignatureManager())
- {
- }
-#endif
-
- ///
- /// Retrieve user data.
- ///
- /// User screen name or null for current logged user
- /// Returns user data.
- public async Task GetUserAsync(string screenName = null)
- {
- string rawResult = null;
- try
- {
- var userScreenName = screenName ?? UserScreenName;
- var uri = new Uri($"{BaseUrl}/users/show.json?screen_name={userScreenName}");
-
- TwitterOAuthRequest request = new TwitterOAuthRequest();
- rawResult = await request.ExecuteGetAsync(uri, _tokens, _signatureManager);
- return JsonSerializer.Deserialize(rawResult);
- }
- catch (UserNotFoundException)
- {
- throw new UserNotFoundException(screenName);
- }
- catch
- {
- if (!string.IsNullOrEmpty(rawResult))
- {
- var errors = JsonSerializer.Deserialize(rawResult);
-
- throw new TwitterException { Errors = errors };
- }
-
- throw;
- }
- }
-
- ///
- /// Retrieve user timeline data with specific parser.
- ///
- /// Strong type for results.
- /// User screen name.
- /// Upper record limit.
- /// Specific results parser.
- /// Returns strongly typed list of results.
- public async Task> GetUserTimeLineAsync(string screenName, int maxRecords, Toolkit.Parsers.IParser parser)
- where TSchema : Toolkit.Parsers.SchemaBase
- {
- string rawResult = null;
- try
- {
- var uri = new Uri($"{BaseUrl}/statuses/user_timeline.json?screen_name={screenName}&count={maxRecords}&include_rts=1&tweet_mode=extended");
-
- TwitterOAuthRequest request = new TwitterOAuthRequest();
- rawResult = await request.ExecuteGetAsync(uri, _tokens, _signatureManager);
-
- var result = parser.Parse(rawResult);
- return result
- .Take(maxRecords)
- .ToList();
- }
- catch (UserNotFoundException)
- {
- throw new UserNotFoundException(screenName);
- }
- catch
- {
- if (!string.IsNullOrEmpty(rawResult))
- {
- var errors = JsonSerializer.Deserialize(rawResult);
-
- throw new TwitterException { Errors = errors };
- }
-
- throw;
- }
- }
-
- ///
- /// Search for specific hash tag with specific parser.
- ///
- /// Strong type for results.
- /// Hash tag.
- /// Upper record limit.
- /// Specific results parser.
- /// Returns strongly typed list of results.
- public async Task> SearchAsync(string hashTag, int maxRecords, Toolkit.Parsers.IParser parser)
- where TSchema : Toolkit.Parsers.SchemaBase
- {
- var uri = new Uri($"{BaseUrl}/search/tweets.json?q={Uri.EscapeDataString(hashTag)}&count={maxRecords}&tweet_mode=extended");
- TwitterOAuthRequest request = new TwitterOAuthRequest();
- var rawResult = await request.ExecuteGetAsync(uri, _tokens, _signatureManager);
-
- var result = parser.Parse(rawResult);
- return result
- .Take(maxRecords)
- .ToList();
- }
-
- ///
- /// Log user in to Twitter.
- ///
- /// Boolean indicating login success.
- public async Task LoginAsync()
- {
- var credentials = _passwordManager.Get("TwitterAccessToken");
- var user = await _storageManager.GetAsync("TwitterScreenName");
- if (!string.IsNullOrEmpty(user) && credentials != null)
- {
- _tokens.AccessToken = credentials.UserName;
- _tokens.AccessTokenSecret = credentials.Password;
- UserScreenName = user;
- LoggedIn = true;
- return true;
- }
-
- if (await InitializeRequestAccessTokensAsync(_tokens.CallbackUri) == false)
- {
- LoggedIn = false;
- return false;
- }
-
- string requestToken = _tokens.RequestToken;
- string twitterUrl = $"{OAuthBaseUrl}/authorize?oauth_token={requestToken}";
-
- Uri startUri = new Uri(twitterUrl);
- Uri endUri = new Uri(_tokens.CallbackUri);
-
- var result = await _authenticationBroker.Authenticate(startUri, endUri);
-
- switch (result.ResponseStatus)
- {
- case AuthenticationResultStatus.Success:
- LoggedIn = true;
- return await ExchangeRequestTokenForAccessTokenAsync(result.ResponseData);
-
- case AuthenticationResultStatus.ErrorHttp:
- Debug.WriteLine("WAB failed, message={0}", result.ResponseErrorDetail.ToString());
- LoggedIn = false;
- return false;
-
- case AuthenticationResultStatus.UserCancel:
- Debug.WriteLine("WAB user aborted.");
- LoggedIn = false;
- return false;
- }
-
- LoggedIn = false;
- return false;
- }
-
- ///
- /// Log user out of Twitter.
- ///
- /// A representing the asynchronous operation.
- public async Task LogoutAsync()
- {
- var credential = _passwordManager.Get("TwitterAccessToken");
-
- if (credential != null)
- {
- _passwordManager.Remove("TwitterAccessToken");
- await _storageManager.SetAsync("TwitterScreenName", null);
- }
-
- UserScreenName = null;
- LoggedIn = false;
- }
-
- ///
- /// Tweets a status update.
- ///
- /// Tweet text.
- /// Pictures to attach to the tweet (up to 4).
- /// Success or failure.
- public async Task TweetStatusAsync(string tweet, params Stream[] pictures)
- {
- return await TweetStatusAsync(new TwitterStatus { Message = tweet }, pictures);
- }
-
- ///
- /// Tweets a status update.
- ///
- /// Tweet text.
- /// Pictures to attach to the tweet (up to 4).
- /// Success or failure.
- public async Task TweetStatusAsync(TwitterStatus status, params Stream[] pictures)
- {
- var mediaIds = string.Empty;
-
- if (pictures != null && pictures.Length > 0)
- {
- var ids = new List();
- foreach (var picture in pictures)
- {
- ids.Add(await UploadPictureAsync(picture));
- }
-
- mediaIds = "&media_ids=" + string.Join(",", ids);
- }
-
- var uri = new Uri($"{BaseUrl}/statuses/update.json?{status.RequestParameters}{mediaIds}");
-
- TwitterOAuthRequest request = new TwitterOAuthRequest();
- await request.ExecutePostAsync(uri, _tokens, _signatureManager);
-
- return true;
- }
-
- ///
- /// Publish a picture to Twitter user's medias.
- ///
- /// Picture stream.
- /// Media ID
- public async Task UploadPictureAsync(Stream stream)
- {
- var uri = new Uri($"{PublishUrl}/media/upload.json");
-
- byte[] fileBytes;
-
- using (var ms = new MemoryStream())
- {
- await stream.CopyToAsync(ms);
- fileBytes = ms.ToArray();
- }
-
- string boundary = DateTime.Now.Ticks.ToString("x");
-
- TwitterOAuthRequest request = new TwitterOAuthRequest();
- return await request.ExecutePostMultipartAsync(uri, _tokens, boundary, fileBytes, _signatureManager);
- }
-
- ///
- /// Open a connection to user streams service (Events, DirectMessages...).
- ///
- /// Specific stream's result parser.
- /// Method invoked each time a result occurs.
- /// Awaitable task.
- public Task StartUserStreamAsync(TwitterUserStreamParser parser, TwitterStreamCallbacks.TwitterStreamCallback callback)
- {
- var uri = new Uri($"{UserStreamUrl}/user.json?replies=all");
-
- _streamRequest = new TwitterOAuthRequest();
-
- return _streamRequest.ExecuteGetStreamAsync(uri, _tokens, rawResult => callback(parser.Parse(rawResult)), _signatureManager);
- }
-
- ///
- /// Stop user's stream
- ///
- public void StopStream()
- {
- _streamRequest?.Abort();
- _streamRequest = null;
- }
-
- ///
- /// Returns parser implementation for specified configuration.
- ///
- /// Query configuration.
- /// Strongly typed parser.
- protected override Toolkit.Parsers.IParser GetDefaultParser(TwitterDataConfig config)
- {
- if (config == null)
- {
- throw new ConfigNullException();
- }
-
- switch (config.QueryType)
- {
- case TwitterQueryType.Search:
- return new TwitterSearchParser();
-
- case TwitterQueryType.Home:
- case TwitterQueryType.User:
- case TwitterQueryType.Custom:
- return new TwitterParser();
-
- default:
- return new TwitterParser();
- }
- }
-
- ///
- /// Wrapper around REST API for making data request.
- ///
- /// Schema to use
- /// Query configuration.
- /// Upper limit for records returned.
- /// The zero-based index of the page that corresponds to the items to retrieve.
- /// IParser implementation for interpreting results.
- /// Strongly typed list of results.
- protected override async Task> GetDataAsync