I'm going to rewrite the application from Monotouh to Monodroid application for android. Correct me if I'm wrong. The logic remains the same as in MonoTouch or change anything? If something changes, please tell me, what?
As far as I understand, only GIU changes. Thanks in advance!
So, this is my code where i call data from my server:
namespace Mobile{
public static class SiteHelper
{
public static string DbPath = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "Sql_1.4.sqlite");
public const string TempDbPath = "./Sql.sqlite";
public static UIView View { get; set; }
public static BaseController Controller { get; set; }
private static event NIHandler _noInternetHandler;
private static bool _noInternetShoved = false;
public static string SiteDomain = "http://mysite.com"; //files which connecting to the DB on server (.asx files)
private delegate void NIHandler ();
public static XDocument DoRequest (string Request)
{
if (_noInternetHandler != null) {
foreach (var del in _noInternetHandler.GetInvocationList()) {
_noInternetHandler -= del as NIHandler;
}
}
if (Controller != null)
_noInternetHandler += new NIHandler (Controller.PushThenNoInternet);
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"myprogMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
UIActivityIndicatorView _preloader = null;
if (Controller != null) {
Controller.InvokeOnMainThread (delegate() {
_preloader = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray);
if (View != null && Request.IndexOf ("login.ashx") == -1
&& Request.IndexOf ("yandex") == -1
&& Request.IndexOf ("GetDialogMessages") == -1) {
lock (_preloader) {
if (_preloader != null && !_preloader.IsAnimating)
_preloader.HidesWhenStopped = true;
_preloader.Frame = new RectangleF (150, 170, 30, 30);
_preloader.Transform = MonoTouch.CoreGraphics.CGAffineTransform.MakeScale ((float)1.3, (float)1.3);
_preloader.StartAnimating ();
View.Add (_preloader);
}
}
});
}
/*ctx.GetText(Resource.String.SiteAddress)*/
Stream Stream = null;
try {
HttpWebRequest request = new HttpWebRequest (new Uri (SiteDomain + "/FolderWithFiles/" + CryptoString));
request.Timeout = 8000;
Stream = request.GetResponse ().GetResponseStream ();
_noInternetShoved = false;
if (_noInternetHandler != null)
_noInternetHandler -= new NIHandler (Controller.PushThenNoInternet);
} catch (WebException) {
if (_noInternetHandler != null)
_noInternetHandler.Invoke ();
var resp = new XDocument (new XElement ("Response",
new XElement ("status", "error"),
new XElement ("error", "Отсутствует интернет"))
);
return resp;
}
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp.Substring (0, Resp.IndexOf ("<html>") == -1 ? Resp.Length : Resp.IndexOf ("<!DOCTYPE html>")));
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (Controller != null && _preloader != null) {
Controller.InvokeOnMainThread (delegate() {
lock (_preloader) {
_preloader.StopAnimating ();
_preloader.RemoveFromSuperview ();
}
});
}
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static XDocument DoWriteFileRequest (string Request, byte[] file)
{
string CryptoString = "";
string Language = "ru";
using (MD5 md5Hash = MD5.Create()) {
string hashKey = Guid.NewGuid ().ToString ().Substring (0, 4);
CryptoString = Request + (Request.Contains ("?") ? "&" : "?") + "hash=" + GetMd5Hash (
md5Hash,
"mobileMobhash_" + hashKey
) + "&hashKey=" + hashKey + "&language=" + Language;
HttpWebRequest Req = (HttpWebRequest)WebRequest.Create (SiteDomain + "/misc/mobile/" + CryptoString);
Req.Method = "POST";
Stream requestStream = Req.GetRequestStream ();
requestStream.Write (file, 0, file.Length);
requestStream.Close ();
Stream Stream = Req.GetResponse ().GetResponseStream ();
StreamReader Sr = new StreamReader (Stream);
string Resp = Sr.ReadToEnd ();
XDocument Response = XDocument.Parse (Resp);
string Hash = Response.Descendants ().Where (x => x.Name == "hash")
.FirstOrDefault ().Value;
string HashKey = Response.Descendants ().Where (x => x.Name == "hashKey")
.FirstOrDefault ().Value;
Sr.Close ();
Stream.Close ();
if (VerifyMd5Hash (
md5Hash,
"mobileSitehash_" + HashKey,
Hash
))
return Response;
else
throw new Exception ();
}
}
public static string GetMd5Hash (MD5 md5Hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash (Encoding.UTF8.GetBytes (input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder ();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++) {
sBuilder.Append (data [i].ToString ("x2"));
}
// Return the hexadecimal string.2
return sBuilder.ToString ();
}
//Geting the info for my app
public static List<PackageListModel> GetUserPackages (int UserID)
{
List<PackageListModel> Events = new List<PackageListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
PackageListModel Event = null;
Event = new PackageListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Title = el.Element("Title").Value,
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
ImageUrl = el.Element("ImageUrl").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
//Получить пользовательские поездки
public static List<TransporterListModel> GetUserTransporters (int UserID)
{
List<TransporterListModel> Events = new List<TransporterListModel> ();
string Req = "SomeFile.ashx?UserID=" + UserID;
XDocument XmlAnswer = DoRequest (Req);
if (XmlAnswer.Descendants ("status").First ().Value == "ok") {
foreach (var el in XmlAnswer.Descendants ("Response").First ().Descendants().Where(x=>x.Name == "Event")) {
TransporterListModel Event = null;
Event = new TransporterListModel ()
{
ID = int.Parse(el.Attribute("ID").Value),
Date = el.Element("Date").Value,
Price = el.Element("Price").Value,
TransportsStr = el.Element("Transports").Value,
Location = el.Element("Location").Value
};
Events.Add (Event);
}
}
return Events;
}
}
}
}
I think you should read this.
In brief - you can reuse application logic that not depends on platform-specific parts, so working with database/server can be shared between MonoTouch and Mono for Android.
Related
I am trying to upload a large file to One Drive using Microsoft Graph API.
Uploading to One Drive works normally, but the file is damaged.
Please help me to solve the problem.
public ActionResult UploadLargeFiles(string id, [FromForm]IFormFile files)
{
string fileName = files.FileName;
int fileSize = Convert.ToInt32(files.Length);
var uploadProvider = new JObject();
var res = new JArray();
var isExistence = _mailService.GetUploadFolder(id);
if (isExistence != HttpStatusCode.OK)
{
var createFolder = _mailService.CreateUploadFolder(id);
if (createFolder != HttpStatusCode.Created)
{
return BadRequest(ModelState);
}
}
if (files.Length > 0)
{
var uploadSessionUrl = _mailService.CreateUploadSession(id, fileName);
if (uploadSessionUrl != null)
{
if (fileSize < 4194304)
{
uploadProvider = _mailService.UploadByteFile(id, uploadSessionUrl, files);
res.Add(uploadProvider);
}
}
else
{
return BadRequest(ModelState);
}
}
return Ok();
}
createUploadSession
public string CreateUploadSession(string upn, string fileName)
{
var uploadSession = _mailGraphService.CreateUploadSession(upn, fileName).Result;
var sessionResult = new UploadSessionDTO(uploadSession);
return sessionResult.uploadUrl;
}
public async Task<UploadSessionDTO> CreateUploadSession(string upn, string fileName)
{
this.InitHttpClient();
var jObject = JObject.FromObject(new { item = new Dictionary<string, object> { { "#microsoft.graph.conflictBehavior", "rename" } }, fileSystemInfo = new Dictionary<string, object> { { "#odata.type", "microsoft.graph.fileSystemInfo" } }, name = fileName });
var toJson = JsonConvert.SerializeObject(jObject);
var content = new StringContent(toJson, Encoding.UTF8, "application/json");
var response = await _client.PostAsync("users/"+ upn + "/drive/root:/MailFiles/" + fileName +":/createUploadSession", content);
if (!response.IsSuccessStatusCode)
return null;
var strData = await response.Content.ReadAsStringAsync();
dynamic uploadSession = JsonConvert.DeserializeObject<UploadSessionDTO>(strData);
return uploadSession;
}
public JObject LargeFileUpload(string upn, string url, IFormFile files)
{
var responseCode = HttpStatusCode.OK;
var jObject = new JObject();
int idx = 0;
int fileSize = Convert.ToInt32(files.Length);
int fragSize = 4 * 1024 * 1024; //4MB => 4 * 1024 * 1024;
var byteRemaining = fileSize;
var numFragments = (byteRemaining / fragSize) + 1;
while (idx < numFragments)
{
var chunkSize = fragSize;
var start = idx * fragSize;
var end = idx * fragSize + chunkSize - 1;
var offset = idx * fragSize;
if (byteRemaining < chunkSize)
{
chunkSize = byteRemaining;
end = fileSize - 1;
}
var contentRange = " bytes " + start + "-" + end + "/" + fileSize;
byte[] file = new byte[chunkSize];
using (var client = new HttpClient())
{
var content = new ByteArrayContent(file);
content.Headers.Add("Content-Length", chunkSize.ToString());
content.Headers.Add("Content-Range", contentRange);
var response = client.PutAsync(url, content);
var strData = response.Result.Content.ReadAsStringAsync().Result;
responseCode = response.Result.StatusCode;
//업로드 성공
if (responseCode == HttpStatusCode.Created)
{
JObject data = JObject.Parse(strData);
string downloadUrl = data["#content.downloadUrl"].ToString();
string itemId = data["id"].ToString();
//파일 크기 -> kb로 변환
fileSize = fileSize / 1000;
jObject = JObject.FromObject(new { name = files.Name, id = itemId, url = downloadUrl, size = (double)fileSize });
}
//업로드 충돌
else if (responseCode == HttpStatusCode.Conflict)
{
var restart = RestartByteFile(upn, url, files.Name);
responseCode = restart;
}
}
byteRemaining = byteRemaining - chunkSize;
idx++;
}
if (responseCode == HttpStatusCode.Created) { return jObject; }
else return jObject = JObject.FromObject(new { result = "실패" });
}
When I checked OneDrive, the file was uploaded normally, and when I downloaded and opened the file, it came out as a damaged file.
I wonder why the file gets corrupted when uploaded, and how to fix it.
If the problem cannot be solved, please let us know that it cannot be solved.
I have a .NET core app, it works perfectly.
But I need to create a batch of new users, by inserting directly into the database.
The problem now is that when I try to login, it failed...
I suspect a problem with the hashed password.
I use the following code to generate my hash and security stamp:
_user.SecurityStamp = Guid.NewGuid().ToString("D");
_user.UserName = _userName;
_user.Email = _email;
var hasher = new Microsoft.AspNetCore.Identity.PasswordHasher<IdentityUser>();
IdentityUser identityUser = new IdentityUser(Guid.Parse(_user.Id), _userName, _email);
_user.PasswordHash = hasher.HashPassword(identityUser, _password);
From my understanding, it should work, but do you have any idea to debug / fix this issue ?
Don't use custom VerifyHashedPassword method.
From the source code of PasswordHasher below, we can see VerifyHashedPassword() can verify automatically with hashedPassword from DB and original input password.
using System;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
namespace Microsoft.AspNet.Identity
{
internal static class Crypto
{
private const int PBKDF2IterCount = 1000;
private const int PBKDF2SubkeyLength = 32;
private const int SaltSize = 16;
public static string HashPassword(string password)
{
if (password == null)
throw new ArgumentNullException("password");
byte[] salt;
byte[] bytes;
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, 16, 1000))
{
salt = rfc2898DeriveBytes.Salt;
bytes = rfc2898DeriveBytes.GetBytes(32);
}
byte[] inArray = new byte[49];
Buffer.BlockCopy((Array) salt, 0, (Array) inArray, 1, 16);
Buffer.BlockCopy((Array) bytes, 0, (Array) inArray, 17, 32);
return Convert.ToBase64String(inArray);
}
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
if (hashedPassword == null)
return false;
if (password == null)
throw new ArgumentNullException("password");
byte[] numArray = Convert.FromBase64String(hashedPassword);
if (numArray.Length != 49 || (int) numArray[0] != 0)
return false;
byte[] salt = new byte[16];
Buffer.BlockCopy((Array) numArray, 1, (Array) salt, 0, 16);
byte[] a = new byte[32];
Buffer.BlockCopy((Array) numArray, 17, (Array) a, 0, 32);
byte[] bytes;
using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, salt, 1000))
bytes = rfc2898DeriveBytes.GetBytes(32);
return Crypto.ByteArraysEqual(a, bytes);
}
[MethodImpl(MethodImplOptions.NoOptimization)]
private static bool ByteArraysEqual(byte[] a, byte[] b)
{
if (object.ReferenceEquals((object) a, (object) b))
return true;
if (a == null || b == null || a.Length != b.Length)
return false;
bool flag = true;
for (int index = 0; index < a.Length; ++index)
flag &= (int) a[index] == (int) b[index];
return flag;
}
}
}
Test Codes
public static User user = new User();
[Route("/")]
public IActionResult Index()
{
//register a user
if(user != null) {
//test data
user.Id = Guid.NewGuid();
user.UserName = "test";
user.Email = "test#x.com";
user.Password = "password";
var hasher = new Microsoft.AspNetCore.Identity.PasswordHasher<IdentityUser>();
IdentityUser identityUser = new IdentityUser(user.Id.ToString());
user.PasswordHash = hasher.HashPassword(identityUser, user.Password);
}
//... save user to DB
return View();
}
Login controller
[HttpPost]
public IActionResult Login(LoginViewModel login)
{
if (ModelState.IsValid)
{
//... Here are codes get Id by email from DB
var hasher = new Microsoft.AspNetCore.Identity.PasswordHasher<IdentityUser>();
IdentityUser identityUser = new IdentityUser(user.Id.ToString());
if (PasswordVerificationResult.Failed == hasher.VerifyHashedPassword(identityUser,user.PasswordHash, login.Password))
ModelState.AddModelError("Password", "password is wrong");
}
else
ModelState.AddModelError("Email", "email or password invalid");
return PartialView("_LoginModalPartial", login);
}
Test of result
use
private readonly RandomNumberGenerator _rng;
public virtual string HashPassword(TUser user, string password)
{
if (_compatibilityMode == PasswordHasherCompatibilityMode.IdentityV2)
{
return Convert.ToBase64String(HashPasswordV2(password, _rng));
}
else
{
return Convert.ToBase64String(HashPasswordV3(password, _rng));
}
}
Reference: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.passwordhasher-1.hashpassword?view=aspnetcore-3.1
https://github.com/dotnet/aspnetcore/blob/master/src/Identity/Extensions.Core/src/PasswordHasher.cs#L96
Read more: https://andrewlock.net/exploring-the-asp-net-core-identity-passwordhasher/#hashing-new-passwords
I'm hoping someone can help me. I am using NAudio and am recording from multiple wsapiloopbackcapture devices and mixing them together. None of this can be written to disk, so I am doing it all in memory and am ultimately loading the data into a concurrent dictionary for another process to use that I will develop later. All this works except that whenever I run my thread to load my chunk data into my dictionary, when I play the audio back I hear a single clip sound and it coincides with how often I run the thread. If I set it to run every 20 seconds then I hear a clip sound at the 20 second mark when I listen to the audio. I need to get rid of this clipping and I can't figure out what is causing it.
Here are the basic steps
private static WasapiLoopbackCapture Wavein = null;
private static WasapiLoopbackCapture Wavein2 = null;
private static WaveFormat pcm8k16bitSt = new WaveFormat(8000, 16, 2);
private static WaveFormat pcm8k16bitMo = new WaveFormat(8000, 16, 1);
private static WaveFormat Bit16;
private static byte[] DataHeader = System.Text.Encoding.UTF8.GetBytes("data");
private static List<byte> SBL = new List<byte>();
private static List<byte> SBL2 = new List<byte>();
private static byte[] chunkdata;
private static byte[] chunkdata2;
internal static ConcurrentDictionary<DateTime, DataFrame> AllSpeakerBytes = new ConcurrentDictionary<DateTime, DataFrame>();
int SdeviceNumber = 0;
int SdeviceNumber2 = 0;
private static MMDevice deviceToRecord = null;
private static MMDevice deviceToRecord2 = null;
deviceToRecord = (new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.All, DeviceState.Active))[SdeviceNumber];
deviceToRecord2 = (new MMDeviceEnumerator().EnumerateAudioEndPoints(DataFlow.All, DeviceState.Active))[SdeviceNumber2];
RecordAllSpeakers();
private void RecordAllSpeakers()
{
if (deviceToRecord != null)
{
Wavein = new WasapiLoopbackCapture(deviceToRecord);
var silence = new SilenceProvider(Wavein.WaveFormat).ToSampleProvider();
var wo = new WaveOutEvent();
wo.DeviceNumber = SdeviceNumber;
wo.Init(silence);
wo.Play();
Wavein.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(SsourceStream_DataAvailable);
Wavein.StartRecording();
SRecFlag = true;
}
if (deviceToRecord2 != null)
{
Wavein2 = new WasapiLoopbackCapture(deviceToRecord2);
var silence = new SilenceProvider(Wavein2.WaveFormat).ToSampleProvider();
var wo = new WaveOutEvent();
wo.DeviceNumber = SdeviceNumber2;
wo.Init(silence);
wo.Play();
Wavein2.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(SsourceStream2_DataAvailable);
Wavein2.StartRecording();
SRecFlag2 = true;
}
}
private void SsourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
if (!SRecFlag) return;
if (Wavein.WaveFormat.BitsPerSample == 32)
{
#region NewStraightConvert
using (RawSourceWaveStream RS = new RawSourceWaveStream(e.Buffer, 0, e.BytesRecorded, WaveFormat.CreateIeeeFloatWaveFormat(Wavein.WaveFormat.SampleRate, Wavein.WaveFormat.Channels)))
using (Wave32To16Stream wav16 = new Wave32To16Stream(RS))
using (MemoryStream ms2 = new MemoryStream())
{
WaveFileWriter.WriteWavFileToStream(ms2, wav16);
ms2.Position = 0;
using (var reader = new WaveFileReader(ms2))
using (var conversionStream0 = new WaveFormatConversionStream(pcm8k16bitSt, reader))
using (var conversionStream1 = new WaveFormatConversionStream(pcm8k16bitMo, conversionStream0))
//using (var conversionStream2 = new WaveFormatConversionStream(muLaw8k8bit, conversionStream1))
{
byte[] SendingBytes;
using (MemoryStream ms3 = new MemoryStream())
{
using (RawSourceWaveStream cc = new RawSourceWaveStream(conversionStream1, pcm8k16bitMo))
{
cc.Position = 0;
cc.CopyTo(ms3);
SendingBytes = ms3.ToArray();
}
}
if (SendingBytes.Length > 0)
{
//SslTcpClient.VociDataToSendST2.AddRange(SendingBytes);
SBL.AddRange(SendingBytes);
}
}
}
#endregion
return;
}
else
{
byte[] outtovoci;
Bit16 = new WaveFormat(Wavein.WaveFormat.SampleRate, 16, Wavein.WaveFormat.Channels);
outtovoci = new byte[e.BytesRecorded];
Array.Copy(e.Buffer, 0, outtovoci, 0, e.BytesRecorded);
using (MemoryStream TESTWaveMS = new MemoryStream())
{
using (MemoryStream TESTWaveMS2 = new MemoryStream())
{
using (WaveFileWriter TESTwaveWriter = new WaveFileWriter(TESTWaveMS, Bit16))
{
TESTwaveWriter.Write(outtovoci, 0, outtovoci.Length);
TESTwaveWriter.Flush();
byte[] tbytes = TESTWaveMS.ToArray();
using (MemoryStream tstream = new MemoryStream(tbytes))
{
using (var reader = new WaveFileReader(tstream))
using (var conversionStream0 = new WaveFormatConversionStream(pcm8k16bitSt, reader))
using (var conversionStream1 = new WaveFormatConversionStream(pcm8k16bitMo, conversionStream0))
//using (var conversionStream2 = new WaveFormatConversionStream(muLaw8k8bit, conversionStream1))
{
WaveFileWriter.WriteWavFileToStream(TESTWaveMS2, conversionStream1);
byte[] tbytes2 = TESTWaveMS2.ToArray();
int fPos = SearchBytes(tbytes2, DataHeader);
if (fPos > 0)
{
fPos = fPos + 8;
}
else
{
fPos = 0;
}
long SendingBytes = tbytes2.Length - fPos;
byte[] WBack = new byte[SendingBytes];
if (SendingBytes > 0)
{
Array.Copy(tbytes2, fPos, WBack, 0, SendingBytes);
//SslTcpClient.VociDataToSendST2.AddRange(WBack);
SBL.AddRange(WBack);
}
}
}
}
}
}
}
}
private void SsourceStream2_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
if (!SRecFlag2) return;
if (Wavein2.WaveFormat.BitsPerSample == 32)
{
#region NewStraightConvert
using (RawSourceWaveStream RS = new RawSourceWaveStream(e.Buffer, 0, e.BytesRecorded, WaveFormat.CreateIeeeFloatWaveFormat(Wavein2.WaveFormat.SampleRate, Wavein2.WaveFormat.Channels)))
using (Wave32To16Stream wav16 = new Wave32To16Stream(RS))
using (MemoryStream ms2 = new MemoryStream())
{
WaveFileWriter.WriteWavFileToStream(ms2, wav16);
ms2.Position = 0;
using (var reader = new WaveFileReader(ms2))
using (var conversionStream0 = new WaveFormatConversionStream(pcm8k16bitSt, reader))
using (var conversionStream1 = new WaveFormatConversionStream(pcm8k16bitMo, conversionStream0))
//using (var conversionStream2 = new WaveFormatConversionStream(muLaw8k8bit, conversionStream1))
{
byte[] SendingBytes;
using (MemoryStream ms3 = new MemoryStream())
{
using (RawSourceWaveStream cc = new RawSourceWaveStream(conversionStream1, pcm8k16bitMo))
{
cc.Position = 0;
cc.CopyTo(ms3);
SendingBytes = ms3.ToArray();
}
}
if (SendingBytes.Length > 0)
{
//SslTcpClient.VociDataToSendST2.AddRange(SendingBytes);
SBL2.AddRange(SendingBytes);
}
}
}
#endregion
return;
}
else
{
byte[] outtovoci;
Bit16 = new WaveFormat(Wavein2.WaveFormat.SampleRate, 16, Wavein2.WaveFormat.Channels);
outtovoci = new byte[e.BytesRecorded];
Array.Copy(e.Buffer, 0, outtovoci, 0, e.BytesRecorded);
using (MemoryStream TESTWaveMS = new MemoryStream())
{
using (MemoryStream TESTWaveMS2 = new MemoryStream())
{
using (WaveFileWriter TESTwaveWriter = new WaveFileWriter(TESTWaveMS, Bit16))
{
TESTwaveWriter.Write(outtovoci, 0, outtovoci.Length);
TESTwaveWriter.Flush();
byte[] tbytes = TESTWaveMS.ToArray();
using (MemoryStream tstream = new MemoryStream(tbytes))
{
using (var reader = new WaveFileReader(tstream))
using (var conversionStream0 = new WaveFormatConversionStream(pcm8k16bitSt, reader))
using (var conversionStream1 = new WaveFormatConversionStream(pcm8k16bitMo, conversionStream0))
//using (var conversionStream2 = new WaveFormatConversionStream(muLaw8k8bit, conversionStream1))
{
WaveFileWriter.WriteWavFileToStream(TESTWaveMS2, conversionStream1);
byte[] tbytes2 = TESTWaveMS2.ToArray();
int fPos = SearchBytes(tbytes2, DataHeader);
if (fPos > 0)
{
fPos = fPos + 8;
}
else
{
fPos = 0;
}
long SendingBytes = tbytes2.Length - fPos;
byte[] WBack = new byte[SendingBytes];
if (SendingBytes > 0)
{
Array.Copy(tbytes2, fPos, WBack, 0, SendingBytes);
//SslTcpClient.VociDataToSendST2.AddRange(WBack);
SBL2.AddRange(WBack);
}
}
}
}
}
}
}
}
private async void timer3_Tick(object sender, EventArgs e)
{
timer3.Enabled = false;
if (SRecFlag == true || SRecFlag2 == true)
{
await Task.Run(() => SyncSpeakers());
}
timer3.Interval = 20000;
timer3.Enabled = true;
}
private static void SyncSpeakers()
{
MemoryStream ms = new MemoryStream();
MemoryStream ms2 = new MemoryStream();
WaveFileReader reader = null;
WaveFileReader reader2 = null;
MixingSampleProvider mixer = null;
int lbc = SBL.Count();
int lbc2 = SBL2.Count();
int lowest = 0;
int[] array = new int[] { lbc, lbc2 };
lowest = array.Where(f => f > 0).Min();
if (deviceToRecord != null && SBL.Count > 0)
{
chunkdata = new byte[lowest];
Array.Copy(SBL.ToArray(), 0, chunkdata, 0, chunkdata.Length);
SwaveWriterS1 = new NAudio.Wave.WaveFileWriter(ms, pcm8k16bitMo);
SwaveWriterS1.Write(chunkdata, 0, chunkdata.Length);
SwaveWriterS1.Flush();
SBL.RemoveRange(0, lowest);
}
if (deviceToRecord2 != null && SBL2.Count > 0)
{
chunkdata2 = new byte[lowest];
Array.Copy(SBL2.ToArray(), 0, chunkdata2, 0, chunkdata2.Length);
SwaveWriterS2 = new NAudio.Wave.WaveFileWriter(ms2, pcm8k16bitMo);
SwaveWriterS2.Write(chunkdata2, 0, chunkdata2.Length);
SwaveWriterS2.Flush();
SBL2.RemoveRange(0, lowest);
}
int SWaves = 0;
if (Wavein != null && SRecFlag == true)
{
ms.Position = 0;
reader = new WaveFileReader(ms);
SWaves++;
}
if (Wavein2 != null && SRecFlag2 == true)
{
ms2.Position = 0;
reader2 = new WaveFileReader(ms2);
SWaves++;
}
if (SWaves == 1)
{
mixer = new MixingSampleProvider(new[] { reader.ToSampleProvider() });
}
else if (SWaves == 2)
{
mixer = new MixingSampleProvider(new[] { reader.ToSampleProvider(), reader2.ToSampleProvider() });
}
if (SWaves > 0)
{
using (MemoryStream lms = new MemoryStream())
{
WaveFileWriter.WriteWavFileToStream(lms, mixer.ToWaveProvider16());
byte[] SendingBytes;
using (MemoryStream ms35 = new MemoryStream())
{
using (RawSourceWaveStream cc = new RawSourceWaveStream(lms, pcm8k16bitMo))
{
cc.Position = 0;
cc.CopyTo(ms35);
SendingBytes = ms35.ToArray();
SwaveWriter.Write(SendingBytes, 0, SendingBytes.Length);
SwaveWriter.Flush();
byte[] lByte = Compress(SendingBytes);
DataFrame aFrame2 = new DataFrame();
aFrame2.bytes = new byte[lByte.Length];
aFrame2.bytesRecorded = SendingBytes.Length;
lByte.CopyTo(aFrame2.bytes, 0);
AllSpeakerBytes.TryAdd(DateTime.UtcNow, aFrame2);
lByte = null;
}
}
}
}
}
internal static byte[] Compress(byte[] data)
{
try
{
//return data;
using (MemoryStream output = new MemoryStream())
{
using (DeflateStream dstream = new DeflateStream(output, CompressionLevel.Optimal))
{
dstream.Write(data, 0, data.Length);
}
return output.ToArray();
}
}
catch (Exception ERR5)
{
//Logging.LogData($"Failure in Compress: {ERR5.ToString()}");
return null;
}
}
internal static byte[] Decompress(byte[] data)
{
//return data;
try
{
using (MemoryStream output = new MemoryStream())
{
using (MemoryStream input = new MemoryStream(data))
{
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
}
return output.ToArray();
}
}
catch (Exception ERR5)
{
//Logging.LogData($"Failure in Decompress: {ERR5.ToString()}");
return null;
}
}
class DataFrame
{
public byte[] bytes { get; set; }
public int bytesRecorded { get; set; }
public string extraData { get; set; } = "";
}
private void btnStop_Click(object sender, EventArgs e)
{
if (Wavein != null)
{
Wavein.StopRecording();
Wavein.Dispose();
Wavein = null;
}
if (Wavein2 != null)
{
Wavein2.StopRecording();
Wavein2.Dispose();
Wavein2 = null;
}
mp3WriterAllSpk = new NAudio.Lame.LameMP3FileWriter(FinalSRFilename, pcm8k16bitMo, 64);
List<DateTime> SpkWrites = AllSpeakerBytes.Select(k => k.Key).OrderBy(c => c).ToList();
foreach (DateTime DT in SpkWrites)
{
byte[] outgoing = Decompress(AllSpeakerBytes[DT].bytes);
mp3WriterAllSpk.Write(outgoing, 0, AllSpeakerBytes[DT].bytesRecorded);
}
mp3WriterAllSpk.Dispose();
SRecFlag = false;
SRecFlag2 = false;
}
This code needs a lot of cleaning up but basically the SyncSpeakers() is being ran every 20 seconds and I am hearing a clipping at 20 second increments of the audio. If I change the timer to run every 10 seconds I will hear a clip sound every 10 seconds of the resulting audio. Any ideas?
I was able to solve this by shaving the first 100 bytes off of the front and replacing them with byte 101. If there is a better way I'd love to hear it.
Thanks!
I am working on CloudStack API now and I have the problem about making the API request. I always got "{ "listtemplatesresponse" : {"errorcode":401,"errortext":"unable to verify user credentials and/or request signature"} }" even though I change the parameter.
This error occurs in some commands that require the parameter and this is the command that I use:
command=listTemplates&templatefilter=featured
I don't know what I did wrong since it works with others. Here is the code I use to make the API request:
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
sortedUrl += "&response=json";
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
And this is signRequest function:
public static String signRequest(String request, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(request.getBytes());
byte[] encryptedBytes = mac.doFinal();
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
} catch (Exception ex) {
System.out.println(ex);
}
return null;
}
Please feel free to ask me if you need more information. All comments and advice are welcome!
Have you tried sorting after you've added "&response=json" to the list of parameters?
E.g.
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
sortedParams.add("response=json");
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
Your API Key and Response parameters need to be part of the sorted Url used when signing, which they appear to be.
try changing
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
to
return URLEncoder.encode(Base64.encodeAsString(encryptedBytes), "UTF-8");
Is it possible with Sharepoint 2010 (not 2013!) to get a list of all the Term Stores on the site using either the web services or the client-side object model?
I know 2013 has added a library for it, but that will not help me on 2010.
If not the whole list, how do I get the Term Store ID, if I know a Term (that might or might not be in the TaxonomyHiddenList)?
Someone mentioned checking out the TaxonomyFieldType fields, so I hacked together these 2 methods. I do not know if these will work under all circumstances.
First function just returns the Term Store ID which is stored in the info of the first TaxonomyFieldType* we come over.
public static string GetDefaultTermStore(string site) {
var context = new ClientContext(site);
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
return node.Value;
}
}
}
throw new Exception("Term Store ID not found!");
}
The second function goes through all the fields and gets all the possible Term Store IDs and returns them in a list.
public static List<string> GetTermStores(string site) {
var context = new ClientContext(site);
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
if (!hashlist.Contains(node.Value)) {
hashlist.Add(node.Value);
}
}
}
}
if (hashlist.Count == 0) throw new Exception("No Term Store IDs not found!");
return hashlist.ToList();
}
Is this a correct answer to my question do anyone have a more sure way to get the IDs?
Does not seem like anyone else has a good answer for this question.
I have added the utility class I made from this below. Big block of uncommented code below for those who might need:
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Services.Protocols;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Xml.XPath;
namespace VitaminTilKanbanPusher.Sharepoint {
public class SharepointTaxonomyAgent {
//URLS:
//http://www.novolocus.com/2012/02/06/working-with-the-taxonomyclientservice-part-1-what-fields-are-there/
//
public static void Test() {
var site = ConfigurationManager.AppSettings["VitaminSite"];
//var list = ConfigurationManager.AppSettings["VitaminList"];
//var id = GetDefaultTermStore(site);
//var ids = GetTermStores(site);
var rs = GetAllTermSetNames(site);
var ts = GetTermSetTerms(site, "Some Name");
//var ts = GetTermSetTerms(site, "Some other name");
//var term = GetTermInfo(site, "Priority");
//var term2 = GetTermInfo(site, "My term");
//var termset = GetTermSetInfo(site, "My term");
//var termsets = GetTermSets(site, "My term");
}
public static string GetDefaultTermStore(string site) {
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
foreach (var field in fields) {
//field.InternalName== "TaxKeyword" -> possibly default?
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
return node.Value;
}
}
}
throw new Exception("Term Store ID not found!");
}
public static List<string> GetTermStores(string site) {
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var doc = XDocument.Parse(field.SchemaXml);
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
if (!hashlist.Contains(node.Value)) {
hashlist.Add(node.Value);
}
}
}
}
if (hashlist.Count == 0) throw new Exception("No Term Store IDs not found!");
return hashlist.ToList();
}
private static List<TermSet> _termSets;
public static List<TermSet> GetAllTermSetNames(string site, string onlySpecificTermSetName = null) {
if (_termSets != null) {
if (onlySpecificTermSetName == null) return _termSets;
foreach (var ts in _termSets) {
if (ts.Name.Equals(onlySpecificTermSetName, StringComparison.InvariantCultureIgnoreCase)) {
return new List<TermSet>() { ts };
}
}
return new List<TermSet>();
}
var context = new ClientContext(site);
context.ExecutingWebRequest += ctx_MixedAuthRequest;
var fields = context.Web.Fields;
context.Load(fields, fs => fs.Include(f => f.SchemaXml, f => f.TypeAsString));
context.ExecuteQuery();
var hashlist = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
var termSets = new List<TermSet>();
TermSet theChosenTermSet = null;
foreach (var field in fields) {
if (field.TypeAsString.StartsWith("TaxonomyFieldType")) {
var ts = new TermSet();
var doc = XDocument.Parse(field.SchemaXml);
var fn = doc.Element("Field");
if (fn == null) continue;
if (fn.Attribute("DisplayName") == null) continue;
if (fn.Attribute("ID") == null) continue;
ts.Name = fn.Attribute("DisplayName").Value;
//Only 1 set?
if (onlySpecificTermSetName != null) {
if (!ts.Name.Equals(onlySpecificTermSetName, StringComparison.InvariantCultureIgnoreCase)) {
theChosenTermSet = ts;
}
}
if (fn.Attribute("Description") != null) {
ts.Description = fn.Attribute("Description").Value;
}
var node = doc.XPathSelectElement("//Name[text()='SspId']/../Value");
if (node != null && !string.IsNullOrEmpty(node.Value)) {
ts.TermStoreId = node.Value;
}
var node2 = doc.XPathSelectElement("//Name[text()='TermSetId']/../Value");
if (node2 != null && !string.IsNullOrEmpty(node2.Value)) {
ts.Id = node2.Value;
}
else {
continue; //No ID found
}
//Unique hites
if (!hashlist.Contains(ts.Id)) {
hashlist.Add(ts.Id);
termSets.Add(ts);
}
}
}
_termSets = termSets;
if (onlySpecificTermSetName != null) return (theChosenTermSet == null ? new List<TermSet>() : new List<TermSet>() { theChosenTermSet });
return termSets;
}
public static TermSet GetTermSetTerms(string site, string termName) {
var ts = GetAllTermSetNames(site, termName);
if (ts.Count == 0) throw new Exception("Could not find termset: " + termName);
var theTermSet = ts[0];
var proxy = new SharepointTaxWS.Taxonomywebservice();
proxy.UseDefaultCredentials = true;
proxy.PreAuthenticate = true;
proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
GetAuthCookie(proxy, site);
var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
var clientTime = DateTime.Now.AddYears(-2).ToUniversalTime().Ticks.ToString();
var termStoreId = new Guid(theTermSet.TermStoreId);// Guid.Parse(theTermSet.TermStoreId);
var termSetId = new Guid(theTermSet.Id);
string clientTimestamps = string.Format("<timeStamp>{0}</timeStamp>", clientTime);
string clientVersion = "<version>1</version>";
string termStoreIds = string.Format("<termStoreId>{0}</termStoreId>", termStoreId.ToString("D"));
string termSetIds = string.Format("<termSetId>{0}</termSetId>", termSetId.ToString("D"));
string serverTermSetTimestampXml;
string result = proxy.GetTermSets(termStoreIds, termSetIds, 1033, clientTimestamps, clientVersion, out serverTermSetTimestampXml);
var term = ParseTermSetInfo(result);
term.Description = theTermSet.Description;
term.Id = theTermSet.Id;
term.Name = theTermSet.Name;
return term;
}
//public static Term GetTermSetInfo(string site, string termName) {
// var proxy = new SharepointTaxWS.Taxonomywebservice();
// proxy.UseDefaultCredentials = true;
// proxy.PreAuthenticate = true;
// proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
// GetAuthCookie(proxy, site);
// var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
// var sets = proxy.GetChildTermsInTermSet(Guid.Parse(""), lciden, Guid.Parse("termsetguid"));
// var term = ParseTermInfo(sets);
// return term;
//}
public static Term GetTermInfo(string site, string termName) {
var proxy = new SharepointTaxWS.Taxonomywebservice();
proxy.UseDefaultCredentials = true;
proxy.PreAuthenticate = true;
proxy.Url = Path.Combine(site, "_vti_bin/taxonomyclientservice.asmx");
GetAuthCookie(proxy, site);
var lciden = 1033; //var lcidno = 1044; // System.Globalization.CultureInfo.CurrentCulture.LCID
var sets = proxy.GetTermsByLabel(termName, lciden, SharepointTaxWS.StringMatchOption.StartsWith, 100, null, false);
var term = ParseTermInfo(sets);
return term;
}
private static TermSet ParseTermSetInfo(string xml) {
//Not done
var info = XDocument.Parse(xml);
var ts = new TermSet();
ts.Terms = new List<Term>();
var n1 = info.XPathSelectElements("//T");
if (n1 != null) {
foreach (var item in n1) {
var t = new Term();
t.Id = item.Attribute("a9").Value;
t.Name = item.XPathSelectElement("LS/TL").Attribute("a32").Value;
t.TermSet = ts;
ts.Terms.Add(t);
}
}
return ts;
}
private static Term ParseTermInfo(string xml) {
var info = XDocument.Parse(xml);
var t = new Term();
var ts = new TermSet();
var n1 = info.XPathSelectElement("TermStore/T");
var n2 = info.XPathSelectElement("TermStore/T/LS/TL");
var n3 = info.XPathSelectElement("TermStore/T/TMS/TM");
if (n1 != null && n1.Attribute("a9") != null) {
t.Id = n1.Attribute("a9").Value;
}
if (n2 != null && n2.Attribute("a32") != null) {
t.Name = n2.Attribute("a32").Value;
}
if (n3 != null && n3.Attribute("a24") != null) {
ts.Id = n3.Attribute("a24").Value;
}
if (n3 != null && n3.Attribute("a12") != null) {
ts.Name = n3.Attribute("a12").Value;
}
t.TermSet = ts;
return t;
}
private static CookieCollection _theAuth;
private static bool _bNoClaims;
static void GetAuthCookie(SoapHttpClientProtocol proxy, string site) {
return;
//if (_bNoClaims) {
// return; //Ingen claims.
//}
//// get the cookie collection - authentication workaround
//CookieCollection cook = null;
//try {
// if (_theAuth == null) {
// cook = ClaimClientContext.GetAuthenticatedCookies(site, 925, 525);
// }
// else {
// cook = _theAuth;
// }
// _theAuth = cook;
// _bNoClaims = false;
//}
//catch (ApplicationException ex) {
// if (ex.Message.Contains("claim")) _bNoClaims = true;
// Console.Write("Auth feilet: " + ex.Message + " - ");
// //IGNORE
//}
//if (_theAuth != null) {
// proxy.CookieContainer = new CookieContainer();
// proxy.CookieContainer.Add(_theAuth);
//}
}
static void ctx_MixedAuthRequest(object sender, WebRequestEventArgs e) {
//add the header that tells SharePoint to use Windows Auth
e.WebRequestExecutor.RequestHeaders.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
}
}
public class TermSet {
public string Id { get; set; }
public string Name { get; set; }
public List<Term> Terms { get; set; }
public string TermStoreId { get; set; }
public string Description { get; set; }
public override string ToString() {
int tc = 0;
if (Terms != null) tc = Terms.Count;
return Name + "|" + Id + " (" + tc + "terms)";
}
}
public class Term {
public string Id { get; set; }
public string Name { get; set; }
public TermSet TermSet { get; set; }
public override string ToString() {
return Name + "|" + Id;
}
}
}